example.e31bb0bc.js 1.4 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866
  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.loadTileSet(url);
  949. }
  950. traverse(cb) {
  951. const tileSets = this.tileSets;
  952. const rootTileSet = tileSets[this.rootSet];
  953. if (!rootTileSet || !rootTileSet.root) return;
  954. traverseSet(rootTileSet.root, cb);
  955. } // Public API
  956. update() {
  957. const stats = this.stats;
  958. const lruCache = this.lruCache;
  959. const tileSets = this.tileSets;
  960. const rootTileSet = tileSets[this.rootSet];
  961. if (!rootTileSet || !rootTileSet.root) return;
  962. const root = rootTileSet.root;
  963. stats.inFrustum = 0, stats.used = 0, stats.active = 0, stats.visible = 0, this.frameCount++;
  964. determineFrustumSet(root, this);
  965. markUsedSetLeaves(root, this);
  966. skipTraversal(root, this);
  967. toggleTiles(root, this); // TODO: We may want to add this function in the requestTileContents function
  968. lruCache.scheduleUnload(null);
  969. } // Overrideable
  970. parseTile(buffer, tile) {
  971. return null;
  972. }
  973. disposeTile(tile) {}
  974. preprocessNode(tile, parentTile, tileSetDir) {
  975. if (tile.content) {
  976. if (!('uri' in tile.content) && 'url' in tile.content) {
  977. tile.content.uri = tile.content.url;
  978. delete tile.content.url;
  979. }
  980. if (tile.content.uri) {
  981. tile.content.uri = _path.default.join(tileSetDir, tile.content.uri);
  982. } // TODO: fix for some cases where tilesets provide the bounding volume
  983. // but volumes are not present. See
  984. if (tile.content.boundingVolume && !('box' in tile.content.boundingVolume || 'sphere' in tile.content.boundingVolume || 'region' in tile.content.boundingVolume)) {
  985. delete tile.content.boundingVolume;
  986. }
  987. }
  988. tile.parent = parentTile;
  989. tile.children = tile.children || [];
  990. tile.__contentEmpty = !tile.content || !tile.content.uri;
  991. tile.__error = 0.0;
  992. tile.__inFrustum = false;
  993. tile.__isLeaf = false;
  994. tile.__wasUsed = false;
  995. tile.__used = false;
  996. tile.__wasVisible = false;
  997. tile.__visible = false;
  998. tile.__wasActive = false;
  999. tile.__active = false;
  1000. tile.__childrenActive = false;
  1001. tile.__loadingState = UNLOADED;
  1002. tile.__loadIndex = 0;
  1003. tile.__loadAbort = null;
  1004. if (parentTile === null) {
  1005. tile.__depth = 0;
  1006. } else {
  1007. tile.__depth = parentTile.__depth + 1;
  1008. }
  1009. }
  1010. setTileActive(tile, state) {}
  1011. setTileVisible(tile, state) {}
  1012. calculateError(tile) {
  1013. return 0;
  1014. }
  1015. tileInView(tile) {
  1016. return true;
  1017. } // Private Functions
  1018. loadTileSet(url) {
  1019. const tileSets = this.tileSets;
  1020. if (!(url in tileSets)) {
  1021. const pr = fetch(url, {
  1022. credentials: 'same-origin'
  1023. }).then(res => {
  1024. if (res.ok) {
  1025. return res.json();
  1026. } else {
  1027. throw new Error(`Status ${res.status} (${res.statusText})`);
  1028. }
  1029. }).then(json => {
  1030. // TODO: Add version query?
  1031. const version = json.asset.version;
  1032. console.assert(version === '1.0' || version === '0.0');
  1033. const basePath = _path.default.dirname(url);
  1034. traverseSet(json.root, (node, parent) => this.preprocessNode(node, parent, basePath));
  1035. tileSets[url] = json; // TODO: schedule an update to avoid doing this too many times
  1036. this.update();
  1037. });
  1038. pr.catch(e => {
  1039. console.error(`TilesLoader: Failed to load tile set json "${url}"`);
  1040. console.error(e);
  1041. delete tileSets[url];
  1042. });
  1043. tileSets[url] = pr;
  1044. }
  1045. return Promise.resolve(tileSets[url]);
  1046. }
  1047. requestTileContents(tile) {
  1048. // If the tile is already being loaded then don't
  1049. // start it again.
  1050. if (tile.__loadingState !== UNLOADED) {
  1051. return;
  1052. } // TODO: reuse the functions created here?
  1053. const lruCache = this.lruCache;
  1054. const downloadQueue = this.downloadQueue;
  1055. const parseQueue = this.parseQueue;
  1056. lruCache.add(tile, t => {
  1057. if (t.__loadingState === LOADING) {
  1058. t.__loadAbort.abort();
  1059. t.__loadAbort = null;
  1060. } else {
  1061. this.disposeTile(t);
  1062. }
  1063. if (t.__loadingState === LOADING) {
  1064. stats.downloading--;
  1065. } else if (t.__loadingState === PARSING) {
  1066. stats.parsing--;
  1067. }
  1068. t.__loadingState = UNLOADED;
  1069. t.__loadIndex++; // TODO: Removing from the queues here is slow
  1070. // parseQueue.remove( t );
  1071. // downloadQueue.remove( t );
  1072. });
  1073. tile.__loadIndex++;
  1074. const loadIndex = tile.__loadIndex;
  1075. const priority = 1 / (tile.__depth + 1);
  1076. const stats = this.stats;
  1077. const controller = new AbortController();
  1078. const signal = controller.signal;
  1079. stats.downloading++;
  1080. tile.__loadAbort = controller;
  1081. tile.__loadingState = LOADING;
  1082. downloadQueue.add(tile, priority, tile => {
  1083. if (tile.__loadIndex !== loadIndex) {
  1084. return Promise.resolve();
  1085. }
  1086. return fetch(tile.content.uri, {
  1087. credentials: 'same-origin',
  1088. signal
  1089. });
  1090. }).then(res => {
  1091. if (tile.__loadIndex !== loadIndex) {
  1092. return;
  1093. }
  1094. if (res.ok) {
  1095. return res.arrayBuffer();
  1096. } else {
  1097. throw new Error(`Failed to load model with error code ${res.status}`);
  1098. }
  1099. }).then(buffer => {
  1100. if (tile.__loadIndex !== loadIndex) {
  1101. return;
  1102. }
  1103. stats.downloading--;
  1104. stats.parsing++;
  1105. tile.__loadAbort = null;
  1106. tile.__loadingState = PARSING;
  1107. return parseQueue.add(buffer, priority, buffer => {
  1108. if (tile.__loadIndex !== loadIndex) {
  1109. return Promise.resolve();
  1110. }
  1111. return this.parseTile(buffer, tile);
  1112. });
  1113. }).then(() => {
  1114. if (tile.__loadIndex !== loadIndex) {
  1115. return;
  1116. }
  1117. stats.parsing--;
  1118. tile.__loadingState = LOADED;
  1119. this.setTileActive(tile, tile.__active);
  1120. this.setTileVisible(tile, tile.__visible);
  1121. }).catch(e => {
  1122. // if it has been unloaded then the tile has been disposed
  1123. if (tile.__loadIndex !== loadIndex) {
  1124. return;
  1125. }
  1126. if (e.name !== 'AbortError') {
  1127. console.error('TilesRenderer : Failed to load tile.');
  1128. console.error(e);
  1129. tile.__loadingState = FAILED;
  1130. } else {
  1131. lruCache.remove(tile);
  1132. }
  1133. });
  1134. }
  1135. }
  1136. exports.TilesRenderer = TilesRenderer;
  1137. },{"path":"../node_modules/path-browserify/index.js","./LRUCache.js":"../src/LRUCache.js","./PriorityQueue.js":"../src/PriorityQueue.js"}],"../src/B3DMLoader.js":[function(require,module,exports) {
  1138. "use strict";
  1139. Object.defineProperty(exports, "__esModule", {
  1140. value: true
  1141. });
  1142. exports.B3DMLoader = void 0;
  1143. // https://github.com/AnalyticalGraphicsInc/3d-tiles/blob/master/specification/TileFormats/Batched3DModel/README.md
  1144. // convert an array of numbers to a string
  1145. function arrayToString(array) {
  1146. let str = '';
  1147. for (let i = 0, l = array.length; i < l; i++) {
  1148. str += String.fromCharCode(array[i]);
  1149. }
  1150. return str;
  1151. }
  1152. class B3DMLoader {
  1153. load(url) {
  1154. return fetch(url, {
  1155. credentials: 'same-origin'
  1156. }).then(res => res.arrayBuffer()).then(buffer => this.parse(buffer));
  1157. }
  1158. parse(buffer) {
  1159. const dataView = new DataView(buffer); // 28-byte header
  1160. // 4 bytes
  1161. const magic = String.fromCharCode(dataView.getUint8(0)) + String.fromCharCode(dataView.getUint8(1)) + String.fromCharCode(dataView.getUint8(2)) + String.fromCharCode(dataView.getUint8(3));
  1162. console.assert(magic === 'b3dm'); // 4 bytes
  1163. const version = dataView.getUint32(4, true);
  1164. console.assert(version === 1); // 4 bytes
  1165. const byteLength = dataView.getUint32(8, true);
  1166. console.assert(byteLength === buffer.byteLength); // 4 bytes
  1167. const featureTableJSONByteLength = dataView.getUint32(12, true); // 4 bytes
  1168. const featureTableBinaryByteLength = dataView.getUint32(16, true); // 4 bytes
  1169. const batchTableJSONByteLength = dataView.getUint32(20, true); // 4 bytes
  1170. const batchTableBinaryByteLength = dataView.getUint32(24, true); // Feature Table
  1171. const featureTableStart = 28;
  1172. const jsonFeatureTableData = new Uint8Array(buffer, featureTableStart, featureTableJSONByteLength);
  1173. const jsonFeatureTable = featureTableJSONByteLength === 0 ? {} : JSON.parse(arrayToString(jsonFeatureTableData)); // const binFeatureTableData = new Uint8Array( buffer, featureTableStart + featureTableJSONByteLength, featureTableBinaryByteLength );
  1174. // TODO: dereference the json feature table data in to the binary array.
  1175. // https://github.com/AnalyticalGraphicsInc/3d-tiles/blob/master/specification/TileFormats/FeatureTable/README.md#json-header
  1176. // Batch Table
  1177. const batchTableStart = featureTableStart + featureTableJSONByteLength + featureTableBinaryByteLength;
  1178. const jsonBatchTableData = new Uint8Array(buffer, batchTableStart, batchTableJSONByteLength);
  1179. const jsonBatchTable = batchTableJSONByteLength === 0 ? {} : JSON.parse(arrayToString(jsonBatchTableData)); // const binBatchTableData = new Uint8Array( buffer, batchTableStart + batchTableJSONByteLength, batchTableBinaryByteLength );
  1180. // TODO: dereference the json batch table data in to the binary array.
  1181. // https://github.com/AnalyticalGraphicsInc/3d-tiles/blob/master/specification/TileFormats/FeatureTable/README.md#json-header
  1182. const glbStart = batchTableStart + batchTableJSONByteLength + batchTableBinaryByteLength;
  1183. const glbBytes = new Uint8Array(buffer, glbStart, byteLength - glbStart); // TODO: Understand how to apply the batchId semantics
  1184. // https://github.com/AnalyticalGraphicsInc/3d-tiles/blob/master/specification/TileFormats/Batched3DModel/README.md#binary-gltf
  1185. return {
  1186. version,
  1187. featureTable: jsonFeatureTable,
  1188. batchTable: jsonBatchTable,
  1189. glbBytes
  1190. };
  1191. }
  1192. }
  1193. exports.B3DMLoader = B3DMLoader;
  1194. },{}],"../node_modules/three/build/three.module.js":[function(require,module,exports) {
  1195. "use strict";
  1196. Object.defineProperty(exports, "__esModule", {
  1197. value: true
  1198. });
  1199. exports.AmbientLight = AmbientLight;
  1200. exports.AmbientLightProbe = AmbientLightProbe;
  1201. exports.AnimationClip = AnimationClip;
  1202. exports.AnimationLoader = AnimationLoader;
  1203. exports.AnimationMixer = AnimationMixer;
  1204. exports.AnimationObjectGroup = AnimationObjectGroup;
  1205. exports.ArcCurve = ArcCurve;
  1206. exports.ArrayCamera = ArrayCamera;
  1207. exports.ArrowHelper = ArrowHelper;
  1208. exports.Audio = Audio;
  1209. exports.AudioAnalyser = AudioAnalyser;
  1210. exports.AudioListener = AudioListener;
  1211. exports.AudioLoader = AudioLoader;
  1212. exports.AxesHelper = AxesHelper;
  1213. exports.AxisHelper = AxisHelper;
  1214. exports.BinaryTextureLoader = BinaryTextureLoader;
  1215. exports.Bone = Bone;
  1216. exports.BooleanKeyframeTrack = BooleanKeyframeTrack;
  1217. exports.BoundingBoxHelper = BoundingBoxHelper;
  1218. exports.Box2 = Box2;
  1219. exports.Box3 = Box3;
  1220. exports.Box3Helper = Box3Helper;
  1221. exports.BoxHelper = BoxHelper;
  1222. exports.BufferAttribute = BufferAttribute;
  1223. exports.BufferGeometry = BufferGeometry;
  1224. exports.BufferGeometryLoader = BufferGeometryLoader;
  1225. exports.Camera = Camera;
  1226. exports.CameraHelper = CameraHelper;
  1227. exports.CanvasRenderer = CanvasRenderer;
  1228. exports.CanvasTexture = CanvasTexture;
  1229. exports.CatmullRomCurve3 = CatmullRomCurve3;
  1230. exports.CircleBufferGeometry = CircleBufferGeometry;
  1231. exports.CircleGeometry = CircleGeometry;
  1232. exports.Clock = Clock;
  1233. exports.ClosedSplineCurve3 = ClosedSplineCurve3;
  1234. exports.Color = Color;
  1235. exports.ColorKeyframeTrack = ColorKeyframeTrack;
  1236. exports.CompressedTexture = CompressedTexture;
  1237. exports.CompressedTextureLoader = CompressedTextureLoader;
  1238. exports.ConeBufferGeometry = ConeBufferGeometry;
  1239. exports.ConeGeometry = ConeGeometry;
  1240. exports.CubeCamera = CubeCamera;
  1241. exports.CubeTexture = CubeTexture;
  1242. exports.CubeTextureLoader = CubeTextureLoader;
  1243. exports.CubicBezierCurve = CubicBezierCurve;
  1244. exports.CubicBezierCurve3 = CubicBezierCurve3;
  1245. exports.CubicInterpolant = CubicInterpolant;
  1246. exports.Curve = Curve;
  1247. exports.CurvePath = CurvePath;
  1248. exports.CylinderBufferGeometry = CylinderBufferGeometry;
  1249. exports.CylinderGeometry = CylinderGeometry;
  1250. exports.Cylindrical = Cylindrical;
  1251. exports.DataTexture = DataTexture;
  1252. exports.DataTexture2DArray = DataTexture2DArray;
  1253. exports.DataTexture3D = DataTexture3D;
  1254. exports.DataTextureLoader = DataTextureLoader;
  1255. exports.DepthTexture = DepthTexture;
  1256. exports.DirectionalLight = DirectionalLight;
  1257. exports.DirectionalLightHelper = DirectionalLightHelper;
  1258. exports.DirectionalLightShadow = DirectionalLightShadow;
  1259. exports.DiscreteInterpolant = DiscreteInterpolant;
  1260. exports.DodecahedronBufferGeometry = DodecahedronBufferGeometry;
  1261. exports.DodecahedronGeometry = DodecahedronGeometry;
  1262. exports.DynamicBufferAttribute = DynamicBufferAttribute;
  1263. exports.EdgesGeometry = EdgesGeometry;
  1264. exports.EdgesHelper = EdgesHelper;
  1265. exports.EllipseCurve = EllipseCurve;
  1266. exports.Euler = Euler;
  1267. exports.EventDispatcher = EventDispatcher;
  1268. exports.ExtrudeBufferGeometry = ExtrudeBufferGeometry;
  1269. exports.ExtrudeGeometry = ExtrudeGeometry;
  1270. exports.Face3 = Face3;
  1271. exports.Face4 = Face4;
  1272. exports.FaceNormalsHelper = FaceNormalsHelper;
  1273. exports.FileLoader = FileLoader;
  1274. exports.Float32Attribute = Float32Attribute;
  1275. exports.Float32BufferAttribute = Float32BufferAttribute;
  1276. exports.Float64Attribute = Float64Attribute;
  1277. exports.Float64BufferAttribute = Float64BufferAttribute;
  1278. exports.Fog = Fog;
  1279. exports.FogExp2 = FogExp2;
  1280. exports.Font = Font;
  1281. exports.FontLoader = FontLoader;
  1282. exports.Frustum = Frustum;
  1283. exports.Geometry = Geometry;
  1284. exports.GridHelper = GridHelper;
  1285. exports.Group = Group;
  1286. exports.HemisphereLight = HemisphereLight;
  1287. exports.HemisphereLightHelper = HemisphereLightHelper;
  1288. exports.HemisphereLightProbe = HemisphereLightProbe;
  1289. exports.IcosahedronBufferGeometry = IcosahedronBufferGeometry;
  1290. exports.IcosahedronGeometry = IcosahedronGeometry;
  1291. exports.ImageBitmapLoader = ImageBitmapLoader;
  1292. exports.ImageLoader = ImageLoader;
  1293. exports.ImmediateRenderObject = ImmediateRenderObject;
  1294. exports.InstancedBufferAttribute = InstancedBufferAttribute;
  1295. exports.InstancedBufferGeometry = InstancedBufferGeometry;
  1296. exports.InstancedInterleavedBuffer = InstancedInterleavedBuffer;
  1297. exports.InstancedMesh = InstancedMesh;
  1298. exports.Int16Attribute = Int16Attribute;
  1299. exports.Int16BufferAttribute = Int16BufferAttribute;
  1300. exports.Int32Attribute = Int32Attribute;
  1301. exports.Int32BufferAttribute = Int32BufferAttribute;
  1302. exports.Int8Attribute = Int8Attribute;
  1303. exports.Int8BufferAttribute = Int8BufferAttribute;
  1304. exports.InterleavedBuffer = InterleavedBuffer;
  1305. exports.InterleavedBufferAttribute = InterleavedBufferAttribute;
  1306. exports.Interpolant = Interpolant;
  1307. exports.JSONLoader = JSONLoader;
  1308. exports.KeyframeTrack = KeyframeTrack;
  1309. exports.LOD = LOD;
  1310. exports.LatheBufferGeometry = LatheBufferGeometry;
  1311. exports.LatheGeometry = LatheGeometry;
  1312. exports.Layers = Layers;
  1313. exports.LensFlare = LensFlare;
  1314. exports.Light = Light;
  1315. exports.LightProbe = LightProbe;
  1316. exports.LightProbeHelper = LightProbeHelper;
  1317. exports.LightShadow = LightShadow;
  1318. exports.Line = Line;
  1319. exports.Line3 = Line3;
  1320. exports.LineBasicMaterial = LineBasicMaterial;
  1321. exports.LineCurve = LineCurve;
  1322. exports.LineCurve3 = LineCurve3;
  1323. exports.LineDashedMaterial = LineDashedMaterial;
  1324. exports.LineLoop = LineLoop;
  1325. exports.LineSegments = LineSegments;
  1326. exports.LinearInterpolant = LinearInterpolant;
  1327. exports.Loader = Loader;
  1328. exports.LoadingManager = LoadingManager;
  1329. exports.Material = Material;
  1330. exports.MaterialLoader = MaterialLoader;
  1331. exports.Matrix3 = Matrix3;
  1332. exports.Matrix4 = Matrix4;
  1333. exports.Mesh = Mesh;
  1334. exports.MeshBasicMaterial = MeshBasicMaterial;
  1335. exports.MeshDepthMaterial = MeshDepthMaterial;
  1336. exports.MeshDistanceMaterial = MeshDistanceMaterial;
  1337. exports.MeshFaceMaterial = MeshFaceMaterial;
  1338. exports.MeshLambertMaterial = MeshLambertMaterial;
  1339. exports.MeshMatcapMaterial = MeshMatcapMaterial;
  1340. exports.MeshNormalMaterial = MeshNormalMaterial;
  1341. exports.MeshPhongMaterial = MeshPhongMaterial;
  1342. exports.MeshPhysicalMaterial = MeshPhysicalMaterial;
  1343. exports.MeshStandardMaterial = MeshStandardMaterial;
  1344. exports.MeshToonMaterial = MeshToonMaterial;
  1345. exports.MultiMaterial = MultiMaterial;
  1346. exports.NumberKeyframeTrack = NumberKeyframeTrack;
  1347. exports.Object3D = Object3D;
  1348. exports.ObjectLoader = ObjectLoader;
  1349. exports.OctahedronBufferGeometry = OctahedronBufferGeometry;
  1350. exports.OctahedronGeometry = OctahedronGeometry;
  1351. exports.OrthographicCamera = OrthographicCamera;
  1352. exports.ParametricBufferGeometry = ParametricBufferGeometry;
  1353. exports.ParametricGeometry = ParametricGeometry;
  1354. exports.Particle = Particle;
  1355. exports.ParticleBasicMaterial = ParticleBasicMaterial;
  1356. exports.ParticleSystem = ParticleSystem;
  1357. exports.ParticleSystemMaterial = ParticleSystemMaterial;
  1358. exports.Path = Path;
  1359. exports.PerspectiveCamera = PerspectiveCamera;
  1360. exports.Plane = Plane;
  1361. exports.PlaneBufferGeometry = PlaneBufferGeometry;
  1362. exports.PlaneGeometry = PlaneGeometry;
  1363. exports.PlaneHelper = PlaneHelper;
  1364. exports.PointCloud = PointCloud;
  1365. exports.PointCloudMaterial = PointCloudMaterial;
  1366. exports.PointLight = PointLight;
  1367. exports.PointLightHelper = PointLightHelper;
  1368. exports.Points = Points;
  1369. exports.PointsMaterial = PointsMaterial;
  1370. exports.PolarGridHelper = PolarGridHelper;
  1371. exports.PolyhedronBufferGeometry = PolyhedronBufferGeometry;
  1372. exports.PolyhedronGeometry = PolyhedronGeometry;
  1373. exports.PositionalAudio = PositionalAudio;
  1374. exports.PositionalAudioHelper = PositionalAudioHelper;
  1375. exports.PropertyBinding = PropertyBinding;
  1376. exports.PropertyMixer = PropertyMixer;
  1377. exports.QuadraticBezierCurve = QuadraticBezierCurve;
  1378. exports.QuadraticBezierCurve3 = QuadraticBezierCurve3;
  1379. exports.Quaternion = Quaternion;
  1380. exports.QuaternionKeyframeTrack = QuaternionKeyframeTrack;
  1381. exports.QuaternionLinearInterpolant = QuaternionLinearInterpolant;
  1382. exports.RawShaderMaterial = RawShaderMaterial;
  1383. exports.Ray = Ray;
  1384. exports.Raycaster = Raycaster;
  1385. exports.RectAreaLight = RectAreaLight;
  1386. exports.RectAreaLightHelper = RectAreaLightHelper;
  1387. exports.RingBufferGeometry = RingBufferGeometry;
  1388. exports.RingGeometry = RingGeometry;
  1389. exports.Scene = Scene;
  1390. exports.ShaderMaterial = ShaderMaterial;
  1391. exports.ShadowMaterial = ShadowMaterial;
  1392. exports.Shape = Shape;
  1393. exports.ShapeBufferGeometry = ShapeBufferGeometry;
  1394. exports.ShapeGeometry = ShapeGeometry;
  1395. exports.ShapePath = ShapePath;
  1396. exports.Skeleton = Skeleton;
  1397. exports.SkeletonHelper = SkeletonHelper;
  1398. exports.SkinnedMesh = SkinnedMesh;
  1399. exports.Sphere = Sphere;
  1400. exports.SphereBufferGeometry = SphereBufferGeometry;
  1401. exports.SphereGeometry = SphereGeometry;
  1402. exports.Spherical = Spherical;
  1403. exports.SphericalHarmonics3 = SphericalHarmonics3;
  1404. exports.Spline = Spline;
  1405. exports.SplineCurve = SplineCurve;
  1406. exports.SplineCurve3 = SplineCurve3;
  1407. exports.SpotLight = SpotLight;
  1408. exports.SpotLightHelper = SpotLightHelper;
  1409. exports.SpotLightShadow = SpotLightShadow;
  1410. exports.Sprite = Sprite;
  1411. exports.SpriteMaterial = SpriteMaterial;
  1412. exports.StereoCamera = StereoCamera;
  1413. exports.StringKeyframeTrack = StringKeyframeTrack;
  1414. exports.TetrahedronBufferGeometry = TetrahedronBufferGeometry;
  1415. exports.TetrahedronGeometry = TetrahedronGeometry;
  1416. exports.TextBufferGeometry = TextBufferGeometry;
  1417. exports.TextGeometry = TextGeometry;
  1418. exports.Texture = Texture;
  1419. exports.TextureLoader = TextureLoader;
  1420. exports.TorusBufferGeometry = TorusBufferGeometry;
  1421. exports.TorusGeometry = TorusGeometry;
  1422. exports.TorusKnotBufferGeometry = TorusKnotBufferGeometry;
  1423. exports.TorusKnotGeometry = TorusKnotGeometry;
  1424. exports.Triangle = Triangle;
  1425. exports.TubeBufferGeometry = TubeBufferGeometry;
  1426. exports.TubeGeometry = TubeGeometry;
  1427. exports.Uint16Attribute = Uint16Attribute;
  1428. exports.Uint16BufferAttribute = Uint16BufferAttribute;
  1429. exports.Uint32Attribute = Uint32Attribute;
  1430. exports.Uint32BufferAttribute = Uint32BufferAttribute;
  1431. exports.Uint8Attribute = Uint8Attribute;
  1432. exports.Uint8BufferAttribute = Uint8BufferAttribute;
  1433. exports.Uint8ClampedAttribute = Uint8ClampedAttribute;
  1434. exports.Uint8ClampedBufferAttribute = Uint8ClampedBufferAttribute;
  1435. exports.Uniform = Uniform;
  1436. exports.Vector2 = Vector2;
  1437. exports.Vector3 = Vector3;
  1438. exports.Vector4 = Vector4;
  1439. exports.VectorKeyframeTrack = VectorKeyframeTrack;
  1440. exports.Vertex = Vertex;
  1441. exports.VertexNormalsHelper = VertexNormalsHelper;
  1442. exports.VideoTexture = VideoTexture;
  1443. exports.WebGLMultisampleRenderTarget = WebGLMultisampleRenderTarget;
  1444. exports.WebGLRenderTarget = WebGLRenderTarget;
  1445. exports.WebGLRenderTargetCube = WebGLRenderTargetCube;
  1446. exports.WebGLRenderer = WebGLRenderer;
  1447. exports.WebGLUtils = WebGLUtils;
  1448. exports.WireframeGeometry = WireframeGeometry;
  1449. exports.WireframeHelper = WireframeHelper;
  1450. exports.XHRLoader = XHRLoader;
  1451. 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;
  1452. 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;
  1453. // Polyfills
  1454. if (Number.EPSILON === undefined) {
  1455. Number.EPSILON = Math.pow(2, -52);
  1456. }
  1457. if (Number.isInteger === undefined) {
  1458. // Missing in IE
  1459. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isInteger
  1460. Number.isInteger = function (value) {
  1461. return typeof value === 'number' && isFinite(value) && Math.floor(value) === value;
  1462. };
  1463. } //
  1464. if (Math.sign === undefined) {
  1465. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sign
  1466. Math.sign = function (x) {
  1467. return x < 0 ? -1 : x > 0 ? 1 : +x;
  1468. };
  1469. }
  1470. if ('name' in Function.prototype === false) {
  1471. // Missing in IE
  1472. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name
  1473. Object.defineProperty(Function.prototype, 'name', {
  1474. get: function () {
  1475. return this.toString().match(/^\s*function\s*([^\(\s]*)/)[1];
  1476. }
  1477. });
  1478. }
  1479. if (Object.assign === undefined) {
  1480. // Missing in IE
  1481. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign
  1482. Object.assign = function (target) {
  1483. if (target === undefined || target === null) {
  1484. throw new TypeError('Cannot convert undefined or null to object');
  1485. }
  1486. var output = Object(target);
  1487. for (var index = 1; index < arguments.length; index++) {
  1488. var source = arguments[index];
  1489. if (source !== undefined && source !== null) {
  1490. for (var nextKey in source) {
  1491. if (Object.prototype.hasOwnProperty.call(source, nextKey)) {
  1492. output[nextKey] = source[nextKey];
  1493. }
  1494. }
  1495. }
  1496. }
  1497. return output;
  1498. };
  1499. }
  1500. var REVISION = '109';
  1501. exports.REVISION = REVISION;
  1502. var MOUSE = {
  1503. LEFT: 0,
  1504. MIDDLE: 1,
  1505. RIGHT: 2,
  1506. ROTATE: 0,
  1507. DOLLY: 1,
  1508. PAN: 2
  1509. };
  1510. exports.MOUSE = MOUSE;
  1511. var TOUCH = {
  1512. ROTATE: 0,
  1513. PAN: 1,
  1514. DOLLY_PAN: 2,
  1515. DOLLY_ROTATE: 3
  1516. };
  1517. exports.TOUCH = TOUCH;
  1518. var CullFaceNone = 0;
  1519. exports.CullFaceNone = CullFaceNone;
  1520. var CullFaceBack = 1;
  1521. exports.CullFaceBack = CullFaceBack;
  1522. var CullFaceFront = 2;
  1523. exports.CullFaceFront = CullFaceFront;
  1524. var CullFaceFrontBack = 3;
  1525. exports.CullFaceFrontBack = CullFaceFrontBack;
  1526. var FrontFaceDirectionCW = 0;
  1527. exports.FrontFaceDirectionCW = FrontFaceDirectionCW;
  1528. var FrontFaceDirectionCCW = 1;
  1529. exports.FrontFaceDirectionCCW = FrontFaceDirectionCCW;
  1530. var BasicShadowMap = 0;
  1531. exports.BasicShadowMap = BasicShadowMap;
  1532. var PCFShadowMap = 1;
  1533. exports.PCFShadowMap = PCFShadowMap;
  1534. var PCFSoftShadowMap = 2;
  1535. exports.PCFSoftShadowMap = PCFSoftShadowMap;
  1536. var VSMShadowMap = 3;
  1537. exports.VSMShadowMap = VSMShadowMap;
  1538. var FrontSide = 0;
  1539. exports.FrontSide = FrontSide;
  1540. var BackSide = 1;
  1541. exports.BackSide = BackSide;
  1542. var DoubleSide = 2;
  1543. exports.DoubleSide = DoubleSide;
  1544. var FlatShading = 1;
  1545. exports.FlatShading = FlatShading;
  1546. var SmoothShading = 2;
  1547. exports.SmoothShading = SmoothShading;
  1548. var NoColors = 0;
  1549. exports.NoColors = NoColors;
  1550. var FaceColors = 1;
  1551. exports.FaceColors = FaceColors;
  1552. var VertexColors = 2;
  1553. exports.VertexColors = VertexColors;
  1554. var NoBlending = 0;
  1555. exports.NoBlending = NoBlending;
  1556. var NormalBlending = 1;
  1557. exports.NormalBlending = NormalBlending;
  1558. var AdditiveBlending = 2;
  1559. exports.AdditiveBlending = AdditiveBlending;
  1560. var SubtractiveBlending = 3;
  1561. exports.SubtractiveBlending = SubtractiveBlending;
  1562. var MultiplyBlending = 4;
  1563. exports.MultiplyBlending = MultiplyBlending;
  1564. var CustomBlending = 5;
  1565. exports.CustomBlending = CustomBlending;
  1566. var AddEquation = 100;
  1567. exports.AddEquation = AddEquation;
  1568. var SubtractEquation = 101;
  1569. exports.SubtractEquation = SubtractEquation;
  1570. var ReverseSubtractEquation = 102;
  1571. exports.ReverseSubtractEquation = ReverseSubtractEquation;
  1572. var MinEquation = 103;
  1573. exports.MinEquation = MinEquation;
  1574. var MaxEquation = 104;
  1575. exports.MaxEquation = MaxEquation;
  1576. var ZeroFactor = 200;
  1577. exports.ZeroFactor = ZeroFactor;
  1578. var OneFactor = 201;
  1579. exports.OneFactor = OneFactor;
  1580. var SrcColorFactor = 202;
  1581. exports.SrcColorFactor = SrcColorFactor;
  1582. var OneMinusSrcColorFactor = 203;
  1583. exports.OneMinusSrcColorFactor = OneMinusSrcColorFactor;
  1584. var SrcAlphaFactor = 204;
  1585. exports.SrcAlphaFactor = SrcAlphaFactor;
  1586. var OneMinusSrcAlphaFactor = 205;
  1587. exports.OneMinusSrcAlphaFactor = OneMinusSrcAlphaFactor;
  1588. var DstAlphaFactor = 206;
  1589. exports.DstAlphaFactor = DstAlphaFactor;
  1590. var OneMinusDstAlphaFactor = 207;
  1591. exports.OneMinusDstAlphaFactor = OneMinusDstAlphaFactor;
  1592. var DstColorFactor = 208;
  1593. exports.DstColorFactor = DstColorFactor;
  1594. var OneMinusDstColorFactor = 209;
  1595. exports.OneMinusDstColorFactor = OneMinusDstColorFactor;
  1596. var SrcAlphaSaturateFactor = 210;
  1597. exports.SrcAlphaSaturateFactor = SrcAlphaSaturateFactor;
  1598. var NeverDepth = 0;
  1599. exports.NeverDepth = NeverDepth;
  1600. var AlwaysDepth = 1;
  1601. exports.AlwaysDepth = AlwaysDepth;
  1602. var LessDepth = 2;
  1603. exports.LessDepth = LessDepth;
  1604. var LessEqualDepth = 3;
  1605. exports.LessEqualDepth = LessEqualDepth;
  1606. var EqualDepth = 4;
  1607. exports.EqualDepth = EqualDepth;
  1608. var GreaterEqualDepth = 5;
  1609. exports.GreaterEqualDepth = GreaterEqualDepth;
  1610. var GreaterDepth = 6;
  1611. exports.GreaterDepth = GreaterDepth;
  1612. var NotEqualDepth = 7;
  1613. exports.NotEqualDepth = NotEqualDepth;
  1614. var MultiplyOperation = 0;
  1615. exports.MultiplyOperation = MultiplyOperation;
  1616. var MixOperation = 1;
  1617. exports.MixOperation = MixOperation;
  1618. var AddOperation = 2;
  1619. exports.AddOperation = AddOperation;
  1620. var NoToneMapping = 0;
  1621. exports.NoToneMapping = NoToneMapping;
  1622. var LinearToneMapping = 1;
  1623. exports.LinearToneMapping = LinearToneMapping;
  1624. var ReinhardToneMapping = 2;
  1625. exports.ReinhardToneMapping = ReinhardToneMapping;
  1626. var Uncharted2ToneMapping = 3;
  1627. exports.Uncharted2ToneMapping = Uncharted2ToneMapping;
  1628. var CineonToneMapping = 4;
  1629. exports.CineonToneMapping = CineonToneMapping;
  1630. var ACESFilmicToneMapping = 5;
  1631. exports.ACESFilmicToneMapping = ACESFilmicToneMapping;
  1632. var UVMapping = 300;
  1633. exports.UVMapping = UVMapping;
  1634. var CubeReflectionMapping = 301;
  1635. exports.CubeReflectionMapping = CubeReflectionMapping;
  1636. var CubeRefractionMapping = 302;
  1637. exports.CubeRefractionMapping = CubeRefractionMapping;
  1638. var EquirectangularReflectionMapping = 303;
  1639. exports.EquirectangularReflectionMapping = EquirectangularReflectionMapping;
  1640. var EquirectangularRefractionMapping = 304;
  1641. exports.EquirectangularRefractionMapping = EquirectangularRefractionMapping;
  1642. var SphericalReflectionMapping = 305;
  1643. exports.SphericalReflectionMapping = SphericalReflectionMapping;
  1644. var CubeUVReflectionMapping = 306;
  1645. exports.CubeUVReflectionMapping = CubeUVReflectionMapping;
  1646. var CubeUVRefractionMapping = 307;
  1647. exports.CubeUVRefractionMapping = CubeUVRefractionMapping;
  1648. var RepeatWrapping = 1000;
  1649. exports.RepeatWrapping = RepeatWrapping;
  1650. var ClampToEdgeWrapping = 1001;
  1651. exports.ClampToEdgeWrapping = ClampToEdgeWrapping;
  1652. var MirroredRepeatWrapping = 1002;
  1653. exports.MirroredRepeatWrapping = MirroredRepeatWrapping;
  1654. var NearestFilter = 1003;
  1655. exports.NearestFilter = NearestFilter;
  1656. var NearestMipmapNearestFilter = 1004;
  1657. exports.NearestMipmapNearestFilter = NearestMipmapNearestFilter;
  1658. var NearestMipMapNearestFilter = 1004;
  1659. exports.NearestMipMapNearestFilter = NearestMipMapNearestFilter;
  1660. var NearestMipmapLinearFilter = 1005;
  1661. exports.NearestMipmapLinearFilter = NearestMipmapLinearFilter;
  1662. var NearestMipMapLinearFilter = 1005;
  1663. exports.NearestMipMapLinearFilter = NearestMipMapLinearFilter;
  1664. var LinearFilter = 1006;
  1665. exports.LinearFilter = LinearFilter;
  1666. var LinearMipmapNearestFilter = 1007;
  1667. exports.LinearMipmapNearestFilter = LinearMipmapNearestFilter;
  1668. var LinearMipMapNearestFilter = 1007;
  1669. exports.LinearMipMapNearestFilter = LinearMipMapNearestFilter;
  1670. var LinearMipmapLinearFilter = 1008;
  1671. exports.LinearMipmapLinearFilter = LinearMipmapLinearFilter;
  1672. var LinearMipMapLinearFilter = 1008;
  1673. exports.LinearMipMapLinearFilter = LinearMipMapLinearFilter;
  1674. var UnsignedByteType = 1009;
  1675. exports.UnsignedByteType = UnsignedByteType;
  1676. var ByteType = 1010;
  1677. exports.ByteType = ByteType;
  1678. var ShortType = 1011;
  1679. exports.ShortType = ShortType;
  1680. var UnsignedShortType = 1012;
  1681. exports.UnsignedShortType = UnsignedShortType;
  1682. var IntType = 1013;
  1683. exports.IntType = IntType;
  1684. var UnsignedIntType = 1014;
  1685. exports.UnsignedIntType = UnsignedIntType;
  1686. var FloatType = 1015;
  1687. exports.FloatType = FloatType;
  1688. var HalfFloatType = 1016;
  1689. exports.HalfFloatType = HalfFloatType;
  1690. var UnsignedShort4444Type = 1017;
  1691. exports.UnsignedShort4444Type = UnsignedShort4444Type;
  1692. var UnsignedShort5551Type = 1018;
  1693. exports.UnsignedShort5551Type = UnsignedShort5551Type;
  1694. var UnsignedShort565Type = 1019;
  1695. exports.UnsignedShort565Type = UnsignedShort565Type;
  1696. var UnsignedInt248Type = 1020;
  1697. exports.UnsignedInt248Type = UnsignedInt248Type;
  1698. var AlphaFormat = 1021;
  1699. exports.AlphaFormat = AlphaFormat;
  1700. var RGBFormat = 1022;
  1701. exports.RGBFormat = RGBFormat;
  1702. var RGBAFormat = 1023;
  1703. exports.RGBAFormat = RGBAFormat;
  1704. var LuminanceFormat = 1024;
  1705. exports.LuminanceFormat = LuminanceFormat;
  1706. var LuminanceAlphaFormat = 1025;
  1707. exports.LuminanceAlphaFormat = LuminanceAlphaFormat;
  1708. var RGBEFormat = RGBAFormat;
  1709. exports.RGBEFormat = RGBEFormat;
  1710. var DepthFormat = 1026;
  1711. exports.DepthFormat = DepthFormat;
  1712. var DepthStencilFormat = 1027;
  1713. exports.DepthStencilFormat = DepthStencilFormat;
  1714. var RedFormat = 1028;
  1715. exports.RedFormat = RedFormat;
  1716. var RGB_S3TC_DXT1_Format = 33776;
  1717. exports.RGB_S3TC_DXT1_Format = RGB_S3TC_DXT1_Format;
  1718. var RGBA_S3TC_DXT1_Format = 33777;
  1719. exports.RGBA_S3TC_DXT1_Format = RGBA_S3TC_DXT1_Format;
  1720. var RGBA_S3TC_DXT3_Format = 33778;
  1721. exports.RGBA_S3TC_DXT3_Format = RGBA_S3TC_DXT3_Format;
  1722. var RGBA_S3TC_DXT5_Format = 33779;
  1723. exports.RGBA_S3TC_DXT5_Format = RGBA_S3TC_DXT5_Format;
  1724. var RGB_PVRTC_4BPPV1_Format = 35840;
  1725. exports.RGB_PVRTC_4BPPV1_Format = RGB_PVRTC_4BPPV1_Format;
  1726. var RGB_PVRTC_2BPPV1_Format = 35841;
  1727. exports.RGB_PVRTC_2BPPV1_Format = RGB_PVRTC_2BPPV1_Format;
  1728. var RGBA_PVRTC_4BPPV1_Format = 35842;
  1729. exports.RGBA_PVRTC_4BPPV1_Format = RGBA_PVRTC_4BPPV1_Format;
  1730. var RGBA_PVRTC_2BPPV1_Format = 35843;
  1731. exports.RGBA_PVRTC_2BPPV1_Format = RGBA_PVRTC_2BPPV1_Format;
  1732. var RGB_ETC1_Format = 36196;
  1733. exports.RGB_ETC1_Format = RGB_ETC1_Format;
  1734. var RGBA_ASTC_4x4_Format = 37808;
  1735. exports.RGBA_ASTC_4x4_Format = RGBA_ASTC_4x4_Format;
  1736. var RGBA_ASTC_5x4_Format = 37809;
  1737. exports.RGBA_ASTC_5x4_Format = RGBA_ASTC_5x4_Format;
  1738. var RGBA_ASTC_5x5_Format = 37810;
  1739. exports.RGBA_ASTC_5x5_Format = RGBA_ASTC_5x5_Format;
  1740. var RGBA_ASTC_6x5_Format = 37811;
  1741. exports.RGBA_ASTC_6x5_Format = RGBA_ASTC_6x5_Format;
  1742. var RGBA_ASTC_6x6_Format = 37812;
  1743. exports.RGBA_ASTC_6x6_Format = RGBA_ASTC_6x6_Format;
  1744. var RGBA_ASTC_8x5_Format = 37813;
  1745. exports.RGBA_ASTC_8x5_Format = RGBA_ASTC_8x5_Format;
  1746. var RGBA_ASTC_8x6_Format = 37814;
  1747. exports.RGBA_ASTC_8x6_Format = RGBA_ASTC_8x6_Format;
  1748. var RGBA_ASTC_8x8_Format = 37815;
  1749. exports.RGBA_ASTC_8x8_Format = RGBA_ASTC_8x8_Format;
  1750. var RGBA_ASTC_10x5_Format = 37816;
  1751. exports.RGBA_ASTC_10x5_Format = RGBA_ASTC_10x5_Format;
  1752. var RGBA_ASTC_10x6_Format = 37817;
  1753. exports.RGBA_ASTC_10x6_Format = RGBA_ASTC_10x6_Format;
  1754. var RGBA_ASTC_10x8_Format = 37818;
  1755. exports.RGBA_ASTC_10x8_Format = RGBA_ASTC_10x8_Format;
  1756. var RGBA_ASTC_10x10_Format = 37819;
  1757. exports.RGBA_ASTC_10x10_Format = RGBA_ASTC_10x10_Format;
  1758. var RGBA_ASTC_12x10_Format = 37820;
  1759. exports.RGBA_ASTC_12x10_Format = RGBA_ASTC_12x10_Format;
  1760. var RGBA_ASTC_12x12_Format = 37821;
  1761. exports.RGBA_ASTC_12x12_Format = RGBA_ASTC_12x12_Format;
  1762. var LoopOnce = 2200;
  1763. exports.LoopOnce = LoopOnce;
  1764. var LoopRepeat = 2201;
  1765. exports.LoopRepeat = LoopRepeat;
  1766. var LoopPingPong = 2202;
  1767. exports.LoopPingPong = LoopPingPong;
  1768. var InterpolateDiscrete = 2300;
  1769. exports.InterpolateDiscrete = InterpolateDiscrete;
  1770. var InterpolateLinear = 2301;
  1771. exports.InterpolateLinear = InterpolateLinear;
  1772. var InterpolateSmooth = 2302;
  1773. exports.InterpolateSmooth = InterpolateSmooth;
  1774. var ZeroCurvatureEnding = 2400;
  1775. exports.ZeroCurvatureEnding = ZeroCurvatureEnding;
  1776. var ZeroSlopeEnding = 2401;
  1777. exports.ZeroSlopeEnding = ZeroSlopeEnding;
  1778. var WrapAroundEnding = 2402;
  1779. exports.WrapAroundEnding = WrapAroundEnding;
  1780. var TrianglesDrawMode = 0;
  1781. exports.TrianglesDrawMode = TrianglesDrawMode;
  1782. var TriangleStripDrawMode = 1;
  1783. exports.TriangleStripDrawMode = TriangleStripDrawMode;
  1784. var TriangleFanDrawMode = 2;
  1785. exports.TriangleFanDrawMode = TriangleFanDrawMode;
  1786. var LinearEncoding = 3000;
  1787. exports.LinearEncoding = LinearEncoding;
  1788. var sRGBEncoding = 3001;
  1789. exports.sRGBEncoding = sRGBEncoding;
  1790. var GammaEncoding = 3007;
  1791. exports.GammaEncoding = GammaEncoding;
  1792. var RGBEEncoding = 3002;
  1793. exports.RGBEEncoding = RGBEEncoding;
  1794. var LogLuvEncoding = 3003;
  1795. exports.LogLuvEncoding = LogLuvEncoding;
  1796. var RGBM7Encoding = 3004;
  1797. exports.RGBM7Encoding = RGBM7Encoding;
  1798. var RGBM16Encoding = 3005;
  1799. exports.RGBM16Encoding = RGBM16Encoding;
  1800. var RGBDEncoding = 3006;
  1801. exports.RGBDEncoding = RGBDEncoding;
  1802. var BasicDepthPacking = 3200;
  1803. exports.BasicDepthPacking = BasicDepthPacking;
  1804. var RGBADepthPacking = 3201;
  1805. exports.RGBADepthPacking = RGBADepthPacking;
  1806. var TangentSpaceNormalMap = 0;
  1807. exports.TangentSpaceNormalMap = TangentSpaceNormalMap;
  1808. var ObjectSpaceNormalMap = 1;
  1809. exports.ObjectSpaceNormalMap = ObjectSpaceNormalMap;
  1810. var ZeroStencilOp = 0;
  1811. exports.ZeroStencilOp = ZeroStencilOp;
  1812. var KeepStencilOp = 7680;
  1813. exports.KeepStencilOp = KeepStencilOp;
  1814. var ReplaceStencilOp = 7681;
  1815. exports.ReplaceStencilOp = ReplaceStencilOp;
  1816. var IncrementStencilOp = 7682;
  1817. exports.IncrementStencilOp = IncrementStencilOp;
  1818. var DecrementStencilOp = 7683;
  1819. exports.DecrementStencilOp = DecrementStencilOp;
  1820. var IncrementWrapStencilOp = 34055;
  1821. exports.IncrementWrapStencilOp = IncrementWrapStencilOp;
  1822. var DecrementWrapStencilOp = 34056;
  1823. exports.DecrementWrapStencilOp = DecrementWrapStencilOp;
  1824. var InvertStencilOp = 5386;
  1825. exports.InvertStencilOp = InvertStencilOp;
  1826. var NeverStencilFunc = 512;
  1827. exports.NeverStencilFunc = NeverStencilFunc;
  1828. var LessStencilFunc = 513;
  1829. exports.LessStencilFunc = LessStencilFunc;
  1830. var EqualStencilFunc = 514;
  1831. exports.EqualStencilFunc = EqualStencilFunc;
  1832. var LessEqualStencilFunc = 515;
  1833. exports.LessEqualStencilFunc = LessEqualStencilFunc;
  1834. var GreaterStencilFunc = 516;
  1835. exports.GreaterStencilFunc = GreaterStencilFunc;
  1836. var NotEqualStencilFunc = 517;
  1837. exports.NotEqualStencilFunc = NotEqualStencilFunc;
  1838. var GreaterEqualStencilFunc = 518;
  1839. exports.GreaterEqualStencilFunc = GreaterEqualStencilFunc;
  1840. var AlwaysStencilFunc = 519;
  1841. /**
  1842. * https://github.com/mrdoob/eventdispatcher.js/
  1843. */
  1844. exports.AlwaysStencilFunc = AlwaysStencilFunc;
  1845. function EventDispatcher() {}
  1846. Object.assign(EventDispatcher.prototype, {
  1847. addEventListener: function (type, listener) {
  1848. if (this._listeners === undefined) this._listeners = {};
  1849. var listeners = this._listeners;
  1850. if (listeners[type] === undefined) {
  1851. listeners[type] = [];
  1852. }
  1853. if (listeners[type].indexOf(listener) === -1) {
  1854. listeners[type].push(listener);
  1855. }
  1856. },
  1857. hasEventListener: function (type, listener) {
  1858. if (this._listeners === undefined) return false;
  1859. var listeners = this._listeners;
  1860. return listeners[type] !== undefined && listeners[type].indexOf(listener) !== -1;
  1861. },
  1862. removeEventListener: function (type, listener) {
  1863. if (this._listeners === undefined) return;
  1864. var listeners = this._listeners;
  1865. var listenerArray = listeners[type];
  1866. if (listenerArray !== undefined) {
  1867. var index = listenerArray.indexOf(listener);
  1868. if (index !== -1) {
  1869. listenerArray.splice(index, 1);
  1870. }
  1871. }
  1872. },
  1873. dispatchEvent: function (event) {
  1874. if (this._listeners === undefined) return;
  1875. var listeners = this._listeners;
  1876. var listenerArray = listeners[event.type];
  1877. if (listenerArray !== undefined) {
  1878. event.target = this;
  1879. var array = listenerArray.slice(0);
  1880. for (var i = 0, l = array.length; i < l; i++) {
  1881. array[i].call(this, event);
  1882. }
  1883. }
  1884. }
  1885. });
  1886. /**
  1887. * @author alteredq / http://alteredqualia.com/
  1888. * @author mrdoob / http://mrdoob.com/
  1889. */
  1890. var _lut = [];
  1891. for (var i = 0; i < 256; i++) {
  1892. _lut[i] = (i < 16 ? '0' : '') + i.toString(16);
  1893. }
  1894. var _Math = {
  1895. DEG2RAD: Math.PI / 180,
  1896. RAD2DEG: 180 / Math.PI,
  1897. generateUUID: function () {
  1898. // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/21963136#21963136
  1899. var d0 = Math.random() * 0xffffffff | 0;
  1900. var d1 = Math.random() * 0xffffffff | 0;
  1901. var d2 = Math.random() * 0xffffffff | 0;
  1902. var d3 = Math.random() * 0xffffffff | 0;
  1903. 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.
  1904. return uuid.toUpperCase();
  1905. },
  1906. clamp: function (value, min, max) {
  1907. return Math.max(min, Math.min(max, value));
  1908. },
  1909. // compute euclidian modulo of m % n
  1910. // https://en.wikipedia.org/wiki/Modulo_operation
  1911. euclideanModulo: function (n, m) {
  1912. return (n % m + m) % m;
  1913. },
  1914. // Linear mapping from range <a1, a2> to range <b1, b2>
  1915. mapLinear: function (x, a1, a2, b1, b2) {
  1916. return b1 + (x - a1) * (b2 - b1) / (a2 - a1);
  1917. },
  1918. // https://en.wikipedia.org/wiki/Linear_interpolation
  1919. lerp: function (x, y, t) {
  1920. return (1 - t) * x + t * y;
  1921. },
  1922. // http://en.wikipedia.org/wiki/Smoothstep
  1923. smoothstep: function (x, min, max) {
  1924. if (x <= min) return 0;
  1925. if (x >= max) return 1;
  1926. x = (x - min) / (max - min);
  1927. return x * x * (3 - 2 * x);
  1928. },
  1929. smootherstep: function (x, min, max) {
  1930. if (x <= min) return 0;
  1931. if (x >= max) return 1;
  1932. x = (x - min) / (max - min);
  1933. return x * x * x * (x * (x * 6 - 15) + 10);
  1934. },
  1935. // Random integer from <low, high> interval
  1936. randInt: function (low, high) {
  1937. return low + Math.floor(Math.random() * (high - low + 1));
  1938. },
  1939. // Random float from <low, high> interval
  1940. randFloat: function (low, high) {
  1941. return low + Math.random() * (high - low);
  1942. },
  1943. // Random float from <-range/2, range/2> interval
  1944. randFloatSpread: function (range) {
  1945. return range * (0.5 - Math.random());
  1946. },
  1947. degToRad: function (degrees) {
  1948. return degrees * _Math.DEG2RAD;
  1949. },
  1950. radToDeg: function (radians) {
  1951. return radians * _Math.RAD2DEG;
  1952. },
  1953. isPowerOfTwo: function (value) {
  1954. return (value & value - 1) === 0 && value !== 0;
  1955. },
  1956. ceilPowerOfTwo: function (value) {
  1957. return Math.pow(2, Math.ceil(Math.log(value) / Math.LN2));
  1958. },
  1959. floorPowerOfTwo: function (value) {
  1960. return Math.pow(2, Math.floor(Math.log(value) / Math.LN2));
  1961. }
  1962. };
  1963. /**
  1964. * @author mrdoob / http://mrdoob.com/
  1965. * @author philogb / http://blog.thejit.org/
  1966. * @author egraether / http://egraether.com/
  1967. * @author zz85 / http://www.lab4games.net/zz85/blog
  1968. */
  1969. exports.Math = _Math;
  1970. function Vector2(x, y) {
  1971. this.x = x || 0;
  1972. this.y = y || 0;
  1973. }
  1974. Object.defineProperties(Vector2.prototype, {
  1975. "width": {
  1976. get: function () {
  1977. return this.x;
  1978. },
  1979. set: function (value) {
  1980. this.x = value;
  1981. }
  1982. },
  1983. "height": {
  1984. get: function () {
  1985. return this.y;
  1986. },
  1987. set: function (value) {
  1988. this.y = value;
  1989. }
  1990. }
  1991. });
  1992. Object.assign(Vector2.prototype, {
  1993. isVector2: true,
  1994. set: function (x, y) {
  1995. this.x = x;
  1996. this.y = y;
  1997. return this;
  1998. },
  1999. setScalar: function (scalar) {
  2000. this.x = scalar;
  2001. this.y = scalar;
  2002. return this;
  2003. },
  2004. setX: function (x) {
  2005. this.x = x;
  2006. return this;
  2007. },
  2008. setY: function (y) {
  2009. this.y = y;
  2010. return this;
  2011. },
  2012. setComponent: function (index, value) {
  2013. switch (index) {
  2014. case 0:
  2015. this.x = value;
  2016. break;
  2017. case 1:
  2018. this.y = value;
  2019. break;
  2020. default:
  2021. throw new Error('index is out of range: ' + index);
  2022. }
  2023. return this;
  2024. },
  2025. getComponent: function (index) {
  2026. switch (index) {
  2027. case 0:
  2028. return this.x;
  2029. case 1:
  2030. return this.y;
  2031. default:
  2032. throw new Error('index is out of range: ' + index);
  2033. }
  2034. },
  2035. clone: function () {
  2036. return new this.constructor(this.x, this.y);
  2037. },
  2038. copy: function (v) {
  2039. this.x = v.x;
  2040. this.y = v.y;
  2041. return this;
  2042. },
  2043. add: function (v, w) {
  2044. if (w !== undefined) {
  2045. console.warn('THREE.Vector2: .add() now only accepts one argument. Use .addVectors( a, b ) instead.');
  2046. return this.addVectors(v, w);
  2047. }
  2048. this.x += v.x;
  2049. this.y += v.y;
  2050. return this;
  2051. },
  2052. addScalar: function (s) {
  2053. this.x += s;
  2054. this.y += s;
  2055. return this;
  2056. },
  2057. addVectors: function (a, b) {
  2058. this.x = a.x + b.x;
  2059. this.y = a.y + b.y;
  2060. return this;
  2061. },
  2062. addScaledVector: function (v, s) {
  2063. this.x += v.x * s;
  2064. this.y += v.y * s;
  2065. return this;
  2066. },
  2067. sub: function (v, w) {
  2068. if (w !== undefined) {
  2069. console.warn('THREE.Vector2: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.');
  2070. return this.subVectors(v, w);
  2071. }
  2072. this.x -= v.x;
  2073. this.y -= v.y;
  2074. return this;
  2075. },
  2076. subScalar: function (s) {
  2077. this.x -= s;
  2078. this.y -= s;
  2079. return this;
  2080. },
  2081. subVectors: function (a, b) {
  2082. this.x = a.x - b.x;
  2083. this.y = a.y - b.y;
  2084. return this;
  2085. },
  2086. multiply: function (v) {
  2087. this.x *= v.x;
  2088. this.y *= v.y;
  2089. return this;
  2090. },
  2091. multiplyScalar: function (scalar) {
  2092. this.x *= scalar;
  2093. this.y *= scalar;
  2094. return this;
  2095. },
  2096. divide: function (v) {
  2097. this.x /= v.x;
  2098. this.y /= v.y;
  2099. return this;
  2100. },
  2101. divideScalar: function (scalar) {
  2102. return this.multiplyScalar(1 / scalar);
  2103. },
  2104. applyMatrix3: function (m) {
  2105. var x = this.x,
  2106. y = this.y;
  2107. var e = m.elements;
  2108. this.x = e[0] * x + e[3] * y + e[6];
  2109. this.y = e[1] * x + e[4] * y + e[7];
  2110. return this;
  2111. },
  2112. min: function (v) {
  2113. this.x = Math.min(this.x, v.x);
  2114. this.y = Math.min(this.y, v.y);
  2115. return this;
  2116. },
  2117. max: function (v) {
  2118. this.x = Math.max(this.x, v.x);
  2119. this.y = Math.max(this.y, v.y);
  2120. return this;
  2121. },
  2122. clamp: function (min, max) {
  2123. // assumes min < max, componentwise
  2124. this.x = Math.max(min.x, Math.min(max.x, this.x));
  2125. this.y = Math.max(min.y, Math.min(max.y, this.y));
  2126. return this;
  2127. },
  2128. clampScalar: function (minVal, maxVal) {
  2129. this.x = Math.max(minVal, Math.min(maxVal, this.x));
  2130. this.y = Math.max(minVal, Math.min(maxVal, this.y));
  2131. return this;
  2132. },
  2133. clampLength: function (min, max) {
  2134. var length = this.length();
  2135. return this.divideScalar(length || 1).multiplyScalar(Math.max(min, Math.min(max, length)));
  2136. },
  2137. floor: function () {
  2138. this.x = Math.floor(this.x);
  2139. this.y = Math.floor(this.y);
  2140. return this;
  2141. },
  2142. ceil: function () {
  2143. this.x = Math.ceil(this.x);
  2144. this.y = Math.ceil(this.y);
  2145. return this;
  2146. },
  2147. round: function () {
  2148. this.x = Math.round(this.x);
  2149. this.y = Math.round(this.y);
  2150. return this;
  2151. },
  2152. roundToZero: function () {
  2153. this.x = this.x < 0 ? Math.ceil(this.x) : Math.floor(this.x);
  2154. this.y = this.y < 0 ? Math.ceil(this.y) : Math.floor(this.y);
  2155. return this;
  2156. },
  2157. negate: function () {
  2158. this.x = -this.x;
  2159. this.y = -this.y;
  2160. return this;
  2161. },
  2162. dot: function (v) {
  2163. return this.x * v.x + this.y * v.y;
  2164. },
  2165. cross: function (v) {
  2166. return this.x * v.y - this.y * v.x;
  2167. },
  2168. lengthSq: function () {
  2169. return this.x * this.x + this.y * this.y;
  2170. },
  2171. length: function () {
  2172. return Math.sqrt(this.x * this.x + this.y * this.y);
  2173. },
  2174. manhattanLength: function () {
  2175. return Math.abs(this.x) + Math.abs(this.y);
  2176. },
  2177. normalize: function () {
  2178. return this.divideScalar(this.length() || 1);
  2179. },
  2180. angle: function () {
  2181. // computes the angle in radians with respect to the positive x-axis
  2182. var angle = Math.atan2(this.y, this.x);
  2183. if (angle < 0) angle += 2 * Math.PI;
  2184. return angle;
  2185. },
  2186. distanceTo: function (v) {
  2187. return Math.sqrt(this.distanceToSquared(v));
  2188. },
  2189. distanceToSquared: function (v) {
  2190. var dx = this.x - v.x,
  2191. dy = this.y - v.y;
  2192. return dx * dx + dy * dy;
  2193. },
  2194. manhattanDistanceTo: function (v) {
  2195. return Math.abs(this.x - v.x) + Math.abs(this.y - v.y);
  2196. },
  2197. setLength: function (length) {
  2198. return this.normalize().multiplyScalar(length);
  2199. },
  2200. lerp: function (v, alpha) {
  2201. this.x += (v.x - this.x) * alpha;
  2202. this.y += (v.y - this.y) * alpha;
  2203. return this;
  2204. },
  2205. lerpVectors: function (v1, v2, alpha) {
  2206. return this.subVectors(v2, v1).multiplyScalar(alpha).add(v1);
  2207. },
  2208. equals: function (v) {
  2209. return v.x === this.x && v.y === this.y;
  2210. },
  2211. fromArray: function (array, offset) {
  2212. if (offset === undefined) offset = 0;
  2213. this.x = array[offset];
  2214. this.y = array[offset + 1];
  2215. return this;
  2216. },
  2217. toArray: function (array, offset) {
  2218. if (array === undefined) array = [];
  2219. if (offset === undefined) offset = 0;
  2220. array[offset] = this.x;
  2221. array[offset + 1] = this.y;
  2222. return array;
  2223. },
  2224. fromBufferAttribute: function (attribute, index, offset) {
  2225. if (offset !== undefined) {
  2226. console.warn('THREE.Vector2: offset has been removed from .fromBufferAttribute().');
  2227. }
  2228. this.x = attribute.getX(index);
  2229. this.y = attribute.getY(index);
  2230. return this;
  2231. },
  2232. rotateAround: function (center, angle) {
  2233. var c = Math.cos(angle),
  2234. s = Math.sin(angle);
  2235. var x = this.x - center.x;
  2236. var y = this.y - center.y;
  2237. this.x = x * c - y * s + center.x;
  2238. this.y = x * s + y * c + center.y;
  2239. return this;
  2240. }
  2241. });
  2242. /**
  2243. * @author mikael emtinger / http://gomo.se/
  2244. * @author alteredq / http://alteredqualia.com/
  2245. * @author WestLangley / http://github.com/WestLangley
  2246. * @author bhouston / http://clara.io
  2247. */
  2248. function Quaternion(x, y, z, w) {
  2249. this._x = x || 0;
  2250. this._y = y || 0;
  2251. this._z = z || 0;
  2252. this._w = w !== undefined ? w : 1;
  2253. }
  2254. Object.assign(Quaternion, {
  2255. slerp: function (qa, qb, qm, t) {
  2256. return qm.copy(qa).slerp(qb, t);
  2257. },
  2258. slerpFlat: function (dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t) {
  2259. // fuzz-free, array-based Quaternion SLERP operation
  2260. var x0 = src0[srcOffset0 + 0],
  2261. y0 = src0[srcOffset0 + 1],
  2262. z0 = src0[srcOffset0 + 2],
  2263. w0 = src0[srcOffset0 + 3],
  2264. x1 = src1[srcOffset1 + 0],
  2265. y1 = src1[srcOffset1 + 1],
  2266. z1 = src1[srcOffset1 + 2],
  2267. w1 = src1[srcOffset1 + 3];
  2268. if (w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1) {
  2269. var s = 1 - t,
  2270. cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1,
  2271. dir = cos >= 0 ? 1 : -1,
  2272. sqrSin = 1 - cos * cos; // Skip the Slerp for tiny steps to avoid numeric problems:
  2273. if (sqrSin > Number.EPSILON) {
  2274. var sin = Math.sqrt(sqrSin),
  2275. len = Math.atan2(sin, cos * dir);
  2276. s = Math.sin(s * len) / sin;
  2277. t = Math.sin(t * len) / sin;
  2278. }
  2279. var tDir = t * dir;
  2280. x0 = x0 * s + x1 * tDir;
  2281. y0 = y0 * s + y1 * tDir;
  2282. z0 = z0 * s + z1 * tDir;
  2283. w0 = w0 * s + w1 * tDir; // Normalize in case we just did a lerp:
  2284. if (s === 1 - t) {
  2285. var f = 1 / Math.sqrt(x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0);
  2286. x0 *= f;
  2287. y0 *= f;
  2288. z0 *= f;
  2289. w0 *= f;
  2290. }
  2291. }
  2292. dst[dstOffset] = x0;
  2293. dst[dstOffset + 1] = y0;
  2294. dst[dstOffset + 2] = z0;
  2295. dst[dstOffset + 3] = w0;
  2296. }
  2297. });
  2298. Object.defineProperties(Quaternion.prototype, {
  2299. x: {
  2300. get: function () {
  2301. return this._x;
  2302. },
  2303. set: function (value) {
  2304. this._x = value;
  2305. this._onChangeCallback();
  2306. }
  2307. },
  2308. y: {
  2309. get: function () {
  2310. return this._y;
  2311. },
  2312. set: function (value) {
  2313. this._y = value;
  2314. this._onChangeCallback();
  2315. }
  2316. },
  2317. z: {
  2318. get: function () {
  2319. return this._z;
  2320. },
  2321. set: function (value) {
  2322. this._z = value;
  2323. this._onChangeCallback();
  2324. }
  2325. },
  2326. w: {
  2327. get: function () {
  2328. return this._w;
  2329. },
  2330. set: function (value) {
  2331. this._w = value;
  2332. this._onChangeCallback();
  2333. }
  2334. }
  2335. });
  2336. Object.assign(Quaternion.prototype, {
  2337. isQuaternion: true,
  2338. set: function (x, y, z, w) {
  2339. this._x = x;
  2340. this._y = y;
  2341. this._z = z;
  2342. this._w = w;
  2343. this._onChangeCallback();
  2344. return this;
  2345. },
  2346. clone: function () {
  2347. return new this.constructor(this._x, this._y, this._z, this._w);
  2348. },
  2349. copy: function (quaternion) {
  2350. this._x = quaternion.x;
  2351. this._y = quaternion.y;
  2352. this._z = quaternion.z;
  2353. this._w = quaternion.w;
  2354. this._onChangeCallback();
  2355. return this;
  2356. },
  2357. setFromEuler: function (euler, update) {
  2358. if (!(euler && euler.isEuler)) {
  2359. throw new Error('THREE.Quaternion: .setFromEuler() now expects an Euler rotation rather than a Vector3 and order.');
  2360. }
  2361. var x = euler._x,
  2362. y = euler._y,
  2363. z = euler._z,
  2364. order = euler.order; // http://www.mathworks.com/matlabcentral/fileexchange/
  2365. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  2366. // content/SpinCalc.m
  2367. var cos = Math.cos;
  2368. var sin = Math.sin;
  2369. var c1 = cos(x / 2);
  2370. var c2 = cos(y / 2);
  2371. var c3 = cos(z / 2);
  2372. var s1 = sin(x / 2);
  2373. var s2 = sin(y / 2);
  2374. var s3 = sin(z / 2);
  2375. if (order === 'XYZ') {
  2376. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  2377. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  2378. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  2379. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  2380. } else if (order === 'YXZ') {
  2381. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  2382. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  2383. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  2384. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  2385. } else if (order === 'ZXY') {
  2386. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  2387. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  2388. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  2389. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  2390. } else if (order === 'ZYX') {
  2391. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  2392. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  2393. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  2394. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  2395. } else if (order === 'YZX') {
  2396. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  2397. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  2398. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  2399. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  2400. } else if (order === 'XZY') {
  2401. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  2402. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  2403. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  2404. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  2405. }
  2406. if (update !== false) this._onChangeCallback();
  2407. return this;
  2408. },
  2409. setFromAxisAngle: function (axis, angle) {
  2410. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  2411. // assumes axis is normalized
  2412. var halfAngle = angle / 2,
  2413. s = Math.sin(halfAngle);
  2414. this._x = axis.x * s;
  2415. this._y = axis.y * s;
  2416. this._z = axis.z * s;
  2417. this._w = Math.cos(halfAngle);
  2418. this._onChangeCallback();
  2419. return this;
  2420. },
  2421. setFromRotationMatrix: function (m) {
  2422. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  2423. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  2424. var te = m.elements,
  2425. m11 = te[0],
  2426. m12 = te[4],
  2427. m13 = te[8],
  2428. m21 = te[1],
  2429. m22 = te[5],
  2430. m23 = te[9],
  2431. m31 = te[2],
  2432. m32 = te[6],
  2433. m33 = te[10],
  2434. trace = m11 + m22 + m33,
  2435. s;
  2436. if (trace > 0) {
  2437. s = 0.5 / Math.sqrt(trace + 1.0);
  2438. this._w = 0.25 / s;
  2439. this._x = (m32 - m23) * s;
  2440. this._y = (m13 - m31) * s;
  2441. this._z = (m21 - m12) * s;
  2442. } else if (m11 > m22 && m11 > m33) {
  2443. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  2444. this._w = (m32 - m23) / s;
  2445. this._x = 0.25 * s;
  2446. this._y = (m12 + m21) / s;
  2447. this._z = (m13 + m31) / s;
  2448. } else if (m22 > m33) {
  2449. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  2450. this._w = (m13 - m31) / s;
  2451. this._x = (m12 + m21) / s;
  2452. this._y = 0.25 * s;
  2453. this._z = (m23 + m32) / s;
  2454. } else {
  2455. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  2456. this._w = (m21 - m12) / s;
  2457. this._x = (m13 + m31) / s;
  2458. this._y = (m23 + m32) / s;
  2459. this._z = 0.25 * s;
  2460. }
  2461. this._onChangeCallback();
  2462. return this;
  2463. },
  2464. setFromUnitVectors: function (vFrom, vTo) {
  2465. // assumes direction vectors vFrom and vTo are normalized
  2466. var EPS = 0.000001;
  2467. var r = vFrom.dot(vTo) + 1;
  2468. if (r < EPS) {
  2469. r = 0;
  2470. if (Math.abs(vFrom.x) > Math.abs(vFrom.z)) {
  2471. this._x = -vFrom.y;
  2472. this._y = vFrom.x;
  2473. this._z = 0;
  2474. this._w = r;
  2475. } else {
  2476. this._x = 0;
  2477. this._y = -vFrom.z;
  2478. this._z = vFrom.y;
  2479. this._w = r;
  2480. }
  2481. } else {
  2482. // crossVectors( vFrom, vTo ); // inlined to avoid cyclic dependency on Vector3
  2483. this._x = vFrom.y * vTo.z - vFrom.z * vTo.y;
  2484. this._y = vFrom.z * vTo.x - vFrom.x * vTo.z;
  2485. this._z = vFrom.x * vTo.y - vFrom.y * vTo.x;
  2486. this._w = r;
  2487. }
  2488. return this.normalize();
  2489. },
  2490. angleTo: function (q) {
  2491. return 2 * Math.acos(Math.abs(_Math.clamp(this.dot(q), -1, 1)));
  2492. },
  2493. rotateTowards: function (q, step) {
  2494. var angle = this.angleTo(q);
  2495. if (angle === 0) return this;
  2496. var t = Math.min(1, step / angle);
  2497. this.slerp(q, t);
  2498. return this;
  2499. },
  2500. inverse: function () {
  2501. // quaternion is assumed to have unit length
  2502. return this.conjugate();
  2503. },
  2504. conjugate: function () {
  2505. this._x *= -1;
  2506. this._y *= -1;
  2507. this._z *= -1;
  2508. this._onChangeCallback();
  2509. return this;
  2510. },
  2511. dot: function (v) {
  2512. return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w;
  2513. },
  2514. lengthSq: function () {
  2515. return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  2516. },
  2517. length: function () {
  2518. return Math.sqrt(this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w);
  2519. },
  2520. normalize: function () {
  2521. var l = this.length();
  2522. if (l === 0) {
  2523. this._x = 0;
  2524. this._y = 0;
  2525. this._z = 0;
  2526. this._w = 1;
  2527. } else {
  2528. l = 1 / l;
  2529. this._x = this._x * l;
  2530. this._y = this._y * l;
  2531. this._z = this._z * l;
  2532. this._w = this._w * l;
  2533. }
  2534. this._onChangeCallback();
  2535. return this;
  2536. },
  2537. multiply: function (q, p) {
  2538. if (p !== undefined) {
  2539. console.warn('THREE.Quaternion: .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead.');
  2540. return this.multiplyQuaternions(q, p);
  2541. }
  2542. return this.multiplyQuaternions(this, q);
  2543. },
  2544. premultiply: function (q) {
  2545. return this.multiplyQuaternions(q, this);
  2546. },
  2547. multiplyQuaternions: function (a, b) {
  2548. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  2549. var qax = a._x,
  2550. qay = a._y,
  2551. qaz = a._z,
  2552. qaw = a._w;
  2553. var qbx = b._x,
  2554. qby = b._y,
  2555. qbz = b._z,
  2556. qbw = b._w;
  2557. this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  2558. this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  2559. this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  2560. this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  2561. this._onChangeCallback();
  2562. return this;
  2563. },
  2564. slerp: function (qb, t) {
  2565. if (t === 0) return this;
  2566. if (t === 1) return this.copy(qb);
  2567. var x = this._x,
  2568. y = this._y,
  2569. z = this._z,
  2570. w = this._w; // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  2571. var cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z;
  2572. if (cosHalfTheta < 0) {
  2573. this._w = -qb._w;
  2574. this._x = -qb._x;
  2575. this._y = -qb._y;
  2576. this._z = -qb._z;
  2577. cosHalfTheta = -cosHalfTheta;
  2578. } else {
  2579. this.copy(qb);
  2580. }
  2581. if (cosHalfTheta >= 1.0) {
  2582. this._w = w;
  2583. this._x = x;
  2584. this._y = y;
  2585. this._z = z;
  2586. return this;
  2587. }
  2588. var sqrSinHalfTheta = 1.0 - cosHalfTheta * cosHalfTheta;
  2589. if (sqrSinHalfTheta <= Number.EPSILON) {
  2590. var s = 1 - t;
  2591. this._w = s * w + t * this._w;
  2592. this._x = s * x + t * this._x;
  2593. this._y = s * y + t * this._y;
  2594. this._z = s * z + t * this._z;
  2595. this.normalize();
  2596. this._onChangeCallback();
  2597. return this;
  2598. }
  2599. var sinHalfTheta = Math.sqrt(sqrSinHalfTheta);
  2600. var halfTheta = Math.atan2(sinHalfTheta, cosHalfTheta);
  2601. var ratioA = Math.sin((1 - t) * halfTheta) / sinHalfTheta,
  2602. ratioB = Math.sin(t * halfTheta) / sinHalfTheta;
  2603. this._w = w * ratioA + this._w * ratioB;
  2604. this._x = x * ratioA + this._x * ratioB;
  2605. this._y = y * ratioA + this._y * ratioB;
  2606. this._z = z * ratioA + this._z * ratioB;
  2607. this._onChangeCallback();
  2608. return this;
  2609. },
  2610. equals: function (quaternion) {
  2611. return quaternion._x === this._x && quaternion._y === this._y && quaternion._z === this._z && quaternion._w === this._w;
  2612. },
  2613. fromArray: function (array, offset) {
  2614. if (offset === undefined) offset = 0;
  2615. this._x = array[offset];
  2616. this._y = array[offset + 1];
  2617. this._z = array[offset + 2];
  2618. this._w = array[offset + 3];
  2619. this._onChangeCallback();
  2620. return this;
  2621. },
  2622. toArray: function (array, offset) {
  2623. if (array === undefined) array = [];
  2624. if (offset === undefined) offset = 0;
  2625. array[offset] = this._x;
  2626. array[offset + 1] = this._y;
  2627. array[offset + 2] = this._z;
  2628. array[offset + 3] = this._w;
  2629. return array;
  2630. },
  2631. _onChange: function (callback) {
  2632. this._onChangeCallback = callback;
  2633. return this;
  2634. },
  2635. _onChangeCallback: function () {}
  2636. });
  2637. /**
  2638. * @author mrdoob / http://mrdoob.com/
  2639. * @author kile / http://kile.stravaganza.org/
  2640. * @author philogb / http://blog.thejit.org/
  2641. * @author mikael emtinger / http://gomo.se/
  2642. * @author egraether / http://egraether.com/
  2643. * @author WestLangley / http://github.com/WestLangley
  2644. */
  2645. var _vector = new Vector3();
  2646. var _quaternion = new Quaternion();
  2647. function Vector3(x, y, z) {
  2648. this.x = x || 0;
  2649. this.y = y || 0;
  2650. this.z = z || 0;
  2651. }
  2652. Object.assign(Vector3.prototype, {
  2653. isVector3: true,
  2654. set: function (x, y, z) {
  2655. this.x = x;
  2656. this.y = y;
  2657. this.z = z;
  2658. return this;
  2659. },
  2660. setScalar: function (scalar) {
  2661. this.x = scalar;
  2662. this.y = scalar;
  2663. this.z = scalar;
  2664. return this;
  2665. },
  2666. setX: function (x) {
  2667. this.x = x;
  2668. return this;
  2669. },
  2670. setY: function (y) {
  2671. this.y = y;
  2672. return this;
  2673. },
  2674. setZ: function (z) {
  2675. this.z = z;
  2676. return this;
  2677. },
  2678. setComponent: function (index, value) {
  2679. switch (index) {
  2680. case 0:
  2681. this.x = value;
  2682. break;
  2683. case 1:
  2684. this.y = value;
  2685. break;
  2686. case 2:
  2687. this.z = value;
  2688. break;
  2689. default:
  2690. throw new Error('index is out of range: ' + index);
  2691. }
  2692. return this;
  2693. },
  2694. getComponent: function (index) {
  2695. switch (index) {
  2696. case 0:
  2697. return this.x;
  2698. case 1:
  2699. return this.y;
  2700. case 2:
  2701. return this.z;
  2702. default:
  2703. throw new Error('index is out of range: ' + index);
  2704. }
  2705. },
  2706. clone: function () {
  2707. return new this.constructor(this.x, this.y, this.z);
  2708. },
  2709. copy: function (v) {
  2710. this.x = v.x;
  2711. this.y = v.y;
  2712. this.z = v.z;
  2713. return this;
  2714. },
  2715. add: function (v, w) {
  2716. if (w !== undefined) {
  2717. console.warn('THREE.Vector3: .add() now only accepts one argument. Use .addVectors( a, b ) instead.');
  2718. return this.addVectors(v, w);
  2719. }
  2720. this.x += v.x;
  2721. this.y += v.y;
  2722. this.z += v.z;
  2723. return this;
  2724. },
  2725. addScalar: function (s) {
  2726. this.x += s;
  2727. this.y += s;
  2728. this.z += s;
  2729. return this;
  2730. },
  2731. addVectors: function (a, b) {
  2732. this.x = a.x + b.x;
  2733. this.y = a.y + b.y;
  2734. this.z = a.z + b.z;
  2735. return this;
  2736. },
  2737. addScaledVector: function (v, s) {
  2738. this.x += v.x * s;
  2739. this.y += v.y * s;
  2740. this.z += v.z * s;
  2741. return this;
  2742. },
  2743. sub: function (v, w) {
  2744. if (w !== undefined) {
  2745. console.warn('THREE.Vector3: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.');
  2746. return this.subVectors(v, w);
  2747. }
  2748. this.x -= v.x;
  2749. this.y -= v.y;
  2750. this.z -= v.z;
  2751. return this;
  2752. },
  2753. subScalar: function (s) {
  2754. this.x -= s;
  2755. this.y -= s;
  2756. this.z -= s;
  2757. return this;
  2758. },
  2759. subVectors: function (a, b) {
  2760. this.x = a.x - b.x;
  2761. this.y = a.y - b.y;
  2762. this.z = a.z - b.z;
  2763. return this;
  2764. },
  2765. multiply: function (v, w) {
  2766. if (w !== undefined) {
  2767. console.warn('THREE.Vector3: .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead.');
  2768. return this.multiplyVectors(v, w);
  2769. }
  2770. this.x *= v.x;
  2771. this.y *= v.y;
  2772. this.z *= v.z;
  2773. return this;
  2774. },
  2775. multiplyScalar: function (scalar) {
  2776. this.x *= scalar;
  2777. this.y *= scalar;
  2778. this.z *= scalar;
  2779. return this;
  2780. },
  2781. multiplyVectors: function (a, b) {
  2782. this.x = a.x * b.x;
  2783. this.y = a.y * b.y;
  2784. this.z = a.z * b.z;
  2785. return this;
  2786. },
  2787. applyEuler: function (euler) {
  2788. if (!(euler && euler.isEuler)) {
  2789. console.error('THREE.Vector3: .applyEuler() now expects an Euler rotation rather than a Vector3 and order.');
  2790. }
  2791. return this.applyQuaternion(_quaternion.setFromEuler(euler));
  2792. },
  2793. applyAxisAngle: function (axis, angle) {
  2794. return this.applyQuaternion(_quaternion.setFromAxisAngle(axis, angle));
  2795. },
  2796. applyMatrix3: function (m) {
  2797. var x = this.x,
  2798. y = this.y,
  2799. z = this.z;
  2800. var e = m.elements;
  2801. this.x = e[0] * x + e[3] * y + e[6] * z;
  2802. this.y = e[1] * x + e[4] * y + e[7] * z;
  2803. this.z = e[2] * x + e[5] * y + e[8] * z;
  2804. return this;
  2805. },
  2806. applyMatrix4: function (m) {
  2807. var x = this.x,
  2808. y = this.y,
  2809. z = this.z;
  2810. var e = m.elements;
  2811. var w = 1 / (e[3] * x + e[7] * y + e[11] * z + e[15]);
  2812. this.x = (e[0] * x + e[4] * y + e[8] * z + e[12]) * w;
  2813. this.y = (e[1] * x + e[5] * y + e[9] * z + e[13]) * w;
  2814. this.z = (e[2] * x + e[6] * y + e[10] * z + e[14]) * w;
  2815. return this;
  2816. },
  2817. applyQuaternion: function (q) {
  2818. var x = this.x,
  2819. y = this.y,
  2820. z = this.z;
  2821. var qx = q.x,
  2822. qy = q.y,
  2823. qz = q.z,
  2824. qw = q.w; // calculate quat * vector
  2825. var ix = qw * x + qy * z - qz * y;
  2826. var iy = qw * y + qz * x - qx * z;
  2827. var iz = qw * z + qx * y - qy * x;
  2828. var iw = -qx * x - qy * y - qz * z; // calculate result * inverse quat
  2829. this.x = ix * qw + iw * -qx + iy * -qz - iz * -qy;
  2830. this.y = iy * qw + iw * -qy + iz * -qx - ix * -qz;
  2831. this.z = iz * qw + iw * -qz + ix * -qy - iy * -qx;
  2832. return this;
  2833. },
  2834. project: function (camera) {
  2835. return this.applyMatrix4(camera.matrixWorldInverse).applyMatrix4(camera.projectionMatrix);
  2836. },
  2837. unproject: function (camera) {
  2838. return this.applyMatrix4(camera.projectionMatrixInverse).applyMatrix4(camera.matrixWorld);
  2839. },
  2840. transformDirection: function (m) {
  2841. // input: THREE.Matrix4 affine matrix
  2842. // vector interpreted as a direction
  2843. var x = this.x,
  2844. y = this.y,
  2845. z = this.z;
  2846. var e = m.elements;
  2847. this.x = e[0] * x + e[4] * y + e[8] * z;
  2848. this.y = e[1] * x + e[5] * y + e[9] * z;
  2849. this.z = e[2] * x + e[6] * y + e[10] * z;
  2850. return this.normalize();
  2851. },
  2852. divide: function (v) {
  2853. this.x /= v.x;
  2854. this.y /= v.y;
  2855. this.z /= v.z;
  2856. return this;
  2857. },
  2858. divideScalar: function (scalar) {
  2859. return this.multiplyScalar(1 / scalar);
  2860. },
  2861. min: function (v) {
  2862. this.x = Math.min(this.x, v.x);
  2863. this.y = Math.min(this.y, v.y);
  2864. this.z = Math.min(this.z, v.z);
  2865. return this;
  2866. },
  2867. max: function (v) {
  2868. this.x = Math.max(this.x, v.x);
  2869. this.y = Math.max(this.y, v.y);
  2870. this.z = Math.max(this.z, v.z);
  2871. return this;
  2872. },
  2873. clamp: function (min, max) {
  2874. // assumes min < max, componentwise
  2875. this.x = Math.max(min.x, Math.min(max.x, this.x));
  2876. this.y = Math.max(min.y, Math.min(max.y, this.y));
  2877. this.z = Math.max(min.z, Math.min(max.z, this.z));
  2878. return this;
  2879. },
  2880. clampScalar: function (minVal, maxVal) {
  2881. this.x = Math.max(minVal, Math.min(maxVal, this.x));
  2882. this.y = Math.max(minVal, Math.min(maxVal, this.y));
  2883. this.z = Math.max(minVal, Math.min(maxVal, this.z));
  2884. return this;
  2885. },
  2886. clampLength: function (min, max) {
  2887. var length = this.length();
  2888. return this.divideScalar(length || 1).multiplyScalar(Math.max(min, Math.min(max, length)));
  2889. },
  2890. floor: function () {
  2891. this.x = Math.floor(this.x);
  2892. this.y = Math.floor(this.y);
  2893. this.z = Math.floor(this.z);
  2894. return this;
  2895. },
  2896. ceil: function () {
  2897. this.x = Math.ceil(this.x);
  2898. this.y = Math.ceil(this.y);
  2899. this.z = Math.ceil(this.z);
  2900. return this;
  2901. },
  2902. round: function () {
  2903. this.x = Math.round(this.x);
  2904. this.y = Math.round(this.y);
  2905. this.z = Math.round(this.z);
  2906. return this;
  2907. },
  2908. roundToZero: function () {
  2909. this.x = this.x < 0 ? Math.ceil(this.x) : Math.floor(this.x);
  2910. this.y = this.y < 0 ? Math.ceil(this.y) : Math.floor(this.y);
  2911. this.z = this.z < 0 ? Math.ceil(this.z) : Math.floor(this.z);
  2912. return this;
  2913. },
  2914. negate: function () {
  2915. this.x = -this.x;
  2916. this.y = -this.y;
  2917. this.z = -this.z;
  2918. return this;
  2919. },
  2920. dot: function (v) {
  2921. return this.x * v.x + this.y * v.y + this.z * v.z;
  2922. },
  2923. // TODO lengthSquared?
  2924. lengthSq: function () {
  2925. return this.x * this.x + this.y * this.y + this.z * this.z;
  2926. },
  2927. length: function () {
  2928. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  2929. },
  2930. manhattanLength: function () {
  2931. return Math.abs(this.x) + Math.abs(this.y) + Math.abs(this.z);
  2932. },
  2933. normalize: function () {
  2934. return this.divideScalar(this.length() || 1);
  2935. },
  2936. setLength: function (length) {
  2937. return this.normalize().multiplyScalar(length);
  2938. },
  2939. lerp: function (v, alpha) {
  2940. this.x += (v.x - this.x) * alpha;
  2941. this.y += (v.y - this.y) * alpha;
  2942. this.z += (v.z - this.z) * alpha;
  2943. return this;
  2944. },
  2945. lerpVectors: function (v1, v2, alpha) {
  2946. return this.subVectors(v2, v1).multiplyScalar(alpha).add(v1);
  2947. },
  2948. cross: function (v, w) {
  2949. if (w !== undefined) {
  2950. console.warn('THREE.Vector3: .cross() now only accepts one argument. Use .crossVectors( a, b ) instead.');
  2951. return this.crossVectors(v, w);
  2952. }
  2953. return this.crossVectors(this, v);
  2954. },
  2955. crossVectors: function (a, b) {
  2956. var ax = a.x,
  2957. ay = a.y,
  2958. az = a.z;
  2959. var bx = b.x,
  2960. by = b.y,
  2961. bz = b.z;
  2962. this.x = ay * bz - az * by;
  2963. this.y = az * bx - ax * bz;
  2964. this.z = ax * by - ay * bx;
  2965. return this;
  2966. },
  2967. projectOnVector: function (v) {
  2968. // v cannot be the zero v
  2969. var scalar = v.dot(this) / v.lengthSq();
  2970. return this.copy(v).multiplyScalar(scalar);
  2971. },
  2972. projectOnPlane: function (planeNormal) {
  2973. _vector.copy(this).projectOnVector(planeNormal);
  2974. return this.sub(_vector);
  2975. },
  2976. reflect: function (normal) {
  2977. // reflect incident vector off plane orthogonal to normal
  2978. // normal is assumed to have unit length
  2979. return this.sub(_vector.copy(normal).multiplyScalar(2 * this.dot(normal)));
  2980. },
  2981. angleTo: function (v) {
  2982. var denominator = Math.sqrt(this.lengthSq() * v.lengthSq());
  2983. if (denominator === 0) console.error('THREE.Vector3: angleTo() can\'t handle zero length vectors.');
  2984. var theta = this.dot(v) / denominator; // clamp, to handle numerical problems
  2985. return Math.acos(_Math.clamp(theta, -1, 1));
  2986. },
  2987. distanceTo: function (v) {
  2988. return Math.sqrt(this.distanceToSquared(v));
  2989. },
  2990. distanceToSquared: function (v) {
  2991. var dx = this.x - v.x,
  2992. dy = this.y - v.y,
  2993. dz = this.z - v.z;
  2994. return dx * dx + dy * dy + dz * dz;
  2995. },
  2996. manhattanDistanceTo: function (v) {
  2997. return Math.abs(this.x - v.x) + Math.abs(this.y - v.y) + Math.abs(this.z - v.z);
  2998. },
  2999. setFromSpherical: function (s) {
  3000. return this.setFromSphericalCoords(s.radius, s.phi, s.theta);
  3001. },
  3002. setFromSphericalCoords: function (radius, phi, theta) {
  3003. var sinPhiRadius = Math.sin(phi) * radius;
  3004. this.x = sinPhiRadius * Math.sin(theta);
  3005. this.y = Math.cos(phi) * radius;
  3006. this.z = sinPhiRadius * Math.cos(theta);
  3007. return this;
  3008. },
  3009. setFromCylindrical: function (c) {
  3010. return this.setFromCylindricalCoords(c.radius, c.theta, c.y);
  3011. },
  3012. setFromCylindricalCoords: function (radius, theta, y) {
  3013. this.x = radius * Math.sin(theta);
  3014. this.y = y;
  3015. this.z = radius * Math.cos(theta);
  3016. return this;
  3017. },
  3018. setFromMatrixPosition: function (m) {
  3019. var e = m.elements;
  3020. this.x = e[12];
  3021. this.y = e[13];
  3022. this.z = e[14];
  3023. return this;
  3024. },
  3025. setFromMatrixScale: function (m) {
  3026. var sx = this.setFromMatrixColumn(m, 0).length();
  3027. var sy = this.setFromMatrixColumn(m, 1).length();
  3028. var sz = this.setFromMatrixColumn(m, 2).length();
  3029. this.x = sx;
  3030. this.y = sy;
  3031. this.z = sz;
  3032. return this;
  3033. },
  3034. setFromMatrixColumn: function (m, index) {
  3035. return this.fromArray(m.elements, index * 4);
  3036. },
  3037. equals: function (v) {
  3038. return v.x === this.x && v.y === this.y && v.z === this.z;
  3039. },
  3040. fromArray: function (array, offset) {
  3041. if (offset === undefined) offset = 0;
  3042. this.x = array[offset];
  3043. this.y = array[offset + 1];
  3044. this.z = array[offset + 2];
  3045. return this;
  3046. },
  3047. toArray: function (array, offset) {
  3048. if (array === undefined) array = [];
  3049. if (offset === undefined) offset = 0;
  3050. array[offset] = this.x;
  3051. array[offset + 1] = this.y;
  3052. array[offset + 2] = this.z;
  3053. return array;
  3054. },
  3055. fromBufferAttribute: function (attribute, index, offset) {
  3056. if (offset !== undefined) {
  3057. console.warn('THREE.Vector3: offset has been removed from .fromBufferAttribute().');
  3058. }
  3059. this.x = attribute.getX(index);
  3060. this.y = attribute.getY(index);
  3061. this.z = attribute.getZ(index);
  3062. return this;
  3063. }
  3064. });
  3065. /**
  3066. * @author alteredq / http://alteredqualia.com/
  3067. * @author WestLangley / http://github.com/WestLangley
  3068. * @author bhouston / http://clara.io
  3069. * @author tschw
  3070. */
  3071. var _vector$1 = new Vector3();
  3072. function Matrix3() {
  3073. this.elements = [1, 0, 0, 0, 1, 0, 0, 0, 1];
  3074. if (arguments.length > 0) {
  3075. console.error('THREE.Matrix3: the constructor no longer reads arguments. use .set() instead.');
  3076. }
  3077. }
  3078. Object.assign(Matrix3.prototype, {
  3079. isMatrix3: true,
  3080. set: function (n11, n12, n13, n21, n22, n23, n31, n32, n33) {
  3081. var te = this.elements;
  3082. te[0] = n11;
  3083. te[1] = n21;
  3084. te[2] = n31;
  3085. te[3] = n12;
  3086. te[4] = n22;
  3087. te[5] = n32;
  3088. te[6] = n13;
  3089. te[7] = n23;
  3090. te[8] = n33;
  3091. return this;
  3092. },
  3093. identity: function () {
  3094. this.set(1, 0, 0, 0, 1, 0, 0, 0, 1);
  3095. return this;
  3096. },
  3097. clone: function () {
  3098. return new this.constructor().fromArray(this.elements);
  3099. },
  3100. copy: function (m) {
  3101. var te = this.elements;
  3102. var me = m.elements;
  3103. te[0] = me[0];
  3104. te[1] = me[1];
  3105. te[2] = me[2];
  3106. te[3] = me[3];
  3107. te[4] = me[4];
  3108. te[5] = me[5];
  3109. te[6] = me[6];
  3110. te[7] = me[7];
  3111. te[8] = me[8];
  3112. return this;
  3113. },
  3114. setFromMatrix4: function (m) {
  3115. var me = m.elements;
  3116. this.set(me[0], me[4], me[8], me[1], me[5], me[9], me[2], me[6], me[10]);
  3117. return this;
  3118. },
  3119. applyToBufferAttribute: function (attribute) {
  3120. for (var i = 0, l = attribute.count; i < l; i++) {
  3121. _vector$1.x = attribute.getX(i);
  3122. _vector$1.y = attribute.getY(i);
  3123. _vector$1.z = attribute.getZ(i);
  3124. _vector$1.applyMatrix3(this);
  3125. attribute.setXYZ(i, _vector$1.x, _vector$1.y, _vector$1.z);
  3126. }
  3127. return attribute;
  3128. },
  3129. multiply: function (m) {
  3130. return this.multiplyMatrices(this, m);
  3131. },
  3132. premultiply: function (m) {
  3133. return this.multiplyMatrices(m, this);
  3134. },
  3135. multiplyMatrices: function (a, b) {
  3136. var ae = a.elements;
  3137. var be = b.elements;
  3138. var te = this.elements;
  3139. var a11 = ae[0],
  3140. a12 = ae[3],
  3141. a13 = ae[6];
  3142. var a21 = ae[1],
  3143. a22 = ae[4],
  3144. a23 = ae[7];
  3145. var a31 = ae[2],
  3146. a32 = ae[5],
  3147. a33 = ae[8];
  3148. var b11 = be[0],
  3149. b12 = be[3],
  3150. b13 = be[6];
  3151. var b21 = be[1],
  3152. b22 = be[4],
  3153. b23 = be[7];
  3154. var b31 = be[2],
  3155. b32 = be[5],
  3156. b33 = be[8];
  3157. te[0] = a11 * b11 + a12 * b21 + a13 * b31;
  3158. te[3] = a11 * b12 + a12 * b22 + a13 * b32;
  3159. te[6] = a11 * b13 + a12 * b23 + a13 * b33;
  3160. te[1] = a21 * b11 + a22 * b21 + a23 * b31;
  3161. te[4] = a21 * b12 + a22 * b22 + a23 * b32;
  3162. te[7] = a21 * b13 + a22 * b23 + a23 * b33;
  3163. te[2] = a31 * b11 + a32 * b21 + a33 * b31;
  3164. te[5] = a31 * b12 + a32 * b22 + a33 * b32;
  3165. te[8] = a31 * b13 + a32 * b23 + a33 * b33;
  3166. return this;
  3167. },
  3168. multiplyScalar: function (s) {
  3169. var te = this.elements;
  3170. te[0] *= s;
  3171. te[3] *= s;
  3172. te[6] *= s;
  3173. te[1] *= s;
  3174. te[4] *= s;
  3175. te[7] *= s;
  3176. te[2] *= s;
  3177. te[5] *= s;
  3178. te[8] *= s;
  3179. return this;
  3180. },
  3181. determinant: function () {
  3182. var te = this.elements;
  3183. var a = te[0],
  3184. b = te[1],
  3185. c = te[2],
  3186. d = te[3],
  3187. e = te[4],
  3188. f = te[5],
  3189. g = te[6],
  3190. h = te[7],
  3191. i = te[8];
  3192. return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g;
  3193. },
  3194. getInverse: function (matrix, throwOnDegenerate) {
  3195. if (matrix && matrix.isMatrix4) {
  3196. console.error("THREE.Matrix3: .getInverse() no longer takes a Matrix4 argument.");
  3197. }
  3198. var me = matrix.elements,
  3199. te = this.elements,
  3200. n11 = me[0],
  3201. n21 = me[1],
  3202. n31 = me[2],
  3203. n12 = me[3],
  3204. n22 = me[4],
  3205. n32 = me[5],
  3206. n13 = me[6],
  3207. n23 = me[7],
  3208. n33 = me[8],
  3209. t11 = n33 * n22 - n32 * n23,
  3210. t12 = n32 * n13 - n33 * n12,
  3211. t13 = n23 * n12 - n22 * n13,
  3212. det = n11 * t11 + n21 * t12 + n31 * t13;
  3213. if (det === 0) {
  3214. var msg = "THREE.Matrix3: .getInverse() can't invert matrix, determinant is 0";
  3215. if (throwOnDegenerate === true) {
  3216. throw new Error(msg);
  3217. } else {
  3218. console.warn(msg);
  3219. }
  3220. return this.identity();
  3221. }
  3222. var detInv = 1 / det;
  3223. te[0] = t11 * detInv;
  3224. te[1] = (n31 * n23 - n33 * n21) * detInv;
  3225. te[2] = (n32 * n21 - n31 * n22) * detInv;
  3226. te[3] = t12 * detInv;
  3227. te[4] = (n33 * n11 - n31 * n13) * detInv;
  3228. te[5] = (n31 * n12 - n32 * n11) * detInv;
  3229. te[6] = t13 * detInv;
  3230. te[7] = (n21 * n13 - n23 * n11) * detInv;
  3231. te[8] = (n22 * n11 - n21 * n12) * detInv;
  3232. return this;
  3233. },
  3234. transpose: function () {
  3235. var tmp,
  3236. m = this.elements;
  3237. tmp = m[1];
  3238. m[1] = m[3];
  3239. m[3] = tmp;
  3240. tmp = m[2];
  3241. m[2] = m[6];
  3242. m[6] = tmp;
  3243. tmp = m[5];
  3244. m[5] = m[7];
  3245. m[7] = tmp;
  3246. return this;
  3247. },
  3248. getNormalMatrix: function (matrix4) {
  3249. return this.setFromMatrix4(matrix4).getInverse(this).transpose();
  3250. },
  3251. transposeIntoArray: function (r) {
  3252. var m = this.elements;
  3253. r[0] = m[0];
  3254. r[1] = m[3];
  3255. r[2] = m[6];
  3256. r[3] = m[1];
  3257. r[4] = m[4];
  3258. r[5] = m[7];
  3259. r[6] = m[2];
  3260. r[7] = m[5];
  3261. r[8] = m[8];
  3262. return this;
  3263. },
  3264. setUvTransform: function (tx, ty, sx, sy, rotation, cx, cy) {
  3265. var c = Math.cos(rotation);
  3266. var s = Math.sin(rotation);
  3267. 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);
  3268. },
  3269. scale: function (sx, sy) {
  3270. var te = this.elements;
  3271. te[0] *= sx;
  3272. te[3] *= sx;
  3273. te[6] *= sx;
  3274. te[1] *= sy;
  3275. te[4] *= sy;
  3276. te[7] *= sy;
  3277. return this;
  3278. },
  3279. rotate: function (theta) {
  3280. var c = Math.cos(theta);
  3281. var s = Math.sin(theta);
  3282. var te = this.elements;
  3283. var a11 = te[0],
  3284. a12 = te[3],
  3285. a13 = te[6];
  3286. var a21 = te[1],
  3287. a22 = te[4],
  3288. a23 = te[7];
  3289. te[0] = c * a11 + s * a21;
  3290. te[3] = c * a12 + s * a22;
  3291. te[6] = c * a13 + s * a23;
  3292. te[1] = -s * a11 + c * a21;
  3293. te[4] = -s * a12 + c * a22;
  3294. te[7] = -s * a13 + c * a23;
  3295. return this;
  3296. },
  3297. translate: function (tx, ty) {
  3298. var te = this.elements;
  3299. te[0] += tx * te[2];
  3300. te[3] += tx * te[5];
  3301. te[6] += tx * te[8];
  3302. te[1] += ty * te[2];
  3303. te[4] += ty * te[5];
  3304. te[7] += ty * te[8];
  3305. return this;
  3306. },
  3307. equals: function (matrix) {
  3308. var te = this.elements;
  3309. var me = matrix.elements;
  3310. for (var i = 0; i < 9; i++) {
  3311. if (te[i] !== me[i]) return false;
  3312. }
  3313. return true;
  3314. },
  3315. fromArray: function (array, offset) {
  3316. if (offset === undefined) offset = 0;
  3317. for (var i = 0; i < 9; i++) {
  3318. this.elements[i] = array[i + offset];
  3319. }
  3320. return this;
  3321. },
  3322. toArray: function (array, offset) {
  3323. if (array === undefined) array = [];
  3324. if (offset === undefined) offset = 0;
  3325. var te = this.elements;
  3326. array[offset] = te[0];
  3327. array[offset + 1] = te[1];
  3328. array[offset + 2] = te[2];
  3329. array[offset + 3] = te[3];
  3330. array[offset + 4] = te[4];
  3331. array[offset + 5] = te[5];
  3332. array[offset + 6] = te[6];
  3333. array[offset + 7] = te[7];
  3334. array[offset + 8] = te[8];
  3335. return array;
  3336. }
  3337. });
  3338. /**
  3339. * @author mrdoob / http://mrdoob.com/
  3340. * @author alteredq / http://alteredqualia.com/
  3341. * @author szimek / https://github.com/szimek/
  3342. */
  3343. var _canvas;
  3344. var ImageUtils = {
  3345. getDataURL: function (image) {
  3346. var canvas;
  3347. if (typeof HTMLCanvasElement == 'undefined') {
  3348. return image.src;
  3349. } else if (image instanceof HTMLCanvasElement) {
  3350. canvas = image;
  3351. } else {
  3352. if (_canvas === undefined) _canvas = document.createElementNS('http://www.w3.org/1999/xhtml', 'canvas');
  3353. _canvas.width = image.width;
  3354. _canvas.height = image.height;
  3355. var context = _canvas.getContext('2d');
  3356. if (image instanceof ImageData) {
  3357. context.putImageData(image, 0, 0);
  3358. } else {
  3359. context.drawImage(image, 0, 0, image.width, image.height);
  3360. }
  3361. canvas = _canvas;
  3362. }
  3363. if (canvas.width > 2048 || canvas.height > 2048) {
  3364. return canvas.toDataURL('image/jpeg', 0.6);
  3365. } else {
  3366. return canvas.toDataURL('image/png');
  3367. }
  3368. }
  3369. };
  3370. /**
  3371. * @author mrdoob / http://mrdoob.com/
  3372. * @author alteredq / http://alteredqualia.com/
  3373. * @author szimek / https://github.com/szimek/
  3374. */
  3375. exports.ImageUtils = ImageUtils;
  3376. var textureId = 0;
  3377. function Texture(image, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding) {
  3378. Object.defineProperty(this, 'id', {
  3379. value: textureId++
  3380. });
  3381. this.uuid = _Math.generateUUID();
  3382. this.name = '';
  3383. this.image = image !== undefined ? image : Texture.DEFAULT_IMAGE;
  3384. this.mipmaps = [];
  3385. this.mapping = mapping !== undefined ? mapping : Texture.DEFAULT_MAPPING;
  3386. this.wrapS = wrapS !== undefined ? wrapS : ClampToEdgeWrapping;
  3387. this.wrapT = wrapT !== undefined ? wrapT : ClampToEdgeWrapping;
  3388. this.magFilter = magFilter !== undefined ? magFilter : LinearFilter;
  3389. this.minFilter = minFilter !== undefined ? minFilter : LinearMipmapLinearFilter;
  3390. this.anisotropy = anisotropy !== undefined ? anisotropy : 1;
  3391. this.format = format !== undefined ? format : RGBAFormat;
  3392. this.type = type !== undefined ? type : UnsignedByteType;
  3393. this.offset = new Vector2(0, 0);
  3394. this.repeat = new Vector2(1, 1);
  3395. this.center = new Vector2(0, 0);
  3396. this.rotation = 0;
  3397. this.matrixAutoUpdate = true;
  3398. this.matrix = new Matrix3();
  3399. this.generateMipmaps = true;
  3400. this.premultiplyAlpha = false;
  3401. this.flipY = true;
  3402. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  3403. // Values of encoding !== THREE.LinearEncoding only supported on map, envMap and emissiveMap.
  3404. //
  3405. // Also changing the encoding after already used by a Material will not automatically make the Material
  3406. // update. You need to explicitly call Material.needsUpdate to trigger it to recompile.
  3407. this.encoding = encoding !== undefined ? encoding : LinearEncoding;
  3408. this.version = 0;
  3409. this.onUpdate = null;
  3410. }
  3411. Texture.DEFAULT_IMAGE = undefined;
  3412. Texture.DEFAULT_MAPPING = UVMapping;
  3413. Texture.prototype = Object.assign(Object.create(EventDispatcher.prototype), {
  3414. constructor: Texture,
  3415. isTexture: true,
  3416. updateMatrix: function () {
  3417. this.matrix.setUvTransform(this.offset.x, this.offset.y, this.repeat.x, this.repeat.y, this.rotation, this.center.x, this.center.y);
  3418. },
  3419. clone: function () {
  3420. return new this.constructor().copy(this);
  3421. },
  3422. copy: function (source) {
  3423. this.name = source.name;
  3424. this.image = source.image;
  3425. this.mipmaps = source.mipmaps.slice(0);
  3426. this.mapping = source.mapping;
  3427. this.wrapS = source.wrapS;
  3428. this.wrapT = source.wrapT;
  3429. this.magFilter = source.magFilter;
  3430. this.minFilter = source.minFilter;
  3431. this.anisotropy = source.anisotropy;
  3432. this.format = source.format;
  3433. this.type = source.type;
  3434. this.offset.copy(source.offset);
  3435. this.repeat.copy(source.repeat);
  3436. this.center.copy(source.center);
  3437. this.rotation = source.rotation;
  3438. this.matrixAutoUpdate = source.matrixAutoUpdate;
  3439. this.matrix.copy(source.matrix);
  3440. this.generateMipmaps = source.generateMipmaps;
  3441. this.premultiplyAlpha = source.premultiplyAlpha;
  3442. this.flipY = source.flipY;
  3443. this.unpackAlignment = source.unpackAlignment;
  3444. this.encoding = source.encoding;
  3445. return this;
  3446. },
  3447. toJSON: function (meta) {
  3448. var isRootObject = meta === undefined || typeof meta === 'string';
  3449. if (!isRootObject && meta.textures[this.uuid] !== undefined) {
  3450. return meta.textures[this.uuid];
  3451. }
  3452. var output = {
  3453. metadata: {
  3454. version: 4.5,
  3455. type: 'Texture',
  3456. generator: 'Texture.toJSON'
  3457. },
  3458. uuid: this.uuid,
  3459. name: this.name,
  3460. mapping: this.mapping,
  3461. repeat: [this.repeat.x, this.repeat.y],
  3462. offset: [this.offset.x, this.offset.y],
  3463. center: [this.center.x, this.center.y],
  3464. rotation: this.rotation,
  3465. wrap: [this.wrapS, this.wrapT],
  3466. format: this.format,
  3467. type: this.type,
  3468. encoding: this.encoding,
  3469. minFilter: this.minFilter,
  3470. magFilter: this.magFilter,
  3471. anisotropy: this.anisotropy,
  3472. flipY: this.flipY,
  3473. premultiplyAlpha: this.premultiplyAlpha,
  3474. unpackAlignment: this.unpackAlignment
  3475. };
  3476. if (this.image !== undefined) {
  3477. // TODO: Move to THREE.Image
  3478. var image = this.image;
  3479. if (image.uuid === undefined) {
  3480. image.uuid = _Math.generateUUID(); // UGH
  3481. }
  3482. if (!isRootObject && meta.images[image.uuid] === undefined) {
  3483. var url;
  3484. if (Array.isArray(image)) {
  3485. // process array of images e.g. CubeTexture
  3486. url = [];
  3487. for (var i = 0, l = image.length; i < l; i++) {
  3488. url.push(ImageUtils.getDataURL(image[i]));
  3489. }
  3490. } else {
  3491. // process single image
  3492. url = ImageUtils.getDataURL(image);
  3493. }
  3494. meta.images[image.uuid] = {
  3495. uuid: image.uuid,
  3496. url: url
  3497. };
  3498. }
  3499. output.image = image.uuid;
  3500. }
  3501. if (!isRootObject) {
  3502. meta.textures[this.uuid] = output;
  3503. }
  3504. return output;
  3505. },
  3506. dispose: function () {
  3507. this.dispatchEvent({
  3508. type: 'dispose'
  3509. });
  3510. },
  3511. transformUv: function (uv) {
  3512. if (this.mapping !== UVMapping) return uv;
  3513. uv.applyMatrix3(this.matrix);
  3514. if (uv.x < 0 || uv.x > 1) {
  3515. switch (this.wrapS) {
  3516. case RepeatWrapping:
  3517. uv.x = uv.x - Math.floor(uv.x);
  3518. break;
  3519. case ClampToEdgeWrapping:
  3520. uv.x = uv.x < 0 ? 0 : 1;
  3521. break;
  3522. case MirroredRepeatWrapping:
  3523. if (Math.abs(Math.floor(uv.x) % 2) === 1) {
  3524. uv.x = Math.ceil(uv.x) - uv.x;
  3525. } else {
  3526. uv.x = uv.x - Math.floor(uv.x);
  3527. }
  3528. break;
  3529. }
  3530. }
  3531. if (uv.y < 0 || uv.y > 1) {
  3532. switch (this.wrapT) {
  3533. case RepeatWrapping:
  3534. uv.y = uv.y - Math.floor(uv.y);
  3535. break;
  3536. case ClampToEdgeWrapping:
  3537. uv.y = uv.y < 0 ? 0 : 1;
  3538. break;
  3539. case MirroredRepeatWrapping:
  3540. if (Math.abs(Math.floor(uv.y) % 2) === 1) {
  3541. uv.y = Math.ceil(uv.y) - uv.y;
  3542. } else {
  3543. uv.y = uv.y - Math.floor(uv.y);
  3544. }
  3545. break;
  3546. }
  3547. }
  3548. if (this.flipY) {
  3549. uv.y = 1 - uv.y;
  3550. }
  3551. return uv;
  3552. }
  3553. });
  3554. Object.defineProperty(Texture.prototype, "needsUpdate", {
  3555. set: function (value) {
  3556. if (value === true) this.version++;
  3557. }
  3558. });
  3559. /**
  3560. * @author supereggbert / http://www.paulbrunt.co.uk/
  3561. * @author philogb / http://blog.thejit.org/
  3562. * @author mikael emtinger / http://gomo.se/
  3563. * @author egraether / http://egraether.com/
  3564. * @author WestLangley / http://github.com/WestLangley
  3565. */
  3566. function Vector4(x, y, z, w) {
  3567. this.x = x || 0;
  3568. this.y = y || 0;
  3569. this.z = z || 0;
  3570. this.w = w !== undefined ? w : 1;
  3571. }
  3572. Object.defineProperties(Vector4.prototype, {
  3573. "width": {
  3574. get: function () {
  3575. return this.z;
  3576. },
  3577. set: function (value) {
  3578. this.z = value;
  3579. }
  3580. },
  3581. "height": {
  3582. get: function () {
  3583. return this.w;
  3584. },
  3585. set: function (value) {
  3586. this.w = value;
  3587. }
  3588. }
  3589. });
  3590. Object.assign(Vector4.prototype, {
  3591. isVector4: true,
  3592. set: function (x, y, z, w) {
  3593. this.x = x;
  3594. this.y = y;
  3595. this.z = z;
  3596. this.w = w;
  3597. return this;
  3598. },
  3599. setScalar: function (scalar) {
  3600. this.x = scalar;
  3601. this.y = scalar;
  3602. this.z = scalar;
  3603. this.w = scalar;
  3604. return this;
  3605. },
  3606. setX: function (x) {
  3607. this.x = x;
  3608. return this;
  3609. },
  3610. setY: function (y) {
  3611. this.y = y;
  3612. return this;
  3613. },
  3614. setZ: function (z) {
  3615. this.z = z;
  3616. return this;
  3617. },
  3618. setW: function (w) {
  3619. this.w = w;
  3620. return this;
  3621. },
  3622. setComponent: function (index, value) {
  3623. switch (index) {
  3624. case 0:
  3625. this.x = value;
  3626. break;
  3627. case 1:
  3628. this.y = value;
  3629. break;
  3630. case 2:
  3631. this.z = value;
  3632. break;
  3633. case 3:
  3634. this.w = value;
  3635. break;
  3636. default:
  3637. throw new Error('index is out of range: ' + index);
  3638. }
  3639. return this;
  3640. },
  3641. getComponent: function (index) {
  3642. switch (index) {
  3643. case 0:
  3644. return this.x;
  3645. case 1:
  3646. return this.y;
  3647. case 2:
  3648. return this.z;
  3649. case 3:
  3650. return this.w;
  3651. default:
  3652. throw new Error('index is out of range: ' + index);
  3653. }
  3654. },
  3655. clone: function () {
  3656. return new this.constructor(this.x, this.y, this.z, this.w);
  3657. },
  3658. copy: function (v) {
  3659. this.x = v.x;
  3660. this.y = v.y;
  3661. this.z = v.z;
  3662. this.w = v.w !== undefined ? v.w : 1;
  3663. return this;
  3664. },
  3665. add: function (v, w) {
  3666. if (w !== undefined) {
  3667. console.warn('THREE.Vector4: .add() now only accepts one argument. Use .addVectors( a, b ) instead.');
  3668. return this.addVectors(v, w);
  3669. }
  3670. this.x += v.x;
  3671. this.y += v.y;
  3672. this.z += v.z;
  3673. this.w += v.w;
  3674. return this;
  3675. },
  3676. addScalar: function (s) {
  3677. this.x += s;
  3678. this.y += s;
  3679. this.z += s;
  3680. this.w += s;
  3681. return this;
  3682. },
  3683. addVectors: function (a, b) {
  3684. this.x = a.x + b.x;
  3685. this.y = a.y + b.y;
  3686. this.z = a.z + b.z;
  3687. this.w = a.w + b.w;
  3688. return this;
  3689. },
  3690. addScaledVector: function (v, s) {
  3691. this.x += v.x * s;
  3692. this.y += v.y * s;
  3693. this.z += v.z * s;
  3694. this.w += v.w * s;
  3695. return this;
  3696. },
  3697. sub: function (v, w) {
  3698. if (w !== undefined) {
  3699. console.warn('THREE.Vector4: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.');
  3700. return this.subVectors(v, w);
  3701. }
  3702. this.x -= v.x;
  3703. this.y -= v.y;
  3704. this.z -= v.z;
  3705. this.w -= v.w;
  3706. return this;
  3707. },
  3708. subScalar: function (s) {
  3709. this.x -= s;
  3710. this.y -= s;
  3711. this.z -= s;
  3712. this.w -= s;
  3713. return this;
  3714. },
  3715. subVectors: function (a, b) {
  3716. this.x = a.x - b.x;
  3717. this.y = a.y - b.y;
  3718. this.z = a.z - b.z;
  3719. this.w = a.w - b.w;
  3720. return this;
  3721. },
  3722. multiplyScalar: function (scalar) {
  3723. this.x *= scalar;
  3724. this.y *= scalar;
  3725. this.z *= scalar;
  3726. this.w *= scalar;
  3727. return this;
  3728. },
  3729. applyMatrix4: function (m) {
  3730. var x = this.x,
  3731. y = this.y,
  3732. z = this.z,
  3733. w = this.w;
  3734. var e = m.elements;
  3735. this.x = e[0] * x + e[4] * y + e[8] * z + e[12] * w;
  3736. this.y = e[1] * x + e[5] * y + e[9] * z + e[13] * w;
  3737. this.z = e[2] * x + e[6] * y + e[10] * z + e[14] * w;
  3738. this.w = e[3] * x + e[7] * y + e[11] * z + e[15] * w;
  3739. return this;
  3740. },
  3741. divideScalar: function (scalar) {
  3742. return this.multiplyScalar(1 / scalar);
  3743. },
  3744. setAxisAngleFromQuaternion: function (q) {
  3745. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  3746. // q is assumed to be normalized
  3747. this.w = 2 * Math.acos(q.w);
  3748. var s = Math.sqrt(1 - q.w * q.w);
  3749. if (s < 0.0001) {
  3750. this.x = 1;
  3751. this.y = 0;
  3752. this.z = 0;
  3753. } else {
  3754. this.x = q.x / s;
  3755. this.y = q.y / s;
  3756. this.z = q.z / s;
  3757. }
  3758. return this;
  3759. },
  3760. setAxisAngleFromRotationMatrix: function (m) {
  3761. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  3762. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  3763. var angle,
  3764. x,
  3765. y,
  3766. z,
  3767. // variables for result
  3768. epsilon = 0.01,
  3769. // margin to allow for rounding errors
  3770. epsilon2 = 0.1,
  3771. // margin to distinguish between 0 and 180 degrees
  3772. te = m.elements,
  3773. m11 = te[0],
  3774. m12 = te[4],
  3775. m13 = te[8],
  3776. m21 = te[1],
  3777. m22 = te[5],
  3778. m23 = te[9],
  3779. m31 = te[2],
  3780. m32 = te[6],
  3781. m33 = te[10];
  3782. if (Math.abs(m12 - m21) < epsilon && Math.abs(m13 - m31) < epsilon && Math.abs(m23 - m32) < epsilon) {
  3783. // singularity found
  3784. // first check for identity matrix which must have +1 for all terms
  3785. // in leading diagonal and zero in other terms
  3786. if (Math.abs(m12 + m21) < epsilon2 && Math.abs(m13 + m31) < epsilon2 && Math.abs(m23 + m32) < epsilon2 && Math.abs(m11 + m22 + m33 - 3) < epsilon2) {
  3787. // this singularity is identity matrix so angle = 0
  3788. this.set(1, 0, 0, 0);
  3789. return this; // zero angle, arbitrary axis
  3790. } // otherwise this singularity is angle = 180
  3791. angle = Math.PI;
  3792. var xx = (m11 + 1) / 2;
  3793. var yy = (m22 + 1) / 2;
  3794. var zz = (m33 + 1) / 2;
  3795. var xy = (m12 + m21) / 4;
  3796. var xz = (m13 + m31) / 4;
  3797. var yz = (m23 + m32) / 4;
  3798. if (xx > yy && xx > zz) {
  3799. // m11 is the largest diagonal term
  3800. if (xx < epsilon) {
  3801. x = 0;
  3802. y = 0.707106781;
  3803. z = 0.707106781;
  3804. } else {
  3805. x = Math.sqrt(xx);
  3806. y = xy / x;
  3807. z = xz / x;
  3808. }
  3809. } else if (yy > zz) {
  3810. // m22 is the largest diagonal term
  3811. if (yy < epsilon) {
  3812. x = 0.707106781;
  3813. y = 0;
  3814. z = 0.707106781;
  3815. } else {
  3816. y = Math.sqrt(yy);
  3817. x = xy / y;
  3818. z = yz / y;
  3819. }
  3820. } else {
  3821. // m33 is the largest diagonal term so base result on this
  3822. if (zz < epsilon) {
  3823. x = 0.707106781;
  3824. y = 0.707106781;
  3825. z = 0;
  3826. } else {
  3827. z = Math.sqrt(zz);
  3828. x = xz / z;
  3829. y = yz / z;
  3830. }
  3831. }
  3832. this.set(x, y, z, angle);
  3833. return this; // return 180 deg rotation
  3834. } // as we have reached here there are no singularities so we can handle normally
  3835. var s = Math.sqrt((m32 - m23) * (m32 - m23) + (m13 - m31) * (m13 - m31) + (m21 - m12) * (m21 - m12)); // used to normalize
  3836. if (Math.abs(s) < 0.001) s = 1; // prevent divide by zero, should not happen if matrix is orthogonal and should be
  3837. // caught by singularity test above, but I've left it in just in case
  3838. this.x = (m32 - m23) / s;
  3839. this.y = (m13 - m31) / s;
  3840. this.z = (m21 - m12) / s;
  3841. this.w = Math.acos((m11 + m22 + m33 - 1) / 2);
  3842. return this;
  3843. },
  3844. min: function (v) {
  3845. this.x = Math.min(this.x, v.x);
  3846. this.y = Math.min(this.y, v.y);
  3847. this.z = Math.min(this.z, v.z);
  3848. this.w = Math.min(this.w, v.w);
  3849. return this;
  3850. },
  3851. max: function (v) {
  3852. this.x = Math.max(this.x, v.x);
  3853. this.y = Math.max(this.y, v.y);
  3854. this.z = Math.max(this.z, v.z);
  3855. this.w = Math.max(this.w, v.w);
  3856. return this;
  3857. },
  3858. clamp: function (min, max) {
  3859. // assumes min < max, componentwise
  3860. this.x = Math.max(min.x, Math.min(max.x, this.x));
  3861. this.y = Math.max(min.y, Math.min(max.y, this.y));
  3862. this.z = Math.max(min.z, Math.min(max.z, this.z));
  3863. this.w = Math.max(min.w, Math.min(max.w, this.w));
  3864. return this;
  3865. },
  3866. clampScalar: function (minVal, maxVal) {
  3867. this.x = Math.max(minVal, Math.min(maxVal, this.x));
  3868. this.y = Math.max(minVal, Math.min(maxVal, this.y));
  3869. this.z = Math.max(minVal, Math.min(maxVal, this.z));
  3870. this.w = Math.max(minVal, Math.min(maxVal, this.w));
  3871. return this;
  3872. },
  3873. clampLength: function (min, max) {
  3874. var length = this.length();
  3875. return this.divideScalar(length || 1).multiplyScalar(Math.max(min, Math.min(max, length)));
  3876. },
  3877. floor: function () {
  3878. this.x = Math.floor(this.x);
  3879. this.y = Math.floor(this.y);
  3880. this.z = Math.floor(this.z);
  3881. this.w = Math.floor(this.w);
  3882. return this;
  3883. },
  3884. ceil: function () {
  3885. this.x = Math.ceil(this.x);
  3886. this.y = Math.ceil(this.y);
  3887. this.z = Math.ceil(this.z);
  3888. this.w = Math.ceil(this.w);
  3889. return this;
  3890. },
  3891. round: function () {
  3892. this.x = Math.round(this.x);
  3893. this.y = Math.round(this.y);
  3894. this.z = Math.round(this.z);
  3895. this.w = Math.round(this.w);
  3896. return this;
  3897. },
  3898. roundToZero: function () {
  3899. this.x = this.x < 0 ? Math.ceil(this.x) : Math.floor(this.x);
  3900. this.y = this.y < 0 ? Math.ceil(this.y) : Math.floor(this.y);
  3901. this.z = this.z < 0 ? Math.ceil(this.z) : Math.floor(this.z);
  3902. this.w = this.w < 0 ? Math.ceil(this.w) : Math.floor(this.w);
  3903. return this;
  3904. },
  3905. negate: function () {
  3906. this.x = -this.x;
  3907. this.y = -this.y;
  3908. this.z = -this.z;
  3909. this.w = -this.w;
  3910. return this;
  3911. },
  3912. dot: function (v) {
  3913. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  3914. },
  3915. lengthSq: function () {
  3916. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  3917. },
  3918. length: function () {
  3919. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  3920. },
  3921. manhattanLength: function () {
  3922. return Math.abs(this.x) + Math.abs(this.y) + Math.abs(this.z) + Math.abs(this.w);
  3923. },
  3924. normalize: function () {
  3925. return this.divideScalar(this.length() || 1);
  3926. },
  3927. setLength: function (length) {
  3928. return this.normalize().multiplyScalar(length);
  3929. },
  3930. lerp: function (v, alpha) {
  3931. this.x += (v.x - this.x) * alpha;
  3932. this.y += (v.y - this.y) * alpha;
  3933. this.z += (v.z - this.z) * alpha;
  3934. this.w += (v.w - this.w) * alpha;
  3935. return this;
  3936. },
  3937. lerpVectors: function (v1, v2, alpha) {
  3938. return this.subVectors(v2, v1).multiplyScalar(alpha).add(v1);
  3939. },
  3940. equals: function (v) {
  3941. return v.x === this.x && v.y === this.y && v.z === this.z && v.w === this.w;
  3942. },
  3943. fromArray: function (array, offset) {
  3944. if (offset === undefined) offset = 0;
  3945. this.x = array[offset];
  3946. this.y = array[offset + 1];
  3947. this.z = array[offset + 2];
  3948. this.w = array[offset + 3];
  3949. return this;
  3950. },
  3951. toArray: function (array, offset) {
  3952. if (array === undefined) array = [];
  3953. if (offset === undefined) offset = 0;
  3954. array[offset] = this.x;
  3955. array[offset + 1] = this.y;
  3956. array[offset + 2] = this.z;
  3957. array[offset + 3] = this.w;
  3958. return array;
  3959. },
  3960. fromBufferAttribute: function (attribute, index, offset) {
  3961. if (offset !== undefined) {
  3962. console.warn('THREE.Vector4: offset has been removed from .fromBufferAttribute().');
  3963. }
  3964. this.x = attribute.getX(index);
  3965. this.y = attribute.getY(index);
  3966. this.z = attribute.getZ(index);
  3967. this.w = attribute.getW(index);
  3968. return this;
  3969. }
  3970. });
  3971. /**
  3972. * @author szimek / https://github.com/szimek/
  3973. * @author alteredq / http://alteredqualia.com/
  3974. * @author Marius Kintel / https://github.com/kintel
  3975. */
  3976. /*
  3977. In options, we can specify:
  3978. * Texture parameters for an auto-generated target texture
  3979. * depthBuffer/stencilBuffer: Booleans to indicate if we should generate these buffers
  3980. */
  3981. function WebGLRenderTarget(width, height, options) {
  3982. this.width = width;
  3983. this.height = height;
  3984. this.scissor = new Vector4(0, 0, width, height);
  3985. this.scissorTest = false;
  3986. this.viewport = new Vector4(0, 0, width, height);
  3987. options = options || {};
  3988. this.texture = new Texture(undefined, undefined, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding);
  3989. this.texture.image = {};
  3990. this.texture.image.width = width;
  3991. this.texture.image.height = height;
  3992. this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false;
  3993. this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter;
  3994. this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
  3995. this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : true;
  3996. this.depthTexture = options.depthTexture !== undefined ? options.depthTexture : null;
  3997. }
  3998. WebGLRenderTarget.prototype = Object.assign(Object.create(EventDispatcher.prototype), {
  3999. constructor: WebGLRenderTarget,
  4000. isWebGLRenderTarget: true,
  4001. setSize: function (width, height) {
  4002. if (this.width !== width || this.height !== height) {
  4003. this.width = width;
  4004. this.height = height;
  4005. this.texture.image.width = width;
  4006. this.texture.image.height = height;
  4007. this.dispose();
  4008. }
  4009. this.viewport.set(0, 0, width, height);
  4010. this.scissor.set(0, 0, width, height);
  4011. },
  4012. clone: function () {
  4013. return new this.constructor().copy(this);
  4014. },
  4015. copy: function (source) {
  4016. this.width = source.width;
  4017. this.height = source.height;
  4018. this.viewport.copy(source.viewport);
  4019. this.texture = source.texture.clone();
  4020. this.depthBuffer = source.depthBuffer;
  4021. this.stencilBuffer = source.stencilBuffer;
  4022. this.depthTexture = source.depthTexture;
  4023. return this;
  4024. },
  4025. dispose: function () {
  4026. this.dispatchEvent({
  4027. type: 'dispose'
  4028. });
  4029. }
  4030. });
  4031. /**
  4032. * @author Mugen87 / https://github.com/Mugen87
  4033. * @author Matt DesLauriers / @mattdesl
  4034. */
  4035. function WebGLMultisampleRenderTarget(width, height, options) {
  4036. WebGLRenderTarget.call(this, width, height, options);
  4037. this.samples = 4;
  4038. }
  4039. WebGLMultisampleRenderTarget.prototype = Object.assign(Object.create(WebGLRenderTarget.prototype), {
  4040. constructor: WebGLMultisampleRenderTarget,
  4041. isWebGLMultisampleRenderTarget: true,
  4042. copy: function (source) {
  4043. WebGLRenderTarget.prototype.copy.call(this, source);
  4044. this.samples = source.samples;
  4045. return this;
  4046. }
  4047. });
  4048. var _v1 = new Vector3();
  4049. var _m1 = new Matrix4();
  4050. var _zero = new Vector3(0, 0, 0);
  4051. var _one = new Vector3(1, 1, 1);
  4052. var _x = new Vector3();
  4053. var _y = new Vector3();
  4054. var _z = new Vector3();
  4055. /**
  4056. * @author mrdoob / http://mrdoob.com/
  4057. * @author supereggbert / http://www.paulbrunt.co.uk/
  4058. * @author philogb / http://blog.thejit.org/
  4059. * @author jordi_ros / http://plattsoft.com
  4060. * @author D1plo1d / http://github.com/D1plo1d
  4061. * @author alteredq / http://alteredqualia.com/
  4062. * @author mikael emtinger / http://gomo.se/
  4063. * @author timknip / http://www.floorplanner.com/
  4064. * @author bhouston / http://clara.io
  4065. * @author WestLangley / http://github.com/WestLangley
  4066. */
  4067. function Matrix4() {
  4068. this.elements = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];
  4069. if (arguments.length > 0) {
  4070. console.error('THREE.Matrix4: the constructor no longer reads arguments. use .set() instead.');
  4071. }
  4072. }
  4073. Object.assign(Matrix4.prototype, {
  4074. isMatrix4: true,
  4075. set: function (n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44) {
  4076. var te = this.elements;
  4077. te[0] = n11;
  4078. te[4] = n12;
  4079. te[8] = n13;
  4080. te[12] = n14;
  4081. te[1] = n21;
  4082. te[5] = n22;
  4083. te[9] = n23;
  4084. te[13] = n24;
  4085. te[2] = n31;
  4086. te[6] = n32;
  4087. te[10] = n33;
  4088. te[14] = n34;
  4089. te[3] = n41;
  4090. te[7] = n42;
  4091. te[11] = n43;
  4092. te[15] = n44;
  4093. return this;
  4094. },
  4095. identity: function () {
  4096. this.set(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1);
  4097. return this;
  4098. },
  4099. clone: function () {
  4100. return new Matrix4().fromArray(this.elements);
  4101. },
  4102. copy: function (m) {
  4103. var te = this.elements;
  4104. var me = m.elements;
  4105. te[0] = me[0];
  4106. te[1] = me[1];
  4107. te[2] = me[2];
  4108. te[3] = me[3];
  4109. te[4] = me[4];
  4110. te[5] = me[5];
  4111. te[6] = me[6];
  4112. te[7] = me[7];
  4113. te[8] = me[8];
  4114. te[9] = me[9];
  4115. te[10] = me[10];
  4116. te[11] = me[11];
  4117. te[12] = me[12];
  4118. te[13] = me[13];
  4119. te[14] = me[14];
  4120. te[15] = me[15];
  4121. return this;
  4122. },
  4123. copyPosition: function (m) {
  4124. var te = this.elements,
  4125. me = m.elements;
  4126. te[12] = me[12];
  4127. te[13] = me[13];
  4128. te[14] = me[14];
  4129. return this;
  4130. },
  4131. extractBasis: function (xAxis, yAxis, zAxis) {
  4132. xAxis.setFromMatrixColumn(this, 0);
  4133. yAxis.setFromMatrixColumn(this, 1);
  4134. zAxis.setFromMatrixColumn(this, 2);
  4135. return this;
  4136. },
  4137. makeBasis: function (xAxis, yAxis, zAxis) {
  4138. 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);
  4139. return this;
  4140. },
  4141. extractRotation: function (m) {
  4142. // this method does not support reflection matrices
  4143. var te = this.elements;
  4144. var me = m.elements;
  4145. var scaleX = 1 / _v1.setFromMatrixColumn(m, 0).length();
  4146. var scaleY = 1 / _v1.setFromMatrixColumn(m, 1).length();
  4147. var scaleZ = 1 / _v1.setFromMatrixColumn(m, 2).length();
  4148. te[0] = me[0] * scaleX;
  4149. te[1] = me[1] * scaleX;
  4150. te[2] = me[2] * scaleX;
  4151. te[3] = 0;
  4152. te[4] = me[4] * scaleY;
  4153. te[5] = me[5] * scaleY;
  4154. te[6] = me[6] * scaleY;
  4155. te[7] = 0;
  4156. te[8] = me[8] * scaleZ;
  4157. te[9] = me[9] * scaleZ;
  4158. te[10] = me[10] * scaleZ;
  4159. te[11] = 0;
  4160. te[12] = 0;
  4161. te[13] = 0;
  4162. te[14] = 0;
  4163. te[15] = 1;
  4164. return this;
  4165. },
  4166. makeRotationFromEuler: function (euler) {
  4167. if (!(euler && euler.isEuler)) {
  4168. console.error('THREE.Matrix4: .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order.');
  4169. }
  4170. var te = this.elements;
  4171. var x = euler.x,
  4172. y = euler.y,
  4173. z = euler.z;
  4174. var a = Math.cos(x),
  4175. b = Math.sin(x);
  4176. var c = Math.cos(y),
  4177. d = Math.sin(y);
  4178. var e = Math.cos(z),
  4179. f = Math.sin(z);
  4180. if (euler.order === 'XYZ') {
  4181. var ae = a * e,
  4182. af = a * f,
  4183. be = b * e,
  4184. bf = b * f;
  4185. te[0] = c * e;
  4186. te[4] = -c * f;
  4187. te[8] = d;
  4188. te[1] = af + be * d;
  4189. te[5] = ae - bf * d;
  4190. te[9] = -b * c;
  4191. te[2] = bf - ae * d;
  4192. te[6] = be + af * d;
  4193. te[10] = a * c;
  4194. } else if (euler.order === 'YXZ') {
  4195. var ce = c * e,
  4196. cf = c * f,
  4197. de = d * e,
  4198. df = d * f;
  4199. te[0] = ce + df * b;
  4200. te[4] = de * b - cf;
  4201. te[8] = a * d;
  4202. te[1] = a * f;
  4203. te[5] = a * e;
  4204. te[9] = -b;
  4205. te[2] = cf * b - de;
  4206. te[6] = df + ce * b;
  4207. te[10] = a * c;
  4208. } else if (euler.order === 'ZXY') {
  4209. var ce = c * e,
  4210. cf = c * f,
  4211. de = d * e,
  4212. df = d * f;
  4213. te[0] = ce - df * b;
  4214. te[4] = -a * f;
  4215. te[8] = de + cf * b;
  4216. te[1] = cf + de * b;
  4217. te[5] = a * e;
  4218. te[9] = df - ce * b;
  4219. te[2] = -a * d;
  4220. te[6] = b;
  4221. te[10] = a * c;
  4222. } else if (euler.order === 'ZYX') {
  4223. var ae = a * e,
  4224. af = a * f,
  4225. be = b * e,
  4226. bf = b * f;
  4227. te[0] = c * e;
  4228. te[4] = be * d - af;
  4229. te[8] = ae * d + bf;
  4230. te[1] = c * f;
  4231. te[5] = bf * d + ae;
  4232. te[9] = af * d - be;
  4233. te[2] = -d;
  4234. te[6] = b * c;
  4235. te[10] = a * c;
  4236. } else if (euler.order === 'YZX') {
  4237. var ac = a * c,
  4238. ad = a * d,
  4239. bc = b * c,
  4240. bd = b * d;
  4241. te[0] = c * e;
  4242. te[4] = bd - ac * f;
  4243. te[8] = bc * f + ad;
  4244. te[1] = f;
  4245. te[5] = a * e;
  4246. te[9] = -b * e;
  4247. te[2] = -d * e;
  4248. te[6] = ad * f + bc;
  4249. te[10] = ac - bd * f;
  4250. } else if (euler.order === 'XZY') {
  4251. var ac = a * c,
  4252. ad = a * d,
  4253. bc = b * c,
  4254. bd = b * d;
  4255. te[0] = c * e;
  4256. te[4] = -f;
  4257. te[8] = d * e;
  4258. te[1] = ac * f + bd;
  4259. te[5] = a * e;
  4260. te[9] = ad * f - bc;
  4261. te[2] = bc * f - ad;
  4262. te[6] = b * e;
  4263. te[10] = bd * f + ac;
  4264. } // bottom row
  4265. te[3] = 0;
  4266. te[7] = 0;
  4267. te[11] = 0; // last column
  4268. te[12] = 0;
  4269. te[13] = 0;
  4270. te[14] = 0;
  4271. te[15] = 1;
  4272. return this;
  4273. },
  4274. makeRotationFromQuaternion: function (q) {
  4275. return this.compose(_zero, q, _one);
  4276. },
  4277. lookAt: function (eye, target, up) {
  4278. var te = this.elements;
  4279. _z.subVectors(eye, target);
  4280. if (_z.lengthSq() === 0) {
  4281. // eye and target are in the same position
  4282. _z.z = 1;
  4283. }
  4284. _z.normalize();
  4285. _x.crossVectors(up, _z);
  4286. if (_x.lengthSq() === 0) {
  4287. // up and z are parallel
  4288. if (Math.abs(up.z) === 1) {
  4289. _z.x += 0.0001;
  4290. } else {
  4291. _z.z += 0.0001;
  4292. }
  4293. _z.normalize();
  4294. _x.crossVectors(up, _z);
  4295. }
  4296. _x.normalize();
  4297. _y.crossVectors(_z, _x);
  4298. te[0] = _x.x;
  4299. te[4] = _y.x;
  4300. te[8] = _z.x;
  4301. te[1] = _x.y;
  4302. te[5] = _y.y;
  4303. te[9] = _z.y;
  4304. te[2] = _x.z;
  4305. te[6] = _y.z;
  4306. te[10] = _z.z;
  4307. return this;
  4308. },
  4309. multiply: function (m, n) {
  4310. if (n !== undefined) {
  4311. console.warn('THREE.Matrix4: .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead.');
  4312. return this.multiplyMatrices(m, n);
  4313. }
  4314. return this.multiplyMatrices(this, m);
  4315. },
  4316. premultiply: function (m) {
  4317. return this.multiplyMatrices(m, this);
  4318. },
  4319. multiplyMatrices: function (a, b) {
  4320. var ae = a.elements;
  4321. var be = b.elements;
  4322. var te = this.elements;
  4323. var a11 = ae[0],
  4324. a12 = ae[4],
  4325. a13 = ae[8],
  4326. a14 = ae[12];
  4327. var a21 = ae[1],
  4328. a22 = ae[5],
  4329. a23 = ae[9],
  4330. a24 = ae[13];
  4331. var a31 = ae[2],
  4332. a32 = ae[6],
  4333. a33 = ae[10],
  4334. a34 = ae[14];
  4335. var a41 = ae[3],
  4336. a42 = ae[7],
  4337. a43 = ae[11],
  4338. a44 = ae[15];
  4339. var b11 = be[0],
  4340. b12 = be[4],
  4341. b13 = be[8],
  4342. b14 = be[12];
  4343. var b21 = be[1],
  4344. b22 = be[5],
  4345. b23 = be[9],
  4346. b24 = be[13];
  4347. var b31 = be[2],
  4348. b32 = be[6],
  4349. b33 = be[10],
  4350. b34 = be[14];
  4351. var b41 = be[3],
  4352. b42 = be[7],
  4353. b43 = be[11],
  4354. b44 = be[15];
  4355. te[0] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  4356. te[4] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  4357. te[8] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  4358. te[12] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  4359. te[1] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  4360. te[5] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  4361. te[9] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  4362. te[13] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  4363. te[2] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  4364. te[6] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  4365. te[10] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  4366. te[14] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  4367. te[3] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  4368. te[7] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  4369. te[11] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  4370. te[15] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  4371. return this;
  4372. },
  4373. multiplyScalar: function (s) {
  4374. var te = this.elements;
  4375. te[0] *= s;
  4376. te[4] *= s;
  4377. te[8] *= s;
  4378. te[12] *= s;
  4379. te[1] *= s;
  4380. te[5] *= s;
  4381. te[9] *= s;
  4382. te[13] *= s;
  4383. te[2] *= s;
  4384. te[6] *= s;
  4385. te[10] *= s;
  4386. te[14] *= s;
  4387. te[3] *= s;
  4388. te[7] *= s;
  4389. te[11] *= s;
  4390. te[15] *= s;
  4391. return this;
  4392. },
  4393. applyToBufferAttribute: function (attribute) {
  4394. for (var i = 0, l = attribute.count; i < l; i++) {
  4395. _v1.x = attribute.getX(i);
  4396. _v1.y = attribute.getY(i);
  4397. _v1.z = attribute.getZ(i);
  4398. _v1.applyMatrix4(this);
  4399. attribute.setXYZ(i, _v1.x, _v1.y, _v1.z);
  4400. }
  4401. return attribute;
  4402. },
  4403. determinant: function () {
  4404. var te = this.elements;
  4405. var n11 = te[0],
  4406. n12 = te[4],
  4407. n13 = te[8],
  4408. n14 = te[12];
  4409. var n21 = te[1],
  4410. n22 = te[5],
  4411. n23 = te[9],
  4412. n24 = te[13];
  4413. var n31 = te[2],
  4414. n32 = te[6],
  4415. n33 = te[10],
  4416. n34 = te[14];
  4417. var n41 = te[3],
  4418. n42 = te[7],
  4419. n43 = te[11],
  4420. n44 = te[15]; //TODO: make this more efficient
  4421. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  4422. 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);
  4423. },
  4424. transpose: function () {
  4425. var te = this.elements;
  4426. var tmp;
  4427. tmp = te[1];
  4428. te[1] = te[4];
  4429. te[4] = tmp;
  4430. tmp = te[2];
  4431. te[2] = te[8];
  4432. te[8] = tmp;
  4433. tmp = te[6];
  4434. te[6] = te[9];
  4435. te[9] = tmp;
  4436. tmp = te[3];
  4437. te[3] = te[12];
  4438. te[12] = tmp;
  4439. tmp = te[7];
  4440. te[7] = te[13];
  4441. te[13] = tmp;
  4442. tmp = te[11];
  4443. te[11] = te[14];
  4444. te[14] = tmp;
  4445. return this;
  4446. },
  4447. setPosition: function (x, y, z) {
  4448. var te = this.elements;
  4449. if (x.isVector3) {
  4450. te[12] = x.x;
  4451. te[13] = x.y;
  4452. te[14] = x.z;
  4453. } else {
  4454. te[12] = x;
  4455. te[13] = y;
  4456. te[14] = z;
  4457. }
  4458. return this;
  4459. },
  4460. getInverse: function (m, throwOnDegenerate) {
  4461. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  4462. var te = this.elements,
  4463. me = m.elements,
  4464. n11 = me[0],
  4465. n21 = me[1],
  4466. n31 = me[2],
  4467. n41 = me[3],
  4468. n12 = me[4],
  4469. n22 = me[5],
  4470. n32 = me[6],
  4471. n42 = me[7],
  4472. n13 = me[8],
  4473. n23 = me[9],
  4474. n33 = me[10],
  4475. n43 = me[11],
  4476. n14 = me[12],
  4477. n24 = me[13],
  4478. n34 = me[14],
  4479. n44 = me[15],
  4480. t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44,
  4481. t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44,
  4482. t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44,
  4483. t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34;
  4484. var det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14;
  4485. if (det === 0) {
  4486. var msg = "THREE.Matrix4: .getInverse() can't invert matrix, determinant is 0";
  4487. if (throwOnDegenerate === true) {
  4488. throw new Error(msg);
  4489. } else {
  4490. console.warn(msg);
  4491. }
  4492. return this.identity();
  4493. }
  4494. var detInv = 1 / det;
  4495. te[0] = t11 * detInv;
  4496. te[1] = (n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44) * detInv;
  4497. te[2] = (n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44) * detInv;
  4498. te[3] = (n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43) * detInv;
  4499. te[4] = t12 * detInv;
  4500. te[5] = (n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44) * detInv;
  4501. te[6] = (n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44) * detInv;
  4502. te[7] = (n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43) * detInv;
  4503. te[8] = t13 * detInv;
  4504. te[9] = (n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44) * detInv;
  4505. te[10] = (n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44) * detInv;
  4506. te[11] = (n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43) * detInv;
  4507. te[12] = t14 * detInv;
  4508. te[13] = (n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34) * detInv;
  4509. te[14] = (n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34) * detInv;
  4510. te[15] = (n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33) * detInv;
  4511. return this;
  4512. },
  4513. scale: function (v) {
  4514. var te = this.elements;
  4515. var x = v.x,
  4516. y = v.y,
  4517. z = v.z;
  4518. te[0] *= x;
  4519. te[4] *= y;
  4520. te[8] *= z;
  4521. te[1] *= x;
  4522. te[5] *= y;
  4523. te[9] *= z;
  4524. te[2] *= x;
  4525. te[6] *= y;
  4526. te[10] *= z;
  4527. te[3] *= x;
  4528. te[7] *= y;
  4529. te[11] *= z;
  4530. return this;
  4531. },
  4532. getMaxScaleOnAxis: function () {
  4533. var te = this.elements;
  4534. var scaleXSq = te[0] * te[0] + te[1] * te[1] + te[2] * te[2];
  4535. var scaleYSq = te[4] * te[4] + te[5] * te[5] + te[6] * te[6];
  4536. var scaleZSq = te[8] * te[8] + te[9] * te[9] + te[10] * te[10];
  4537. return Math.sqrt(Math.max(scaleXSq, scaleYSq, scaleZSq));
  4538. },
  4539. makeTranslation: function (x, y, z) {
  4540. this.set(1, 0, 0, x, 0, 1, 0, y, 0, 0, 1, z, 0, 0, 0, 1);
  4541. return this;
  4542. },
  4543. makeRotationX: function (theta) {
  4544. var c = Math.cos(theta),
  4545. s = Math.sin(theta);
  4546. this.set(1, 0, 0, 0, 0, c, -s, 0, 0, s, c, 0, 0, 0, 0, 1);
  4547. return this;
  4548. },
  4549. makeRotationY: function (theta) {
  4550. var c = Math.cos(theta),
  4551. s = Math.sin(theta);
  4552. this.set(c, 0, s, 0, 0, 1, 0, 0, -s, 0, c, 0, 0, 0, 0, 1);
  4553. return this;
  4554. },
  4555. makeRotationZ: function (theta) {
  4556. var c = Math.cos(theta),
  4557. s = Math.sin(theta);
  4558. this.set(c, -s, 0, 0, s, c, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1);
  4559. return this;
  4560. },
  4561. makeRotationAxis: function (axis, angle) {
  4562. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  4563. var c = Math.cos(angle);
  4564. var s = Math.sin(angle);
  4565. var t = 1 - c;
  4566. var x = axis.x,
  4567. y = axis.y,
  4568. z = axis.z;
  4569. var tx = t * x,
  4570. ty = t * y;
  4571. 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);
  4572. return this;
  4573. },
  4574. makeScale: function (x, y, z) {
  4575. this.set(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1);
  4576. return this;
  4577. },
  4578. makeShear: function (x, y, z) {
  4579. this.set(1, y, z, 0, x, 1, z, 0, x, y, 1, 0, 0, 0, 0, 1);
  4580. return this;
  4581. },
  4582. compose: function (position, quaternion, scale) {
  4583. var te = this.elements;
  4584. var x = quaternion._x,
  4585. y = quaternion._y,
  4586. z = quaternion._z,
  4587. w = quaternion._w;
  4588. var x2 = x + x,
  4589. y2 = y + y,
  4590. z2 = z + z;
  4591. var xx = x * x2,
  4592. xy = x * y2,
  4593. xz = x * z2;
  4594. var yy = y * y2,
  4595. yz = y * z2,
  4596. zz = z * z2;
  4597. var wx = w * x2,
  4598. wy = w * y2,
  4599. wz = w * z2;
  4600. var sx = scale.x,
  4601. sy = scale.y,
  4602. sz = scale.z;
  4603. te[0] = (1 - (yy + zz)) * sx;
  4604. te[1] = (xy + wz) * sx;
  4605. te[2] = (xz - wy) * sx;
  4606. te[3] = 0;
  4607. te[4] = (xy - wz) * sy;
  4608. te[5] = (1 - (xx + zz)) * sy;
  4609. te[6] = (yz + wx) * sy;
  4610. te[7] = 0;
  4611. te[8] = (xz + wy) * sz;
  4612. te[9] = (yz - wx) * sz;
  4613. te[10] = (1 - (xx + yy)) * sz;
  4614. te[11] = 0;
  4615. te[12] = position.x;
  4616. te[13] = position.y;
  4617. te[14] = position.z;
  4618. te[15] = 1;
  4619. return this;
  4620. },
  4621. decompose: function (position, quaternion, scale) {
  4622. var te = this.elements;
  4623. var sx = _v1.set(te[0], te[1], te[2]).length();
  4624. var sy = _v1.set(te[4], te[5], te[6]).length();
  4625. var sz = _v1.set(te[8], te[9], te[10]).length(); // if determine is negative, we need to invert one scale
  4626. var det = this.determinant();
  4627. if (det < 0) sx = -sx;
  4628. position.x = te[12];
  4629. position.y = te[13];
  4630. position.z = te[14]; // scale the rotation part
  4631. _m1.copy(this);
  4632. var invSX = 1 / sx;
  4633. var invSY = 1 / sy;
  4634. var invSZ = 1 / sz;
  4635. _m1.elements[0] *= invSX;
  4636. _m1.elements[1] *= invSX;
  4637. _m1.elements[2] *= invSX;
  4638. _m1.elements[4] *= invSY;
  4639. _m1.elements[5] *= invSY;
  4640. _m1.elements[6] *= invSY;
  4641. _m1.elements[8] *= invSZ;
  4642. _m1.elements[9] *= invSZ;
  4643. _m1.elements[10] *= invSZ;
  4644. quaternion.setFromRotationMatrix(_m1);
  4645. scale.x = sx;
  4646. scale.y = sy;
  4647. scale.z = sz;
  4648. return this;
  4649. },
  4650. makePerspective: function (left, right, top, bottom, near, far) {
  4651. if (far === undefined) {
  4652. console.warn('THREE.Matrix4: .makePerspective() has been redefined and has a new signature. Please check the docs.');
  4653. }
  4654. var te = this.elements;
  4655. var x = 2 * near / (right - left);
  4656. var y = 2 * near / (top - bottom);
  4657. var a = (right + left) / (right - left);
  4658. var b = (top + bottom) / (top - bottom);
  4659. var c = -(far + near) / (far - near);
  4660. var d = -2 * far * near / (far - near);
  4661. te[0] = x;
  4662. te[4] = 0;
  4663. te[8] = a;
  4664. te[12] = 0;
  4665. te[1] = 0;
  4666. te[5] = y;
  4667. te[9] = b;
  4668. te[13] = 0;
  4669. te[2] = 0;
  4670. te[6] = 0;
  4671. te[10] = c;
  4672. te[14] = d;
  4673. te[3] = 0;
  4674. te[7] = 0;
  4675. te[11] = -1;
  4676. te[15] = 0;
  4677. return this;
  4678. },
  4679. makeOrthographic: function (left, right, top, bottom, near, far) {
  4680. var te = this.elements;
  4681. var w = 1.0 / (right - left);
  4682. var h = 1.0 / (top - bottom);
  4683. var p = 1.0 / (far - near);
  4684. var x = (right + left) * w;
  4685. var y = (top + bottom) * h;
  4686. var z = (far + near) * p;
  4687. te[0] = 2 * w;
  4688. te[4] = 0;
  4689. te[8] = 0;
  4690. te[12] = -x;
  4691. te[1] = 0;
  4692. te[5] = 2 * h;
  4693. te[9] = 0;
  4694. te[13] = -y;
  4695. te[2] = 0;
  4696. te[6] = 0;
  4697. te[10] = -2 * p;
  4698. te[14] = -z;
  4699. te[3] = 0;
  4700. te[7] = 0;
  4701. te[11] = 0;
  4702. te[15] = 1;
  4703. return this;
  4704. },
  4705. equals: function (matrix) {
  4706. var te = this.elements;
  4707. var me = matrix.elements;
  4708. for (var i = 0; i < 16; i++) {
  4709. if (te[i] !== me[i]) return false;
  4710. }
  4711. return true;
  4712. },
  4713. fromArray: function (array, offset) {
  4714. if (offset === undefined) offset = 0;
  4715. for (var i = 0; i < 16; i++) {
  4716. this.elements[i] = array[i + offset];
  4717. }
  4718. return this;
  4719. },
  4720. toArray: function (array, offset) {
  4721. if (array === undefined) array = [];
  4722. if (offset === undefined) offset = 0;
  4723. var te = this.elements;
  4724. array[offset] = te[0];
  4725. array[offset + 1] = te[1];
  4726. array[offset + 2] = te[2];
  4727. array[offset + 3] = te[3];
  4728. array[offset + 4] = te[4];
  4729. array[offset + 5] = te[5];
  4730. array[offset + 6] = te[6];
  4731. array[offset + 7] = te[7];
  4732. array[offset + 8] = te[8];
  4733. array[offset + 9] = te[9];
  4734. array[offset + 10] = te[10];
  4735. array[offset + 11] = te[11];
  4736. array[offset + 12] = te[12];
  4737. array[offset + 13] = te[13];
  4738. array[offset + 14] = te[14];
  4739. array[offset + 15] = te[15];
  4740. return array;
  4741. }
  4742. });
  4743. /**
  4744. * @author mrdoob / http://mrdoob.com/
  4745. * @author WestLangley / http://github.com/WestLangley
  4746. * @author bhouston / http://clara.io
  4747. */
  4748. var _matrix = new Matrix4();
  4749. var _quaternion$1 = new Quaternion();
  4750. function Euler(x, y, z, order) {
  4751. this._x = x || 0;
  4752. this._y = y || 0;
  4753. this._z = z || 0;
  4754. this._order = order || Euler.DefaultOrder;
  4755. }
  4756. Euler.RotationOrders = ['XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX'];
  4757. Euler.DefaultOrder = 'XYZ';
  4758. Object.defineProperties(Euler.prototype, {
  4759. x: {
  4760. get: function () {
  4761. return this._x;
  4762. },
  4763. set: function (value) {
  4764. this._x = value;
  4765. this._onChangeCallback();
  4766. }
  4767. },
  4768. y: {
  4769. get: function () {
  4770. return this._y;
  4771. },
  4772. set: function (value) {
  4773. this._y = value;
  4774. this._onChangeCallback();
  4775. }
  4776. },
  4777. z: {
  4778. get: function () {
  4779. return this._z;
  4780. },
  4781. set: function (value) {
  4782. this._z = value;
  4783. this._onChangeCallback();
  4784. }
  4785. },
  4786. order: {
  4787. get: function () {
  4788. return this._order;
  4789. },
  4790. set: function (value) {
  4791. this._order = value;
  4792. this._onChangeCallback();
  4793. }
  4794. }
  4795. });
  4796. Object.assign(Euler.prototype, {
  4797. isEuler: true,
  4798. set: function (x, y, z, order) {
  4799. this._x = x;
  4800. this._y = y;
  4801. this._z = z;
  4802. this._order = order || this._order;
  4803. this._onChangeCallback();
  4804. return this;
  4805. },
  4806. clone: function () {
  4807. return new this.constructor(this._x, this._y, this._z, this._order);
  4808. },
  4809. copy: function (euler) {
  4810. this._x = euler._x;
  4811. this._y = euler._y;
  4812. this._z = euler._z;
  4813. this._order = euler._order;
  4814. this._onChangeCallback();
  4815. return this;
  4816. },
  4817. setFromRotationMatrix: function (m, order, update) {
  4818. var clamp = _Math.clamp; // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  4819. var te = m.elements;
  4820. var m11 = te[0],
  4821. m12 = te[4],
  4822. m13 = te[8];
  4823. var m21 = te[1],
  4824. m22 = te[5],
  4825. m23 = te[9];
  4826. var m31 = te[2],
  4827. m32 = te[6],
  4828. m33 = te[10];
  4829. order = order || this._order;
  4830. if (order === 'XYZ') {
  4831. this._y = Math.asin(clamp(m13, -1, 1));
  4832. if (Math.abs(m13) < 0.9999999) {
  4833. this._x = Math.atan2(-m23, m33);
  4834. this._z = Math.atan2(-m12, m11);
  4835. } else {
  4836. this._x = Math.atan2(m32, m22);
  4837. this._z = 0;
  4838. }
  4839. } else if (order === 'YXZ') {
  4840. this._x = Math.asin(-clamp(m23, -1, 1));
  4841. if (Math.abs(m23) < 0.9999999) {
  4842. this._y = Math.atan2(m13, m33);
  4843. this._z = Math.atan2(m21, m22);
  4844. } else {
  4845. this._y = Math.atan2(-m31, m11);
  4846. this._z = 0;
  4847. }
  4848. } else if (order === 'ZXY') {
  4849. this._x = Math.asin(clamp(m32, -1, 1));
  4850. if (Math.abs(m32) < 0.9999999) {
  4851. this._y = Math.atan2(-m31, m33);
  4852. this._z = Math.atan2(-m12, m22);
  4853. } else {
  4854. this._y = 0;
  4855. this._z = Math.atan2(m21, m11);
  4856. }
  4857. } else if (order === 'ZYX') {
  4858. this._y = Math.asin(-clamp(m31, -1, 1));
  4859. if (Math.abs(m31) < 0.9999999) {
  4860. this._x = Math.atan2(m32, m33);
  4861. this._z = Math.atan2(m21, m11);
  4862. } else {
  4863. this._x = 0;
  4864. this._z = Math.atan2(-m12, m22);
  4865. }
  4866. } else if (order === 'YZX') {
  4867. this._z = Math.asin(clamp(m21, -1, 1));
  4868. if (Math.abs(m21) < 0.9999999) {
  4869. this._x = Math.atan2(-m23, m22);
  4870. this._y = Math.atan2(-m31, m11);
  4871. } else {
  4872. this._x = 0;
  4873. this._y = Math.atan2(m13, m33);
  4874. }
  4875. } else if (order === 'XZY') {
  4876. this._z = Math.asin(-clamp(m12, -1, 1));
  4877. if (Math.abs(m12) < 0.9999999) {
  4878. this._x = Math.atan2(m32, m22);
  4879. this._y = Math.atan2(m13, m11);
  4880. } else {
  4881. this._x = Math.atan2(-m23, m33);
  4882. this._y = 0;
  4883. }
  4884. } else {
  4885. console.warn('THREE.Euler: .setFromRotationMatrix() given unsupported order: ' + order);
  4886. }
  4887. this._order = order;
  4888. if (update !== false) this._onChangeCallback();
  4889. return this;
  4890. },
  4891. setFromQuaternion: function (q, order, update) {
  4892. _matrix.makeRotationFromQuaternion(q);
  4893. return this.setFromRotationMatrix(_matrix, order, update);
  4894. },
  4895. setFromVector3: function (v, order) {
  4896. return this.set(v.x, v.y, v.z, order || this._order);
  4897. },
  4898. reorder: function (newOrder) {
  4899. // WARNING: this discards revolution information -bhouston
  4900. _quaternion$1.setFromEuler(this);
  4901. return this.setFromQuaternion(_quaternion$1, newOrder);
  4902. },
  4903. equals: function (euler) {
  4904. return euler._x === this._x && euler._y === this._y && euler._z === this._z && euler._order === this._order;
  4905. },
  4906. fromArray: function (array) {
  4907. this._x = array[0];
  4908. this._y = array[1];
  4909. this._z = array[2];
  4910. if (array[3] !== undefined) this._order = array[3];
  4911. this._onChangeCallback();
  4912. return this;
  4913. },
  4914. toArray: function (array, offset) {
  4915. if (array === undefined) array = [];
  4916. if (offset === undefined) offset = 0;
  4917. array[offset] = this._x;
  4918. array[offset + 1] = this._y;
  4919. array[offset + 2] = this._z;
  4920. array[offset + 3] = this._order;
  4921. return array;
  4922. },
  4923. toVector3: function (optionalResult) {
  4924. if (optionalResult) {
  4925. return optionalResult.set(this._x, this._y, this._z);
  4926. } else {
  4927. return new Vector3(this._x, this._y, this._z);
  4928. }
  4929. },
  4930. _onChange: function (callback) {
  4931. this._onChangeCallback = callback;
  4932. return this;
  4933. },
  4934. _onChangeCallback: function () {}
  4935. });
  4936. /**
  4937. * @author mrdoob / http://mrdoob.com/
  4938. */
  4939. function Layers() {
  4940. this.mask = 1 | 0;
  4941. }
  4942. Object.assign(Layers.prototype, {
  4943. set: function (channel) {
  4944. this.mask = 1 << channel | 0;
  4945. },
  4946. enable: function (channel) {
  4947. this.mask |= 1 << channel | 0;
  4948. },
  4949. enableAll: function () {
  4950. this.mask = 0xffffffff | 0;
  4951. },
  4952. toggle: function (channel) {
  4953. this.mask ^= 1 << channel | 0;
  4954. },
  4955. disable: function (channel) {
  4956. this.mask &= ~(1 << channel | 0);
  4957. },
  4958. disableAll: function () {
  4959. this.mask = 0;
  4960. },
  4961. test: function (layers) {
  4962. return (this.mask & layers.mask) !== 0;
  4963. }
  4964. });
  4965. var _object3DId = 0;
  4966. var _v1$1 = new Vector3();
  4967. var _q1 = new Quaternion();
  4968. var _m1$1 = new Matrix4();
  4969. var _target = new Vector3();
  4970. var _position = new Vector3();
  4971. var _scale = new Vector3();
  4972. var _quaternion$2 = new Quaternion();
  4973. var _xAxis = new Vector3(1, 0, 0);
  4974. var _yAxis = new Vector3(0, 1, 0);
  4975. var _zAxis = new Vector3(0, 0, 1);
  4976. var _addedEvent = {
  4977. type: 'added'
  4978. };
  4979. var _removedEvent = {
  4980. type: 'removed'
  4981. };
  4982. /**
  4983. * @author mrdoob / http://mrdoob.com/
  4984. * @author mikael emtinger / http://gomo.se/
  4985. * @author alteredq / http://alteredqualia.com/
  4986. * @author WestLangley / http://github.com/WestLangley
  4987. * @author elephantatwork / www.elephantatwork.ch
  4988. */
  4989. function Object3D() {
  4990. Object.defineProperty(this, 'id', {
  4991. value: _object3DId++
  4992. });
  4993. this.uuid = _Math.generateUUID();
  4994. this.name = '';
  4995. this.type = 'Object3D';
  4996. this.parent = null;
  4997. this.children = [];
  4998. this.up = Object3D.DefaultUp.clone();
  4999. var position = new Vector3();
  5000. var rotation = new Euler();
  5001. var quaternion = new Quaternion();
  5002. var scale = new Vector3(1, 1, 1);
  5003. function onRotationChange() {
  5004. quaternion.setFromEuler(rotation, false);
  5005. }
  5006. function onQuaternionChange() {
  5007. rotation.setFromQuaternion(quaternion, undefined, false);
  5008. }
  5009. rotation._onChange(onRotationChange);
  5010. quaternion._onChange(onQuaternionChange);
  5011. Object.defineProperties(this, {
  5012. position: {
  5013. configurable: true,
  5014. enumerable: true,
  5015. value: position
  5016. },
  5017. rotation: {
  5018. configurable: true,
  5019. enumerable: true,
  5020. value: rotation
  5021. },
  5022. quaternion: {
  5023. configurable: true,
  5024. enumerable: true,
  5025. value: quaternion
  5026. },
  5027. scale: {
  5028. configurable: true,
  5029. enumerable: true,
  5030. value: scale
  5031. },
  5032. modelViewMatrix: {
  5033. value: new Matrix4()
  5034. },
  5035. normalMatrix: {
  5036. value: new Matrix3()
  5037. }
  5038. });
  5039. this.matrix = new Matrix4();
  5040. this.matrixWorld = new Matrix4();
  5041. this.matrixAutoUpdate = Object3D.DefaultMatrixAutoUpdate;
  5042. this.matrixWorldNeedsUpdate = false;
  5043. this.layers = new Layers();
  5044. this.visible = true;
  5045. this.castShadow = false;
  5046. this.receiveShadow = false;
  5047. this.frustumCulled = true;
  5048. this.renderOrder = 0;
  5049. this.userData = {};
  5050. }
  5051. Object3D.DefaultUp = new Vector3(0, 1, 0);
  5052. Object3D.DefaultMatrixAutoUpdate = true;
  5053. Object3D.prototype = Object.assign(Object.create(EventDispatcher.prototype), {
  5054. constructor: Object3D,
  5055. isObject3D: true,
  5056. onBeforeRender: function () {},
  5057. onAfterRender: function () {},
  5058. applyMatrix: function (matrix) {
  5059. if (this.matrixAutoUpdate) this.updateMatrix();
  5060. this.matrix.premultiply(matrix);
  5061. this.matrix.decompose(this.position, this.quaternion, this.scale);
  5062. },
  5063. applyQuaternion: function (q) {
  5064. this.quaternion.premultiply(q);
  5065. return this;
  5066. },
  5067. setRotationFromAxisAngle: function (axis, angle) {
  5068. // assumes axis is normalized
  5069. this.quaternion.setFromAxisAngle(axis, angle);
  5070. },
  5071. setRotationFromEuler: function (euler) {
  5072. this.quaternion.setFromEuler(euler, true);
  5073. },
  5074. setRotationFromMatrix: function (m) {
  5075. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  5076. this.quaternion.setFromRotationMatrix(m);
  5077. },
  5078. setRotationFromQuaternion: function (q) {
  5079. // assumes q is normalized
  5080. this.quaternion.copy(q);
  5081. },
  5082. rotateOnAxis: function (axis, angle) {
  5083. // rotate object on axis in object space
  5084. // axis is assumed to be normalized
  5085. _q1.setFromAxisAngle(axis, angle);
  5086. this.quaternion.multiply(_q1);
  5087. return this;
  5088. },
  5089. rotateOnWorldAxis: function (axis, angle) {
  5090. // rotate object on axis in world space
  5091. // axis is assumed to be normalized
  5092. // method assumes no rotated parent
  5093. _q1.setFromAxisAngle(axis, angle);
  5094. this.quaternion.premultiply(_q1);
  5095. return this;
  5096. },
  5097. rotateX: function (angle) {
  5098. return this.rotateOnAxis(_xAxis, angle);
  5099. },
  5100. rotateY: function (angle) {
  5101. return this.rotateOnAxis(_yAxis, angle);
  5102. },
  5103. rotateZ: function (angle) {
  5104. return this.rotateOnAxis(_zAxis, angle);
  5105. },
  5106. translateOnAxis: function (axis, distance) {
  5107. // translate object by distance along axis in object space
  5108. // axis is assumed to be normalized
  5109. _v1$1.copy(axis).applyQuaternion(this.quaternion);
  5110. this.position.add(_v1$1.multiplyScalar(distance));
  5111. return this;
  5112. },
  5113. translateX: function (distance) {
  5114. return this.translateOnAxis(_xAxis, distance);
  5115. },
  5116. translateY: function (distance) {
  5117. return this.translateOnAxis(_yAxis, distance);
  5118. },
  5119. translateZ: function (distance) {
  5120. return this.translateOnAxis(_zAxis, distance);
  5121. },
  5122. localToWorld: function (vector) {
  5123. return vector.applyMatrix4(this.matrixWorld);
  5124. },
  5125. worldToLocal: function (vector) {
  5126. return vector.applyMatrix4(_m1$1.getInverse(this.matrixWorld));
  5127. },
  5128. lookAt: function (x, y, z) {
  5129. // This method does not support objects having non-uniformly-scaled parent(s)
  5130. if (x.isVector3) {
  5131. _target.copy(x);
  5132. } else {
  5133. _target.set(x, y, z);
  5134. }
  5135. var parent = this.parent;
  5136. this.updateWorldMatrix(true, false);
  5137. _position.setFromMatrixPosition(this.matrixWorld);
  5138. if (this.isCamera || this.isLight) {
  5139. _m1$1.lookAt(_position, _target, this.up);
  5140. } else {
  5141. _m1$1.lookAt(_target, _position, this.up);
  5142. }
  5143. this.quaternion.setFromRotationMatrix(_m1$1);
  5144. if (parent) {
  5145. _m1$1.extractRotation(parent.matrixWorld);
  5146. _q1.setFromRotationMatrix(_m1$1);
  5147. this.quaternion.premultiply(_q1.inverse());
  5148. }
  5149. },
  5150. add: function (object) {
  5151. if (arguments.length > 1) {
  5152. for (var i = 0; i < arguments.length; i++) {
  5153. this.add(arguments[i]);
  5154. }
  5155. return this;
  5156. }
  5157. if (object === this) {
  5158. console.error("THREE.Object3D.add: object can't be added as a child of itself.", object);
  5159. return this;
  5160. }
  5161. if (object && object.isObject3D) {
  5162. if (object.parent !== null) {
  5163. object.parent.remove(object);
  5164. }
  5165. object.parent = this;
  5166. this.children.push(object);
  5167. object.dispatchEvent(_addedEvent);
  5168. } else {
  5169. console.error("THREE.Object3D.add: object not an instance of THREE.Object3D.", object);
  5170. }
  5171. return this;
  5172. },
  5173. remove: function (object) {
  5174. if (arguments.length > 1) {
  5175. for (var i = 0; i < arguments.length; i++) {
  5176. this.remove(arguments[i]);
  5177. }
  5178. return this;
  5179. }
  5180. var index = this.children.indexOf(object);
  5181. if (index !== -1) {
  5182. object.parent = null;
  5183. this.children.splice(index, 1);
  5184. object.dispatchEvent(_removedEvent);
  5185. }
  5186. return this;
  5187. },
  5188. attach: function (object) {
  5189. // adds object as a child of this, while maintaining the object's world transform
  5190. this.updateWorldMatrix(true, false);
  5191. _m1$1.getInverse(this.matrixWorld);
  5192. if (object.parent !== null) {
  5193. object.parent.updateWorldMatrix(true, false);
  5194. _m1$1.multiply(object.parent.matrixWorld);
  5195. }
  5196. object.applyMatrix(_m1$1);
  5197. object.updateWorldMatrix(false, false);
  5198. this.add(object);
  5199. return this;
  5200. },
  5201. getObjectById: function (id) {
  5202. return this.getObjectByProperty('id', id);
  5203. },
  5204. getObjectByName: function (name) {
  5205. return this.getObjectByProperty('name', name);
  5206. },
  5207. getObjectByProperty: function (name, value) {
  5208. if (this[name] === value) return this;
  5209. for (var i = 0, l = this.children.length; i < l; i++) {
  5210. var child = this.children[i];
  5211. var object = child.getObjectByProperty(name, value);
  5212. if (object !== undefined) {
  5213. return object;
  5214. }
  5215. }
  5216. return undefined;
  5217. },
  5218. getWorldPosition: function (target) {
  5219. if (target === undefined) {
  5220. console.warn('THREE.Object3D: .getWorldPosition() target is now required');
  5221. target = new Vector3();
  5222. }
  5223. this.updateMatrixWorld(true);
  5224. return target.setFromMatrixPosition(this.matrixWorld);
  5225. },
  5226. getWorldQuaternion: function (target) {
  5227. if (target === undefined) {
  5228. console.warn('THREE.Object3D: .getWorldQuaternion() target is now required');
  5229. target = new Quaternion();
  5230. }
  5231. this.updateMatrixWorld(true);
  5232. this.matrixWorld.decompose(_position, target, _scale);
  5233. return target;
  5234. },
  5235. getWorldScale: function (target) {
  5236. if (target === undefined) {
  5237. console.warn('THREE.Object3D: .getWorldScale() target is now required');
  5238. target = new Vector3();
  5239. }
  5240. this.updateMatrixWorld(true);
  5241. this.matrixWorld.decompose(_position, _quaternion$2, target);
  5242. return target;
  5243. },
  5244. getWorldDirection: function (target) {
  5245. if (target === undefined) {
  5246. console.warn('THREE.Object3D: .getWorldDirection() target is now required');
  5247. target = new Vector3();
  5248. }
  5249. this.updateMatrixWorld(true);
  5250. var e = this.matrixWorld.elements;
  5251. return target.set(e[8], e[9], e[10]).normalize();
  5252. },
  5253. raycast: function () {},
  5254. traverse: function (callback) {
  5255. callback(this);
  5256. var children = this.children;
  5257. for (var i = 0, l = children.length; i < l; i++) {
  5258. children[i].traverse(callback);
  5259. }
  5260. },
  5261. traverseVisible: function (callback) {
  5262. if (this.visible === false) return;
  5263. callback(this);
  5264. var children = this.children;
  5265. for (var i = 0, l = children.length; i < l; i++) {
  5266. children[i].traverseVisible(callback);
  5267. }
  5268. },
  5269. traverseAncestors: function (callback) {
  5270. var parent = this.parent;
  5271. if (parent !== null) {
  5272. callback(parent);
  5273. parent.traverseAncestors(callback);
  5274. }
  5275. },
  5276. updateMatrix: function () {
  5277. this.matrix.compose(this.position, this.quaternion, this.scale);
  5278. this.matrixWorldNeedsUpdate = true;
  5279. },
  5280. updateMatrixWorld: function (force) {
  5281. if (this.matrixAutoUpdate) this.updateMatrix();
  5282. if (this.matrixWorldNeedsUpdate || force) {
  5283. if (this.parent === null) {
  5284. this.matrixWorld.copy(this.matrix);
  5285. } else {
  5286. this.matrixWorld.multiplyMatrices(this.parent.matrixWorld, this.matrix);
  5287. }
  5288. this.matrixWorldNeedsUpdate = false;
  5289. force = true;
  5290. } // update children
  5291. var children = this.children;
  5292. for (var i = 0, l = children.length; i < l; i++) {
  5293. children[i].updateMatrixWorld(force);
  5294. }
  5295. },
  5296. updateWorldMatrix: function (updateParents, updateChildren) {
  5297. var parent = this.parent;
  5298. if (updateParents === true && parent !== null) {
  5299. parent.updateWorldMatrix(true, false);
  5300. }
  5301. if (this.matrixAutoUpdate) this.updateMatrix();
  5302. if (this.parent === null) {
  5303. this.matrixWorld.copy(this.matrix);
  5304. } else {
  5305. this.matrixWorld.multiplyMatrices(this.parent.matrixWorld, this.matrix);
  5306. } // update children
  5307. if (updateChildren === true) {
  5308. var children = this.children;
  5309. for (var i = 0, l = children.length; i < l; i++) {
  5310. children[i].updateWorldMatrix(false, true);
  5311. }
  5312. }
  5313. },
  5314. toJSON: function (meta) {
  5315. // meta is a string when called from JSON.stringify
  5316. var isRootObject = meta === undefined || typeof meta === 'string';
  5317. var output = {}; // meta is a hash used to collect geometries, materials.
  5318. // not providing it implies that this is the root object
  5319. // being serialized.
  5320. if (isRootObject) {
  5321. // initialize meta obj
  5322. meta = {
  5323. geometries: {},
  5324. materials: {},
  5325. textures: {},
  5326. images: {},
  5327. shapes: {}
  5328. };
  5329. output.metadata = {
  5330. version: 4.5,
  5331. type: 'Object',
  5332. generator: 'Object3D.toJSON'
  5333. };
  5334. } // standard Object3D serialization
  5335. var object = {};
  5336. object.uuid = this.uuid;
  5337. object.type = this.type;
  5338. if (this.name !== '') object.name = this.name;
  5339. if (this.castShadow === true) object.castShadow = true;
  5340. if (this.receiveShadow === true) object.receiveShadow = true;
  5341. if (this.visible === false) object.visible = false;
  5342. if (this.frustumCulled === false) object.frustumCulled = false;
  5343. if (this.renderOrder !== 0) object.renderOrder = this.renderOrder;
  5344. if (JSON.stringify(this.userData) !== '{}') object.userData = this.userData;
  5345. object.layers = this.layers.mask;
  5346. object.matrix = this.matrix.toArray();
  5347. if (this.matrixAutoUpdate === false) object.matrixAutoUpdate = false; // object specific properties
  5348. if (this.isMesh && this.drawMode !== TrianglesDrawMode) object.drawMode = this.drawMode; //
  5349. function serialize(library, element) {
  5350. if (library[element.uuid] === undefined) {
  5351. library[element.uuid] = element.toJSON(meta);
  5352. }
  5353. return element.uuid;
  5354. }
  5355. if (this.isMesh || this.isLine || this.isPoints) {
  5356. object.geometry = serialize(meta.geometries, this.geometry);
  5357. var parameters = this.geometry.parameters;
  5358. if (parameters !== undefined && parameters.shapes !== undefined) {
  5359. var shapes = parameters.shapes;
  5360. if (Array.isArray(shapes)) {
  5361. for (var i = 0, l = shapes.length; i < l; i++) {
  5362. var shape = shapes[i];
  5363. serialize(meta.shapes, shape);
  5364. }
  5365. } else {
  5366. serialize(meta.shapes, shapes);
  5367. }
  5368. }
  5369. }
  5370. if (this.material !== undefined) {
  5371. if (Array.isArray(this.material)) {
  5372. var uuids = [];
  5373. for (var i = 0, l = this.material.length; i < l; i++) {
  5374. uuids.push(serialize(meta.materials, this.material[i]));
  5375. }
  5376. object.material = uuids;
  5377. } else {
  5378. object.material = serialize(meta.materials, this.material);
  5379. }
  5380. } //
  5381. if (this.children.length > 0) {
  5382. object.children = [];
  5383. for (var i = 0; i < this.children.length; i++) {
  5384. object.children.push(this.children[i].toJSON(meta).object);
  5385. }
  5386. }
  5387. if (isRootObject) {
  5388. var geometries = extractFromCache(meta.geometries);
  5389. var materials = extractFromCache(meta.materials);
  5390. var textures = extractFromCache(meta.textures);
  5391. var images = extractFromCache(meta.images);
  5392. var shapes = extractFromCache(meta.shapes);
  5393. if (geometries.length > 0) output.geometries = geometries;
  5394. if (materials.length > 0) output.materials = materials;
  5395. if (textures.length > 0) output.textures = textures;
  5396. if (images.length > 0) output.images = images;
  5397. if (shapes.length > 0) output.shapes = shapes;
  5398. }
  5399. output.object = object;
  5400. return output; // extract data from the cache hash
  5401. // remove metadata on each item
  5402. // and return as array
  5403. function extractFromCache(cache) {
  5404. var values = [];
  5405. for (var key in cache) {
  5406. var data = cache[key];
  5407. delete data.metadata;
  5408. values.push(data);
  5409. }
  5410. return values;
  5411. }
  5412. },
  5413. clone: function (recursive) {
  5414. return new this.constructor().copy(this, recursive);
  5415. },
  5416. copy: function (source, recursive) {
  5417. if (recursive === undefined) recursive = true;
  5418. this.name = source.name;
  5419. this.up.copy(source.up);
  5420. this.position.copy(source.position);
  5421. this.quaternion.copy(source.quaternion);
  5422. this.scale.copy(source.scale);
  5423. this.matrix.copy(source.matrix);
  5424. this.matrixWorld.copy(source.matrixWorld);
  5425. this.matrixAutoUpdate = source.matrixAutoUpdate;
  5426. this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;
  5427. this.layers.mask = source.layers.mask;
  5428. this.visible = source.visible;
  5429. this.castShadow = source.castShadow;
  5430. this.receiveShadow = source.receiveShadow;
  5431. this.frustumCulled = source.frustumCulled;
  5432. this.renderOrder = source.renderOrder;
  5433. this.userData = JSON.parse(JSON.stringify(source.userData));
  5434. if (recursive === true) {
  5435. for (var i = 0; i < source.children.length; i++) {
  5436. var child = source.children[i];
  5437. this.add(child.clone());
  5438. }
  5439. }
  5440. return this;
  5441. }
  5442. });
  5443. /**
  5444. * @author mrdoob / http://mrdoob.com/
  5445. */
  5446. function Scene() {
  5447. Object3D.call(this);
  5448. this.type = 'Scene';
  5449. this.background = null;
  5450. this.fog = null;
  5451. this.overrideMaterial = null;
  5452. this.autoUpdate = true; // checked by the renderer
  5453. if (typeof __THREE_DEVTOOLS__ !== 'undefined') {
  5454. __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent('observe', {
  5455. detail: this
  5456. })); // eslint-disable-line no-undef
  5457. }
  5458. }
  5459. Scene.prototype = Object.assign(Object.create(Object3D.prototype), {
  5460. constructor: Scene,
  5461. isScene: true,
  5462. copy: function (source, recursive) {
  5463. Object3D.prototype.copy.call(this, source, recursive);
  5464. if (source.background !== null) this.background = source.background.clone();
  5465. if (source.fog !== null) this.fog = source.fog.clone();
  5466. if (source.overrideMaterial !== null) this.overrideMaterial = source.overrideMaterial.clone();
  5467. this.autoUpdate = source.autoUpdate;
  5468. this.matrixAutoUpdate = source.matrixAutoUpdate;
  5469. return this;
  5470. },
  5471. toJSON: function (meta) {
  5472. var data = Object3D.prototype.toJSON.call(this, meta);
  5473. if (this.background !== null) data.object.background = this.background.toJSON(meta);
  5474. if (this.fog !== null) data.object.fog = this.fog.toJSON();
  5475. return data;
  5476. },
  5477. dispose: function () {
  5478. this.dispatchEvent({
  5479. type: 'dispose'
  5480. });
  5481. }
  5482. });
  5483. var _points = [new Vector3(), new Vector3(), new Vector3(), new Vector3(), new Vector3(), new Vector3(), new Vector3(), new Vector3()];
  5484. var _vector$2 = new Vector3(); // triangle centered vertices
  5485. var _v0 = new Vector3();
  5486. var _v1$2 = new Vector3();
  5487. var _v2 = new Vector3(); // triangle edge vectors
  5488. var _f0 = new Vector3();
  5489. var _f1 = new Vector3();
  5490. var _f2 = new Vector3();
  5491. var _center = new Vector3();
  5492. var _extents = new Vector3();
  5493. var _triangleNormal = new Vector3();
  5494. var _testAxis = new Vector3();
  5495. /**
  5496. * @author bhouston / http://clara.io
  5497. * @author WestLangley / http://github.com/WestLangley
  5498. */
  5499. function Box3(min, max) {
  5500. this.min = min !== undefined ? min : new Vector3(+Infinity, +Infinity, +Infinity);
  5501. this.max = max !== undefined ? max : new Vector3(-Infinity, -Infinity, -Infinity);
  5502. }
  5503. Object.assign(Box3.prototype, {
  5504. isBox3: true,
  5505. set: function (min, max) {
  5506. this.min.copy(min);
  5507. this.max.copy(max);
  5508. return this;
  5509. },
  5510. setFromArray: function (array) {
  5511. var minX = +Infinity;
  5512. var minY = +Infinity;
  5513. var minZ = +Infinity;
  5514. var maxX = -Infinity;
  5515. var maxY = -Infinity;
  5516. var maxZ = -Infinity;
  5517. for (var i = 0, l = array.length; i < l; i += 3) {
  5518. var x = array[i];
  5519. var y = array[i + 1];
  5520. var z = array[i + 2];
  5521. if (x < minX) minX = x;
  5522. if (y < minY) minY = y;
  5523. if (z < minZ) minZ = z;
  5524. if (x > maxX) maxX = x;
  5525. if (y > maxY) maxY = y;
  5526. if (z > maxZ) maxZ = z;
  5527. }
  5528. this.min.set(minX, minY, minZ);
  5529. this.max.set(maxX, maxY, maxZ);
  5530. return this;
  5531. },
  5532. setFromBufferAttribute: function (attribute) {
  5533. var minX = +Infinity;
  5534. var minY = +Infinity;
  5535. var minZ = +Infinity;
  5536. var maxX = -Infinity;
  5537. var maxY = -Infinity;
  5538. var maxZ = -Infinity;
  5539. for (var i = 0, l = attribute.count; i < l; i++) {
  5540. var x = attribute.getX(i);
  5541. var y = attribute.getY(i);
  5542. var z = attribute.getZ(i);
  5543. if (x < minX) minX = x;
  5544. if (y < minY) minY = y;
  5545. if (z < minZ) minZ = z;
  5546. if (x > maxX) maxX = x;
  5547. if (y > maxY) maxY = y;
  5548. if (z > maxZ) maxZ = z;
  5549. }
  5550. this.min.set(minX, minY, minZ);
  5551. this.max.set(maxX, maxY, maxZ);
  5552. return this;
  5553. },
  5554. setFromPoints: function (points) {
  5555. this.makeEmpty();
  5556. for (var i = 0, il = points.length; i < il; i++) {
  5557. this.expandByPoint(points[i]);
  5558. }
  5559. return this;
  5560. },
  5561. setFromCenterAndSize: function (center, size) {
  5562. var halfSize = _vector$2.copy(size).multiplyScalar(0.5);
  5563. this.min.copy(center).sub(halfSize);
  5564. this.max.copy(center).add(halfSize);
  5565. return this;
  5566. },
  5567. setFromObject: function (object) {
  5568. this.makeEmpty();
  5569. return this.expandByObject(object);
  5570. },
  5571. clone: function () {
  5572. return new this.constructor().copy(this);
  5573. },
  5574. copy: function (box) {
  5575. this.min.copy(box.min);
  5576. this.max.copy(box.max);
  5577. return this;
  5578. },
  5579. makeEmpty: function () {
  5580. this.min.x = this.min.y = this.min.z = +Infinity;
  5581. this.max.x = this.max.y = this.max.z = -Infinity;
  5582. return this;
  5583. },
  5584. isEmpty: function () {
  5585. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  5586. return this.max.x < this.min.x || this.max.y < this.min.y || this.max.z < this.min.z;
  5587. },
  5588. getCenter: function (target) {
  5589. if (target === undefined) {
  5590. console.warn('THREE.Box3: .getCenter() target is now required');
  5591. target = new Vector3();
  5592. }
  5593. return this.isEmpty() ? target.set(0, 0, 0) : target.addVectors(this.min, this.max).multiplyScalar(0.5);
  5594. },
  5595. getSize: function (target) {
  5596. if (target === undefined) {
  5597. console.warn('THREE.Box3: .getSize() target is now required');
  5598. target = new Vector3();
  5599. }
  5600. return this.isEmpty() ? target.set(0, 0, 0) : target.subVectors(this.max, this.min);
  5601. },
  5602. expandByPoint: function (point) {
  5603. this.min.min(point);
  5604. this.max.max(point);
  5605. return this;
  5606. },
  5607. expandByVector: function (vector) {
  5608. this.min.sub(vector);
  5609. this.max.add(vector);
  5610. return this;
  5611. },
  5612. expandByScalar: function (scalar) {
  5613. this.min.addScalar(-scalar);
  5614. this.max.addScalar(scalar);
  5615. return this;
  5616. },
  5617. expandByObject: function (object) {
  5618. var i, l; // Computes the world-axis-aligned bounding box of an object (including its children),
  5619. // accounting for both the object's, and children's, world transforms
  5620. object.updateWorldMatrix(false, false);
  5621. var geometry = object.geometry;
  5622. if (geometry !== undefined) {
  5623. if (geometry.isGeometry) {
  5624. var vertices = geometry.vertices;
  5625. for (i = 0, l = vertices.length; i < l; i++) {
  5626. _vector$2.copy(vertices[i]);
  5627. _vector$2.applyMatrix4(object.matrixWorld);
  5628. this.expandByPoint(_vector$2);
  5629. }
  5630. } else if (geometry.isBufferGeometry) {
  5631. var attribute = geometry.attributes.position;
  5632. if (attribute !== undefined) {
  5633. for (i = 0, l = attribute.count; i < l; i++) {
  5634. _vector$2.fromBufferAttribute(attribute, i).applyMatrix4(object.matrixWorld);
  5635. this.expandByPoint(_vector$2);
  5636. }
  5637. }
  5638. }
  5639. } //
  5640. var children = object.children;
  5641. for (i = 0, l = children.length; i < l; i++) {
  5642. this.expandByObject(children[i]);
  5643. }
  5644. return this;
  5645. },
  5646. containsPoint: function (point) {
  5647. 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;
  5648. },
  5649. containsBox: function (box) {
  5650. 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;
  5651. },
  5652. getParameter: function (point, target) {
  5653. // This can potentially have a divide by zero if the box
  5654. // has a size dimension of 0.
  5655. if (target === undefined) {
  5656. console.warn('THREE.Box3: .getParameter() target is now required');
  5657. target = new Vector3();
  5658. }
  5659. 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));
  5660. },
  5661. intersectsBox: function (box) {
  5662. // using 6 splitting planes to rule out intersections.
  5663. 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;
  5664. },
  5665. intersectsSphere: function (sphere) {
  5666. // Find the point on the AABB closest to the sphere center.
  5667. this.clampPoint(sphere.center, _vector$2); // If that point is inside the sphere, the AABB and sphere intersect.
  5668. return _vector$2.distanceToSquared(sphere.center) <= sphere.radius * sphere.radius;
  5669. },
  5670. intersectsPlane: function (plane) {
  5671. // We compute the minimum and maximum dot product values. If those values
  5672. // are on the same side (back or front) of the plane, then there is no intersection.
  5673. var min, max;
  5674. if (plane.normal.x > 0) {
  5675. min = plane.normal.x * this.min.x;
  5676. max = plane.normal.x * this.max.x;
  5677. } else {
  5678. min = plane.normal.x * this.max.x;
  5679. max = plane.normal.x * this.min.x;
  5680. }
  5681. if (plane.normal.y > 0) {
  5682. min += plane.normal.y * this.min.y;
  5683. max += plane.normal.y * this.max.y;
  5684. } else {
  5685. min += plane.normal.y * this.max.y;
  5686. max += plane.normal.y * this.min.y;
  5687. }
  5688. if (plane.normal.z > 0) {
  5689. min += plane.normal.z * this.min.z;
  5690. max += plane.normal.z * this.max.z;
  5691. } else {
  5692. min += plane.normal.z * this.max.z;
  5693. max += plane.normal.z * this.min.z;
  5694. }
  5695. return min <= -plane.constant && max >= -plane.constant;
  5696. },
  5697. intersectsTriangle: function (triangle) {
  5698. if (this.isEmpty()) {
  5699. return false;
  5700. } // compute box center and extents
  5701. this.getCenter(_center);
  5702. _extents.subVectors(this.max, _center); // translate triangle to aabb origin
  5703. _v0.subVectors(triangle.a, _center);
  5704. _v1$2.subVectors(triangle.b, _center);
  5705. _v2.subVectors(triangle.c, _center); // compute edge vectors for triangle
  5706. _f0.subVectors(_v1$2, _v0);
  5707. _f1.subVectors(_v2, _v1$2);
  5708. _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
  5709. // 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
  5710. // axis_ij = u_i x f_j (u0, u1, u2 = face normals of aabb = x,y,z axes vectors since aabb is axis aligned)
  5711. 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];
  5712. if (!satForAxes(axes, _v0, _v1$2, _v2, _extents)) {
  5713. return false;
  5714. } // test 3 face normals from the aabb
  5715. axes = [1, 0, 0, 0, 1, 0, 0, 0, 1];
  5716. if (!satForAxes(axes, _v0, _v1$2, _v2, _extents)) {
  5717. return false;
  5718. } // finally testing the face normal of the triangle
  5719. // use already existing triangle edge vectors here
  5720. _triangleNormal.crossVectors(_f0, _f1);
  5721. axes = [_triangleNormal.x, _triangleNormal.y, _triangleNormal.z];
  5722. return satForAxes(axes, _v0, _v1$2, _v2, _extents);
  5723. },
  5724. clampPoint: function (point, target) {
  5725. if (target === undefined) {
  5726. console.warn('THREE.Box3: .clampPoint() target is now required');
  5727. target = new Vector3();
  5728. }
  5729. return target.copy(point).clamp(this.min, this.max);
  5730. },
  5731. distanceToPoint: function (point) {
  5732. var clampedPoint = _vector$2.copy(point).clamp(this.min, this.max);
  5733. return clampedPoint.sub(point).length();
  5734. },
  5735. getBoundingSphere: function (target) {
  5736. if (target === undefined) {
  5737. console.error('THREE.Box3: .getBoundingSphere() target is now required'); //target = new Sphere(); // removed to avoid cyclic dependency
  5738. }
  5739. this.getCenter(target.center);
  5740. target.radius = this.getSize(_vector$2).length() * 0.5;
  5741. return target;
  5742. },
  5743. intersect: function (box) {
  5744. this.min.max(box.min);
  5745. 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.
  5746. if (this.isEmpty()) this.makeEmpty();
  5747. return this;
  5748. },
  5749. union: function (box) {
  5750. this.min.min(box.min);
  5751. this.max.max(box.max);
  5752. return this;
  5753. },
  5754. applyMatrix4: function (matrix) {
  5755. // transform of empty box is an empty box.
  5756. if (this.isEmpty()) return this; // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  5757. _points[0].set(this.min.x, this.min.y, this.min.z).applyMatrix4(matrix); // 000
  5758. _points[1].set(this.min.x, this.min.y, this.max.z).applyMatrix4(matrix); // 001
  5759. _points[2].set(this.min.x, this.max.y, this.min.z).applyMatrix4(matrix); // 010
  5760. _points[3].set(this.min.x, this.max.y, this.max.z).applyMatrix4(matrix); // 011
  5761. _points[4].set(this.max.x, this.min.y, this.min.z).applyMatrix4(matrix); // 100
  5762. _points[5].set(this.max.x, this.min.y, this.max.z).applyMatrix4(matrix); // 101
  5763. _points[6].set(this.max.x, this.max.y, this.min.z).applyMatrix4(matrix); // 110
  5764. _points[7].set(this.max.x, this.max.y, this.max.z).applyMatrix4(matrix); // 111
  5765. this.setFromPoints(_points);
  5766. return this;
  5767. },
  5768. translate: function (offset) {
  5769. this.min.add(offset);
  5770. this.max.add(offset);
  5771. return this;
  5772. },
  5773. equals: function (box) {
  5774. return box.min.equals(this.min) && box.max.equals(this.max);
  5775. }
  5776. });
  5777. function satForAxes(axes, v0, v1, v2, extents) {
  5778. var i, j;
  5779. for (i = 0, j = axes.length - 3; i <= j; i += 3) {
  5780. _testAxis.fromArray(axes, i); // project the aabb onto the seperating axis
  5781. 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
  5782. var p0 = v0.dot(_testAxis);
  5783. var p1 = v1.dot(_testAxis);
  5784. var p2 = v2.dot(_testAxis); // actual test, basically see if either of the most extreme of the triangle points intersects r
  5785. if (Math.max(-Math.max(p0, p1, p2), Math.min(p0, p1, p2)) > r) {
  5786. // points of the projected triangle are outside the projected half-length of the aabb
  5787. // the axis is seperating and we can exit
  5788. return false;
  5789. }
  5790. }
  5791. return true;
  5792. }
  5793. var _box = new Box3();
  5794. /**
  5795. * @author bhouston / http://clara.io
  5796. * @author mrdoob / http://mrdoob.com/
  5797. */
  5798. function Sphere(center, radius) {
  5799. this.center = center !== undefined ? center : new Vector3();
  5800. this.radius = radius !== undefined ? radius : 0;
  5801. }
  5802. Object.assign(Sphere.prototype, {
  5803. set: function (center, radius) {
  5804. this.center.copy(center);
  5805. this.radius = radius;
  5806. return this;
  5807. },
  5808. setFromPoints: function (points, optionalCenter) {
  5809. var center = this.center;
  5810. if (optionalCenter !== undefined) {
  5811. center.copy(optionalCenter);
  5812. } else {
  5813. _box.setFromPoints(points).getCenter(center);
  5814. }
  5815. var maxRadiusSq = 0;
  5816. for (var i = 0, il = points.length; i < il; i++) {
  5817. maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(points[i]));
  5818. }
  5819. this.radius = Math.sqrt(maxRadiusSq);
  5820. return this;
  5821. },
  5822. clone: function () {
  5823. return new this.constructor().copy(this);
  5824. },
  5825. copy: function (sphere) {
  5826. this.center.copy(sphere.center);
  5827. this.radius = sphere.radius;
  5828. return this;
  5829. },
  5830. empty: function () {
  5831. return this.radius <= 0;
  5832. },
  5833. containsPoint: function (point) {
  5834. return point.distanceToSquared(this.center) <= this.radius * this.radius;
  5835. },
  5836. distanceToPoint: function (point) {
  5837. return point.distanceTo(this.center) - this.radius;
  5838. },
  5839. intersectsSphere: function (sphere) {
  5840. var radiusSum = this.radius + sphere.radius;
  5841. return sphere.center.distanceToSquared(this.center) <= radiusSum * radiusSum;
  5842. },
  5843. intersectsBox: function (box) {
  5844. return box.intersectsSphere(this);
  5845. },
  5846. intersectsPlane: function (plane) {
  5847. return Math.abs(plane.distanceToPoint(this.center)) <= this.radius;
  5848. },
  5849. clampPoint: function (point, target) {
  5850. var deltaLengthSq = this.center.distanceToSquared(point);
  5851. if (target === undefined) {
  5852. console.warn('THREE.Sphere: .clampPoint() target is now required');
  5853. target = new Vector3();
  5854. }
  5855. target.copy(point);
  5856. if (deltaLengthSq > this.radius * this.radius) {
  5857. target.sub(this.center).normalize();
  5858. target.multiplyScalar(this.radius).add(this.center);
  5859. }
  5860. return target;
  5861. },
  5862. getBoundingBox: function (target) {
  5863. if (target === undefined) {
  5864. console.warn('THREE.Sphere: .getBoundingBox() target is now required');
  5865. target = new Box3();
  5866. }
  5867. target.set(this.center, this.center);
  5868. target.expandByScalar(this.radius);
  5869. return target;
  5870. },
  5871. applyMatrix4: function (matrix) {
  5872. this.center.applyMatrix4(matrix);
  5873. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  5874. return this;
  5875. },
  5876. translate: function (offset) {
  5877. this.center.add(offset);
  5878. return this;
  5879. },
  5880. equals: function (sphere) {
  5881. return sphere.center.equals(this.center) && sphere.radius === this.radius;
  5882. }
  5883. });
  5884. var _vector$3 = new Vector3();
  5885. var _segCenter = new Vector3();
  5886. var _segDir = new Vector3();
  5887. var _diff = new Vector3();
  5888. var _edge1 = new Vector3();
  5889. var _edge2 = new Vector3();
  5890. var _normal = new Vector3();
  5891. /**
  5892. * @author bhouston / http://clara.io
  5893. */
  5894. function Ray(origin, direction) {
  5895. this.origin = origin !== undefined ? origin : new Vector3();
  5896. this.direction = direction !== undefined ? direction : new Vector3();
  5897. }
  5898. Object.assign(Ray.prototype, {
  5899. set: function (origin, direction) {
  5900. this.origin.copy(origin);
  5901. this.direction.copy(direction);
  5902. return this;
  5903. },
  5904. clone: function () {
  5905. return new this.constructor().copy(this);
  5906. },
  5907. copy: function (ray) {
  5908. this.origin.copy(ray.origin);
  5909. this.direction.copy(ray.direction);
  5910. return this;
  5911. },
  5912. at: function (t, target) {
  5913. if (target === undefined) {
  5914. console.warn('THREE.Ray: .at() target is now required');
  5915. target = new Vector3();
  5916. }
  5917. return target.copy(this.direction).multiplyScalar(t).add(this.origin);
  5918. },
  5919. lookAt: function (v) {
  5920. this.direction.copy(v).sub(this.origin).normalize();
  5921. return this;
  5922. },
  5923. recast: function (t) {
  5924. this.origin.copy(this.at(t, _vector$3));
  5925. return this;
  5926. },
  5927. closestPointToPoint: function (point, target) {
  5928. if (target === undefined) {
  5929. console.warn('THREE.Ray: .closestPointToPoint() target is now required');
  5930. target = new Vector3();
  5931. }
  5932. target.subVectors(point, this.origin);
  5933. var directionDistance = target.dot(this.direction);
  5934. if (directionDistance < 0) {
  5935. return target.copy(this.origin);
  5936. }
  5937. return target.copy(this.direction).multiplyScalar(directionDistance).add(this.origin);
  5938. },
  5939. distanceToPoint: function (point) {
  5940. return Math.sqrt(this.distanceSqToPoint(point));
  5941. },
  5942. distanceSqToPoint: function (point) {
  5943. var directionDistance = _vector$3.subVectors(point, this.origin).dot(this.direction); // point behind the ray
  5944. if (directionDistance < 0) {
  5945. return this.origin.distanceToSquared(point);
  5946. }
  5947. _vector$3.copy(this.direction).multiplyScalar(directionDistance).add(this.origin);
  5948. return _vector$3.distanceToSquared(point);
  5949. },
  5950. distanceSqToSegment: function (v0, v1, optionalPointOnRay, optionalPointOnSegment) {
  5951. // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteDistRaySegment.h
  5952. // It returns the min distance between the ray and the segment
  5953. // defined by v0 and v1
  5954. // It can also set two optional targets :
  5955. // - The closest point on the ray
  5956. // - The closest point on the segment
  5957. _segCenter.copy(v0).add(v1).multiplyScalar(0.5);
  5958. _segDir.copy(v1).sub(v0).normalize();
  5959. _diff.copy(this.origin).sub(_segCenter);
  5960. var segExtent = v0.distanceTo(v1) * 0.5;
  5961. var a01 = -this.direction.dot(_segDir);
  5962. var b0 = _diff.dot(this.direction);
  5963. var b1 = -_diff.dot(_segDir);
  5964. var c = _diff.lengthSq();
  5965. var det = Math.abs(1 - a01 * a01);
  5966. var s0, s1, sqrDist, extDet;
  5967. if (det > 0) {
  5968. // The ray and segment are not parallel.
  5969. s0 = a01 * b1 - b0;
  5970. s1 = a01 * b0 - b1;
  5971. extDet = segExtent * det;
  5972. if (s0 >= 0) {
  5973. if (s1 >= -extDet) {
  5974. if (s1 <= extDet) {
  5975. // region 0
  5976. // Minimum at interior points of ray and segment.
  5977. var invDet = 1 / det;
  5978. s0 *= invDet;
  5979. s1 *= invDet;
  5980. sqrDist = s0 * (s0 + a01 * s1 + 2 * b0) + s1 * (a01 * s0 + s1 + 2 * b1) + c;
  5981. } else {
  5982. // region 1
  5983. s1 = segExtent;
  5984. s0 = Math.max(0, -(a01 * s1 + b0));
  5985. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  5986. }
  5987. } else {
  5988. // region 5
  5989. s1 = -segExtent;
  5990. s0 = Math.max(0, -(a01 * s1 + b0));
  5991. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  5992. }
  5993. } else {
  5994. if (s1 <= -extDet) {
  5995. // region 4
  5996. s0 = Math.max(0, -(-a01 * segExtent + b0));
  5997. s1 = s0 > 0 ? -segExtent : Math.min(Math.max(-segExtent, -b1), segExtent);
  5998. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  5999. } else if (s1 <= extDet) {
  6000. // region 3
  6001. s0 = 0;
  6002. s1 = Math.min(Math.max(-segExtent, -b1), segExtent);
  6003. sqrDist = s1 * (s1 + 2 * b1) + c;
  6004. } else {
  6005. // region 2
  6006. s0 = Math.max(0, -(a01 * segExtent + b0));
  6007. s1 = s0 > 0 ? segExtent : Math.min(Math.max(-segExtent, -b1), segExtent);
  6008. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  6009. }
  6010. }
  6011. } else {
  6012. // Ray and segment are parallel.
  6013. s1 = a01 > 0 ? -segExtent : segExtent;
  6014. s0 = Math.max(0, -(a01 * s1 + b0));
  6015. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  6016. }
  6017. if (optionalPointOnRay) {
  6018. optionalPointOnRay.copy(this.direction).multiplyScalar(s0).add(this.origin);
  6019. }
  6020. if (optionalPointOnSegment) {
  6021. optionalPointOnSegment.copy(_segDir).multiplyScalar(s1).add(_segCenter);
  6022. }
  6023. return sqrDist;
  6024. },
  6025. intersectSphere: function (sphere, target) {
  6026. _vector$3.subVectors(sphere.center, this.origin);
  6027. var tca = _vector$3.dot(this.direction);
  6028. var d2 = _vector$3.dot(_vector$3) - tca * tca;
  6029. var radius2 = sphere.radius * sphere.radius;
  6030. if (d2 > radius2) return null;
  6031. var thc = Math.sqrt(radius2 - d2); // t0 = first intersect point - entrance on front of sphere
  6032. var t0 = tca - thc; // t1 = second intersect point - exit point on back of sphere
  6033. var t1 = tca + thc; // test to see if both t0 and t1 are behind the ray - if so, return null
  6034. if (t0 < 0 && t1 < 0) return null; // test to see if t0 is behind the ray:
  6035. // if it is, the ray is inside the sphere, so return the second exit point scaled by t1,
  6036. // in order to always return an intersect point that is in front of the ray.
  6037. 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
  6038. return this.at(t0, target);
  6039. },
  6040. intersectsSphere: function (sphere) {
  6041. return this.distanceSqToPoint(sphere.center) <= sphere.radius * sphere.radius;
  6042. },
  6043. distanceToPlane: function (plane) {
  6044. var denominator = plane.normal.dot(this.direction);
  6045. if (denominator === 0) {
  6046. // line is coplanar, return origin
  6047. if (plane.distanceToPoint(this.origin) === 0) {
  6048. return 0;
  6049. } // Null is preferable to undefined since undefined means.... it is undefined
  6050. return null;
  6051. }
  6052. var t = -(this.origin.dot(plane.normal) + plane.constant) / denominator; // Return if the ray never intersects the plane
  6053. return t >= 0 ? t : null;
  6054. },
  6055. intersectPlane: function (plane, target) {
  6056. var t = this.distanceToPlane(plane);
  6057. if (t === null) {
  6058. return null;
  6059. }
  6060. return this.at(t, target);
  6061. },
  6062. intersectsPlane: function (plane) {
  6063. // check if the ray lies on the plane first
  6064. var distToPoint = plane.distanceToPoint(this.origin);
  6065. if (distToPoint === 0) {
  6066. return true;
  6067. }
  6068. var denominator = plane.normal.dot(this.direction);
  6069. if (denominator * distToPoint < 0) {
  6070. return true;
  6071. } // ray origin is behind the plane (and is pointing behind it)
  6072. return false;
  6073. },
  6074. intersectBox: function (box, target) {
  6075. var tmin, tmax, tymin, tymax, tzmin, tzmax;
  6076. var invdirx = 1 / this.direction.x,
  6077. invdiry = 1 / this.direction.y,
  6078. invdirz = 1 / this.direction.z;
  6079. var origin = this.origin;
  6080. if (invdirx >= 0) {
  6081. tmin = (box.min.x - origin.x) * invdirx;
  6082. tmax = (box.max.x - origin.x) * invdirx;
  6083. } else {
  6084. tmin = (box.max.x - origin.x) * invdirx;
  6085. tmax = (box.min.x - origin.x) * invdirx;
  6086. }
  6087. if (invdiry >= 0) {
  6088. tymin = (box.min.y - origin.y) * invdiry;
  6089. tymax = (box.max.y - origin.y) * invdiry;
  6090. } else {
  6091. tymin = (box.max.y - origin.y) * invdiry;
  6092. tymax = (box.min.y - origin.y) * invdiry;
  6093. }
  6094. if (tmin > tymax || tymin > tmax) return null; // These lines also handle the case where tmin or tmax is NaN
  6095. // (result of 0 * Infinity). x !== x returns true if x is NaN
  6096. if (tymin > tmin || tmin !== tmin) tmin = tymin;
  6097. if (tymax < tmax || tmax !== tmax) tmax = tymax;
  6098. if (invdirz >= 0) {
  6099. tzmin = (box.min.z - origin.z) * invdirz;
  6100. tzmax = (box.max.z - origin.z) * invdirz;
  6101. } else {
  6102. tzmin = (box.max.z - origin.z) * invdirz;
  6103. tzmax = (box.min.z - origin.z) * invdirz;
  6104. }
  6105. if (tmin > tzmax || tzmin > tmax) return null;
  6106. if (tzmin > tmin || tmin !== tmin) tmin = tzmin;
  6107. if (tzmax < tmax || tmax !== tmax) tmax = tzmax; //return point closest to the ray (positive side)
  6108. if (tmax < 0) return null;
  6109. return this.at(tmin >= 0 ? tmin : tmax, target);
  6110. },
  6111. intersectsBox: function (box) {
  6112. return this.intersectBox(box, _vector$3) !== null;
  6113. },
  6114. intersectTriangle: function (a, b, c, backfaceCulling, target) {
  6115. // Compute the offset origin, edges, and normal.
  6116. // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h
  6117. _edge1.subVectors(b, a);
  6118. _edge2.subVectors(c, a);
  6119. _normal.crossVectors(_edge1, _edge2); // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  6120. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  6121. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  6122. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  6123. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  6124. var DdN = this.direction.dot(_normal);
  6125. var sign;
  6126. if (DdN > 0) {
  6127. if (backfaceCulling) return null;
  6128. sign = 1;
  6129. } else if (DdN < 0) {
  6130. sign = -1;
  6131. DdN = -DdN;
  6132. } else {
  6133. return null;
  6134. }
  6135. _diff.subVectors(this.origin, a);
  6136. var DdQxE2 = sign * this.direction.dot(_edge2.crossVectors(_diff, _edge2)); // b1 < 0, no intersection
  6137. if (DdQxE2 < 0) {
  6138. return null;
  6139. }
  6140. var DdE1xQ = sign * this.direction.dot(_edge1.cross(_diff)); // b2 < 0, no intersection
  6141. if (DdE1xQ < 0) {
  6142. return null;
  6143. } // b1+b2 > 1, no intersection
  6144. if (DdQxE2 + DdE1xQ > DdN) {
  6145. return null;
  6146. } // Line intersects triangle, check if ray does.
  6147. var QdN = -sign * _diff.dot(_normal); // t < 0, no intersection
  6148. if (QdN < 0) {
  6149. return null;
  6150. } // Ray intersects triangle.
  6151. return this.at(QdN / DdN, target);
  6152. },
  6153. applyMatrix4: function (matrix4) {
  6154. this.origin.applyMatrix4(matrix4);
  6155. this.direction.transformDirection(matrix4);
  6156. return this;
  6157. },
  6158. equals: function (ray) {
  6159. return ray.origin.equals(this.origin) && ray.direction.equals(this.direction);
  6160. }
  6161. });
  6162. /**
  6163. * @author bhouston / http://clara.io
  6164. * @author mrdoob / http://mrdoob.com/
  6165. */
  6166. var _v0$1 = new Vector3();
  6167. var _v1$3 = new Vector3();
  6168. var _v2$1 = new Vector3();
  6169. var _v3 = new Vector3();
  6170. var _vab = new Vector3();
  6171. var _vac = new Vector3();
  6172. var _vbc = new Vector3();
  6173. var _vap = new Vector3();
  6174. var _vbp = new Vector3();
  6175. var _vcp = new Vector3();
  6176. function Triangle(a, b, c) {
  6177. this.a = a !== undefined ? a : new Vector3();
  6178. this.b = b !== undefined ? b : new Vector3();
  6179. this.c = c !== undefined ? c : new Vector3();
  6180. }
  6181. Object.assign(Triangle, {
  6182. getNormal: function (a, b, c, target) {
  6183. if (target === undefined) {
  6184. console.warn('THREE.Triangle: .getNormal() target is now required');
  6185. target = new Vector3();
  6186. }
  6187. target.subVectors(c, b);
  6188. _v0$1.subVectors(a, b);
  6189. target.cross(_v0$1);
  6190. var targetLengthSq = target.lengthSq();
  6191. if (targetLengthSq > 0) {
  6192. return target.multiplyScalar(1 / Math.sqrt(targetLengthSq));
  6193. }
  6194. return target.set(0, 0, 0);
  6195. },
  6196. // static/instance method to calculate barycentric coordinates
  6197. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  6198. getBarycoord: function (point, a, b, c, target) {
  6199. _v0$1.subVectors(c, a);
  6200. _v1$3.subVectors(b, a);
  6201. _v2$1.subVectors(point, a);
  6202. var dot00 = _v0$1.dot(_v0$1);
  6203. var dot01 = _v0$1.dot(_v1$3);
  6204. var dot02 = _v0$1.dot(_v2$1);
  6205. var dot11 = _v1$3.dot(_v1$3);
  6206. var dot12 = _v1$3.dot(_v2$1);
  6207. var denom = dot00 * dot11 - dot01 * dot01;
  6208. if (target === undefined) {
  6209. console.warn('THREE.Triangle: .getBarycoord() target is now required');
  6210. target = new Vector3();
  6211. } // collinear or singular triangle
  6212. if (denom === 0) {
  6213. // arbitrary location outside of triangle?
  6214. // not sure if this is the best idea, maybe should be returning undefined
  6215. return target.set(-2, -1, -1);
  6216. }
  6217. var invDenom = 1 / denom;
  6218. var u = (dot11 * dot02 - dot01 * dot12) * invDenom;
  6219. var v = (dot00 * dot12 - dot01 * dot02) * invDenom; // barycentric coordinates must always sum to 1
  6220. return target.set(1 - u - v, v, u);
  6221. },
  6222. containsPoint: function (point, a, b, c) {
  6223. Triangle.getBarycoord(point, a, b, c, _v3);
  6224. return _v3.x >= 0 && _v3.y >= 0 && _v3.x + _v3.y <= 1;
  6225. },
  6226. getUV: function (point, p1, p2, p3, uv1, uv2, uv3, target) {
  6227. this.getBarycoord(point, p1, p2, p3, _v3);
  6228. target.set(0, 0);
  6229. target.addScaledVector(uv1, _v3.x);
  6230. target.addScaledVector(uv2, _v3.y);
  6231. target.addScaledVector(uv3, _v3.z);
  6232. return target;
  6233. },
  6234. isFrontFacing: function (a, b, c, direction) {
  6235. _v0$1.subVectors(c, b);
  6236. _v1$3.subVectors(a, b); // strictly front facing
  6237. return _v0$1.cross(_v1$3).dot(direction) < 0 ? true : false;
  6238. }
  6239. });
  6240. Object.assign(Triangle.prototype, {
  6241. set: function (a, b, c) {
  6242. this.a.copy(a);
  6243. this.b.copy(b);
  6244. this.c.copy(c);
  6245. return this;
  6246. },
  6247. setFromPointsAndIndices: function (points, i0, i1, i2) {
  6248. this.a.copy(points[i0]);
  6249. this.b.copy(points[i1]);
  6250. this.c.copy(points[i2]);
  6251. return this;
  6252. },
  6253. clone: function () {
  6254. return new this.constructor().copy(this);
  6255. },
  6256. copy: function (triangle) {
  6257. this.a.copy(triangle.a);
  6258. this.b.copy(triangle.b);
  6259. this.c.copy(triangle.c);
  6260. return this;
  6261. },
  6262. getArea: function () {
  6263. _v0$1.subVectors(this.c, this.b);
  6264. _v1$3.subVectors(this.a, this.b);
  6265. return _v0$1.cross(_v1$3).length() * 0.5;
  6266. },
  6267. getMidpoint: function (target) {
  6268. if (target === undefined) {
  6269. console.warn('THREE.Triangle: .getMidpoint() target is now required');
  6270. target = new Vector3();
  6271. }
  6272. return target.addVectors(this.a, this.b).add(this.c).multiplyScalar(1 / 3);
  6273. },
  6274. getNormal: function (target) {
  6275. return Triangle.getNormal(this.a, this.b, this.c, target);
  6276. },
  6277. getPlane: function (target) {
  6278. if (target === undefined) {
  6279. console.warn('THREE.Triangle: .getPlane() target is now required');
  6280. target = new Vector3();
  6281. }
  6282. return target.setFromCoplanarPoints(this.a, this.b, this.c);
  6283. },
  6284. getBarycoord: function (point, target) {
  6285. return Triangle.getBarycoord(point, this.a, this.b, this.c, target);
  6286. },
  6287. getUV: function (point, uv1, uv2, uv3, target) {
  6288. return Triangle.getUV(point, this.a, this.b, this.c, uv1, uv2, uv3, target);
  6289. },
  6290. containsPoint: function (point) {
  6291. return Triangle.containsPoint(point, this.a, this.b, this.c);
  6292. },
  6293. isFrontFacing: function (direction) {
  6294. return Triangle.isFrontFacing(this.a, this.b, this.c, direction);
  6295. },
  6296. intersectsBox: function (box) {
  6297. return box.intersectsTriangle(this);
  6298. },
  6299. closestPointToPoint: function (p, target) {
  6300. if (target === undefined) {
  6301. console.warn('THREE.Triangle: .closestPointToPoint() target is now required');
  6302. target = new Vector3();
  6303. }
  6304. var a = this.a,
  6305. b = this.b,
  6306. c = this.c;
  6307. var v, w; // algorithm thanks to Real-Time Collision Detection by Christer Ericson,
  6308. // published by Morgan Kaufmann Publishers, (c) 2005 Elsevier Inc.,
  6309. // under the accompanying license; see chapter 5.1.5 for detailed explanation.
  6310. // basically, we're distinguishing which of the voronoi regions of the triangle
  6311. // the point lies in with the minimum amount of redundant computation.
  6312. _vab.subVectors(b, a);
  6313. _vac.subVectors(c, a);
  6314. _vap.subVectors(p, a);
  6315. var d1 = _vab.dot(_vap);
  6316. var d2 = _vac.dot(_vap);
  6317. if (d1 <= 0 && d2 <= 0) {
  6318. // vertex region of A; barycentric coords (1, 0, 0)
  6319. return target.copy(a);
  6320. }
  6321. _vbp.subVectors(p, b);
  6322. var d3 = _vab.dot(_vbp);
  6323. var d4 = _vac.dot(_vbp);
  6324. if (d3 >= 0 && d4 <= d3) {
  6325. // vertex region of B; barycentric coords (0, 1, 0)
  6326. return target.copy(b);
  6327. }
  6328. var vc = d1 * d4 - d3 * d2;
  6329. if (vc <= 0 && d1 >= 0 && d3 <= 0) {
  6330. v = d1 / (d1 - d3); // edge region of AB; barycentric coords (1-v, v, 0)
  6331. return target.copy(a).addScaledVector(_vab, v);
  6332. }
  6333. _vcp.subVectors(p, c);
  6334. var d5 = _vab.dot(_vcp);
  6335. var d6 = _vac.dot(_vcp);
  6336. if (d6 >= 0 && d5 <= d6) {
  6337. // vertex region of C; barycentric coords (0, 0, 1)
  6338. return target.copy(c);
  6339. }
  6340. var vb = d5 * d2 - d1 * d6;
  6341. if (vb <= 0 && d2 >= 0 && d6 <= 0) {
  6342. w = d2 / (d2 - d6); // edge region of AC; barycentric coords (1-w, 0, w)
  6343. return target.copy(a).addScaledVector(_vac, w);
  6344. }
  6345. var va = d3 * d6 - d5 * d4;
  6346. if (va <= 0 && d4 - d3 >= 0 && d5 - d6 >= 0) {
  6347. _vbc.subVectors(c, b);
  6348. w = (d4 - d3) / (d4 - d3 + (d5 - d6)); // edge region of BC; barycentric coords (0, 1-w, w)
  6349. return target.copy(b).addScaledVector(_vbc, w); // edge region of BC
  6350. } // face region
  6351. var denom = 1 / (va + vb + vc); // u = va * denom
  6352. v = vb * denom;
  6353. w = vc * denom;
  6354. return target.copy(a).addScaledVector(_vab, v).addScaledVector(_vac, w);
  6355. },
  6356. equals: function (triangle) {
  6357. return triangle.a.equals(this.a) && triangle.b.equals(this.b) && triangle.c.equals(this.c);
  6358. }
  6359. });
  6360. /**
  6361. * @author mrdoob / http://mrdoob.com/
  6362. */
  6363. var _colorKeywords = {
  6364. 'aliceblue': 0xF0F8FF,
  6365. 'antiquewhite': 0xFAEBD7,
  6366. 'aqua': 0x00FFFF,
  6367. 'aquamarine': 0x7FFFD4,
  6368. 'azure': 0xF0FFFF,
  6369. 'beige': 0xF5F5DC,
  6370. 'bisque': 0xFFE4C4,
  6371. 'black': 0x000000,
  6372. 'blanchedalmond': 0xFFEBCD,
  6373. 'blue': 0x0000FF,
  6374. 'blueviolet': 0x8A2BE2,
  6375. 'brown': 0xA52A2A,
  6376. 'burlywood': 0xDEB887,
  6377. 'cadetblue': 0x5F9EA0,
  6378. 'chartreuse': 0x7FFF00,
  6379. 'chocolate': 0xD2691E,
  6380. 'coral': 0xFF7F50,
  6381. 'cornflowerblue': 0x6495ED,
  6382. 'cornsilk': 0xFFF8DC,
  6383. 'crimson': 0xDC143C,
  6384. 'cyan': 0x00FFFF,
  6385. 'darkblue': 0x00008B,
  6386. 'darkcyan': 0x008B8B,
  6387. 'darkgoldenrod': 0xB8860B,
  6388. 'darkgray': 0xA9A9A9,
  6389. 'darkgreen': 0x006400,
  6390. 'darkgrey': 0xA9A9A9,
  6391. 'darkkhaki': 0xBDB76B,
  6392. 'darkmagenta': 0x8B008B,
  6393. 'darkolivegreen': 0x556B2F,
  6394. 'darkorange': 0xFF8C00,
  6395. 'darkorchid': 0x9932CC,
  6396. 'darkred': 0x8B0000,
  6397. 'darksalmon': 0xE9967A,
  6398. 'darkseagreen': 0x8FBC8F,
  6399. 'darkslateblue': 0x483D8B,
  6400. 'darkslategray': 0x2F4F4F,
  6401. 'darkslategrey': 0x2F4F4F,
  6402. 'darkturquoise': 0x00CED1,
  6403. 'darkviolet': 0x9400D3,
  6404. 'deeppink': 0xFF1493,
  6405. 'deepskyblue': 0x00BFFF,
  6406. 'dimgray': 0x696969,
  6407. 'dimgrey': 0x696969,
  6408. 'dodgerblue': 0x1E90FF,
  6409. 'firebrick': 0xB22222,
  6410. 'floralwhite': 0xFFFAF0,
  6411. 'forestgreen': 0x228B22,
  6412. 'fuchsia': 0xFF00FF,
  6413. 'gainsboro': 0xDCDCDC,
  6414. 'ghostwhite': 0xF8F8FF,
  6415. 'gold': 0xFFD700,
  6416. 'goldenrod': 0xDAA520,
  6417. 'gray': 0x808080,
  6418. 'green': 0x008000,
  6419. 'greenyellow': 0xADFF2F,
  6420. 'grey': 0x808080,
  6421. 'honeydew': 0xF0FFF0,
  6422. 'hotpink': 0xFF69B4,
  6423. 'indianred': 0xCD5C5C,
  6424. 'indigo': 0x4B0082,
  6425. 'ivory': 0xFFFFF0,
  6426. 'khaki': 0xF0E68C,
  6427. 'lavender': 0xE6E6FA,
  6428. 'lavenderblush': 0xFFF0F5,
  6429. 'lawngreen': 0x7CFC00,
  6430. 'lemonchiffon': 0xFFFACD,
  6431. 'lightblue': 0xADD8E6,
  6432. 'lightcoral': 0xF08080,
  6433. 'lightcyan': 0xE0FFFF,
  6434. 'lightgoldenrodyellow': 0xFAFAD2,
  6435. 'lightgray': 0xD3D3D3,
  6436. 'lightgreen': 0x90EE90,
  6437. 'lightgrey': 0xD3D3D3,
  6438. 'lightpink': 0xFFB6C1,
  6439. 'lightsalmon': 0xFFA07A,
  6440. 'lightseagreen': 0x20B2AA,
  6441. 'lightskyblue': 0x87CEFA,
  6442. 'lightslategray': 0x778899,
  6443. 'lightslategrey': 0x778899,
  6444. 'lightsteelblue': 0xB0C4DE,
  6445. 'lightyellow': 0xFFFFE0,
  6446. 'lime': 0x00FF00,
  6447. 'limegreen': 0x32CD32,
  6448. 'linen': 0xFAF0E6,
  6449. 'magenta': 0xFF00FF,
  6450. 'maroon': 0x800000,
  6451. 'mediumaquamarine': 0x66CDAA,
  6452. 'mediumblue': 0x0000CD,
  6453. 'mediumorchid': 0xBA55D3,
  6454. 'mediumpurple': 0x9370DB,
  6455. 'mediumseagreen': 0x3CB371,
  6456. 'mediumslateblue': 0x7B68EE,
  6457. 'mediumspringgreen': 0x00FA9A,
  6458. 'mediumturquoise': 0x48D1CC,
  6459. 'mediumvioletred': 0xC71585,
  6460. 'midnightblue': 0x191970,
  6461. 'mintcream': 0xF5FFFA,
  6462. 'mistyrose': 0xFFE4E1,
  6463. 'moccasin': 0xFFE4B5,
  6464. 'navajowhite': 0xFFDEAD,
  6465. 'navy': 0x000080,
  6466. 'oldlace': 0xFDF5E6,
  6467. 'olive': 0x808000,
  6468. 'olivedrab': 0x6B8E23,
  6469. 'orange': 0xFFA500,
  6470. 'orangered': 0xFF4500,
  6471. 'orchid': 0xDA70D6,
  6472. 'palegoldenrod': 0xEEE8AA,
  6473. 'palegreen': 0x98FB98,
  6474. 'paleturquoise': 0xAFEEEE,
  6475. 'palevioletred': 0xDB7093,
  6476. 'papayawhip': 0xFFEFD5,
  6477. 'peachpuff': 0xFFDAB9,
  6478. 'peru': 0xCD853F,
  6479. 'pink': 0xFFC0CB,
  6480. 'plum': 0xDDA0DD,
  6481. 'powderblue': 0xB0E0E6,
  6482. 'purple': 0x800080,
  6483. 'rebeccapurple': 0x663399,
  6484. 'red': 0xFF0000,
  6485. 'rosybrown': 0xBC8F8F,
  6486. 'royalblue': 0x4169E1,
  6487. 'saddlebrown': 0x8B4513,
  6488. 'salmon': 0xFA8072,
  6489. 'sandybrown': 0xF4A460,
  6490. 'seagreen': 0x2E8B57,
  6491. 'seashell': 0xFFF5EE,
  6492. 'sienna': 0xA0522D,
  6493. 'silver': 0xC0C0C0,
  6494. 'skyblue': 0x87CEEB,
  6495. 'slateblue': 0x6A5ACD,
  6496. 'slategray': 0x708090,
  6497. 'slategrey': 0x708090,
  6498. 'snow': 0xFFFAFA,
  6499. 'springgreen': 0x00FF7F,
  6500. 'steelblue': 0x4682B4,
  6501. 'tan': 0xD2B48C,
  6502. 'teal': 0x008080,
  6503. 'thistle': 0xD8BFD8,
  6504. 'tomato': 0xFF6347,
  6505. 'turquoise': 0x40E0D0,
  6506. 'violet': 0xEE82EE,
  6507. 'wheat': 0xF5DEB3,
  6508. 'white': 0xFFFFFF,
  6509. 'whitesmoke': 0xF5F5F5,
  6510. 'yellow': 0xFFFF00,
  6511. 'yellowgreen': 0x9ACD32
  6512. };
  6513. var _hslA = {
  6514. h: 0,
  6515. s: 0,
  6516. l: 0
  6517. };
  6518. var _hslB = {
  6519. h: 0,
  6520. s: 0,
  6521. l: 0
  6522. };
  6523. function Color(r, g, b) {
  6524. if (g === undefined && b === undefined) {
  6525. // r is THREE.Color, hex or string
  6526. return this.set(r);
  6527. }
  6528. return this.setRGB(r, g, b);
  6529. }
  6530. function hue2rgb(p, q, t) {
  6531. if (t < 0) t += 1;
  6532. if (t > 1) t -= 1;
  6533. if (t < 1 / 6) return p + (q - p) * 6 * t;
  6534. if (t < 1 / 2) return q;
  6535. if (t < 2 / 3) return p + (q - p) * 6 * (2 / 3 - t);
  6536. return p;
  6537. }
  6538. function SRGBToLinear(c) {
  6539. return c < 0.04045 ? c * 0.0773993808 : Math.pow(c * 0.9478672986 + 0.0521327014, 2.4);
  6540. }
  6541. function LinearToSRGB(c) {
  6542. return c < 0.0031308 ? c * 12.92 : 1.055 * Math.pow(c, 0.41666) - 0.055;
  6543. }
  6544. Object.assign(Color.prototype, {
  6545. isColor: true,
  6546. r: 1,
  6547. g: 1,
  6548. b: 1,
  6549. set: function (value) {
  6550. if (value && value.isColor) {
  6551. this.copy(value);
  6552. } else if (typeof value === 'number') {
  6553. this.setHex(value);
  6554. } else if (typeof value === 'string') {
  6555. this.setStyle(value);
  6556. }
  6557. return this;
  6558. },
  6559. setScalar: function (scalar) {
  6560. this.r = scalar;
  6561. this.g = scalar;
  6562. this.b = scalar;
  6563. return this;
  6564. },
  6565. setHex: function (hex) {
  6566. hex = Math.floor(hex);
  6567. this.r = (hex >> 16 & 255) / 255;
  6568. this.g = (hex >> 8 & 255) / 255;
  6569. this.b = (hex & 255) / 255;
  6570. return this;
  6571. },
  6572. setRGB: function (r, g, b) {
  6573. this.r = r;
  6574. this.g = g;
  6575. this.b = b;
  6576. return this;
  6577. },
  6578. setHSL: function (h, s, l) {
  6579. // h,s,l ranges are in 0.0 - 1.0
  6580. h = _Math.euclideanModulo(h, 1);
  6581. s = _Math.clamp(s, 0, 1);
  6582. l = _Math.clamp(l, 0, 1);
  6583. if (s === 0) {
  6584. this.r = this.g = this.b = l;
  6585. } else {
  6586. var p = l <= 0.5 ? l * (1 + s) : l + s - l * s;
  6587. var q = 2 * l - p;
  6588. this.r = hue2rgb(q, p, h + 1 / 3);
  6589. this.g = hue2rgb(q, p, h);
  6590. this.b = hue2rgb(q, p, h - 1 / 3);
  6591. }
  6592. return this;
  6593. },
  6594. setStyle: function (style) {
  6595. function handleAlpha(string) {
  6596. if (string === undefined) return;
  6597. if (parseFloat(string) < 1) {
  6598. console.warn('THREE.Color: Alpha component of ' + style + ' will be ignored.');
  6599. }
  6600. }
  6601. var m;
  6602. if (m = /^((?:rgb|hsl)a?)\(\s*([^\)]*)\)/.exec(style)) {
  6603. // rgb / hsl
  6604. var color;
  6605. var name = m[1];
  6606. var components = m[2];
  6607. switch (name) {
  6608. case 'rgb':
  6609. case 'rgba':
  6610. if (color = /^(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec(components)) {
  6611. // rgb(255,0,0) rgba(255,0,0,0.5)
  6612. this.r = Math.min(255, parseInt(color[1], 10)) / 255;
  6613. this.g = Math.min(255, parseInt(color[2], 10)) / 255;
  6614. this.b = Math.min(255, parseInt(color[3], 10)) / 255;
  6615. handleAlpha(color[5]);
  6616. return this;
  6617. }
  6618. if (color = /^(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec(components)) {
  6619. // rgb(100%,0%,0%) rgba(100%,0%,0%,0.5)
  6620. this.r = Math.min(100, parseInt(color[1], 10)) / 100;
  6621. this.g = Math.min(100, parseInt(color[2], 10)) / 100;
  6622. this.b = Math.min(100, parseInt(color[3], 10)) / 100;
  6623. handleAlpha(color[5]);
  6624. return this;
  6625. }
  6626. break;
  6627. case 'hsl':
  6628. case 'hsla':
  6629. if (color = /^([0-9]*\.?[0-9]+)\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec(components)) {
  6630. // hsl(120,50%,50%) hsla(120,50%,50%,0.5)
  6631. var h = parseFloat(color[1]) / 360;
  6632. var s = parseInt(color[2], 10) / 100;
  6633. var l = parseInt(color[3], 10) / 100;
  6634. handleAlpha(color[5]);
  6635. return this.setHSL(h, s, l);
  6636. }
  6637. break;
  6638. }
  6639. } else if (m = /^\#([A-Fa-f0-9]+)$/.exec(style)) {
  6640. // hex color
  6641. var hex = m[1];
  6642. var size = hex.length;
  6643. if (size === 3) {
  6644. // #ff0
  6645. this.r = parseInt(hex.charAt(0) + hex.charAt(0), 16) / 255;
  6646. this.g = parseInt(hex.charAt(1) + hex.charAt(1), 16) / 255;
  6647. this.b = parseInt(hex.charAt(2) + hex.charAt(2), 16) / 255;
  6648. return this;
  6649. } else if (size === 6) {
  6650. // #ff0000
  6651. this.r = parseInt(hex.charAt(0) + hex.charAt(1), 16) / 255;
  6652. this.g = parseInt(hex.charAt(2) + hex.charAt(3), 16) / 255;
  6653. this.b = parseInt(hex.charAt(4) + hex.charAt(5), 16) / 255;
  6654. return this;
  6655. }
  6656. }
  6657. if (style && style.length > 0) {
  6658. // color keywords
  6659. var hex = _colorKeywords[style];
  6660. if (hex !== undefined) {
  6661. // red
  6662. this.setHex(hex);
  6663. } else {
  6664. // unknown color
  6665. console.warn('THREE.Color: Unknown color ' + style);
  6666. }
  6667. }
  6668. return this;
  6669. },
  6670. clone: function () {
  6671. return new this.constructor(this.r, this.g, this.b);
  6672. },
  6673. copy: function (color) {
  6674. this.r = color.r;
  6675. this.g = color.g;
  6676. this.b = color.b;
  6677. return this;
  6678. },
  6679. copyGammaToLinear: function (color, gammaFactor) {
  6680. if (gammaFactor === undefined) gammaFactor = 2.0;
  6681. this.r = Math.pow(color.r, gammaFactor);
  6682. this.g = Math.pow(color.g, gammaFactor);
  6683. this.b = Math.pow(color.b, gammaFactor);
  6684. return this;
  6685. },
  6686. copyLinearToGamma: function (color, gammaFactor) {
  6687. if (gammaFactor === undefined) gammaFactor = 2.0;
  6688. var safeInverse = gammaFactor > 0 ? 1.0 / gammaFactor : 1.0;
  6689. this.r = Math.pow(color.r, safeInverse);
  6690. this.g = Math.pow(color.g, safeInverse);
  6691. this.b = Math.pow(color.b, safeInverse);
  6692. return this;
  6693. },
  6694. convertGammaToLinear: function (gammaFactor) {
  6695. this.copyGammaToLinear(this, gammaFactor);
  6696. return this;
  6697. },
  6698. convertLinearToGamma: function (gammaFactor) {
  6699. this.copyLinearToGamma(this, gammaFactor);
  6700. return this;
  6701. },
  6702. copySRGBToLinear: function (color) {
  6703. this.r = SRGBToLinear(color.r);
  6704. this.g = SRGBToLinear(color.g);
  6705. this.b = SRGBToLinear(color.b);
  6706. return this;
  6707. },
  6708. copyLinearToSRGB: function (color) {
  6709. this.r = LinearToSRGB(color.r);
  6710. this.g = LinearToSRGB(color.g);
  6711. this.b = LinearToSRGB(color.b);
  6712. return this;
  6713. },
  6714. convertSRGBToLinear: function () {
  6715. this.copySRGBToLinear(this);
  6716. return this;
  6717. },
  6718. convertLinearToSRGB: function () {
  6719. this.copyLinearToSRGB(this);
  6720. return this;
  6721. },
  6722. getHex: function () {
  6723. return this.r * 255 << 16 ^ this.g * 255 << 8 ^ this.b * 255 << 0;
  6724. },
  6725. getHexString: function () {
  6726. return ('000000' + this.getHex().toString(16)).slice(-6);
  6727. },
  6728. getHSL: function (target) {
  6729. // h,s,l ranges are in 0.0 - 1.0
  6730. if (target === undefined) {
  6731. console.warn('THREE.Color: .getHSL() target is now required');
  6732. target = {
  6733. h: 0,
  6734. s: 0,
  6735. l: 0
  6736. };
  6737. }
  6738. var r = this.r,
  6739. g = this.g,
  6740. b = this.b;
  6741. var max = Math.max(r, g, b);
  6742. var min = Math.min(r, g, b);
  6743. var hue, saturation;
  6744. var lightness = (min + max) / 2.0;
  6745. if (min === max) {
  6746. hue = 0;
  6747. saturation = 0;
  6748. } else {
  6749. var delta = max - min;
  6750. saturation = lightness <= 0.5 ? delta / (max + min) : delta / (2 - max - min);
  6751. switch (max) {
  6752. case r:
  6753. hue = (g - b) / delta + (g < b ? 6 : 0);
  6754. break;
  6755. case g:
  6756. hue = (b - r) / delta + 2;
  6757. break;
  6758. case b:
  6759. hue = (r - g) / delta + 4;
  6760. break;
  6761. }
  6762. hue /= 6;
  6763. }
  6764. target.h = hue;
  6765. target.s = saturation;
  6766. target.l = lightness;
  6767. return target;
  6768. },
  6769. getStyle: function () {
  6770. return 'rgb(' + (this.r * 255 | 0) + ',' + (this.g * 255 | 0) + ',' + (this.b * 255 | 0) + ')';
  6771. },
  6772. offsetHSL: function (h, s, l) {
  6773. this.getHSL(_hslA);
  6774. _hslA.h += h;
  6775. _hslA.s += s;
  6776. _hslA.l += l;
  6777. this.setHSL(_hslA.h, _hslA.s, _hslA.l);
  6778. return this;
  6779. },
  6780. add: function (color) {
  6781. this.r += color.r;
  6782. this.g += color.g;
  6783. this.b += color.b;
  6784. return this;
  6785. },
  6786. addColors: function (color1, color2) {
  6787. this.r = color1.r + color2.r;
  6788. this.g = color1.g + color2.g;
  6789. this.b = color1.b + color2.b;
  6790. return this;
  6791. },
  6792. addScalar: function (s) {
  6793. this.r += s;
  6794. this.g += s;
  6795. this.b += s;
  6796. return this;
  6797. },
  6798. sub: function (color) {
  6799. this.r = Math.max(0, this.r - color.r);
  6800. this.g = Math.max(0, this.g - color.g);
  6801. this.b = Math.max(0, this.b - color.b);
  6802. return this;
  6803. },
  6804. multiply: function (color) {
  6805. this.r *= color.r;
  6806. this.g *= color.g;
  6807. this.b *= color.b;
  6808. return this;
  6809. },
  6810. multiplyScalar: function (s) {
  6811. this.r *= s;
  6812. this.g *= s;
  6813. this.b *= s;
  6814. return this;
  6815. },
  6816. lerp: function (color, alpha) {
  6817. this.r += (color.r - this.r) * alpha;
  6818. this.g += (color.g - this.g) * alpha;
  6819. this.b += (color.b - this.b) * alpha;
  6820. return this;
  6821. },
  6822. lerpHSL: function (color, alpha) {
  6823. this.getHSL(_hslA);
  6824. color.getHSL(_hslB);
  6825. var h = _Math.lerp(_hslA.h, _hslB.h, alpha);
  6826. var s = _Math.lerp(_hslA.s, _hslB.s, alpha);
  6827. var l = _Math.lerp(_hslA.l, _hslB.l, alpha);
  6828. this.setHSL(h, s, l);
  6829. return this;
  6830. },
  6831. equals: function (c) {
  6832. return c.r === this.r && c.g === this.g && c.b === this.b;
  6833. },
  6834. fromArray: function (array, offset) {
  6835. if (offset === undefined) offset = 0;
  6836. this.r = array[offset];
  6837. this.g = array[offset + 1];
  6838. this.b = array[offset + 2];
  6839. return this;
  6840. },
  6841. toArray: function (array, offset) {
  6842. if (array === undefined) array = [];
  6843. if (offset === undefined) offset = 0;
  6844. array[offset] = this.r;
  6845. array[offset + 1] = this.g;
  6846. array[offset + 2] = this.b;
  6847. return array;
  6848. },
  6849. toJSON: function () {
  6850. return this.getHex();
  6851. }
  6852. });
  6853. /**
  6854. * @author mrdoob / http://mrdoob.com/
  6855. * @author alteredq / http://alteredqualia.com/
  6856. */
  6857. function Face3(a, b, c, normal, color, materialIndex) {
  6858. this.a = a;
  6859. this.b = b;
  6860. this.c = c;
  6861. this.normal = normal && normal.isVector3 ? normal : new Vector3();
  6862. this.vertexNormals = Array.isArray(normal) ? normal : [];
  6863. this.color = color && color.isColor ? color : new Color();
  6864. this.vertexColors = Array.isArray(color) ? color : [];
  6865. this.materialIndex = materialIndex !== undefined ? materialIndex : 0;
  6866. }
  6867. Object.assign(Face3.prototype, {
  6868. clone: function () {
  6869. return new this.constructor().copy(this);
  6870. },
  6871. copy: function (source) {
  6872. this.a = source.a;
  6873. this.b = source.b;
  6874. this.c = source.c;
  6875. this.normal.copy(source.normal);
  6876. this.color.copy(source.color);
  6877. this.materialIndex = source.materialIndex;
  6878. for (var i = 0, il = source.vertexNormals.length; i < il; i++) {
  6879. this.vertexNormals[i] = source.vertexNormals[i].clone();
  6880. }
  6881. for (var i = 0, il = source.vertexColors.length; i < il; i++) {
  6882. this.vertexColors[i] = source.vertexColors[i].clone();
  6883. }
  6884. return this;
  6885. }
  6886. });
  6887. /**
  6888. * @author mrdoob / http://mrdoob.com/
  6889. * @author alteredq / http://alteredqualia.com/
  6890. */
  6891. var materialId = 0;
  6892. function Material() {
  6893. Object.defineProperty(this, 'id', {
  6894. value: materialId++
  6895. });
  6896. this.uuid = _Math.generateUUID();
  6897. this.name = '';
  6898. this.type = 'Material';
  6899. this.fog = true;
  6900. this.blending = NormalBlending;
  6901. this.side = FrontSide;
  6902. this.flatShading = false;
  6903. this.vertexTangents = false;
  6904. this.vertexColors = NoColors; // THREE.NoColors, THREE.VertexColors, THREE.FaceColors
  6905. this.opacity = 1;
  6906. this.transparent = false;
  6907. this.blendSrc = SrcAlphaFactor;
  6908. this.blendDst = OneMinusSrcAlphaFactor;
  6909. this.blendEquation = AddEquation;
  6910. this.blendSrcAlpha = null;
  6911. this.blendDstAlpha = null;
  6912. this.blendEquationAlpha = null;
  6913. this.depthFunc = LessEqualDepth;
  6914. this.depthTest = true;
  6915. this.depthWrite = true;
  6916. this.stencilWriteMask = 0xff;
  6917. this.stencilFunc = AlwaysStencilFunc;
  6918. this.stencilRef = 0;
  6919. this.stencilFuncMask = 0xff;
  6920. this.stencilFail = KeepStencilOp;
  6921. this.stencilZFail = KeepStencilOp;
  6922. this.stencilZPass = KeepStencilOp;
  6923. this.stencilWrite = false;
  6924. this.clippingPlanes = null;
  6925. this.clipIntersection = false;
  6926. this.clipShadows = false;
  6927. this.shadowSide = null;
  6928. this.colorWrite = true;
  6929. this.precision = null; // override the renderer's default precision for this material
  6930. this.polygonOffset = false;
  6931. this.polygonOffsetFactor = 0;
  6932. this.polygonOffsetUnits = 0;
  6933. this.dithering = false;
  6934. this.alphaTest = 0;
  6935. this.premultipliedAlpha = false;
  6936. this.visible = true;
  6937. this.toneMapped = true;
  6938. this.userData = {};
  6939. this.needsUpdate = true;
  6940. }
  6941. Material.prototype = Object.assign(Object.create(EventDispatcher.prototype), {
  6942. constructor: Material,
  6943. isMaterial: true,
  6944. onBeforeCompile: function () {},
  6945. setValues: function (values) {
  6946. if (values === undefined) return;
  6947. for (var key in values) {
  6948. var newValue = values[key];
  6949. if (newValue === undefined) {
  6950. console.warn("THREE.Material: '" + key + "' parameter is undefined.");
  6951. continue;
  6952. } // for backward compatability if shading is set in the constructor
  6953. if (key === 'shading') {
  6954. console.warn('THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.');
  6955. this.flatShading = newValue === FlatShading ? true : false;
  6956. continue;
  6957. }
  6958. var currentValue = this[key];
  6959. if (currentValue === undefined) {
  6960. console.warn("THREE." + this.type + ": '" + key + "' is not a property of this material.");
  6961. continue;
  6962. }
  6963. if (currentValue && currentValue.isColor) {
  6964. currentValue.set(newValue);
  6965. } else if (currentValue && currentValue.isVector3 && newValue && newValue.isVector3) {
  6966. currentValue.copy(newValue);
  6967. } else {
  6968. this[key] = newValue;
  6969. }
  6970. }
  6971. },
  6972. toJSON: function (meta) {
  6973. var isRoot = meta === undefined || typeof meta === 'string';
  6974. if (isRoot) {
  6975. meta = {
  6976. textures: {},
  6977. images: {}
  6978. };
  6979. }
  6980. var data = {
  6981. metadata: {
  6982. version: 4.5,
  6983. type: 'Material',
  6984. generator: 'Material.toJSON'
  6985. }
  6986. }; // standard Material serialization
  6987. data.uuid = this.uuid;
  6988. data.type = this.type;
  6989. if (this.name !== '') data.name = this.name;
  6990. if (this.color && this.color.isColor) data.color = this.color.getHex();
  6991. if (this.roughness !== undefined) data.roughness = this.roughness;
  6992. if (this.metalness !== undefined) data.metalness = this.metalness;
  6993. if (this.sheen && this.sheen.isColor) data.sheen = this.sheen.getHex();
  6994. if (this.emissive && this.emissive.isColor) data.emissive = this.emissive.getHex();
  6995. if (this.emissiveIntensity && this.emissiveIntensity !== 1) data.emissiveIntensity = this.emissiveIntensity;
  6996. if (this.specular && this.specular.isColor) data.specular = this.specular.getHex();
  6997. if (this.shininess !== undefined) data.shininess = this.shininess;
  6998. if (this.clearcoat !== undefined) data.clearcoat = this.clearcoat;
  6999. if (this.clearcoatRoughness !== undefined) data.clearcoatRoughness = this.clearcoatRoughness;
  7000. if (this.clearcoatNormalMap && this.clearcoatNormalMap.isTexture) {
  7001. data.clearcoatNormalMap = this.clearcoatNormalMap.toJSON(meta).uuid;
  7002. data.clearcoatNormalScale = this.clearcoatNormalScale.toArray();
  7003. }
  7004. if (this.map && this.map.isTexture) data.map = this.map.toJSON(meta).uuid;
  7005. if (this.matcap && this.matcap.isTexture) data.matcap = this.matcap.toJSON(meta).uuid;
  7006. if (this.alphaMap && this.alphaMap.isTexture) data.alphaMap = this.alphaMap.toJSON(meta).uuid;
  7007. if (this.lightMap && this.lightMap.isTexture) data.lightMap = this.lightMap.toJSON(meta).uuid;
  7008. if (this.aoMap && this.aoMap.isTexture) {
  7009. data.aoMap = this.aoMap.toJSON(meta).uuid;
  7010. data.aoMapIntensity = this.aoMapIntensity;
  7011. }
  7012. if (this.bumpMap && this.bumpMap.isTexture) {
  7013. data.bumpMap = this.bumpMap.toJSON(meta).uuid;
  7014. data.bumpScale = this.bumpScale;
  7015. }
  7016. if (this.normalMap && this.normalMap.isTexture) {
  7017. data.normalMap = this.normalMap.toJSON(meta).uuid;
  7018. data.normalMapType = this.normalMapType;
  7019. data.normalScale = this.normalScale.toArray();
  7020. }
  7021. if (this.displacementMap && this.displacementMap.isTexture) {
  7022. data.displacementMap = this.displacementMap.toJSON(meta).uuid;
  7023. data.displacementScale = this.displacementScale;
  7024. data.displacementBias = this.displacementBias;
  7025. }
  7026. if (this.roughnessMap && this.roughnessMap.isTexture) data.roughnessMap = this.roughnessMap.toJSON(meta).uuid;
  7027. if (this.metalnessMap && this.metalnessMap.isTexture) data.metalnessMap = this.metalnessMap.toJSON(meta).uuid;
  7028. if (this.emissiveMap && this.emissiveMap.isTexture) data.emissiveMap = this.emissiveMap.toJSON(meta).uuid;
  7029. if (this.specularMap && this.specularMap.isTexture) data.specularMap = this.specularMap.toJSON(meta).uuid;
  7030. if (this.envMap && this.envMap.isTexture) {
  7031. data.envMap = this.envMap.toJSON(meta).uuid;
  7032. data.reflectivity = this.reflectivity; // Scale behind envMap
  7033. data.refractionRatio = this.refractionRatio;
  7034. if (this.combine !== undefined) data.combine = this.combine;
  7035. if (this.envMapIntensity !== undefined) data.envMapIntensity = this.envMapIntensity;
  7036. }
  7037. if (this.gradientMap && this.gradientMap.isTexture) {
  7038. data.gradientMap = this.gradientMap.toJSON(meta).uuid;
  7039. }
  7040. if (this.size !== undefined) data.size = this.size;
  7041. if (this.sizeAttenuation !== undefined) data.sizeAttenuation = this.sizeAttenuation;
  7042. if (this.blending !== NormalBlending) data.blending = this.blending;
  7043. if (this.flatShading === true) data.flatShading = this.flatShading;
  7044. if (this.side !== FrontSide) data.side = this.side;
  7045. if (this.vertexColors !== NoColors) data.vertexColors = this.vertexColors;
  7046. if (this.opacity < 1) data.opacity = this.opacity;
  7047. if (this.transparent === true) data.transparent = this.transparent;
  7048. data.depthFunc = this.depthFunc;
  7049. data.depthTest = this.depthTest;
  7050. data.depthWrite = this.depthWrite;
  7051. data.stencilWrite = this.stencilWrite;
  7052. data.stencilWriteMask = this.stencilWriteMask;
  7053. data.stencilFunc = this.stencilFunc;
  7054. data.stencilRef = this.stencilRef;
  7055. data.stencilFuncMask = this.stencilFuncMask;
  7056. data.stencilFail = this.stencilFail;
  7057. data.stencilZFail = this.stencilZFail;
  7058. data.stencilZPass = this.stencilZPass; // rotation (SpriteMaterial)
  7059. if (this.rotation && this.rotation !== 0) data.rotation = this.rotation;
  7060. if (this.polygonOffset === true) data.polygonOffset = true;
  7061. if (this.polygonOffsetFactor !== 0) data.polygonOffsetFactor = this.polygonOffsetFactor;
  7062. if (this.polygonOffsetUnits !== 0) data.polygonOffsetUnits = this.polygonOffsetUnits;
  7063. if (this.linewidth && this.linewidth !== 1) data.linewidth = this.linewidth;
  7064. if (this.dashSize !== undefined) data.dashSize = this.dashSize;
  7065. if (this.gapSize !== undefined) data.gapSize = this.gapSize;
  7066. if (this.scale !== undefined) data.scale = this.scale;
  7067. if (this.dithering === true) data.dithering = true;
  7068. if (this.alphaTest > 0) data.alphaTest = this.alphaTest;
  7069. if (this.premultipliedAlpha === true) data.premultipliedAlpha = this.premultipliedAlpha;
  7070. if (this.wireframe === true) data.wireframe = this.wireframe;
  7071. if (this.wireframeLinewidth > 1) data.wireframeLinewidth = this.wireframeLinewidth;
  7072. if (this.wireframeLinecap !== 'round') data.wireframeLinecap = this.wireframeLinecap;
  7073. if (this.wireframeLinejoin !== 'round') data.wireframeLinejoin = this.wireframeLinejoin;
  7074. if (this.morphTargets === true) data.morphTargets = true;
  7075. if (this.morphNormals === true) data.morphNormals = true;
  7076. if (this.skinning === true) data.skinning = true;
  7077. if (this.visible === false) data.visible = false;
  7078. if (this.toneMapped === false) data.toneMapped = false;
  7079. if (JSON.stringify(this.userData) !== '{}') data.userData = this.userData; // TODO: Copied from Object3D.toJSON
  7080. function extractFromCache(cache) {
  7081. var values = [];
  7082. for (var key in cache) {
  7083. var data = cache[key];
  7084. delete data.metadata;
  7085. values.push(data);
  7086. }
  7087. return values;
  7088. }
  7089. if (isRoot) {
  7090. var textures = extractFromCache(meta.textures);
  7091. var images = extractFromCache(meta.images);
  7092. if (textures.length > 0) data.textures = textures;
  7093. if (images.length > 0) data.images = images;
  7094. }
  7095. return data;
  7096. },
  7097. clone: function () {
  7098. return new this.constructor().copy(this);
  7099. },
  7100. copy: function (source) {
  7101. this.name = source.name;
  7102. this.fog = source.fog;
  7103. this.blending = source.blending;
  7104. this.side = source.side;
  7105. this.flatShading = source.flatShading;
  7106. this.vertexColors = source.vertexColors;
  7107. this.opacity = source.opacity;
  7108. this.transparent = source.transparent;
  7109. this.blendSrc = source.blendSrc;
  7110. this.blendDst = source.blendDst;
  7111. this.blendEquation = source.blendEquation;
  7112. this.blendSrcAlpha = source.blendSrcAlpha;
  7113. this.blendDstAlpha = source.blendDstAlpha;
  7114. this.blendEquationAlpha = source.blendEquationAlpha;
  7115. this.depthFunc = source.depthFunc;
  7116. this.depthTest = source.depthTest;
  7117. this.depthWrite = source.depthWrite;
  7118. this.stencilWrite = source.stencilWrite;
  7119. this.stencilWriteMask = source.stencilWriteMask;
  7120. this.stencilFunc = source.stencilFunc;
  7121. this.stencilRef = source.stencilRef;
  7122. this.stencilFuncMask = source.stencilFuncMask;
  7123. this.stencilFail = source.stencilFail;
  7124. this.stencilZFail = source.stencilZFail;
  7125. this.stencilZPass = source.stencilZPass;
  7126. this.colorWrite = source.colorWrite;
  7127. this.precision = source.precision;
  7128. this.polygonOffset = source.polygonOffset;
  7129. this.polygonOffsetFactor = source.polygonOffsetFactor;
  7130. this.polygonOffsetUnits = source.polygonOffsetUnits;
  7131. this.dithering = source.dithering;
  7132. this.alphaTest = source.alphaTest;
  7133. this.premultipliedAlpha = source.premultipliedAlpha;
  7134. this.visible = source.visible;
  7135. this.toneMapped = source.toneMapped;
  7136. this.userData = JSON.parse(JSON.stringify(source.userData));
  7137. this.clipShadows = source.clipShadows;
  7138. this.clipIntersection = source.clipIntersection;
  7139. var srcPlanes = source.clippingPlanes,
  7140. dstPlanes = null;
  7141. if (srcPlanes !== null) {
  7142. var n = srcPlanes.length;
  7143. dstPlanes = new Array(n);
  7144. for (var i = 0; i !== n; ++i) dstPlanes[i] = srcPlanes[i].clone();
  7145. }
  7146. this.clippingPlanes = dstPlanes;
  7147. this.shadowSide = source.shadowSide;
  7148. return this;
  7149. },
  7150. dispose: function () {
  7151. this.dispatchEvent({
  7152. type: 'dispose'
  7153. });
  7154. }
  7155. });
  7156. /**
  7157. * @author mrdoob / http://mrdoob.com/
  7158. * @author alteredq / http://alteredqualia.com/
  7159. *
  7160. * parameters = {
  7161. * color: <hex>,
  7162. * opacity: <float>,
  7163. * map: new THREE.Texture( <Image> ),
  7164. *
  7165. * lightMap: new THREE.Texture( <Image> ),
  7166. * lightMapIntensity: <float>
  7167. *
  7168. * aoMap: new THREE.Texture( <Image> ),
  7169. * aoMapIntensity: <float>
  7170. *
  7171. * specularMap: new THREE.Texture( <Image> ),
  7172. *
  7173. * alphaMap: new THREE.Texture( <Image> ),
  7174. *
  7175. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  7176. * combine: THREE.Multiply,
  7177. * reflectivity: <float>,
  7178. * refractionRatio: <float>,
  7179. *
  7180. * depthTest: <bool>,
  7181. * depthWrite: <bool>,
  7182. *
  7183. * wireframe: <boolean>,
  7184. * wireframeLinewidth: <float>,
  7185. *
  7186. * skinning: <bool>,
  7187. * morphTargets: <bool>
  7188. * }
  7189. */
  7190. function MeshBasicMaterial(parameters) {
  7191. Material.call(this);
  7192. this.type = 'MeshBasicMaterial';
  7193. this.color = new Color(0xffffff); // emissive
  7194. this.map = null;
  7195. this.lightMap = null;
  7196. this.lightMapIntensity = 1.0;
  7197. this.aoMap = null;
  7198. this.aoMapIntensity = 1.0;
  7199. this.specularMap = null;
  7200. this.alphaMap = null;
  7201. this.envMap = null;
  7202. this.combine = MultiplyOperation;
  7203. this.reflectivity = 1;
  7204. this.refractionRatio = 0.98;
  7205. this.wireframe = false;
  7206. this.wireframeLinewidth = 1;
  7207. this.wireframeLinecap = 'round';
  7208. this.wireframeLinejoin = 'round';
  7209. this.skinning = false;
  7210. this.morphTargets = false;
  7211. this.setValues(parameters);
  7212. }
  7213. MeshBasicMaterial.prototype = Object.create(Material.prototype);
  7214. MeshBasicMaterial.prototype.constructor = MeshBasicMaterial;
  7215. MeshBasicMaterial.prototype.isMeshBasicMaterial = true;
  7216. MeshBasicMaterial.prototype.copy = function (source) {
  7217. Material.prototype.copy.call(this, source);
  7218. this.color.copy(source.color);
  7219. this.map = source.map;
  7220. this.lightMap = source.lightMap;
  7221. this.lightMapIntensity = source.lightMapIntensity;
  7222. this.aoMap = source.aoMap;
  7223. this.aoMapIntensity = source.aoMapIntensity;
  7224. this.specularMap = source.specularMap;
  7225. this.alphaMap = source.alphaMap;
  7226. this.envMap = source.envMap;
  7227. this.combine = source.combine;
  7228. this.reflectivity = source.reflectivity;
  7229. this.refractionRatio = source.refractionRatio;
  7230. this.wireframe = source.wireframe;
  7231. this.wireframeLinewidth = source.wireframeLinewidth;
  7232. this.wireframeLinecap = source.wireframeLinecap;
  7233. this.wireframeLinejoin = source.wireframeLinejoin;
  7234. this.skinning = source.skinning;
  7235. this.morphTargets = source.morphTargets;
  7236. return this;
  7237. };
  7238. /**
  7239. * @author mrdoob / http://mrdoob.com/
  7240. */
  7241. function BufferAttribute(array, itemSize, normalized) {
  7242. if (Array.isArray(array)) {
  7243. throw new TypeError('THREE.BufferAttribute: array should be a Typed Array.');
  7244. }
  7245. this.name = '';
  7246. this.array = array;
  7247. this.itemSize = itemSize;
  7248. this.count = array !== undefined ? array.length / itemSize : 0;
  7249. this.normalized = normalized === true;
  7250. this.dynamic = false;
  7251. this.updateRange = {
  7252. offset: 0,
  7253. count: -1
  7254. };
  7255. this.version = 0;
  7256. }
  7257. Object.defineProperty(BufferAttribute.prototype, 'needsUpdate', {
  7258. set: function (value) {
  7259. if (value === true) this.version++;
  7260. }
  7261. });
  7262. Object.assign(BufferAttribute.prototype, {
  7263. isBufferAttribute: true,
  7264. onUploadCallback: function () {},
  7265. setDynamic: function (value) {
  7266. this.dynamic = value;
  7267. return this;
  7268. },
  7269. copy: function (source) {
  7270. this.name = source.name;
  7271. this.array = new source.array.constructor(source.array);
  7272. this.itemSize = source.itemSize;
  7273. this.count = source.count;
  7274. this.normalized = source.normalized;
  7275. this.dynamic = source.dynamic;
  7276. return this;
  7277. },
  7278. copyAt: function (index1, attribute, index2) {
  7279. index1 *= this.itemSize;
  7280. index2 *= attribute.itemSize;
  7281. for (var i = 0, l = this.itemSize; i < l; i++) {
  7282. this.array[index1 + i] = attribute.array[index2 + i];
  7283. }
  7284. return this;
  7285. },
  7286. copyArray: function (array) {
  7287. this.array.set(array);
  7288. return this;
  7289. },
  7290. copyColorsArray: function (colors) {
  7291. var array = this.array,
  7292. offset = 0;
  7293. for (var i = 0, l = colors.length; i < l; i++) {
  7294. var color = colors[i];
  7295. if (color === undefined) {
  7296. console.warn('THREE.BufferAttribute.copyColorsArray(): color is undefined', i);
  7297. color = new Color();
  7298. }
  7299. array[offset++] = color.r;
  7300. array[offset++] = color.g;
  7301. array[offset++] = color.b;
  7302. }
  7303. return this;
  7304. },
  7305. copyVector2sArray: function (vectors) {
  7306. var array = this.array,
  7307. offset = 0;
  7308. for (var i = 0, l = vectors.length; i < l; i++) {
  7309. var vector = vectors[i];
  7310. if (vector === undefined) {
  7311. console.warn('THREE.BufferAttribute.copyVector2sArray(): vector is undefined', i);
  7312. vector = new Vector2();
  7313. }
  7314. array[offset++] = vector.x;
  7315. array[offset++] = vector.y;
  7316. }
  7317. return this;
  7318. },
  7319. copyVector3sArray: function (vectors) {
  7320. var array = this.array,
  7321. offset = 0;
  7322. for (var i = 0, l = vectors.length; i < l; i++) {
  7323. var vector = vectors[i];
  7324. if (vector === undefined) {
  7325. console.warn('THREE.BufferAttribute.copyVector3sArray(): vector is undefined', i);
  7326. vector = new Vector3();
  7327. }
  7328. array[offset++] = vector.x;
  7329. array[offset++] = vector.y;
  7330. array[offset++] = vector.z;
  7331. }
  7332. return this;
  7333. },
  7334. copyVector4sArray: function (vectors) {
  7335. var array = this.array,
  7336. offset = 0;
  7337. for (var i = 0, l = vectors.length; i < l; i++) {
  7338. var vector = vectors[i];
  7339. if (vector === undefined) {
  7340. console.warn('THREE.BufferAttribute.copyVector4sArray(): vector is undefined', i);
  7341. vector = new Vector4();
  7342. }
  7343. array[offset++] = vector.x;
  7344. array[offset++] = vector.y;
  7345. array[offset++] = vector.z;
  7346. array[offset++] = vector.w;
  7347. }
  7348. return this;
  7349. },
  7350. set: function (value, offset) {
  7351. if (offset === undefined) offset = 0;
  7352. this.array.set(value, offset);
  7353. return this;
  7354. },
  7355. getX: function (index) {
  7356. return this.array[index * this.itemSize];
  7357. },
  7358. setX: function (index, x) {
  7359. this.array[index * this.itemSize] = x;
  7360. return this;
  7361. },
  7362. getY: function (index) {
  7363. return this.array[index * this.itemSize + 1];
  7364. },
  7365. setY: function (index, y) {
  7366. this.array[index * this.itemSize + 1] = y;
  7367. return this;
  7368. },
  7369. getZ: function (index) {
  7370. return this.array[index * this.itemSize + 2];
  7371. },
  7372. setZ: function (index, z) {
  7373. this.array[index * this.itemSize + 2] = z;
  7374. return this;
  7375. },
  7376. getW: function (index) {
  7377. return this.array[index * this.itemSize + 3];
  7378. },
  7379. setW: function (index, w) {
  7380. this.array[index * this.itemSize + 3] = w;
  7381. return this;
  7382. },
  7383. setXY: function (index, x, y) {
  7384. index *= this.itemSize;
  7385. this.array[index + 0] = x;
  7386. this.array[index + 1] = y;
  7387. return this;
  7388. },
  7389. setXYZ: function (index, x, y, z) {
  7390. index *= this.itemSize;
  7391. this.array[index + 0] = x;
  7392. this.array[index + 1] = y;
  7393. this.array[index + 2] = z;
  7394. return this;
  7395. },
  7396. setXYZW: function (index, x, y, z, w) {
  7397. index *= this.itemSize;
  7398. this.array[index + 0] = x;
  7399. this.array[index + 1] = y;
  7400. this.array[index + 2] = z;
  7401. this.array[index + 3] = w;
  7402. return this;
  7403. },
  7404. onUpload: function (callback) {
  7405. this.onUploadCallback = callback;
  7406. return this;
  7407. },
  7408. clone: function () {
  7409. return new this.constructor(this.array, this.itemSize).copy(this);
  7410. },
  7411. toJSON: function () {
  7412. return {
  7413. itemSize: this.itemSize,
  7414. type: this.array.constructor.name,
  7415. array: Array.prototype.slice.call(this.array),
  7416. normalized: this.normalized
  7417. };
  7418. }
  7419. }); //
  7420. function Int8BufferAttribute(array, itemSize, normalized) {
  7421. BufferAttribute.call(this, new Int8Array(array), itemSize, normalized);
  7422. }
  7423. Int8BufferAttribute.prototype = Object.create(BufferAttribute.prototype);
  7424. Int8BufferAttribute.prototype.constructor = Int8BufferAttribute;
  7425. function Uint8BufferAttribute(array, itemSize, normalized) {
  7426. BufferAttribute.call(this, new Uint8Array(array), itemSize, normalized);
  7427. }
  7428. Uint8BufferAttribute.prototype = Object.create(BufferAttribute.prototype);
  7429. Uint8BufferAttribute.prototype.constructor = Uint8BufferAttribute;
  7430. function Uint8ClampedBufferAttribute(array, itemSize, normalized) {
  7431. BufferAttribute.call(this, new Uint8ClampedArray(array), itemSize, normalized);
  7432. }
  7433. Uint8ClampedBufferAttribute.prototype = Object.create(BufferAttribute.prototype);
  7434. Uint8ClampedBufferAttribute.prototype.constructor = Uint8ClampedBufferAttribute;
  7435. function Int16BufferAttribute(array, itemSize, normalized) {
  7436. BufferAttribute.call(this, new Int16Array(array), itemSize, normalized);
  7437. }
  7438. Int16BufferAttribute.prototype = Object.create(BufferAttribute.prototype);
  7439. Int16BufferAttribute.prototype.constructor = Int16BufferAttribute;
  7440. function Uint16BufferAttribute(array, itemSize, normalized) {
  7441. BufferAttribute.call(this, new Uint16Array(array), itemSize, normalized);
  7442. }
  7443. Uint16BufferAttribute.prototype = Object.create(BufferAttribute.prototype);
  7444. Uint16BufferAttribute.prototype.constructor = Uint16BufferAttribute;
  7445. function Int32BufferAttribute(array, itemSize, normalized) {
  7446. BufferAttribute.call(this, new Int32Array(array), itemSize, normalized);
  7447. }
  7448. Int32BufferAttribute.prototype = Object.create(BufferAttribute.prototype);
  7449. Int32BufferAttribute.prototype.constructor = Int32BufferAttribute;
  7450. function Uint32BufferAttribute(array, itemSize, normalized) {
  7451. BufferAttribute.call(this, new Uint32Array(array), itemSize, normalized);
  7452. }
  7453. Uint32BufferAttribute.prototype = Object.create(BufferAttribute.prototype);
  7454. Uint32BufferAttribute.prototype.constructor = Uint32BufferAttribute;
  7455. function Float32BufferAttribute(array, itemSize, normalized) {
  7456. BufferAttribute.call(this, new Float32Array(array), itemSize, normalized);
  7457. }
  7458. Float32BufferAttribute.prototype = Object.create(BufferAttribute.prototype);
  7459. Float32BufferAttribute.prototype.constructor = Float32BufferAttribute;
  7460. function Float64BufferAttribute(array, itemSize, normalized) {
  7461. BufferAttribute.call(this, new Float64Array(array), itemSize, normalized);
  7462. }
  7463. Float64BufferAttribute.prototype = Object.create(BufferAttribute.prototype);
  7464. Float64BufferAttribute.prototype.constructor = Float64BufferAttribute;
  7465. /**
  7466. * @author mrdoob / http://mrdoob.com/
  7467. */
  7468. function DirectGeometry() {
  7469. this.vertices = [];
  7470. this.normals = [];
  7471. this.colors = [];
  7472. this.uvs = [];
  7473. this.uvs2 = [];
  7474. this.groups = [];
  7475. this.morphTargets = {};
  7476. this.skinWeights = [];
  7477. this.skinIndices = []; // this.lineDistances = [];
  7478. this.boundingBox = null;
  7479. this.boundingSphere = null; // update flags
  7480. this.verticesNeedUpdate = false;
  7481. this.normalsNeedUpdate = false;
  7482. this.colorsNeedUpdate = false;
  7483. this.uvsNeedUpdate = false;
  7484. this.groupsNeedUpdate = false;
  7485. }
  7486. Object.assign(DirectGeometry.prototype, {
  7487. computeGroups: function (geometry) {
  7488. var group;
  7489. var groups = [];
  7490. var materialIndex = undefined;
  7491. var faces = geometry.faces;
  7492. for (var i = 0; i < faces.length; i++) {
  7493. var face = faces[i]; // materials
  7494. if (face.materialIndex !== materialIndex) {
  7495. materialIndex = face.materialIndex;
  7496. if (group !== undefined) {
  7497. group.count = i * 3 - group.start;
  7498. groups.push(group);
  7499. }
  7500. group = {
  7501. start: i * 3,
  7502. materialIndex: materialIndex
  7503. };
  7504. }
  7505. }
  7506. if (group !== undefined) {
  7507. group.count = i * 3 - group.start;
  7508. groups.push(group);
  7509. }
  7510. this.groups = groups;
  7511. },
  7512. fromGeometry: function (geometry) {
  7513. var faces = geometry.faces;
  7514. var vertices = geometry.vertices;
  7515. var faceVertexUvs = geometry.faceVertexUvs;
  7516. var hasFaceVertexUv = faceVertexUvs[0] && faceVertexUvs[0].length > 0;
  7517. var hasFaceVertexUv2 = faceVertexUvs[1] && faceVertexUvs[1].length > 0; // morphs
  7518. var morphTargets = geometry.morphTargets;
  7519. var morphTargetsLength = morphTargets.length;
  7520. var morphTargetsPosition;
  7521. if (morphTargetsLength > 0) {
  7522. morphTargetsPosition = [];
  7523. for (var i = 0; i < morphTargetsLength; i++) {
  7524. morphTargetsPosition[i] = {
  7525. name: morphTargets[i].name,
  7526. data: []
  7527. };
  7528. }
  7529. this.morphTargets.position = morphTargetsPosition;
  7530. }
  7531. var morphNormals = geometry.morphNormals;
  7532. var morphNormalsLength = morphNormals.length;
  7533. var morphTargetsNormal;
  7534. if (morphNormalsLength > 0) {
  7535. morphTargetsNormal = [];
  7536. for (var i = 0; i < morphNormalsLength; i++) {
  7537. morphTargetsNormal[i] = {
  7538. name: morphNormals[i].name,
  7539. data: []
  7540. };
  7541. }
  7542. this.morphTargets.normal = morphTargetsNormal;
  7543. } // skins
  7544. var skinIndices = geometry.skinIndices;
  7545. var skinWeights = geometry.skinWeights;
  7546. var hasSkinIndices = skinIndices.length === vertices.length;
  7547. var hasSkinWeights = skinWeights.length === vertices.length; //
  7548. if (vertices.length > 0 && faces.length === 0) {
  7549. console.error('THREE.DirectGeometry: Faceless geometries are not supported.');
  7550. }
  7551. for (var i = 0; i < faces.length; i++) {
  7552. var face = faces[i];
  7553. this.vertices.push(vertices[face.a], vertices[face.b], vertices[face.c]);
  7554. var vertexNormals = face.vertexNormals;
  7555. if (vertexNormals.length === 3) {
  7556. this.normals.push(vertexNormals[0], vertexNormals[1], vertexNormals[2]);
  7557. } else {
  7558. var normal = face.normal;
  7559. this.normals.push(normal, normal, normal);
  7560. }
  7561. var vertexColors = face.vertexColors;
  7562. if (vertexColors.length === 3) {
  7563. this.colors.push(vertexColors[0], vertexColors[1], vertexColors[2]);
  7564. } else {
  7565. var color = face.color;
  7566. this.colors.push(color, color, color);
  7567. }
  7568. if (hasFaceVertexUv === true) {
  7569. var vertexUvs = faceVertexUvs[0][i];
  7570. if (vertexUvs !== undefined) {
  7571. this.uvs.push(vertexUvs[0], vertexUvs[1], vertexUvs[2]);
  7572. } else {
  7573. console.warn('THREE.DirectGeometry.fromGeometry(): Undefined vertexUv ', i);
  7574. this.uvs.push(new Vector2(), new Vector2(), new Vector2());
  7575. }
  7576. }
  7577. if (hasFaceVertexUv2 === true) {
  7578. var vertexUvs = faceVertexUvs[1][i];
  7579. if (vertexUvs !== undefined) {
  7580. this.uvs2.push(vertexUvs[0], vertexUvs[1], vertexUvs[2]);
  7581. } else {
  7582. console.warn('THREE.DirectGeometry.fromGeometry(): Undefined vertexUv2 ', i);
  7583. this.uvs2.push(new Vector2(), new Vector2(), new Vector2());
  7584. }
  7585. } // morphs
  7586. for (var j = 0; j < morphTargetsLength; j++) {
  7587. var morphTarget = morphTargets[j].vertices;
  7588. morphTargetsPosition[j].data.push(morphTarget[face.a], morphTarget[face.b], morphTarget[face.c]);
  7589. }
  7590. for (var j = 0; j < morphNormalsLength; j++) {
  7591. var morphNormal = morphNormals[j].vertexNormals[i];
  7592. morphTargetsNormal[j].data.push(morphNormal.a, morphNormal.b, morphNormal.c);
  7593. } // skins
  7594. if (hasSkinIndices) {
  7595. this.skinIndices.push(skinIndices[face.a], skinIndices[face.b], skinIndices[face.c]);
  7596. }
  7597. if (hasSkinWeights) {
  7598. this.skinWeights.push(skinWeights[face.a], skinWeights[face.b], skinWeights[face.c]);
  7599. }
  7600. }
  7601. this.computeGroups(geometry);
  7602. this.verticesNeedUpdate = geometry.verticesNeedUpdate;
  7603. this.normalsNeedUpdate = geometry.normalsNeedUpdate;
  7604. this.colorsNeedUpdate = geometry.colorsNeedUpdate;
  7605. this.uvsNeedUpdate = geometry.uvsNeedUpdate;
  7606. this.groupsNeedUpdate = geometry.groupsNeedUpdate;
  7607. if (geometry.boundingSphere !== null) {
  7608. this.boundingSphere = geometry.boundingSphere.clone();
  7609. }
  7610. if (geometry.boundingBox !== null) {
  7611. this.boundingBox = geometry.boundingBox.clone();
  7612. }
  7613. return this;
  7614. }
  7615. });
  7616. /**
  7617. * @author mrdoob / http://mrdoob.com/
  7618. */
  7619. function arrayMax(array) {
  7620. if (array.length === 0) return -Infinity;
  7621. var max = array[0];
  7622. for (var i = 1, l = array.length; i < l; ++i) {
  7623. if (array[i] > max) max = array[i];
  7624. }
  7625. return max;
  7626. }
  7627. /**
  7628. * @author alteredq / http://alteredqualia.com/
  7629. * @author mrdoob / http://mrdoob.com/
  7630. */
  7631. var _bufferGeometryId = 1; // BufferGeometry uses odd numbers as Id
  7632. var _m1$2 = new Matrix4();
  7633. var _obj = new Object3D();
  7634. var _offset = new Vector3();
  7635. var _box$1 = new Box3();
  7636. var _boxMorphTargets = new Box3();
  7637. var _vector$4 = new Vector3();
  7638. function BufferGeometry() {
  7639. Object.defineProperty(this, 'id', {
  7640. value: _bufferGeometryId += 2
  7641. });
  7642. this.uuid = _Math.generateUUID();
  7643. this.name = '';
  7644. this.type = 'BufferGeometry';
  7645. this.index = null;
  7646. this.attributes = {};
  7647. this.morphAttributes = {};
  7648. this.groups = [];
  7649. this.boundingBox = null;
  7650. this.boundingSphere = null;
  7651. this.drawRange = {
  7652. start: 0,
  7653. count: Infinity
  7654. };
  7655. this.userData = {};
  7656. }
  7657. BufferGeometry.prototype = Object.assign(Object.create(EventDispatcher.prototype), {
  7658. constructor: BufferGeometry,
  7659. isBufferGeometry: true,
  7660. getIndex: function () {
  7661. return this.index;
  7662. },
  7663. setIndex: function (index) {
  7664. if (Array.isArray(index)) {
  7665. this.index = new (arrayMax(index) > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute)(index, 1);
  7666. } else {
  7667. this.index = index;
  7668. }
  7669. },
  7670. addAttribute: function (name, attribute) {
  7671. if (!(attribute && attribute.isBufferAttribute) && !(attribute && attribute.isInterleavedBufferAttribute)) {
  7672. console.warn('THREE.BufferGeometry: .addAttribute() now expects ( name, attribute ).');
  7673. return this.addAttribute(name, new BufferAttribute(arguments[1], arguments[2]));
  7674. }
  7675. if (name === 'index') {
  7676. console.warn('THREE.BufferGeometry.addAttribute: Use .setIndex() for index attribute.');
  7677. this.setIndex(attribute);
  7678. return this;
  7679. }
  7680. return this.setAttribute(name, attribute);
  7681. },
  7682. getAttribute: function (name) {
  7683. return this.attributes[name];
  7684. },
  7685. setAttribute: function (name, attribute) {
  7686. this.attributes[name] = attribute;
  7687. return this;
  7688. },
  7689. removeAttribute: function (name) {
  7690. delete this.attributes[name];
  7691. return this;
  7692. },
  7693. addGroup: function (start, count, materialIndex) {
  7694. this.groups.push({
  7695. start: start,
  7696. count: count,
  7697. materialIndex: materialIndex !== undefined ? materialIndex : 0
  7698. });
  7699. },
  7700. clearGroups: function () {
  7701. this.groups = [];
  7702. },
  7703. setDrawRange: function (start, count) {
  7704. this.drawRange.start = start;
  7705. this.drawRange.count = count;
  7706. },
  7707. applyMatrix: function (matrix) {
  7708. var position = this.attributes.position;
  7709. if (position !== undefined) {
  7710. matrix.applyToBufferAttribute(position);
  7711. position.needsUpdate = true;
  7712. }
  7713. var normal = this.attributes.normal;
  7714. if (normal !== undefined) {
  7715. var normalMatrix = new Matrix3().getNormalMatrix(matrix);
  7716. normalMatrix.applyToBufferAttribute(normal);
  7717. normal.needsUpdate = true;
  7718. }
  7719. var tangent = this.attributes.tangent;
  7720. if (tangent !== undefined) {
  7721. var normalMatrix = new Matrix3().getNormalMatrix(matrix); // Tangent is vec4, but the '.w' component is a sign value (+1/-1).
  7722. normalMatrix.applyToBufferAttribute(tangent);
  7723. tangent.needsUpdate = true;
  7724. }
  7725. if (this.boundingBox !== null) {
  7726. this.computeBoundingBox();
  7727. }
  7728. if (this.boundingSphere !== null) {
  7729. this.computeBoundingSphere();
  7730. }
  7731. return this;
  7732. },
  7733. rotateX: function (angle) {
  7734. // rotate geometry around world x-axis
  7735. _m1$2.makeRotationX(angle);
  7736. this.applyMatrix(_m1$2);
  7737. return this;
  7738. },
  7739. rotateY: function (angle) {
  7740. // rotate geometry around world y-axis
  7741. _m1$2.makeRotationY(angle);
  7742. this.applyMatrix(_m1$2);
  7743. return this;
  7744. },
  7745. rotateZ: function (angle) {
  7746. // rotate geometry around world z-axis
  7747. _m1$2.makeRotationZ(angle);
  7748. this.applyMatrix(_m1$2);
  7749. return this;
  7750. },
  7751. translate: function (x, y, z) {
  7752. // translate geometry
  7753. _m1$2.makeTranslation(x, y, z);
  7754. this.applyMatrix(_m1$2);
  7755. return this;
  7756. },
  7757. scale: function (x, y, z) {
  7758. // scale geometry
  7759. _m1$2.makeScale(x, y, z);
  7760. this.applyMatrix(_m1$2);
  7761. return this;
  7762. },
  7763. lookAt: function (vector) {
  7764. _obj.lookAt(vector);
  7765. _obj.updateMatrix();
  7766. this.applyMatrix(_obj.matrix);
  7767. return this;
  7768. },
  7769. center: function () {
  7770. this.computeBoundingBox();
  7771. this.boundingBox.getCenter(_offset).negate();
  7772. this.translate(_offset.x, _offset.y, _offset.z);
  7773. return this;
  7774. },
  7775. setFromObject: function (object) {
  7776. // console.log( 'THREE.BufferGeometry.setFromObject(). Converting', object, this );
  7777. var geometry = object.geometry;
  7778. if (object.isPoints || object.isLine) {
  7779. var positions = new Float32BufferAttribute(geometry.vertices.length * 3, 3);
  7780. var colors = new Float32BufferAttribute(geometry.colors.length * 3, 3);
  7781. this.addAttribute('position', positions.copyVector3sArray(geometry.vertices));
  7782. this.addAttribute('color', colors.copyColorsArray(geometry.colors));
  7783. if (geometry.lineDistances && geometry.lineDistances.length === geometry.vertices.length) {
  7784. var lineDistances = new Float32BufferAttribute(geometry.lineDistances.length, 1);
  7785. this.addAttribute('lineDistance', lineDistances.copyArray(geometry.lineDistances));
  7786. }
  7787. if (geometry.boundingSphere !== null) {
  7788. this.boundingSphere = geometry.boundingSphere.clone();
  7789. }
  7790. if (geometry.boundingBox !== null) {
  7791. this.boundingBox = geometry.boundingBox.clone();
  7792. }
  7793. } else if (object.isMesh) {
  7794. if (geometry && geometry.isGeometry) {
  7795. this.fromGeometry(geometry);
  7796. }
  7797. }
  7798. return this;
  7799. },
  7800. setFromPoints: function (points) {
  7801. var position = [];
  7802. for (var i = 0, l = points.length; i < l; i++) {
  7803. var point = points[i];
  7804. position.push(point.x, point.y, point.z || 0);
  7805. }
  7806. this.addAttribute('position', new Float32BufferAttribute(position, 3));
  7807. return this;
  7808. },
  7809. updateFromObject: function (object) {
  7810. var geometry = object.geometry;
  7811. if (object.isMesh) {
  7812. var direct = geometry.__directGeometry;
  7813. if (geometry.elementsNeedUpdate === true) {
  7814. direct = undefined;
  7815. geometry.elementsNeedUpdate = false;
  7816. }
  7817. if (direct === undefined) {
  7818. return this.fromGeometry(geometry);
  7819. }
  7820. direct.verticesNeedUpdate = geometry.verticesNeedUpdate;
  7821. direct.normalsNeedUpdate = geometry.normalsNeedUpdate;
  7822. direct.colorsNeedUpdate = geometry.colorsNeedUpdate;
  7823. direct.uvsNeedUpdate = geometry.uvsNeedUpdate;
  7824. direct.groupsNeedUpdate = geometry.groupsNeedUpdate;
  7825. geometry.verticesNeedUpdate = false;
  7826. geometry.normalsNeedUpdate = false;
  7827. geometry.colorsNeedUpdate = false;
  7828. geometry.uvsNeedUpdate = false;
  7829. geometry.groupsNeedUpdate = false;
  7830. geometry = direct;
  7831. }
  7832. var attribute;
  7833. if (geometry.verticesNeedUpdate === true) {
  7834. attribute = this.attributes.position;
  7835. if (attribute !== undefined) {
  7836. attribute.copyVector3sArray(geometry.vertices);
  7837. attribute.needsUpdate = true;
  7838. }
  7839. geometry.verticesNeedUpdate = false;
  7840. }
  7841. if (geometry.normalsNeedUpdate === true) {
  7842. attribute = this.attributes.normal;
  7843. if (attribute !== undefined) {
  7844. attribute.copyVector3sArray(geometry.normals);
  7845. attribute.needsUpdate = true;
  7846. }
  7847. geometry.normalsNeedUpdate = false;
  7848. }
  7849. if (geometry.colorsNeedUpdate === true) {
  7850. attribute = this.attributes.color;
  7851. if (attribute !== undefined) {
  7852. attribute.copyColorsArray(geometry.colors);
  7853. attribute.needsUpdate = true;
  7854. }
  7855. geometry.colorsNeedUpdate = false;
  7856. }
  7857. if (geometry.uvsNeedUpdate) {
  7858. attribute = this.attributes.uv;
  7859. if (attribute !== undefined) {
  7860. attribute.copyVector2sArray(geometry.uvs);
  7861. attribute.needsUpdate = true;
  7862. }
  7863. geometry.uvsNeedUpdate = false;
  7864. }
  7865. if (geometry.lineDistancesNeedUpdate) {
  7866. attribute = this.attributes.lineDistance;
  7867. if (attribute !== undefined) {
  7868. attribute.copyArray(geometry.lineDistances);
  7869. attribute.needsUpdate = true;
  7870. }
  7871. geometry.lineDistancesNeedUpdate = false;
  7872. }
  7873. if (geometry.groupsNeedUpdate) {
  7874. geometry.computeGroups(object.geometry);
  7875. this.groups = geometry.groups;
  7876. geometry.groupsNeedUpdate = false;
  7877. }
  7878. return this;
  7879. },
  7880. fromGeometry: function (geometry) {
  7881. geometry.__directGeometry = new DirectGeometry().fromGeometry(geometry);
  7882. return this.fromDirectGeometry(geometry.__directGeometry);
  7883. },
  7884. fromDirectGeometry: function (geometry) {
  7885. var positions = new Float32Array(geometry.vertices.length * 3);
  7886. this.addAttribute('position', new BufferAttribute(positions, 3).copyVector3sArray(geometry.vertices));
  7887. if (geometry.normals.length > 0) {
  7888. var normals = new Float32Array(geometry.normals.length * 3);
  7889. this.addAttribute('normal', new BufferAttribute(normals, 3).copyVector3sArray(geometry.normals));
  7890. }
  7891. if (geometry.colors.length > 0) {
  7892. var colors = new Float32Array(geometry.colors.length * 3);
  7893. this.addAttribute('color', new BufferAttribute(colors, 3).copyColorsArray(geometry.colors));
  7894. }
  7895. if (geometry.uvs.length > 0) {
  7896. var uvs = new Float32Array(geometry.uvs.length * 2);
  7897. this.addAttribute('uv', new BufferAttribute(uvs, 2).copyVector2sArray(geometry.uvs));
  7898. }
  7899. if (geometry.uvs2.length > 0) {
  7900. var uvs2 = new Float32Array(geometry.uvs2.length * 2);
  7901. this.addAttribute('uv2', new BufferAttribute(uvs2, 2).copyVector2sArray(geometry.uvs2));
  7902. } // groups
  7903. this.groups = geometry.groups; // morphs
  7904. for (var name in geometry.morphTargets) {
  7905. var array = [];
  7906. var morphTargets = geometry.morphTargets[name];
  7907. for (var i = 0, l = morphTargets.length; i < l; i++) {
  7908. var morphTarget = morphTargets[i];
  7909. var attribute = new Float32BufferAttribute(morphTarget.data.length * 3, 3);
  7910. attribute.name = morphTarget.name;
  7911. array.push(attribute.copyVector3sArray(morphTarget.data));
  7912. }
  7913. this.morphAttributes[name] = array;
  7914. } // skinning
  7915. if (geometry.skinIndices.length > 0) {
  7916. var skinIndices = new Float32BufferAttribute(geometry.skinIndices.length * 4, 4);
  7917. this.addAttribute('skinIndex', skinIndices.copyVector4sArray(geometry.skinIndices));
  7918. }
  7919. if (geometry.skinWeights.length > 0) {
  7920. var skinWeights = new Float32BufferAttribute(geometry.skinWeights.length * 4, 4);
  7921. this.addAttribute('skinWeight', skinWeights.copyVector4sArray(geometry.skinWeights));
  7922. } //
  7923. if (geometry.boundingSphere !== null) {
  7924. this.boundingSphere = geometry.boundingSphere.clone();
  7925. }
  7926. if (geometry.boundingBox !== null) {
  7927. this.boundingBox = geometry.boundingBox.clone();
  7928. }
  7929. return this;
  7930. },
  7931. computeBoundingBox: function () {
  7932. if (this.boundingBox === null) {
  7933. this.boundingBox = new Box3();
  7934. }
  7935. var position = this.attributes.position;
  7936. var morphAttributesPosition = this.morphAttributes.position;
  7937. if (position !== undefined) {
  7938. this.boundingBox.setFromBufferAttribute(position); // process morph attributes if present
  7939. if (morphAttributesPosition) {
  7940. for (var i = 0, il = morphAttributesPosition.length; i < il; i++) {
  7941. var morphAttribute = morphAttributesPosition[i];
  7942. _box$1.setFromBufferAttribute(morphAttribute);
  7943. this.boundingBox.expandByPoint(_box$1.min);
  7944. this.boundingBox.expandByPoint(_box$1.max);
  7945. }
  7946. }
  7947. } else {
  7948. this.boundingBox.makeEmpty();
  7949. }
  7950. if (isNaN(this.boundingBox.min.x) || isNaN(this.boundingBox.min.y) || isNaN(this.boundingBox.min.z)) {
  7951. console.error('THREE.BufferGeometry.computeBoundingBox: Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this);
  7952. }
  7953. },
  7954. computeBoundingSphere: function () {
  7955. if (this.boundingSphere === null) {
  7956. this.boundingSphere = new Sphere();
  7957. }
  7958. var position = this.attributes.position;
  7959. var morphAttributesPosition = this.morphAttributes.position;
  7960. if (position) {
  7961. // first, find the center of the bounding sphere
  7962. var center = this.boundingSphere.center;
  7963. _box$1.setFromBufferAttribute(position); // process morph attributes if present
  7964. if (morphAttributesPosition) {
  7965. for (var i = 0, il = morphAttributesPosition.length; i < il; i++) {
  7966. var morphAttribute = morphAttributesPosition[i];
  7967. _boxMorphTargets.setFromBufferAttribute(morphAttribute);
  7968. _box$1.expandByPoint(_boxMorphTargets.min);
  7969. _box$1.expandByPoint(_boxMorphTargets.max);
  7970. }
  7971. }
  7972. _box$1.getCenter(center); // second, try to find a boundingSphere with a radius smaller than the
  7973. // boundingSphere of the boundingBox: sqrt(3) smaller in the best case
  7974. var maxRadiusSq = 0;
  7975. for (var i = 0, il = position.count; i < il; i++) {
  7976. _vector$4.fromBufferAttribute(position, i);
  7977. maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(_vector$4));
  7978. } // process morph attributes if present
  7979. if (morphAttributesPosition) {
  7980. for (var i = 0, il = morphAttributesPosition.length; i < il; i++) {
  7981. var morphAttribute = morphAttributesPosition[i];
  7982. for (var j = 0, jl = morphAttribute.count; j < jl; j++) {
  7983. _vector$4.fromBufferAttribute(morphAttribute, j);
  7984. maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(_vector$4));
  7985. }
  7986. }
  7987. }
  7988. this.boundingSphere.radius = Math.sqrt(maxRadiusSq);
  7989. if (isNaN(this.boundingSphere.radius)) {
  7990. console.error('THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this);
  7991. }
  7992. }
  7993. },
  7994. computeFaceNormals: function () {// backwards compatibility
  7995. },
  7996. computeVertexNormals: function () {
  7997. var index = this.index;
  7998. var attributes = this.attributes;
  7999. if (attributes.position) {
  8000. var positions = attributes.position.array;
  8001. if (attributes.normal === undefined) {
  8002. this.addAttribute('normal', new BufferAttribute(new Float32Array(positions.length), 3));
  8003. } else {
  8004. // reset existing normals to zero
  8005. var array = attributes.normal.array;
  8006. for (var i = 0, il = array.length; i < il; i++) {
  8007. array[i] = 0;
  8008. }
  8009. }
  8010. var normals = attributes.normal.array;
  8011. var vA, vB, vC;
  8012. var pA = new Vector3(),
  8013. pB = new Vector3(),
  8014. pC = new Vector3();
  8015. var cb = new Vector3(),
  8016. ab = new Vector3(); // indexed elements
  8017. if (index) {
  8018. var indices = index.array;
  8019. for (var i = 0, il = index.count; i < il; i += 3) {
  8020. vA = indices[i + 0] * 3;
  8021. vB = indices[i + 1] * 3;
  8022. vC = indices[i + 2] * 3;
  8023. pA.fromArray(positions, vA);
  8024. pB.fromArray(positions, vB);
  8025. pC.fromArray(positions, vC);
  8026. cb.subVectors(pC, pB);
  8027. ab.subVectors(pA, pB);
  8028. cb.cross(ab);
  8029. normals[vA] += cb.x;
  8030. normals[vA + 1] += cb.y;
  8031. normals[vA + 2] += cb.z;
  8032. normals[vB] += cb.x;
  8033. normals[vB + 1] += cb.y;
  8034. normals[vB + 2] += cb.z;
  8035. normals[vC] += cb.x;
  8036. normals[vC + 1] += cb.y;
  8037. normals[vC + 2] += cb.z;
  8038. }
  8039. } else {
  8040. // non-indexed elements (unconnected triangle soup)
  8041. for (var i = 0, il = positions.length; i < il; i += 9) {
  8042. pA.fromArray(positions, i);
  8043. pB.fromArray(positions, i + 3);
  8044. pC.fromArray(positions, i + 6);
  8045. cb.subVectors(pC, pB);
  8046. ab.subVectors(pA, pB);
  8047. cb.cross(ab);
  8048. normals[i] = cb.x;
  8049. normals[i + 1] = cb.y;
  8050. normals[i + 2] = cb.z;
  8051. normals[i + 3] = cb.x;
  8052. normals[i + 4] = cb.y;
  8053. normals[i + 5] = cb.z;
  8054. normals[i + 6] = cb.x;
  8055. normals[i + 7] = cb.y;
  8056. normals[i + 8] = cb.z;
  8057. }
  8058. }
  8059. this.normalizeNormals();
  8060. attributes.normal.needsUpdate = true;
  8061. }
  8062. },
  8063. merge: function (geometry, offset) {
  8064. if (!(geometry && geometry.isBufferGeometry)) {
  8065. console.error('THREE.BufferGeometry.merge(): geometry not an instance of THREE.BufferGeometry.', geometry);
  8066. return;
  8067. }
  8068. if (offset === undefined) {
  8069. offset = 0;
  8070. console.warn('THREE.BufferGeometry.merge(): Overwriting original geometry, starting at offset=0. ' + 'Use BufferGeometryUtils.mergeBufferGeometries() for lossless merge.');
  8071. }
  8072. var attributes = this.attributes;
  8073. for (var key in attributes) {
  8074. if (geometry.attributes[key] === undefined) continue;
  8075. var attribute1 = attributes[key];
  8076. var attributeArray1 = attribute1.array;
  8077. var attribute2 = geometry.attributes[key];
  8078. var attributeArray2 = attribute2.array;
  8079. var attributeOffset = attribute2.itemSize * offset;
  8080. var length = Math.min(attributeArray2.length, attributeArray1.length - attributeOffset);
  8081. for (var i = 0, j = attributeOffset; i < length; i++, j++) {
  8082. attributeArray1[j] = attributeArray2[i];
  8083. }
  8084. }
  8085. return this;
  8086. },
  8087. normalizeNormals: function () {
  8088. var normals = this.attributes.normal;
  8089. for (var i = 0, il = normals.count; i < il; i++) {
  8090. _vector$4.x = normals.getX(i);
  8091. _vector$4.y = normals.getY(i);
  8092. _vector$4.z = normals.getZ(i);
  8093. _vector$4.normalize();
  8094. normals.setXYZ(i, _vector$4.x, _vector$4.y, _vector$4.z);
  8095. }
  8096. },
  8097. toNonIndexed: function () {
  8098. function convertBufferAttribute(attribute, indices) {
  8099. var array = attribute.array;
  8100. var itemSize = attribute.itemSize;
  8101. var array2 = new array.constructor(indices.length * itemSize);
  8102. var index = 0,
  8103. index2 = 0;
  8104. for (var i = 0, l = indices.length; i < l; i++) {
  8105. index = indices[i] * itemSize;
  8106. for (var j = 0; j < itemSize; j++) {
  8107. array2[index2++] = array[index++];
  8108. }
  8109. }
  8110. return new BufferAttribute(array2, itemSize);
  8111. } //
  8112. if (this.index === null) {
  8113. console.warn('THREE.BufferGeometry.toNonIndexed(): Geometry is already non-indexed.');
  8114. return this;
  8115. }
  8116. var geometry2 = new BufferGeometry();
  8117. var indices = this.index.array;
  8118. var attributes = this.attributes; // attributes
  8119. for (var name in attributes) {
  8120. var attribute = attributes[name];
  8121. var newAttribute = convertBufferAttribute(attribute, indices);
  8122. geometry2.addAttribute(name, newAttribute);
  8123. } // morph attributes
  8124. var morphAttributes = this.morphAttributes;
  8125. for (name in morphAttributes) {
  8126. var morphArray = [];
  8127. var morphAttribute = morphAttributes[name]; // morphAttribute: array of Float32BufferAttributes
  8128. for (var i = 0, il = morphAttribute.length; i < il; i++) {
  8129. var attribute = morphAttribute[i];
  8130. var newAttribute = convertBufferAttribute(attribute, indices);
  8131. morphArray.push(newAttribute);
  8132. }
  8133. geometry2.morphAttributes[name] = morphArray;
  8134. } // groups
  8135. var groups = this.groups;
  8136. for (var i = 0, l = groups.length; i < l; i++) {
  8137. var group = groups[i];
  8138. geometry2.addGroup(group.start, group.count, group.materialIndex);
  8139. }
  8140. return geometry2;
  8141. },
  8142. toJSON: function () {
  8143. var data = {
  8144. metadata: {
  8145. version: 4.5,
  8146. type: 'BufferGeometry',
  8147. generator: 'BufferGeometry.toJSON'
  8148. }
  8149. }; // standard BufferGeometry serialization
  8150. data.uuid = this.uuid;
  8151. data.type = this.type;
  8152. if (this.name !== '') data.name = this.name;
  8153. if (Object.keys(this.userData).length > 0) data.userData = this.userData;
  8154. if (this.parameters !== undefined) {
  8155. var parameters = this.parameters;
  8156. for (var key in parameters) {
  8157. if (parameters[key] !== undefined) data[key] = parameters[key];
  8158. }
  8159. return data;
  8160. }
  8161. data.data = {
  8162. attributes: {}
  8163. };
  8164. var index = this.index;
  8165. if (index !== null) {
  8166. data.data.index = {
  8167. type: index.array.constructor.name,
  8168. array: Array.prototype.slice.call(index.array)
  8169. };
  8170. }
  8171. var attributes = this.attributes;
  8172. for (var key in attributes) {
  8173. var attribute = attributes[key];
  8174. var attributeData = attribute.toJSON();
  8175. if (attribute.name !== '') attributeData.name = attribute.name;
  8176. data.data.attributes[key] = attributeData;
  8177. }
  8178. var morphAttributes = {};
  8179. var hasMorphAttributes = false;
  8180. for (var key in this.morphAttributes) {
  8181. var attributeArray = this.morphAttributes[key];
  8182. var array = [];
  8183. for (var i = 0, il = attributeArray.length; i < il; i++) {
  8184. var attribute = attributeArray[i];
  8185. var attributeData = attribute.toJSON();
  8186. if (attribute.name !== '') attributeData.name = attribute.name;
  8187. array.push(attributeData);
  8188. }
  8189. if (array.length > 0) {
  8190. morphAttributes[key] = array;
  8191. hasMorphAttributes = true;
  8192. }
  8193. }
  8194. if (hasMorphAttributes) data.data.morphAttributes = morphAttributes;
  8195. var groups = this.groups;
  8196. if (groups.length > 0) {
  8197. data.data.groups = JSON.parse(JSON.stringify(groups));
  8198. }
  8199. var boundingSphere = this.boundingSphere;
  8200. if (boundingSphere !== null) {
  8201. data.data.boundingSphere = {
  8202. center: boundingSphere.center.toArray(),
  8203. radius: boundingSphere.radius
  8204. };
  8205. }
  8206. return data;
  8207. },
  8208. clone: function () {
  8209. /*
  8210. // Handle primitives
  8211. var parameters = this.parameters;
  8212. if ( parameters !== undefined ) {
  8213. var values = [];
  8214. for ( var key in parameters ) {
  8215. values.push( parameters[ key ] );
  8216. }
  8217. var geometry = Object.create( this.constructor.prototype );
  8218. this.constructor.apply( geometry, values );
  8219. return geometry;
  8220. }
  8221. return new this.constructor().copy( this );
  8222. */
  8223. return new BufferGeometry().copy(this);
  8224. },
  8225. copy: function (source) {
  8226. var name, i, l; // reset
  8227. this.index = null;
  8228. this.attributes = {};
  8229. this.morphAttributes = {};
  8230. this.groups = [];
  8231. this.boundingBox = null;
  8232. this.boundingSphere = null; // name
  8233. this.name = source.name; // index
  8234. var index = source.index;
  8235. if (index !== null) {
  8236. this.setIndex(index.clone());
  8237. } // attributes
  8238. var attributes = source.attributes;
  8239. for (name in attributes) {
  8240. var attribute = attributes[name];
  8241. this.addAttribute(name, attribute.clone());
  8242. } // morph attributes
  8243. var morphAttributes = source.morphAttributes;
  8244. for (name in morphAttributes) {
  8245. var array = [];
  8246. var morphAttribute = morphAttributes[name]; // morphAttribute: array of Float32BufferAttributes
  8247. for (i = 0, l = morphAttribute.length; i < l; i++) {
  8248. array.push(morphAttribute[i].clone());
  8249. }
  8250. this.morphAttributes[name] = array;
  8251. } // groups
  8252. var groups = source.groups;
  8253. for (i = 0, l = groups.length; i < l; i++) {
  8254. var group = groups[i];
  8255. this.addGroup(group.start, group.count, group.materialIndex);
  8256. } // bounding box
  8257. var boundingBox = source.boundingBox;
  8258. if (boundingBox !== null) {
  8259. this.boundingBox = boundingBox.clone();
  8260. } // bounding sphere
  8261. var boundingSphere = source.boundingSphere;
  8262. if (boundingSphere !== null) {
  8263. this.boundingSphere = boundingSphere.clone();
  8264. } // draw range
  8265. this.drawRange.start = source.drawRange.start;
  8266. this.drawRange.count = source.drawRange.count; // user data
  8267. this.userData = source.userData;
  8268. return this;
  8269. },
  8270. dispose: function () {
  8271. this.dispatchEvent({
  8272. type: 'dispose'
  8273. });
  8274. }
  8275. });
  8276. /**
  8277. * @author mrdoob / http://mrdoob.com/
  8278. * @author alteredq / http://alteredqualia.com/
  8279. * @author mikael emtinger / http://gomo.se/
  8280. * @author jonobr1 / http://jonobr1.com/
  8281. */
  8282. var _inverseMatrix = new Matrix4();
  8283. var _ray = new Ray();
  8284. var _sphere = new Sphere();
  8285. var _vA = new Vector3();
  8286. var _vB = new Vector3();
  8287. var _vC = new Vector3();
  8288. var _tempA = new Vector3();
  8289. var _tempB = new Vector3();
  8290. var _tempC = new Vector3();
  8291. var _morphA = new Vector3();
  8292. var _morphB = new Vector3();
  8293. var _morphC = new Vector3();
  8294. var _uvA = new Vector2();
  8295. var _uvB = new Vector2();
  8296. var _uvC = new Vector2();
  8297. var _intersectionPoint = new Vector3();
  8298. var _intersectionPointWorld = new Vector3();
  8299. function Mesh(geometry, material) {
  8300. Object3D.call(this);
  8301. this.type = 'Mesh';
  8302. this.geometry = geometry !== undefined ? geometry : new BufferGeometry();
  8303. this.material = material !== undefined ? material : new MeshBasicMaterial({
  8304. color: Math.random() * 0xffffff
  8305. });
  8306. this.drawMode = TrianglesDrawMode;
  8307. this.updateMorphTargets();
  8308. }
  8309. Mesh.prototype = Object.assign(Object.create(Object3D.prototype), {
  8310. constructor: Mesh,
  8311. isMesh: true,
  8312. setDrawMode: function (value) {
  8313. this.drawMode = value;
  8314. },
  8315. copy: function (source) {
  8316. Object3D.prototype.copy.call(this, source);
  8317. this.drawMode = source.drawMode;
  8318. if (source.morphTargetInfluences !== undefined) {
  8319. this.morphTargetInfluences = source.morphTargetInfluences.slice();
  8320. }
  8321. if (source.morphTargetDictionary !== undefined) {
  8322. this.morphTargetDictionary = Object.assign({}, source.morphTargetDictionary);
  8323. }
  8324. return this;
  8325. },
  8326. updateMorphTargets: function () {
  8327. var geometry = this.geometry;
  8328. var m, ml, name;
  8329. if (geometry.isBufferGeometry) {
  8330. var morphAttributes = geometry.morphAttributes;
  8331. var keys = Object.keys(morphAttributes);
  8332. if (keys.length > 0) {
  8333. var morphAttribute = morphAttributes[keys[0]];
  8334. if (morphAttribute !== undefined) {
  8335. this.morphTargetInfluences = [];
  8336. this.morphTargetDictionary = {};
  8337. for (m = 0, ml = morphAttribute.length; m < ml; m++) {
  8338. name = morphAttribute[m].name || String(m);
  8339. this.morphTargetInfluences.push(0);
  8340. this.morphTargetDictionary[name] = m;
  8341. }
  8342. }
  8343. }
  8344. } else {
  8345. var morphTargets = geometry.morphTargets;
  8346. if (morphTargets !== undefined && morphTargets.length > 0) {
  8347. console.error('THREE.Mesh.updateMorphTargets() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');
  8348. }
  8349. }
  8350. },
  8351. raycast: function (raycaster, intersects) {
  8352. var geometry = this.geometry;
  8353. var material = this.material;
  8354. var matrixWorld = this.matrixWorld;
  8355. if (material === undefined) return; // Checking boundingSphere distance to ray
  8356. if (geometry.boundingSphere === null) geometry.computeBoundingSphere();
  8357. _sphere.copy(geometry.boundingSphere);
  8358. _sphere.applyMatrix4(matrixWorld);
  8359. if (raycaster.ray.intersectsSphere(_sphere) === false) return; //
  8360. _inverseMatrix.getInverse(matrixWorld);
  8361. _ray.copy(raycaster.ray).applyMatrix4(_inverseMatrix); // Check boundingBox before continuing
  8362. if (geometry.boundingBox !== null) {
  8363. if (_ray.intersectsBox(geometry.boundingBox) === false) return;
  8364. }
  8365. var intersection;
  8366. if (geometry.isBufferGeometry) {
  8367. var a, b, c;
  8368. var index = geometry.index;
  8369. var position = geometry.attributes.position;
  8370. var morphPosition = geometry.morphAttributes.position;
  8371. var uv = geometry.attributes.uv;
  8372. var uv2 = geometry.attributes.uv2;
  8373. var groups = geometry.groups;
  8374. var drawRange = geometry.drawRange;
  8375. var i, j, il, jl;
  8376. var group, groupMaterial;
  8377. var start, end;
  8378. if (index !== null) {
  8379. // indexed buffer geometry
  8380. if (Array.isArray(material)) {
  8381. for (i = 0, il = groups.length; i < il; i++) {
  8382. group = groups[i];
  8383. groupMaterial = material[group.materialIndex];
  8384. start = Math.max(group.start, drawRange.start);
  8385. end = Math.min(group.start + group.count, drawRange.start + drawRange.count);
  8386. for (j = start, jl = end; j < jl; j += 3) {
  8387. a = index.getX(j);
  8388. b = index.getX(j + 1);
  8389. c = index.getX(j + 2);
  8390. intersection = checkBufferGeometryIntersection(this, groupMaterial, raycaster, _ray, position, morphPosition, uv, uv2, a, b, c);
  8391. if (intersection) {
  8392. intersection.faceIndex = Math.floor(j / 3); // triangle number in indexed buffer semantics
  8393. intersection.face.materialIndex = group.materialIndex;
  8394. intersects.push(intersection);
  8395. }
  8396. }
  8397. }
  8398. } else {
  8399. start = Math.max(0, drawRange.start);
  8400. end = Math.min(index.count, drawRange.start + drawRange.count);
  8401. for (i = start, il = end; i < il; i += 3) {
  8402. a = index.getX(i);
  8403. b = index.getX(i + 1);
  8404. c = index.getX(i + 2);
  8405. intersection = checkBufferGeometryIntersection(this, material, raycaster, _ray, position, morphPosition, uv, uv2, a, b, c);
  8406. if (intersection) {
  8407. intersection.faceIndex = Math.floor(i / 3); // triangle number in indexed buffer semantics
  8408. intersects.push(intersection);
  8409. }
  8410. }
  8411. }
  8412. } else if (position !== undefined) {
  8413. // non-indexed buffer geometry
  8414. if (Array.isArray(material)) {
  8415. for (i = 0, il = groups.length; i < il; i++) {
  8416. group = groups[i];
  8417. groupMaterial = material[group.materialIndex];
  8418. start = Math.max(group.start, drawRange.start);
  8419. end = Math.min(group.start + group.count, drawRange.start + drawRange.count);
  8420. for (j = start, jl = end; j < jl; j += 3) {
  8421. a = j;
  8422. b = j + 1;
  8423. c = j + 2;
  8424. intersection = checkBufferGeometryIntersection(this, groupMaterial, raycaster, _ray, position, morphPosition, uv, uv2, a, b, c);
  8425. if (intersection) {
  8426. intersection.faceIndex = Math.floor(j / 3); // triangle number in non-indexed buffer semantics
  8427. intersection.face.materialIndex = group.materialIndex;
  8428. intersects.push(intersection);
  8429. }
  8430. }
  8431. }
  8432. } else {
  8433. start = Math.max(0, drawRange.start);
  8434. end = Math.min(position.count, drawRange.start + drawRange.count);
  8435. for (i = start, il = end; i < il; i += 3) {
  8436. a = i;
  8437. b = i + 1;
  8438. c = i + 2;
  8439. intersection = checkBufferGeometryIntersection(this, material, raycaster, _ray, position, morphPosition, uv, uv2, a, b, c);
  8440. if (intersection) {
  8441. intersection.faceIndex = Math.floor(i / 3); // triangle number in non-indexed buffer semantics
  8442. intersects.push(intersection);
  8443. }
  8444. }
  8445. }
  8446. }
  8447. } else if (geometry.isGeometry) {
  8448. var fvA, fvB, fvC;
  8449. var isMultiMaterial = Array.isArray(material);
  8450. var vertices = geometry.vertices;
  8451. var faces = geometry.faces;
  8452. var uvs;
  8453. var faceVertexUvs = geometry.faceVertexUvs[0];
  8454. if (faceVertexUvs.length > 0) uvs = faceVertexUvs;
  8455. for (var f = 0, fl = faces.length; f < fl; f++) {
  8456. var face = faces[f];
  8457. var faceMaterial = isMultiMaterial ? material[face.materialIndex] : material;
  8458. if (faceMaterial === undefined) continue;
  8459. fvA = vertices[face.a];
  8460. fvB = vertices[face.b];
  8461. fvC = vertices[face.c];
  8462. intersection = checkIntersection(this, faceMaterial, raycaster, _ray, fvA, fvB, fvC, _intersectionPoint);
  8463. if (intersection) {
  8464. if (uvs && uvs[f]) {
  8465. var uvs_f = uvs[f];
  8466. _uvA.copy(uvs_f[0]);
  8467. _uvB.copy(uvs_f[1]);
  8468. _uvC.copy(uvs_f[2]);
  8469. intersection.uv = Triangle.getUV(_intersectionPoint, fvA, fvB, fvC, _uvA, _uvB, _uvC, new Vector2());
  8470. }
  8471. intersection.face = face;
  8472. intersection.faceIndex = f;
  8473. intersects.push(intersection);
  8474. }
  8475. }
  8476. }
  8477. },
  8478. clone: function () {
  8479. return new this.constructor(this.geometry, this.material).copy(this);
  8480. }
  8481. });
  8482. function checkIntersection(object, material, raycaster, ray, pA, pB, pC, point) {
  8483. var intersect;
  8484. if (material.side === BackSide) {
  8485. intersect = ray.intersectTriangle(pC, pB, pA, true, point);
  8486. } else {
  8487. intersect = ray.intersectTriangle(pA, pB, pC, material.side !== DoubleSide, point);
  8488. }
  8489. if (intersect === null) return null;
  8490. _intersectionPointWorld.copy(point);
  8491. _intersectionPointWorld.applyMatrix4(object.matrixWorld);
  8492. var distance = raycaster.ray.origin.distanceTo(_intersectionPointWorld);
  8493. if (distance < raycaster.near || distance > raycaster.far) return null;
  8494. return {
  8495. distance: distance,
  8496. point: _intersectionPointWorld.clone(),
  8497. object: object
  8498. };
  8499. }
  8500. function checkBufferGeometryIntersection(object, material, raycaster, ray, position, morphPosition, uv, uv2, a, b, c) {
  8501. _vA.fromBufferAttribute(position, a);
  8502. _vB.fromBufferAttribute(position, b);
  8503. _vC.fromBufferAttribute(position, c);
  8504. var morphInfluences = object.morphTargetInfluences;
  8505. if (material.morphTargets && morphPosition && morphInfluences) {
  8506. _morphA.set(0, 0, 0);
  8507. _morphB.set(0, 0, 0);
  8508. _morphC.set(0, 0, 0);
  8509. for (var i = 0, il = morphPosition.length; i < il; i++) {
  8510. var influence = morphInfluences[i];
  8511. var morphAttribute = morphPosition[i];
  8512. if (influence === 0) continue;
  8513. _tempA.fromBufferAttribute(morphAttribute, a);
  8514. _tempB.fromBufferAttribute(morphAttribute, b);
  8515. _tempC.fromBufferAttribute(morphAttribute, c);
  8516. _morphA.addScaledVector(_tempA.sub(_vA), influence);
  8517. _morphB.addScaledVector(_tempB.sub(_vB), influence);
  8518. _morphC.addScaledVector(_tempC.sub(_vC), influence);
  8519. }
  8520. _vA.add(_morphA);
  8521. _vB.add(_morphB);
  8522. _vC.add(_morphC);
  8523. }
  8524. var intersection = checkIntersection(object, material, raycaster, ray, _vA, _vB, _vC, _intersectionPoint);
  8525. if (intersection) {
  8526. if (uv) {
  8527. _uvA.fromBufferAttribute(uv, a);
  8528. _uvB.fromBufferAttribute(uv, b);
  8529. _uvC.fromBufferAttribute(uv, c);
  8530. intersection.uv = Triangle.getUV(_intersectionPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2());
  8531. }
  8532. if (uv2) {
  8533. _uvA.fromBufferAttribute(uv2, a);
  8534. _uvB.fromBufferAttribute(uv2, b);
  8535. _uvC.fromBufferAttribute(uv2, c);
  8536. intersection.uv2 = Triangle.getUV(_intersectionPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2());
  8537. }
  8538. var face = new Face3(a, b, c);
  8539. Triangle.getNormal(_vA, _vB, _vC, face.normal);
  8540. intersection.face = face;
  8541. }
  8542. return intersection;
  8543. }
  8544. /**
  8545. * @author mrdoob / http://mrdoob.com/
  8546. * @author kile / http://kile.stravaganza.org/
  8547. * @author alteredq / http://alteredqualia.com/
  8548. * @author mikael emtinger / http://gomo.se/
  8549. * @author zz85 / http://www.lab4games.net/zz85/blog
  8550. * @author bhouston / http://clara.io
  8551. */
  8552. var _geometryId = 0; // Geometry uses even numbers as Id
  8553. var _m1$3 = new Matrix4();
  8554. var _obj$1 = new Object3D();
  8555. var _offset$1 = new Vector3();
  8556. function Geometry() {
  8557. Object.defineProperty(this, 'id', {
  8558. value: _geometryId += 2
  8559. });
  8560. this.uuid = _Math.generateUUID();
  8561. this.name = '';
  8562. this.type = 'Geometry';
  8563. this.vertices = [];
  8564. this.colors = [];
  8565. this.faces = [];
  8566. this.faceVertexUvs = [[]];
  8567. this.morphTargets = [];
  8568. this.morphNormals = [];
  8569. this.skinWeights = [];
  8570. this.skinIndices = [];
  8571. this.lineDistances = [];
  8572. this.boundingBox = null;
  8573. this.boundingSphere = null; // update flags
  8574. this.elementsNeedUpdate = false;
  8575. this.verticesNeedUpdate = false;
  8576. this.uvsNeedUpdate = false;
  8577. this.normalsNeedUpdate = false;
  8578. this.colorsNeedUpdate = false;
  8579. this.lineDistancesNeedUpdate = false;
  8580. this.groupsNeedUpdate = false;
  8581. }
  8582. Geometry.prototype = Object.assign(Object.create(EventDispatcher.prototype), {
  8583. constructor: Geometry,
  8584. isGeometry: true,
  8585. applyMatrix: function (matrix) {
  8586. var normalMatrix = new Matrix3().getNormalMatrix(matrix);
  8587. for (var i = 0, il = this.vertices.length; i < il; i++) {
  8588. var vertex = this.vertices[i];
  8589. vertex.applyMatrix4(matrix);
  8590. }
  8591. for (var i = 0, il = this.faces.length; i < il; i++) {
  8592. var face = this.faces[i];
  8593. face.normal.applyMatrix3(normalMatrix).normalize();
  8594. for (var j = 0, jl = face.vertexNormals.length; j < jl; j++) {
  8595. face.vertexNormals[j].applyMatrix3(normalMatrix).normalize();
  8596. }
  8597. }
  8598. if (this.boundingBox !== null) {
  8599. this.computeBoundingBox();
  8600. }
  8601. if (this.boundingSphere !== null) {
  8602. this.computeBoundingSphere();
  8603. }
  8604. this.verticesNeedUpdate = true;
  8605. this.normalsNeedUpdate = true;
  8606. return this;
  8607. },
  8608. rotateX: function (angle) {
  8609. // rotate geometry around world x-axis
  8610. _m1$3.makeRotationX(angle);
  8611. this.applyMatrix(_m1$3);
  8612. return this;
  8613. },
  8614. rotateY: function (angle) {
  8615. // rotate geometry around world y-axis
  8616. _m1$3.makeRotationY(angle);
  8617. this.applyMatrix(_m1$3);
  8618. return this;
  8619. },
  8620. rotateZ: function (angle) {
  8621. // rotate geometry around world z-axis
  8622. _m1$3.makeRotationZ(angle);
  8623. this.applyMatrix(_m1$3);
  8624. return this;
  8625. },
  8626. translate: function (x, y, z) {
  8627. // translate geometry
  8628. _m1$3.makeTranslation(x, y, z);
  8629. this.applyMatrix(_m1$3);
  8630. return this;
  8631. },
  8632. scale: function (x, y, z) {
  8633. // scale geometry
  8634. _m1$3.makeScale(x, y, z);
  8635. this.applyMatrix(_m1$3);
  8636. return this;
  8637. },
  8638. lookAt: function (vector) {
  8639. _obj$1.lookAt(vector);
  8640. _obj$1.updateMatrix();
  8641. this.applyMatrix(_obj$1.matrix);
  8642. return this;
  8643. },
  8644. fromBufferGeometry: function (geometry) {
  8645. var scope = this;
  8646. var indices = geometry.index !== null ? geometry.index.array : undefined;
  8647. var attributes = geometry.attributes;
  8648. if (attributes.position === undefined) {
  8649. console.error('THREE.Geometry.fromBufferGeometry(): Position attribute required for conversion.');
  8650. return this;
  8651. }
  8652. var positions = attributes.position.array;
  8653. var normals = attributes.normal !== undefined ? attributes.normal.array : undefined;
  8654. var colors = attributes.color !== undefined ? attributes.color.array : undefined;
  8655. var uvs = attributes.uv !== undefined ? attributes.uv.array : undefined;
  8656. var uvs2 = attributes.uv2 !== undefined ? attributes.uv2.array : undefined;
  8657. if (uvs2 !== undefined) this.faceVertexUvs[1] = [];
  8658. for (var i = 0; i < positions.length; i += 3) {
  8659. scope.vertices.push(new Vector3().fromArray(positions, i));
  8660. if (colors !== undefined) {
  8661. scope.colors.push(new Color().fromArray(colors, i));
  8662. }
  8663. }
  8664. function addFace(a, b, c, materialIndex) {
  8665. var vertexColors = colors === undefined ? [] : [scope.colors[a].clone(), scope.colors[b].clone(), scope.colors[c].clone()];
  8666. var vertexNormals = normals === undefined ? [] : [new Vector3().fromArray(normals, a * 3), new Vector3().fromArray(normals, b * 3), new Vector3().fromArray(normals, c * 3)];
  8667. var face = new Face3(a, b, c, vertexNormals, vertexColors, materialIndex);
  8668. scope.faces.push(face);
  8669. if (uvs !== undefined) {
  8670. scope.faceVertexUvs[0].push([new Vector2().fromArray(uvs, a * 2), new Vector2().fromArray(uvs, b * 2), new Vector2().fromArray(uvs, c * 2)]);
  8671. }
  8672. if (uvs2 !== undefined) {
  8673. scope.faceVertexUvs[1].push([new Vector2().fromArray(uvs2, a * 2), new Vector2().fromArray(uvs2, b * 2), new Vector2().fromArray(uvs2, c * 2)]);
  8674. }
  8675. }
  8676. var groups = geometry.groups;
  8677. if (groups.length > 0) {
  8678. for (var i = 0; i < groups.length; i++) {
  8679. var group = groups[i];
  8680. var start = group.start;
  8681. var count = group.count;
  8682. for (var j = start, jl = start + count; j < jl; j += 3) {
  8683. if (indices !== undefined) {
  8684. addFace(indices[j], indices[j + 1], indices[j + 2], group.materialIndex);
  8685. } else {
  8686. addFace(j, j + 1, j + 2, group.materialIndex);
  8687. }
  8688. }
  8689. }
  8690. } else {
  8691. if (indices !== undefined) {
  8692. for (var i = 0; i < indices.length; i += 3) {
  8693. addFace(indices[i], indices[i + 1], indices[i + 2]);
  8694. }
  8695. } else {
  8696. for (var i = 0; i < positions.length / 3; i += 3) {
  8697. addFace(i, i + 1, i + 2);
  8698. }
  8699. }
  8700. }
  8701. this.computeFaceNormals();
  8702. if (geometry.boundingBox !== null) {
  8703. this.boundingBox = geometry.boundingBox.clone();
  8704. }
  8705. if (geometry.boundingSphere !== null) {
  8706. this.boundingSphere = geometry.boundingSphere.clone();
  8707. }
  8708. return this;
  8709. },
  8710. center: function () {
  8711. this.computeBoundingBox();
  8712. this.boundingBox.getCenter(_offset$1).negate();
  8713. this.translate(_offset$1.x, _offset$1.y, _offset$1.z);
  8714. return this;
  8715. },
  8716. normalize: function () {
  8717. this.computeBoundingSphere();
  8718. var center = this.boundingSphere.center;
  8719. var radius = this.boundingSphere.radius;
  8720. var s = radius === 0 ? 1 : 1.0 / radius;
  8721. var matrix = new Matrix4();
  8722. matrix.set(s, 0, 0, -s * center.x, 0, s, 0, -s * center.y, 0, 0, s, -s * center.z, 0, 0, 0, 1);
  8723. this.applyMatrix(matrix);
  8724. return this;
  8725. },
  8726. computeFaceNormals: function () {
  8727. var cb = new Vector3(),
  8728. ab = new Vector3();
  8729. for (var f = 0, fl = this.faces.length; f < fl; f++) {
  8730. var face = this.faces[f];
  8731. var vA = this.vertices[face.a];
  8732. var vB = this.vertices[face.b];
  8733. var vC = this.vertices[face.c];
  8734. cb.subVectors(vC, vB);
  8735. ab.subVectors(vA, vB);
  8736. cb.cross(ab);
  8737. cb.normalize();
  8738. face.normal.copy(cb);
  8739. }
  8740. },
  8741. computeVertexNormals: function (areaWeighted) {
  8742. if (areaWeighted === undefined) areaWeighted = true;
  8743. var v, vl, f, fl, face, vertices;
  8744. vertices = new Array(this.vertices.length);
  8745. for (v = 0, vl = this.vertices.length; v < vl; v++) {
  8746. vertices[v] = new Vector3();
  8747. }
  8748. if (areaWeighted) {
  8749. // vertex normals weighted by triangle areas
  8750. // http://www.iquilezles.org/www/articles/normals/normals.htm
  8751. var vA, vB, vC;
  8752. var cb = new Vector3(),
  8753. ab = new Vector3();
  8754. for (f = 0, fl = this.faces.length; f < fl; f++) {
  8755. face = this.faces[f];
  8756. vA = this.vertices[face.a];
  8757. vB = this.vertices[face.b];
  8758. vC = this.vertices[face.c];
  8759. cb.subVectors(vC, vB);
  8760. ab.subVectors(vA, vB);
  8761. cb.cross(ab);
  8762. vertices[face.a].add(cb);
  8763. vertices[face.b].add(cb);
  8764. vertices[face.c].add(cb);
  8765. }
  8766. } else {
  8767. this.computeFaceNormals();
  8768. for (f = 0, fl = this.faces.length; f < fl; f++) {
  8769. face = this.faces[f];
  8770. vertices[face.a].add(face.normal);
  8771. vertices[face.b].add(face.normal);
  8772. vertices[face.c].add(face.normal);
  8773. }
  8774. }
  8775. for (v = 0, vl = this.vertices.length; v < vl; v++) {
  8776. vertices[v].normalize();
  8777. }
  8778. for (f = 0, fl = this.faces.length; f < fl; f++) {
  8779. face = this.faces[f];
  8780. var vertexNormals = face.vertexNormals;
  8781. if (vertexNormals.length === 3) {
  8782. vertexNormals[0].copy(vertices[face.a]);
  8783. vertexNormals[1].copy(vertices[face.b]);
  8784. vertexNormals[2].copy(vertices[face.c]);
  8785. } else {
  8786. vertexNormals[0] = vertices[face.a].clone();
  8787. vertexNormals[1] = vertices[face.b].clone();
  8788. vertexNormals[2] = vertices[face.c].clone();
  8789. }
  8790. }
  8791. if (this.faces.length > 0) {
  8792. this.normalsNeedUpdate = true;
  8793. }
  8794. },
  8795. computeFlatVertexNormals: function () {
  8796. var f, fl, face;
  8797. this.computeFaceNormals();
  8798. for (f = 0, fl = this.faces.length; f < fl; f++) {
  8799. face = this.faces[f];
  8800. var vertexNormals = face.vertexNormals;
  8801. if (vertexNormals.length === 3) {
  8802. vertexNormals[0].copy(face.normal);
  8803. vertexNormals[1].copy(face.normal);
  8804. vertexNormals[2].copy(face.normal);
  8805. } else {
  8806. vertexNormals[0] = face.normal.clone();
  8807. vertexNormals[1] = face.normal.clone();
  8808. vertexNormals[2] = face.normal.clone();
  8809. }
  8810. }
  8811. if (this.faces.length > 0) {
  8812. this.normalsNeedUpdate = true;
  8813. }
  8814. },
  8815. computeMorphNormals: function () {
  8816. var i, il, f, fl, face; // save original normals
  8817. // - create temp variables on first access
  8818. // otherwise just copy (for faster repeated calls)
  8819. for (f = 0, fl = this.faces.length; f < fl; f++) {
  8820. face = this.faces[f];
  8821. if (!face.__originalFaceNormal) {
  8822. face.__originalFaceNormal = face.normal.clone();
  8823. } else {
  8824. face.__originalFaceNormal.copy(face.normal);
  8825. }
  8826. if (!face.__originalVertexNormals) face.__originalVertexNormals = [];
  8827. for (i = 0, il = face.vertexNormals.length; i < il; i++) {
  8828. if (!face.__originalVertexNormals[i]) {
  8829. face.__originalVertexNormals[i] = face.vertexNormals[i].clone();
  8830. } else {
  8831. face.__originalVertexNormals[i].copy(face.vertexNormals[i]);
  8832. }
  8833. }
  8834. } // use temp geometry to compute face and vertex normals for each morph
  8835. var tmpGeo = new Geometry();
  8836. tmpGeo.faces = this.faces;
  8837. for (i = 0, il = this.morphTargets.length; i < il; i++) {
  8838. // create on first access
  8839. if (!this.morphNormals[i]) {
  8840. this.morphNormals[i] = {};
  8841. this.morphNormals[i].faceNormals = [];
  8842. this.morphNormals[i].vertexNormals = [];
  8843. var dstNormalsFace = this.morphNormals[i].faceNormals;
  8844. var dstNormalsVertex = this.morphNormals[i].vertexNormals;
  8845. var faceNormal, vertexNormals;
  8846. for (f = 0, fl = this.faces.length; f < fl; f++) {
  8847. faceNormal = new Vector3();
  8848. vertexNormals = {
  8849. a: new Vector3(),
  8850. b: new Vector3(),
  8851. c: new Vector3()
  8852. };
  8853. dstNormalsFace.push(faceNormal);
  8854. dstNormalsVertex.push(vertexNormals);
  8855. }
  8856. }
  8857. var morphNormals = this.morphNormals[i]; // set vertices to morph target
  8858. tmpGeo.vertices = this.morphTargets[i].vertices; // compute morph normals
  8859. tmpGeo.computeFaceNormals();
  8860. tmpGeo.computeVertexNormals(); // store morph normals
  8861. var faceNormal, vertexNormals;
  8862. for (f = 0, fl = this.faces.length; f < fl; f++) {
  8863. face = this.faces[f];
  8864. faceNormal = morphNormals.faceNormals[f];
  8865. vertexNormals = morphNormals.vertexNormals[f];
  8866. faceNormal.copy(face.normal);
  8867. vertexNormals.a.copy(face.vertexNormals[0]);
  8868. vertexNormals.b.copy(face.vertexNormals[1]);
  8869. vertexNormals.c.copy(face.vertexNormals[2]);
  8870. }
  8871. } // restore original normals
  8872. for (f = 0, fl = this.faces.length; f < fl; f++) {
  8873. face = this.faces[f];
  8874. face.normal = face.__originalFaceNormal;
  8875. face.vertexNormals = face.__originalVertexNormals;
  8876. }
  8877. },
  8878. computeBoundingBox: function () {
  8879. if (this.boundingBox === null) {
  8880. this.boundingBox = new Box3();
  8881. }
  8882. this.boundingBox.setFromPoints(this.vertices);
  8883. },
  8884. computeBoundingSphere: function () {
  8885. if (this.boundingSphere === null) {
  8886. this.boundingSphere = new Sphere();
  8887. }
  8888. this.boundingSphere.setFromPoints(this.vertices);
  8889. },
  8890. merge: function (geometry, matrix, materialIndexOffset) {
  8891. if (!(geometry && geometry.isGeometry)) {
  8892. console.error('THREE.Geometry.merge(): geometry not an instance of THREE.Geometry.', geometry);
  8893. return;
  8894. }
  8895. var normalMatrix,
  8896. vertexOffset = this.vertices.length,
  8897. vertices1 = this.vertices,
  8898. vertices2 = geometry.vertices,
  8899. faces1 = this.faces,
  8900. faces2 = geometry.faces,
  8901. colors1 = this.colors,
  8902. colors2 = geometry.colors;
  8903. if (materialIndexOffset === undefined) materialIndexOffset = 0;
  8904. if (matrix !== undefined) {
  8905. normalMatrix = new Matrix3().getNormalMatrix(matrix);
  8906. } // vertices
  8907. for (var i = 0, il = vertices2.length; i < il; i++) {
  8908. var vertex = vertices2[i];
  8909. var vertexCopy = vertex.clone();
  8910. if (matrix !== undefined) vertexCopy.applyMatrix4(matrix);
  8911. vertices1.push(vertexCopy);
  8912. } // colors
  8913. for (var i = 0, il = colors2.length; i < il; i++) {
  8914. colors1.push(colors2[i].clone());
  8915. } // faces
  8916. for (i = 0, il = faces2.length; i < il; i++) {
  8917. var face = faces2[i],
  8918. faceCopy,
  8919. normal,
  8920. color,
  8921. faceVertexNormals = face.vertexNormals,
  8922. faceVertexColors = face.vertexColors;
  8923. faceCopy = new Face3(face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset);
  8924. faceCopy.normal.copy(face.normal);
  8925. if (normalMatrix !== undefined) {
  8926. faceCopy.normal.applyMatrix3(normalMatrix).normalize();
  8927. }
  8928. for (var j = 0, jl = faceVertexNormals.length; j < jl; j++) {
  8929. normal = faceVertexNormals[j].clone();
  8930. if (normalMatrix !== undefined) {
  8931. normal.applyMatrix3(normalMatrix).normalize();
  8932. }
  8933. faceCopy.vertexNormals.push(normal);
  8934. }
  8935. faceCopy.color.copy(face.color);
  8936. for (var j = 0, jl = faceVertexColors.length; j < jl; j++) {
  8937. color = faceVertexColors[j];
  8938. faceCopy.vertexColors.push(color.clone());
  8939. }
  8940. faceCopy.materialIndex = face.materialIndex + materialIndexOffset;
  8941. faces1.push(faceCopy);
  8942. } // uvs
  8943. for (var i = 0, il = geometry.faceVertexUvs.length; i < il; i++) {
  8944. var faceVertexUvs2 = geometry.faceVertexUvs[i];
  8945. if (this.faceVertexUvs[i] === undefined) this.faceVertexUvs[i] = [];
  8946. for (var j = 0, jl = faceVertexUvs2.length; j < jl; j++) {
  8947. var uvs2 = faceVertexUvs2[j],
  8948. uvsCopy = [];
  8949. for (var k = 0, kl = uvs2.length; k < kl; k++) {
  8950. uvsCopy.push(uvs2[k].clone());
  8951. }
  8952. this.faceVertexUvs[i].push(uvsCopy);
  8953. }
  8954. }
  8955. },
  8956. mergeMesh: function (mesh) {
  8957. if (!(mesh && mesh.isMesh)) {
  8958. console.error('THREE.Geometry.mergeMesh(): mesh not an instance of THREE.Mesh.', mesh);
  8959. return;
  8960. }
  8961. if (mesh.matrixAutoUpdate) mesh.updateMatrix();
  8962. this.merge(mesh.geometry, mesh.matrix);
  8963. },
  8964. /*
  8965. * Checks for duplicate vertices with hashmap.
  8966. * Duplicated vertices are removed
  8967. * and faces' vertices are updated.
  8968. */
  8969. mergeVertices: function () {
  8970. var verticesMap = {}; // Hashmap for looking up vertices by position coordinates (and making sure they are unique)
  8971. var unique = [],
  8972. changes = [];
  8973. var v, key;
  8974. var precisionPoints = 4; // number of decimal points, e.g. 4 for epsilon of 0.0001
  8975. var precision = Math.pow(10, precisionPoints);
  8976. var i, il, face;
  8977. var indices, j, jl;
  8978. for (i = 0, il = this.vertices.length; i < il; i++) {
  8979. v = this.vertices[i];
  8980. key = Math.round(v.x * precision) + '_' + Math.round(v.y * precision) + '_' + Math.round(v.z * precision);
  8981. if (verticesMap[key] === undefined) {
  8982. verticesMap[key] = i;
  8983. unique.push(this.vertices[i]);
  8984. changes[i] = unique.length - 1;
  8985. } else {
  8986. //console.log('Duplicate vertex found. ', i, ' could be using ', verticesMap[key]);
  8987. changes[i] = changes[verticesMap[key]];
  8988. }
  8989. } // if faces are completely degenerate after merging vertices, we
  8990. // have to remove them from the geometry.
  8991. var faceIndicesToRemove = [];
  8992. for (i = 0, il = this.faces.length; i < il; i++) {
  8993. face = this.faces[i];
  8994. face.a = changes[face.a];
  8995. face.b = changes[face.b];
  8996. face.c = changes[face.c];
  8997. indices = [face.a, face.b, face.c]; // if any duplicate vertices are found in a Face3
  8998. // we have to remove the face as nothing can be saved
  8999. for (var n = 0; n < 3; n++) {
  9000. if (indices[n] === indices[(n + 1) % 3]) {
  9001. faceIndicesToRemove.push(i);
  9002. break;
  9003. }
  9004. }
  9005. }
  9006. for (i = faceIndicesToRemove.length - 1; i >= 0; i--) {
  9007. var idx = faceIndicesToRemove[i];
  9008. this.faces.splice(idx, 1);
  9009. for (j = 0, jl = this.faceVertexUvs.length; j < jl; j++) {
  9010. this.faceVertexUvs[j].splice(idx, 1);
  9011. }
  9012. } // Use unique set of vertices
  9013. var diff = this.vertices.length - unique.length;
  9014. this.vertices = unique;
  9015. return diff;
  9016. },
  9017. setFromPoints: function (points) {
  9018. this.vertices = [];
  9019. for (var i = 0, l = points.length; i < l; i++) {
  9020. var point = points[i];
  9021. this.vertices.push(new Vector3(point.x, point.y, point.z || 0));
  9022. }
  9023. return this;
  9024. },
  9025. sortFacesByMaterialIndex: function () {
  9026. var faces = this.faces;
  9027. var length = faces.length; // tag faces
  9028. for (var i = 0; i < length; i++) {
  9029. faces[i]._id = i;
  9030. } // sort faces
  9031. function materialIndexSort(a, b) {
  9032. return a.materialIndex - b.materialIndex;
  9033. }
  9034. faces.sort(materialIndexSort); // sort uvs
  9035. var uvs1 = this.faceVertexUvs[0];
  9036. var uvs2 = this.faceVertexUvs[1];
  9037. var newUvs1, newUvs2;
  9038. if (uvs1 && uvs1.length === length) newUvs1 = [];
  9039. if (uvs2 && uvs2.length === length) newUvs2 = [];
  9040. for (var i = 0; i < length; i++) {
  9041. var id = faces[i]._id;
  9042. if (newUvs1) newUvs1.push(uvs1[id]);
  9043. if (newUvs2) newUvs2.push(uvs2[id]);
  9044. }
  9045. if (newUvs1) this.faceVertexUvs[0] = newUvs1;
  9046. if (newUvs2) this.faceVertexUvs[1] = newUvs2;
  9047. },
  9048. toJSON: function () {
  9049. var data = {
  9050. metadata: {
  9051. version: 4.5,
  9052. type: 'Geometry',
  9053. generator: 'Geometry.toJSON'
  9054. }
  9055. }; // standard Geometry serialization
  9056. data.uuid = this.uuid;
  9057. data.type = this.type;
  9058. if (this.name !== '') data.name = this.name;
  9059. if (this.parameters !== undefined) {
  9060. var parameters = this.parameters;
  9061. for (var key in parameters) {
  9062. if (parameters[key] !== undefined) data[key] = parameters[key];
  9063. }
  9064. return data;
  9065. }
  9066. var vertices = [];
  9067. for (var i = 0; i < this.vertices.length; i++) {
  9068. var vertex = this.vertices[i];
  9069. vertices.push(vertex.x, vertex.y, vertex.z);
  9070. }
  9071. var faces = [];
  9072. var normals = [];
  9073. var normalsHash = {};
  9074. var colors = [];
  9075. var colorsHash = {};
  9076. var uvs = [];
  9077. var uvsHash = {};
  9078. for (var i = 0; i < this.faces.length; i++) {
  9079. var face = this.faces[i];
  9080. var hasMaterial = true;
  9081. var hasFaceUv = false; // deprecated
  9082. var hasFaceVertexUv = this.faceVertexUvs[0][i] !== undefined;
  9083. var hasFaceNormal = face.normal.length() > 0;
  9084. var hasFaceVertexNormal = face.vertexNormals.length > 0;
  9085. var hasFaceColor = face.color.r !== 1 || face.color.g !== 1 || face.color.b !== 1;
  9086. var hasFaceVertexColor = face.vertexColors.length > 0;
  9087. var faceType = 0;
  9088. faceType = setBit(faceType, 0, 0); // isQuad
  9089. faceType = setBit(faceType, 1, hasMaterial);
  9090. faceType = setBit(faceType, 2, hasFaceUv);
  9091. faceType = setBit(faceType, 3, hasFaceVertexUv);
  9092. faceType = setBit(faceType, 4, hasFaceNormal);
  9093. faceType = setBit(faceType, 5, hasFaceVertexNormal);
  9094. faceType = setBit(faceType, 6, hasFaceColor);
  9095. faceType = setBit(faceType, 7, hasFaceVertexColor);
  9096. faces.push(faceType);
  9097. faces.push(face.a, face.b, face.c);
  9098. faces.push(face.materialIndex);
  9099. if (hasFaceVertexUv) {
  9100. var faceVertexUvs = this.faceVertexUvs[0][i];
  9101. faces.push(getUvIndex(faceVertexUvs[0]), getUvIndex(faceVertexUvs[1]), getUvIndex(faceVertexUvs[2]));
  9102. }
  9103. if (hasFaceNormal) {
  9104. faces.push(getNormalIndex(face.normal));
  9105. }
  9106. if (hasFaceVertexNormal) {
  9107. var vertexNormals = face.vertexNormals;
  9108. faces.push(getNormalIndex(vertexNormals[0]), getNormalIndex(vertexNormals[1]), getNormalIndex(vertexNormals[2]));
  9109. }
  9110. if (hasFaceColor) {
  9111. faces.push(getColorIndex(face.color));
  9112. }
  9113. if (hasFaceVertexColor) {
  9114. var vertexColors = face.vertexColors;
  9115. faces.push(getColorIndex(vertexColors[0]), getColorIndex(vertexColors[1]), getColorIndex(vertexColors[2]));
  9116. }
  9117. }
  9118. function setBit(value, position, enabled) {
  9119. return enabled ? value | 1 << position : value & ~(1 << position);
  9120. }
  9121. function getNormalIndex(normal) {
  9122. var hash = normal.x.toString() + normal.y.toString() + normal.z.toString();
  9123. if (normalsHash[hash] !== undefined) {
  9124. return normalsHash[hash];
  9125. }
  9126. normalsHash[hash] = normals.length / 3;
  9127. normals.push(normal.x, normal.y, normal.z);
  9128. return normalsHash[hash];
  9129. }
  9130. function getColorIndex(color) {
  9131. var hash = color.r.toString() + color.g.toString() + color.b.toString();
  9132. if (colorsHash[hash] !== undefined) {
  9133. return colorsHash[hash];
  9134. }
  9135. colorsHash[hash] = colors.length;
  9136. colors.push(color.getHex());
  9137. return colorsHash[hash];
  9138. }
  9139. function getUvIndex(uv) {
  9140. var hash = uv.x.toString() + uv.y.toString();
  9141. if (uvsHash[hash] !== undefined) {
  9142. return uvsHash[hash];
  9143. }
  9144. uvsHash[hash] = uvs.length / 2;
  9145. uvs.push(uv.x, uv.y);
  9146. return uvsHash[hash];
  9147. }
  9148. data.data = {};
  9149. data.data.vertices = vertices;
  9150. data.data.normals = normals;
  9151. if (colors.length > 0) data.data.colors = colors;
  9152. if (uvs.length > 0) data.data.uvs = [uvs]; // temporal backward compatibility
  9153. data.data.faces = faces;
  9154. return data;
  9155. },
  9156. clone: function () {
  9157. /*
  9158. // Handle primitives
  9159. var parameters = this.parameters;
  9160. if ( parameters !== undefined ) {
  9161. var values = [];
  9162. for ( var key in parameters ) {
  9163. values.push( parameters[ key ] );
  9164. }
  9165. var geometry = Object.create( this.constructor.prototype );
  9166. this.constructor.apply( geometry, values );
  9167. return geometry;
  9168. }
  9169. return new this.constructor().copy( this );
  9170. */
  9171. return new Geometry().copy(this);
  9172. },
  9173. copy: function (source) {
  9174. var i, il, j, jl, k, kl; // reset
  9175. this.vertices = [];
  9176. this.colors = [];
  9177. this.faces = [];
  9178. this.faceVertexUvs = [[]];
  9179. this.morphTargets = [];
  9180. this.morphNormals = [];
  9181. this.skinWeights = [];
  9182. this.skinIndices = [];
  9183. this.lineDistances = [];
  9184. this.boundingBox = null;
  9185. this.boundingSphere = null; // name
  9186. this.name = source.name; // vertices
  9187. var vertices = source.vertices;
  9188. for (i = 0, il = vertices.length; i < il; i++) {
  9189. this.vertices.push(vertices[i].clone());
  9190. } // colors
  9191. var colors = source.colors;
  9192. for (i = 0, il = colors.length; i < il; i++) {
  9193. this.colors.push(colors[i].clone());
  9194. } // faces
  9195. var faces = source.faces;
  9196. for (i = 0, il = faces.length; i < il; i++) {
  9197. this.faces.push(faces[i].clone());
  9198. } // face vertex uvs
  9199. for (i = 0, il = source.faceVertexUvs.length; i < il; i++) {
  9200. var faceVertexUvs = source.faceVertexUvs[i];
  9201. if (this.faceVertexUvs[i] === undefined) {
  9202. this.faceVertexUvs[i] = [];
  9203. }
  9204. for (j = 0, jl = faceVertexUvs.length; j < jl; j++) {
  9205. var uvs = faceVertexUvs[j],
  9206. uvsCopy = [];
  9207. for (k = 0, kl = uvs.length; k < kl; k++) {
  9208. var uv = uvs[k];
  9209. uvsCopy.push(uv.clone());
  9210. }
  9211. this.faceVertexUvs[i].push(uvsCopy);
  9212. }
  9213. } // morph targets
  9214. var morphTargets = source.morphTargets;
  9215. for (i = 0, il = morphTargets.length; i < il; i++) {
  9216. var morphTarget = {};
  9217. morphTarget.name = morphTargets[i].name; // vertices
  9218. if (morphTargets[i].vertices !== undefined) {
  9219. morphTarget.vertices = [];
  9220. for (j = 0, jl = morphTargets[i].vertices.length; j < jl; j++) {
  9221. morphTarget.vertices.push(morphTargets[i].vertices[j].clone());
  9222. }
  9223. } // normals
  9224. if (morphTargets[i].normals !== undefined) {
  9225. morphTarget.normals = [];
  9226. for (j = 0, jl = morphTargets[i].normals.length; j < jl; j++) {
  9227. morphTarget.normals.push(morphTargets[i].normals[j].clone());
  9228. }
  9229. }
  9230. this.morphTargets.push(morphTarget);
  9231. } // morph normals
  9232. var morphNormals = source.morphNormals;
  9233. for (i = 0, il = morphNormals.length; i < il; i++) {
  9234. var morphNormal = {}; // vertex normals
  9235. if (morphNormals[i].vertexNormals !== undefined) {
  9236. morphNormal.vertexNormals = [];
  9237. for (j = 0, jl = morphNormals[i].vertexNormals.length; j < jl; j++) {
  9238. var srcVertexNormal = morphNormals[i].vertexNormals[j];
  9239. var destVertexNormal = {};
  9240. destVertexNormal.a = srcVertexNormal.a.clone();
  9241. destVertexNormal.b = srcVertexNormal.b.clone();
  9242. destVertexNormal.c = srcVertexNormal.c.clone();
  9243. morphNormal.vertexNormals.push(destVertexNormal);
  9244. }
  9245. } // face normals
  9246. if (morphNormals[i].faceNormals !== undefined) {
  9247. morphNormal.faceNormals = [];
  9248. for (j = 0, jl = morphNormals[i].faceNormals.length; j < jl; j++) {
  9249. morphNormal.faceNormals.push(morphNormals[i].faceNormals[j].clone());
  9250. }
  9251. }
  9252. this.morphNormals.push(morphNormal);
  9253. } // skin weights
  9254. var skinWeights = source.skinWeights;
  9255. for (i = 0, il = skinWeights.length; i < il; i++) {
  9256. this.skinWeights.push(skinWeights[i].clone());
  9257. } // skin indices
  9258. var skinIndices = source.skinIndices;
  9259. for (i = 0, il = skinIndices.length; i < il; i++) {
  9260. this.skinIndices.push(skinIndices[i].clone());
  9261. } // line distances
  9262. var lineDistances = source.lineDistances;
  9263. for (i = 0, il = lineDistances.length; i < il; i++) {
  9264. this.lineDistances.push(lineDistances[i]);
  9265. } // bounding box
  9266. var boundingBox = source.boundingBox;
  9267. if (boundingBox !== null) {
  9268. this.boundingBox = boundingBox.clone();
  9269. } // bounding sphere
  9270. var boundingSphere = source.boundingSphere;
  9271. if (boundingSphere !== null) {
  9272. this.boundingSphere = boundingSphere.clone();
  9273. } // update flags
  9274. this.elementsNeedUpdate = source.elementsNeedUpdate;
  9275. this.verticesNeedUpdate = source.verticesNeedUpdate;
  9276. this.uvsNeedUpdate = source.uvsNeedUpdate;
  9277. this.normalsNeedUpdate = source.normalsNeedUpdate;
  9278. this.colorsNeedUpdate = source.colorsNeedUpdate;
  9279. this.lineDistancesNeedUpdate = source.lineDistancesNeedUpdate;
  9280. this.groupsNeedUpdate = source.groupsNeedUpdate;
  9281. return this;
  9282. },
  9283. dispose: function () {
  9284. this.dispatchEvent({
  9285. type: 'dispose'
  9286. });
  9287. }
  9288. });
  9289. /**
  9290. * @author mrdoob / http://mrdoob.com/
  9291. * @author Mugen87 / https://github.com/Mugen87
  9292. */
  9293. // BoxGeometry
  9294. class BoxGeometry extends Geometry {
  9295. constructor(width, height, depth, widthSegments, heightSegments, depthSegments) {
  9296. super();
  9297. this.type = 'BoxGeometry';
  9298. this.parameters = {
  9299. width: width,
  9300. height: height,
  9301. depth: depth,
  9302. widthSegments: widthSegments,
  9303. heightSegments: heightSegments,
  9304. depthSegments: depthSegments
  9305. };
  9306. this.fromBufferGeometry(new BoxBufferGeometry(width, height, depth, widthSegments, heightSegments, depthSegments));
  9307. this.mergeVertices();
  9308. }
  9309. } // BoxBufferGeometry
  9310. exports.CubeGeometry = exports.BoxGeometry = BoxGeometry;
  9311. class BoxBufferGeometry extends BufferGeometry {
  9312. constructor(width, height, depth, widthSegments, heightSegments, depthSegments) {
  9313. super();
  9314. this.type = 'BoxBufferGeometry';
  9315. this.parameters = {
  9316. width: width,
  9317. height: height,
  9318. depth: depth,
  9319. widthSegments: widthSegments,
  9320. heightSegments: heightSegments,
  9321. depthSegments: depthSegments
  9322. };
  9323. var scope = this;
  9324. width = width || 1;
  9325. height = height || 1;
  9326. depth = depth || 1; // segments
  9327. widthSegments = Math.floor(widthSegments) || 1;
  9328. heightSegments = Math.floor(heightSegments) || 1;
  9329. depthSegments = Math.floor(depthSegments) || 1; // buffers
  9330. var indices = [];
  9331. var vertices = [];
  9332. var normals = [];
  9333. var uvs = []; // helper variables
  9334. var numberOfVertices = 0;
  9335. var groupStart = 0; // build each side of the box geometry
  9336. buildPlane('z', 'y', 'x', -1, -1, depth, height, width, depthSegments, heightSegments, 0); // px
  9337. buildPlane('z', 'y', 'x', 1, -1, depth, height, -width, depthSegments, heightSegments, 1); // nx
  9338. buildPlane('x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2); // py
  9339. buildPlane('x', 'z', 'y', 1, -1, width, depth, -height, widthSegments, depthSegments, 3); // ny
  9340. buildPlane('x', 'y', 'z', 1, -1, width, height, depth, widthSegments, heightSegments, 4); // pz
  9341. buildPlane('x', 'y', 'z', -1, -1, width, height, -depth, widthSegments, heightSegments, 5); // nz
  9342. // build geometry
  9343. this.setIndex(indices);
  9344. this.addAttribute('position', new Float32BufferAttribute(vertices, 3));
  9345. this.addAttribute('normal', new Float32BufferAttribute(normals, 3));
  9346. this.addAttribute('uv', new Float32BufferAttribute(uvs, 2));
  9347. function buildPlane(u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex) {
  9348. var segmentWidth = width / gridX;
  9349. var segmentHeight = height / gridY;
  9350. var widthHalf = width / 2;
  9351. var heightHalf = height / 2;
  9352. var depthHalf = depth / 2;
  9353. var gridX1 = gridX + 1;
  9354. var gridY1 = gridY + 1;
  9355. var vertexCounter = 0;
  9356. var groupCount = 0;
  9357. var ix, iy;
  9358. var vector = new Vector3(); // generate vertices, normals and uvs
  9359. for (iy = 0; iy < gridY1; iy++) {
  9360. var y = iy * segmentHeight - heightHalf;
  9361. for (ix = 0; ix < gridX1; ix++) {
  9362. var x = ix * segmentWidth - widthHalf; // set values to correct vector component
  9363. vector[u] = x * udir;
  9364. vector[v] = y * vdir;
  9365. vector[w] = depthHalf; // now apply vector to vertex buffer
  9366. vertices.push(vector.x, vector.y, vector.z); // set values to correct vector component
  9367. vector[u] = 0;
  9368. vector[v] = 0;
  9369. vector[w] = depth > 0 ? 1 : -1; // now apply vector to normal buffer
  9370. normals.push(vector.x, vector.y, vector.z); // uvs
  9371. uvs.push(ix / gridX);
  9372. uvs.push(1 - iy / gridY); // counters
  9373. vertexCounter += 1;
  9374. }
  9375. } // indices
  9376. // 1. you need three indices to draw a single face
  9377. // 2. a single segment consists of two faces
  9378. // 3. so we need to generate six (2*3) indices per segment
  9379. for (iy = 0; iy < gridY; iy++) {
  9380. for (ix = 0; ix < gridX; ix++) {
  9381. var a = numberOfVertices + ix + gridX1 * iy;
  9382. var b = numberOfVertices + ix + gridX1 * (iy + 1);
  9383. var c = numberOfVertices + (ix + 1) + gridX1 * (iy + 1);
  9384. var d = numberOfVertices + (ix + 1) + gridX1 * iy; // faces
  9385. indices.push(a, b, d);
  9386. indices.push(b, c, d); // increase counter
  9387. groupCount += 6;
  9388. }
  9389. } // add a group to the geometry. this will ensure multi material support
  9390. scope.addGroup(groupStart, groupCount, materialIndex); // calculate new start value for groups
  9391. groupStart += groupCount; // update total number of vertices
  9392. numberOfVertices += vertexCounter;
  9393. }
  9394. }
  9395. }
  9396. /**
  9397. * Uniform Utilities
  9398. */
  9399. exports.BoxBufferGeometry = BoxBufferGeometry;
  9400. function cloneUniforms(src) {
  9401. var dst = {};
  9402. for (var u in src) {
  9403. dst[u] = {};
  9404. for (var p in src[u]) {
  9405. var property = src[u][p];
  9406. if (property && (property.isColor || property.isMatrix3 || property.isMatrix4 || property.isVector2 || property.isVector3 || property.isVector4 || property.isTexture)) {
  9407. dst[u][p] = property.clone();
  9408. } else if (Array.isArray(property)) {
  9409. dst[u][p] = property.slice();
  9410. } else {
  9411. dst[u][p] = property;
  9412. }
  9413. }
  9414. }
  9415. return dst;
  9416. }
  9417. function mergeUniforms(uniforms) {
  9418. var merged = {};
  9419. for (var u = 0; u < uniforms.length; u++) {
  9420. var tmp = cloneUniforms(uniforms[u]);
  9421. for (var p in tmp) {
  9422. merged[p] = tmp[p];
  9423. }
  9424. }
  9425. return merged;
  9426. } // Legacy
  9427. var UniformsUtils = {
  9428. clone: cloneUniforms,
  9429. merge: mergeUniforms
  9430. };
  9431. exports.UniformsUtils = UniformsUtils;
  9432. var default_vertex = "void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}";
  9433. var default_fragment = "void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}";
  9434. /**
  9435. * @author alteredq / http://alteredqualia.com/
  9436. *
  9437. * parameters = {
  9438. * defines: { "label" : "value" },
  9439. * uniforms: { "parameter1": { value: 1.0 }, "parameter2": { value2: 2 } },
  9440. *
  9441. * fragmentShader: <string>,
  9442. * vertexShader: <string>,
  9443. *
  9444. * wireframe: <boolean>,
  9445. * wireframeLinewidth: <float>,
  9446. *
  9447. * lights: <bool>,
  9448. *
  9449. * skinning: <bool>,
  9450. * morphTargets: <bool>,
  9451. * morphNormals: <bool>
  9452. * }
  9453. */
  9454. function ShaderMaterial(parameters) {
  9455. Material.call(this);
  9456. this.type = 'ShaderMaterial';
  9457. this.defines = {};
  9458. this.uniforms = {};
  9459. this.vertexShader = default_vertex;
  9460. this.fragmentShader = default_fragment;
  9461. this.linewidth = 1;
  9462. this.wireframe = false;
  9463. this.wireframeLinewidth = 1;
  9464. this.fog = false; // set to use scene fog
  9465. this.lights = false; // set to use scene lights
  9466. this.clipping = false; // set to use user-defined clipping planes
  9467. this.skinning = false; // set to use skinning attribute streams
  9468. this.morphTargets = false; // set to use morph targets
  9469. this.morphNormals = false; // set to use morph normals
  9470. this.extensions = {
  9471. derivatives: false,
  9472. // set to use derivatives
  9473. fragDepth: false,
  9474. // set to use fragment depth values
  9475. drawBuffers: false,
  9476. // set to use draw buffers
  9477. shaderTextureLOD: false // set to use shader texture LOD
  9478. }; // When rendered geometry doesn't include these attributes but the material does,
  9479. // use these default values in WebGL. This avoids errors when buffer data is missing.
  9480. this.defaultAttributeValues = {
  9481. 'color': [1, 1, 1],
  9482. 'uv': [0, 0],
  9483. 'uv2': [0, 0]
  9484. };
  9485. this.index0AttributeName = undefined;
  9486. this.uniformsNeedUpdate = false;
  9487. if (parameters !== undefined) {
  9488. if (parameters.attributes !== undefined) {
  9489. console.error('THREE.ShaderMaterial: attributes should now be defined in THREE.BufferGeometry instead.');
  9490. }
  9491. this.setValues(parameters);
  9492. }
  9493. }
  9494. ShaderMaterial.prototype = Object.create(Material.prototype);
  9495. ShaderMaterial.prototype.constructor = ShaderMaterial;
  9496. ShaderMaterial.prototype.isShaderMaterial = true;
  9497. ShaderMaterial.prototype.copy = function (source) {
  9498. Material.prototype.copy.call(this, source);
  9499. this.fragmentShader = source.fragmentShader;
  9500. this.vertexShader = source.vertexShader;
  9501. this.uniforms = cloneUniforms(source.uniforms);
  9502. this.defines = Object.assign({}, source.defines);
  9503. this.wireframe = source.wireframe;
  9504. this.wireframeLinewidth = source.wireframeLinewidth;
  9505. this.lights = source.lights;
  9506. this.clipping = source.clipping;
  9507. this.skinning = source.skinning;
  9508. this.morphTargets = source.morphTargets;
  9509. this.morphNormals = source.morphNormals;
  9510. this.extensions = source.extensions;
  9511. return this;
  9512. };
  9513. ShaderMaterial.prototype.toJSON = function (meta) {
  9514. var data = Material.prototype.toJSON.call(this, meta);
  9515. data.uniforms = {};
  9516. for (var name in this.uniforms) {
  9517. var uniform = this.uniforms[name];
  9518. var value = uniform.value;
  9519. if (value && value.isTexture) {
  9520. data.uniforms[name] = {
  9521. type: 't',
  9522. value: value.toJSON(meta).uuid
  9523. };
  9524. } else if (value && value.isColor) {
  9525. data.uniforms[name] = {
  9526. type: 'c',
  9527. value: value.getHex()
  9528. };
  9529. } else if (value && value.isVector2) {
  9530. data.uniforms[name] = {
  9531. type: 'v2',
  9532. value: value.toArray()
  9533. };
  9534. } else if (value && value.isVector3) {
  9535. data.uniforms[name] = {
  9536. type: 'v3',
  9537. value: value.toArray()
  9538. };
  9539. } else if (value && value.isVector4) {
  9540. data.uniforms[name] = {
  9541. type: 'v4',
  9542. value: value.toArray()
  9543. };
  9544. } else if (value && value.isMatrix3) {
  9545. data.uniforms[name] = {
  9546. type: 'm3',
  9547. value: value.toArray()
  9548. };
  9549. } else if (value && value.isMatrix4) {
  9550. data.uniforms[name] = {
  9551. type: 'm4',
  9552. value: value.toArray()
  9553. };
  9554. } else {
  9555. data.uniforms[name] = {
  9556. value: value
  9557. }; // note: the array variants v2v, v3v, v4v, m4v and tv are not supported so far
  9558. }
  9559. }
  9560. if (Object.keys(this.defines).length > 0) data.defines = this.defines;
  9561. data.vertexShader = this.vertexShader;
  9562. data.fragmentShader = this.fragmentShader;
  9563. var extensions = {};
  9564. for (var key in this.extensions) {
  9565. if (this.extensions[key] === true) extensions[key] = true;
  9566. }
  9567. if (Object.keys(extensions).length > 0) data.extensions = extensions;
  9568. return data;
  9569. };
  9570. /**
  9571. * @author mrdoob / http://mrdoob.com/
  9572. * @author mikael emtinger / http://gomo.se/
  9573. * @author WestLangley / http://github.com/WestLangley
  9574. */
  9575. function Camera() {
  9576. Object3D.call(this);
  9577. this.type = 'Camera';
  9578. this.matrixWorldInverse = new Matrix4();
  9579. this.projectionMatrix = new Matrix4();
  9580. this.projectionMatrixInverse = new Matrix4();
  9581. }
  9582. Camera.prototype = Object.assign(Object.create(Object3D.prototype), {
  9583. constructor: Camera,
  9584. isCamera: true,
  9585. copy: function (source, recursive) {
  9586. Object3D.prototype.copy.call(this, source, recursive);
  9587. this.matrixWorldInverse.copy(source.matrixWorldInverse);
  9588. this.projectionMatrix.copy(source.projectionMatrix);
  9589. this.projectionMatrixInverse.copy(source.projectionMatrixInverse);
  9590. return this;
  9591. },
  9592. getWorldDirection: function (target) {
  9593. if (target === undefined) {
  9594. console.warn('THREE.Camera: .getWorldDirection() target is now required');
  9595. target = new Vector3();
  9596. }
  9597. this.updateMatrixWorld(true);
  9598. var e = this.matrixWorld.elements;
  9599. return target.set(-e[8], -e[9], -e[10]).normalize();
  9600. },
  9601. updateMatrixWorld: function (force) {
  9602. Object3D.prototype.updateMatrixWorld.call(this, force);
  9603. this.matrixWorldInverse.getInverse(this.matrixWorld);
  9604. },
  9605. clone: function () {
  9606. return new this.constructor().copy(this);
  9607. }
  9608. });
  9609. /**
  9610. * @author mrdoob / http://mrdoob.com/
  9611. * @author greggman / http://games.greggman.com/
  9612. * @author zz85 / http://www.lab4games.net/zz85/blog
  9613. * @author tschw
  9614. */
  9615. function PerspectiveCamera(fov, aspect, near, far) {
  9616. Camera.call(this);
  9617. this.type = 'PerspectiveCamera';
  9618. this.fov = fov !== undefined ? fov : 50;
  9619. this.zoom = 1;
  9620. this.near = near !== undefined ? near : 0.1;
  9621. this.far = far !== undefined ? far : 2000;
  9622. this.focus = 10;
  9623. this.aspect = aspect !== undefined ? aspect : 1;
  9624. this.view = null;
  9625. this.filmGauge = 35; // width of the film (default in millimeters)
  9626. this.filmOffset = 0; // horizontal film offset (same unit as gauge)
  9627. this.updateProjectionMatrix();
  9628. }
  9629. PerspectiveCamera.prototype = Object.assign(Object.create(Camera.prototype), {
  9630. constructor: PerspectiveCamera,
  9631. isPerspectiveCamera: true,
  9632. copy: function (source, recursive) {
  9633. Camera.prototype.copy.call(this, source, recursive);
  9634. this.fov = source.fov;
  9635. this.zoom = source.zoom;
  9636. this.near = source.near;
  9637. this.far = source.far;
  9638. this.focus = source.focus;
  9639. this.aspect = source.aspect;
  9640. this.view = source.view === null ? null : Object.assign({}, source.view);
  9641. this.filmGauge = source.filmGauge;
  9642. this.filmOffset = source.filmOffset;
  9643. return this;
  9644. },
  9645. /**
  9646. * Sets the FOV by focal length in respect to the current .filmGauge.
  9647. *
  9648. * The default film gauge is 35, so that the focal length can be specified for
  9649. * a 35mm (full frame) camera.
  9650. *
  9651. * Values for focal length and film gauge must have the same unit.
  9652. */
  9653. setFocalLength: function (focalLength) {
  9654. // see http://www.bobatkins.com/photography/technical/field_of_view.html
  9655. var vExtentSlope = 0.5 * this.getFilmHeight() / focalLength;
  9656. this.fov = _Math.RAD2DEG * 2 * Math.atan(vExtentSlope);
  9657. this.updateProjectionMatrix();
  9658. },
  9659. /**
  9660. * Calculates the focal length from the current .fov and .filmGauge.
  9661. */
  9662. getFocalLength: function () {
  9663. var vExtentSlope = Math.tan(_Math.DEG2RAD * 0.5 * this.fov);
  9664. return 0.5 * this.getFilmHeight() / vExtentSlope;
  9665. },
  9666. getEffectiveFOV: function () {
  9667. return _Math.RAD2DEG * 2 * Math.atan(Math.tan(_Math.DEG2RAD * 0.5 * this.fov) / this.zoom);
  9668. },
  9669. getFilmWidth: function () {
  9670. // film not completely covered in portrait format (aspect < 1)
  9671. return this.filmGauge * Math.min(this.aspect, 1);
  9672. },
  9673. getFilmHeight: function () {
  9674. // film not completely covered in landscape format (aspect > 1)
  9675. return this.filmGauge / Math.max(this.aspect, 1);
  9676. },
  9677. /**
  9678. * Sets an offset in a larger frustum. This is useful for multi-window or
  9679. * multi-monitor/multi-machine setups.
  9680. *
  9681. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  9682. * the monitors are in grid like this
  9683. *
  9684. * +---+---+---+
  9685. * | A | B | C |
  9686. * +---+---+---+
  9687. * | D | E | F |
  9688. * +---+---+---+
  9689. *
  9690. * then for each monitor you would call it like this
  9691. *
  9692. * var w = 1920;
  9693. * var h = 1080;
  9694. * var fullWidth = w * 3;
  9695. * var fullHeight = h * 2;
  9696. *
  9697. * --A--
  9698. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  9699. * --B--
  9700. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  9701. * --C--
  9702. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  9703. * --D--
  9704. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  9705. * --E--
  9706. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  9707. * --F--
  9708. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  9709. *
  9710. * Note there is no reason monitors have to be the same size or in a grid.
  9711. */
  9712. setViewOffset: function (fullWidth, fullHeight, x, y, width, height) {
  9713. this.aspect = fullWidth / fullHeight;
  9714. if (this.view === null) {
  9715. this.view = {
  9716. enabled: true,
  9717. fullWidth: 1,
  9718. fullHeight: 1,
  9719. offsetX: 0,
  9720. offsetY: 0,
  9721. width: 1,
  9722. height: 1
  9723. };
  9724. }
  9725. this.view.enabled = true;
  9726. this.view.fullWidth = fullWidth;
  9727. this.view.fullHeight = fullHeight;
  9728. this.view.offsetX = x;
  9729. this.view.offsetY = y;
  9730. this.view.width = width;
  9731. this.view.height = height;
  9732. this.updateProjectionMatrix();
  9733. },
  9734. clearViewOffset: function () {
  9735. if (this.view !== null) {
  9736. this.view.enabled = false;
  9737. }
  9738. this.updateProjectionMatrix();
  9739. },
  9740. updateProjectionMatrix: function () {
  9741. var near = this.near,
  9742. top = near * Math.tan(_Math.DEG2RAD * 0.5 * this.fov) / this.zoom,
  9743. height = 2 * top,
  9744. width = this.aspect * height,
  9745. left = -0.5 * width,
  9746. view = this.view;
  9747. if (this.view !== null && this.view.enabled) {
  9748. var fullWidth = view.fullWidth,
  9749. fullHeight = view.fullHeight;
  9750. left += view.offsetX * width / fullWidth;
  9751. top -= view.offsetY * height / fullHeight;
  9752. width *= view.width / fullWidth;
  9753. height *= view.height / fullHeight;
  9754. }
  9755. var skew = this.filmOffset;
  9756. if (skew !== 0) left += near * skew / this.getFilmWidth();
  9757. this.projectionMatrix.makePerspective(left, left + width, top, top - height, near, this.far);
  9758. this.projectionMatrixInverse.getInverse(this.projectionMatrix);
  9759. },
  9760. toJSON: function (meta) {
  9761. var data = Object3D.prototype.toJSON.call(this, meta);
  9762. data.object.fov = this.fov;
  9763. data.object.zoom = this.zoom;
  9764. data.object.near = this.near;
  9765. data.object.far = this.far;
  9766. data.object.focus = this.focus;
  9767. data.object.aspect = this.aspect;
  9768. if (this.view !== null) data.object.view = Object.assign({}, this.view);
  9769. data.object.filmGauge = this.filmGauge;
  9770. data.object.filmOffset = this.filmOffset;
  9771. return data;
  9772. }
  9773. });
  9774. /**
  9775. * Camera for rendering cube maps
  9776. * - renders scene into axis-aligned cube
  9777. *
  9778. * @author alteredq / http://alteredqualia.com/
  9779. */
  9780. var fov = 90,
  9781. aspect = 1;
  9782. function CubeCamera(near, far, cubeResolution, options) {
  9783. Object3D.call(this);
  9784. this.type = 'CubeCamera';
  9785. var cameraPX = new PerspectiveCamera(fov, aspect, near, far);
  9786. cameraPX.up.set(0, -1, 0);
  9787. cameraPX.lookAt(new Vector3(1, 0, 0));
  9788. this.add(cameraPX);
  9789. var cameraNX = new PerspectiveCamera(fov, aspect, near, far);
  9790. cameraNX.up.set(0, -1, 0);
  9791. cameraNX.lookAt(new Vector3(-1, 0, 0));
  9792. this.add(cameraNX);
  9793. var cameraPY = new PerspectiveCamera(fov, aspect, near, far);
  9794. cameraPY.up.set(0, 0, 1);
  9795. cameraPY.lookAt(new Vector3(0, 1, 0));
  9796. this.add(cameraPY);
  9797. var cameraNY = new PerspectiveCamera(fov, aspect, near, far);
  9798. cameraNY.up.set(0, 0, -1);
  9799. cameraNY.lookAt(new Vector3(0, -1, 0));
  9800. this.add(cameraNY);
  9801. var cameraPZ = new PerspectiveCamera(fov, aspect, near, far);
  9802. cameraPZ.up.set(0, -1, 0);
  9803. cameraPZ.lookAt(new Vector3(0, 0, 1));
  9804. this.add(cameraPZ);
  9805. var cameraNZ = new PerspectiveCamera(fov, aspect, near, far);
  9806. cameraNZ.up.set(0, -1, 0);
  9807. cameraNZ.lookAt(new Vector3(0, 0, -1));
  9808. this.add(cameraNZ);
  9809. options = options || {
  9810. format: RGBFormat,
  9811. magFilter: LinearFilter,
  9812. minFilter: LinearFilter
  9813. };
  9814. this.renderTarget = new WebGLRenderTargetCube(cubeResolution, cubeResolution, options);
  9815. this.renderTarget.texture.name = "CubeCamera";
  9816. this.update = function (renderer, scene) {
  9817. if (this.parent === null) this.updateMatrixWorld();
  9818. var currentRenderTarget = renderer.getRenderTarget();
  9819. var renderTarget = this.renderTarget;
  9820. var generateMipmaps = renderTarget.texture.generateMipmaps;
  9821. renderTarget.texture.generateMipmaps = false;
  9822. renderer.setRenderTarget(renderTarget, 0);
  9823. renderer.render(scene, cameraPX);
  9824. renderer.setRenderTarget(renderTarget, 1);
  9825. renderer.render(scene, cameraNX);
  9826. renderer.setRenderTarget(renderTarget, 2);
  9827. renderer.render(scene, cameraPY);
  9828. renderer.setRenderTarget(renderTarget, 3);
  9829. renderer.render(scene, cameraNY);
  9830. renderer.setRenderTarget(renderTarget, 4);
  9831. renderer.render(scene, cameraPZ);
  9832. renderTarget.texture.generateMipmaps = generateMipmaps;
  9833. renderer.setRenderTarget(renderTarget, 5);
  9834. renderer.render(scene, cameraNZ);
  9835. renderer.setRenderTarget(currentRenderTarget);
  9836. };
  9837. this.clear = function (renderer, color, depth, stencil) {
  9838. var currentRenderTarget = renderer.getRenderTarget();
  9839. var renderTarget = this.renderTarget;
  9840. for (var i = 0; i < 6; i++) {
  9841. renderer.setRenderTarget(renderTarget, i);
  9842. renderer.clear(color, depth, stencil);
  9843. }
  9844. renderer.setRenderTarget(currentRenderTarget);
  9845. };
  9846. }
  9847. CubeCamera.prototype = Object.create(Object3D.prototype);
  9848. CubeCamera.prototype.constructor = CubeCamera;
  9849. /**
  9850. * @author alteredq / http://alteredqualia.com
  9851. * @author WestLangley / http://github.com/WestLangley
  9852. */
  9853. function WebGLRenderTargetCube(width, height, options) {
  9854. WebGLRenderTarget.call(this, width, height, options);
  9855. }
  9856. WebGLRenderTargetCube.prototype = Object.create(WebGLRenderTarget.prototype);
  9857. WebGLRenderTargetCube.prototype.constructor = WebGLRenderTargetCube;
  9858. WebGLRenderTargetCube.prototype.isWebGLRenderTargetCube = true;
  9859. WebGLRenderTargetCube.prototype.fromEquirectangularTexture = function (renderer, texture) {
  9860. this.texture.type = texture.type;
  9861. this.texture.format = texture.format;
  9862. this.texture.encoding = texture.encoding;
  9863. var scene = new Scene();
  9864. var shader = {
  9865. uniforms: {
  9866. tEquirect: {
  9867. value: null
  9868. }
  9869. },
  9870. 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'),
  9871. 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')
  9872. };
  9873. var material = new ShaderMaterial({
  9874. type: 'CubemapFromEquirect',
  9875. uniforms: cloneUniforms(shader.uniforms),
  9876. vertexShader: shader.vertexShader,
  9877. fragmentShader: shader.fragmentShader,
  9878. side: BackSide,
  9879. blending: NoBlending
  9880. });
  9881. material.uniforms.tEquirect.value = texture;
  9882. var mesh = new Mesh(new BoxBufferGeometry(5, 5, 5), material);
  9883. scene.add(mesh);
  9884. var camera = new CubeCamera(1, 10, 1);
  9885. camera.renderTarget = this;
  9886. camera.renderTarget.texture.name = 'CubeCameraTexture';
  9887. camera.update(renderer, scene);
  9888. mesh.geometry.dispose();
  9889. mesh.material.dispose();
  9890. return this;
  9891. };
  9892. /**
  9893. * @author alteredq / http://alteredqualia.com/
  9894. */
  9895. function DataTexture(data, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding) {
  9896. Texture.call(this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding);
  9897. this.image = {
  9898. data: data || null,
  9899. width: width || 1,
  9900. height: height || 1
  9901. };
  9902. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  9903. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  9904. this.generateMipmaps = false;
  9905. this.flipY = false;
  9906. this.unpackAlignment = 1;
  9907. this.needsUpdate = true;
  9908. }
  9909. DataTexture.prototype = Object.create(Texture.prototype);
  9910. DataTexture.prototype.constructor = DataTexture;
  9911. DataTexture.prototype.isDataTexture = true;
  9912. /**
  9913. * @author bhouston / http://clara.io
  9914. */
  9915. var _vector1 = new Vector3();
  9916. var _vector2 = new Vector3();
  9917. var _normalMatrix = new Matrix3();
  9918. function Plane(normal, constant) {
  9919. // normal is assumed to be normalized
  9920. this.normal = normal !== undefined ? normal : new Vector3(1, 0, 0);
  9921. this.constant = constant !== undefined ? constant : 0;
  9922. }
  9923. Object.assign(Plane.prototype, {
  9924. isPlane: true,
  9925. set: function (normal, constant) {
  9926. this.normal.copy(normal);
  9927. this.constant = constant;
  9928. return this;
  9929. },
  9930. setComponents: function (x, y, z, w) {
  9931. this.normal.set(x, y, z);
  9932. this.constant = w;
  9933. return this;
  9934. },
  9935. setFromNormalAndCoplanarPoint: function (normal, point) {
  9936. this.normal.copy(normal);
  9937. this.constant = -point.dot(this.normal);
  9938. return this;
  9939. },
  9940. setFromCoplanarPoints: function (a, b, c) {
  9941. 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)?
  9942. this.setFromNormalAndCoplanarPoint(normal, a);
  9943. return this;
  9944. },
  9945. clone: function () {
  9946. return new this.constructor().copy(this);
  9947. },
  9948. copy: function (plane) {
  9949. this.normal.copy(plane.normal);
  9950. this.constant = plane.constant;
  9951. return this;
  9952. },
  9953. normalize: function () {
  9954. // Note: will lead to a divide by zero if the plane is invalid.
  9955. var inverseNormalLength = 1.0 / this.normal.length();
  9956. this.normal.multiplyScalar(inverseNormalLength);
  9957. this.constant *= inverseNormalLength;
  9958. return this;
  9959. },
  9960. negate: function () {
  9961. this.constant *= -1;
  9962. this.normal.negate();
  9963. return this;
  9964. },
  9965. distanceToPoint: function (point) {
  9966. return this.normal.dot(point) + this.constant;
  9967. },
  9968. distanceToSphere: function (sphere) {
  9969. return this.distanceToPoint(sphere.center) - sphere.radius;
  9970. },
  9971. projectPoint: function (point, target) {
  9972. if (target === undefined) {
  9973. console.warn('THREE.Plane: .projectPoint() target is now required');
  9974. target = new Vector3();
  9975. }
  9976. return target.copy(this.normal).multiplyScalar(-this.distanceToPoint(point)).add(point);
  9977. },
  9978. intersectLine: function (line, target) {
  9979. if (target === undefined) {
  9980. console.warn('THREE.Plane: .intersectLine() target is now required');
  9981. target = new Vector3();
  9982. }
  9983. var direction = line.delta(_vector1);
  9984. var denominator = this.normal.dot(direction);
  9985. if (denominator === 0) {
  9986. // line is coplanar, return origin
  9987. if (this.distanceToPoint(line.start) === 0) {
  9988. return target.copy(line.start);
  9989. } // Unsure if this is the correct method to handle this case.
  9990. return undefined;
  9991. }
  9992. var t = -(line.start.dot(this.normal) + this.constant) / denominator;
  9993. if (t < 0 || t > 1) {
  9994. return undefined;
  9995. }
  9996. return target.copy(direction).multiplyScalar(t).add(line.start);
  9997. },
  9998. intersectsLine: function (line) {
  9999. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  10000. var startSign = this.distanceToPoint(line.start);
  10001. var endSign = this.distanceToPoint(line.end);
  10002. return startSign < 0 && endSign > 0 || endSign < 0 && startSign > 0;
  10003. },
  10004. intersectsBox: function (box) {
  10005. return box.intersectsPlane(this);
  10006. },
  10007. intersectsSphere: function (sphere) {
  10008. return sphere.intersectsPlane(this);
  10009. },
  10010. coplanarPoint: function (target) {
  10011. if (target === undefined) {
  10012. console.warn('THREE.Plane: .coplanarPoint() target is now required');
  10013. target = new Vector3();
  10014. }
  10015. return target.copy(this.normal).multiplyScalar(-this.constant);
  10016. },
  10017. applyMatrix4: function (matrix, optionalNormalMatrix) {
  10018. var normalMatrix = optionalNormalMatrix || _normalMatrix.getNormalMatrix(matrix);
  10019. var referencePoint = this.coplanarPoint(_vector1).applyMatrix4(matrix);
  10020. var normal = this.normal.applyMatrix3(normalMatrix).normalize();
  10021. this.constant = -referencePoint.dot(normal);
  10022. return this;
  10023. },
  10024. translate: function (offset) {
  10025. this.constant -= offset.dot(this.normal);
  10026. return this;
  10027. },
  10028. equals: function (plane) {
  10029. return plane.normal.equals(this.normal) && plane.constant === this.constant;
  10030. }
  10031. });
  10032. /**
  10033. * @author mrdoob / http://mrdoob.com/
  10034. * @author alteredq / http://alteredqualia.com/
  10035. * @author bhouston / http://clara.io
  10036. */
  10037. var _sphere$1 = new Sphere();
  10038. var _vector$5 = new Vector3();
  10039. function Frustum(p0, p1, p2, p3, p4, p5) {
  10040. 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()];
  10041. }
  10042. Object.assign(Frustum.prototype, {
  10043. set: function (p0, p1, p2, p3, p4, p5) {
  10044. var planes = this.planes;
  10045. planes[0].copy(p0);
  10046. planes[1].copy(p1);
  10047. planes[2].copy(p2);
  10048. planes[3].copy(p3);
  10049. planes[4].copy(p4);
  10050. planes[5].copy(p5);
  10051. return this;
  10052. },
  10053. clone: function () {
  10054. return new this.constructor().copy(this);
  10055. },
  10056. copy: function (frustum) {
  10057. var planes = this.planes;
  10058. for (var i = 0; i < 6; i++) {
  10059. planes[i].copy(frustum.planes[i]);
  10060. }
  10061. return this;
  10062. },
  10063. setFromMatrix: function (m) {
  10064. var planes = this.planes;
  10065. var me = m.elements;
  10066. var me0 = me[0],
  10067. me1 = me[1],
  10068. me2 = me[2],
  10069. me3 = me[3];
  10070. var me4 = me[4],
  10071. me5 = me[5],
  10072. me6 = me[6],
  10073. me7 = me[7];
  10074. var me8 = me[8],
  10075. me9 = me[9],
  10076. me10 = me[10],
  10077. me11 = me[11];
  10078. var me12 = me[12],
  10079. me13 = me[13],
  10080. me14 = me[14],
  10081. me15 = me[15];
  10082. planes[0].setComponents(me3 - me0, me7 - me4, me11 - me8, me15 - me12).normalize();
  10083. planes[1].setComponents(me3 + me0, me7 + me4, me11 + me8, me15 + me12).normalize();
  10084. planes[2].setComponents(me3 + me1, me7 + me5, me11 + me9, me15 + me13).normalize();
  10085. planes[3].setComponents(me3 - me1, me7 - me5, me11 - me9, me15 - me13).normalize();
  10086. planes[4].setComponents(me3 - me2, me7 - me6, me11 - me10, me15 - me14).normalize();
  10087. planes[5].setComponents(me3 + me2, me7 + me6, me11 + me10, me15 + me14).normalize();
  10088. return this;
  10089. },
  10090. intersectsObject: function (object) {
  10091. var geometry = object.geometry;
  10092. if (geometry.boundingSphere === null) geometry.computeBoundingSphere();
  10093. _sphere$1.copy(geometry.boundingSphere).applyMatrix4(object.matrixWorld);
  10094. return this.intersectsSphere(_sphere$1);
  10095. },
  10096. intersectsSprite: function (sprite) {
  10097. _sphere$1.center.set(0, 0, 0);
  10098. _sphere$1.radius = 0.7071067811865476;
  10099. _sphere$1.applyMatrix4(sprite.matrixWorld);
  10100. return this.intersectsSphere(_sphere$1);
  10101. },
  10102. intersectsSphere: function (sphere) {
  10103. var planes = this.planes;
  10104. var center = sphere.center;
  10105. var negRadius = -sphere.radius;
  10106. for (var i = 0; i < 6; i++) {
  10107. var distance = planes[i].distanceToPoint(center);
  10108. if (distance < negRadius) {
  10109. return false;
  10110. }
  10111. }
  10112. return true;
  10113. },
  10114. intersectsBox: function (box) {
  10115. var planes = this.planes;
  10116. for (var i = 0; i < 6; i++) {
  10117. var plane = planes[i]; // corner at max distance
  10118. _vector$5.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  10119. _vector$5.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  10120. _vector$5.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  10121. if (plane.distanceToPoint(_vector$5) < 0) {
  10122. return false;
  10123. }
  10124. }
  10125. return true;
  10126. },
  10127. containsPoint: function (point) {
  10128. var planes = this.planes;
  10129. for (var i = 0; i < 6; i++) {
  10130. if (planes[i].distanceToPoint(point) < 0) {
  10131. return false;
  10132. }
  10133. }
  10134. return true;
  10135. }
  10136. });
  10137. var alphamap_fragment = "#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, vUv ).g;\n#endif";
  10138. var alphamap_pars_fragment = "#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif";
  10139. var alphatest_fragment = "#ifdef ALPHATEST\n\tif ( diffuseColor.a < ALPHATEST ) discard;\n#endif";
  10140. 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";
  10141. var aomap_pars_fragment = "#ifdef USE_AOMAP\n\tuniform sampler2D aoMap;\n\tuniform float aoMapIntensity;\n#endif";
  10142. var begin_vertex = "vec3 transformed = vec3( position );";
  10143. var beginnormal_vertex = "vec3 objectNormal = vec3( normal );\n#ifdef USE_TANGENT\n\tvec3 objectTangent = vec3( tangent.xyz );\n#endif";
  10144. 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";
  10145. 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";
  10146. 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";
  10147. 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";
  10148. var clipping_planes_pars_vertex = "#if NUM_CLIPPING_PLANES > 0 && ! defined( STANDARD ) && ! defined( PHONG ) && ! defined( MATCAP )\n\tvarying vec3 vViewPosition;\n#endif";
  10149. var clipping_planes_vertex = "#if NUM_CLIPPING_PLANES > 0 && ! defined( STANDARD ) && ! defined( PHONG ) && ! defined( MATCAP )\n\tvViewPosition = - mvPosition.xyz;\n#endif";
  10150. var color_fragment = "#ifdef USE_COLOR\n\tdiffuseColor.rgb *= vColor;\n#endif";
  10151. var color_pars_fragment = "#ifdef USE_COLOR\n\tvarying vec3 vColor;\n#endif";
  10152. var color_pars_vertex = "#ifdef USE_COLOR\n\tvarying vec3 vColor;\n#endif";
  10153. var color_vertex = "#ifdef USE_COLOR\n\tvColor.xyz = color.xyz;\n#endif";
  10154. 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}";
  10155. 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";
  10156. 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";
  10157. var displacementmap_pars_vertex = "#ifdef USE_DISPLACEMENTMAP\n\tuniform sampler2D displacementMap;\n\tuniform float displacementScale;\n\tuniform float displacementBias;\n#endif";
  10158. var displacementmap_vertex = "#ifdef USE_DISPLACEMENTMAP\n\ttransformed += normalize( objectNormal ) * ( texture2D( displacementMap, vUv ).x * displacementScale + displacementBias );\n#endif";
  10159. var emissivemap_fragment = "#ifdef USE_EMISSIVEMAP\n\tvec4 emissiveColor = texture2D( emissiveMap, vUv );\n\temissiveColor.rgb = emissiveMapTexelToLinear( emissiveColor ).rgb;\n\ttotalEmissiveRadiance *= emissiveColor.rgb;\n#endif";
  10160. var emissivemap_pars_fragment = "#ifdef USE_EMISSIVEMAP\n\tuniform sampler2D emissiveMap;\n#endif";
  10161. var encodings_fragment = "gl_FragColor = linearToOutputTexel( gl_FragColor );";
  10162. 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}";
  10163. 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";
  10164. 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";
  10165. 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";
  10166. 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";
  10167. 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";
  10168. var fog_vertex = "#ifdef USE_FOG\n\tfogDepth = -mvPosition.z;\n#endif";
  10169. var fog_pars_vertex = "#ifdef USE_FOG\n\tvarying float fogDepth;\n#endif";
  10170. 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";
  10171. 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";
  10172. 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";
  10173. var lightmap_fragment = "#ifdef USE_LIGHTMAP\n\treflectedLight.indirectDiffuse += PI * texture2D( lightMap, vUv2 ).xyz * lightMapIntensity;\n#endif";
  10174. var lightmap_pars_fragment = "#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif";
  10175. 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";
  10176. 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";
  10177. 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";
  10178. var lights_phong_fragment = "BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;";
  10179. 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)";
  10180. 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";
  10181. 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}";
  10182. 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";
  10183. 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";
  10184. 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";
  10185. 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";
  10186. 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";
  10187. 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";
  10188. 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";
  10189. var map_fragment = "#ifdef USE_MAP\n\tvec4 texelColor = texture2D( map, vUv );\n\ttexelColor = mapTexelToLinear( texelColor );\n\tdiffuseColor *= texelColor;\n#endif";
  10190. var map_pars_fragment = "#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif";
  10191. 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";
  10192. var map_particle_pars_fragment = "#ifdef USE_MAP\n\tuniform mat3 uvTransform;\n\tuniform sampler2D map;\n#endif";
  10193. var metalnessmap_fragment = "float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n\tvec4 texelMetalness = texture2D( metalnessMap, vUv );\n\tmetalnessFactor *= texelMetalness.b;\n#endif";
  10194. var metalnessmap_pars_fragment = "#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif";
  10195. 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";
  10196. 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";
  10197. 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";
  10198. 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;";
  10199. 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";
  10200. 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";
  10201. var clearcoat_normal_fragment_begin = "#ifdef CLEARCOAT\n\tvec3 clearcoatNormal = geometryNormal;\n#endif";
  10202. 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";
  10203. var clearcoat_normalmap_pars_fragment = "#ifdef USE_CLEARCOAT_NORMALMAP\n\tuniform sampler2D clearcoatNormalMap;\n\tuniform vec2 clearcoatNormalScale;\n#endif";
  10204. 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}";
  10205. var premultiplied_alpha_fragment = "#ifdef PREMULTIPLIED_ALPHA\n\tgl_FragColor.rgb *= gl_FragColor.a;\n#endif";
  10206. 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;";
  10207. var dithering_fragment = "#ifdef DITHERING\n\tgl_FragColor.rgb = dithering( gl_FragColor.rgb );\n#endif";
  10208. 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";
  10209. var roughnessmap_fragment = "float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n\tvec4 texelRoughness = texture2D( roughnessMap, vUv );\n\troughnessFactor *= texelRoughness.g;\n#endif";
  10210. var roughnessmap_pars_fragment = "#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif";
  10211. 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";
  10212. 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";
  10213. 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";
  10214. 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}";
  10215. 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";
  10216. 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";
  10217. 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";
  10218. 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";
  10219. 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";
  10220. var specularmap_pars_fragment = "#ifdef USE_SPECULARMAP\n\tuniform sampler2D specularMap;\n#endif";
  10221. var tonemapping_fragment = "#if defined( TONE_MAPPING )\n\tgl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif";
  10222. 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}";
  10223. var uv_pars_fragment = "#ifdef USE_UV\n\tvarying vec2 vUv;\n#endif";
  10224. var uv_pars_vertex = "#ifdef USE_UV\n\tvarying vec2 vUv;\n\tuniform mat3 uvTransform;\n#endif";
  10225. var uv_vertex = "#ifdef USE_UV\n\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n#endif";
  10226. var uv2_pars_fragment = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvarying vec2 vUv2;\n#endif";
  10227. var uv2_pars_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tattribute vec2 uv2;\n\tvarying vec2 vUv2;\n#endif";
  10228. var uv2_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvUv2 = uv2;\n#endif";
  10229. 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";
  10230. 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}";
  10231. 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}";
  10232. 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}";
  10233. 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}";
  10234. 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}";
  10235. 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}";
  10236. 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}";
  10237. 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}";
  10238. 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}";
  10239. 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}";
  10240. 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}";
  10241. 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}";
  10242. 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}";
  10243. 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}";
  10244. 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}";
  10245. 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}";
  10246. 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}";
  10247. 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}";
  10248. 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}";
  10249. 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}";
  10250. 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}";
  10251. 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}";
  10252. 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}";
  10253. 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}";
  10254. 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}";
  10255. 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}";
  10256. 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}";
  10257. 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}";
  10258. 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}";
  10259. 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}";
  10260. var ShaderChunk = {
  10261. alphamap_fragment: alphamap_fragment,
  10262. alphamap_pars_fragment: alphamap_pars_fragment,
  10263. alphatest_fragment: alphatest_fragment,
  10264. aomap_fragment: aomap_fragment,
  10265. aomap_pars_fragment: aomap_pars_fragment,
  10266. begin_vertex: begin_vertex,
  10267. beginnormal_vertex: beginnormal_vertex,
  10268. bsdfs: bsdfs,
  10269. bumpmap_pars_fragment: bumpmap_pars_fragment,
  10270. clipping_planes_fragment: clipping_planes_fragment,
  10271. clipping_planes_pars_fragment: clipping_planes_pars_fragment,
  10272. clipping_planes_pars_vertex: clipping_planes_pars_vertex,
  10273. clipping_planes_vertex: clipping_planes_vertex,
  10274. color_fragment: color_fragment,
  10275. color_pars_fragment: color_pars_fragment,
  10276. color_pars_vertex: color_pars_vertex,
  10277. color_vertex: color_vertex,
  10278. common: common,
  10279. cube_uv_reflection_fragment: cube_uv_reflection_fragment,
  10280. defaultnormal_vertex: defaultnormal_vertex,
  10281. displacementmap_pars_vertex: displacementmap_pars_vertex,
  10282. displacementmap_vertex: displacementmap_vertex,
  10283. emissivemap_fragment: emissivemap_fragment,
  10284. emissivemap_pars_fragment: emissivemap_pars_fragment,
  10285. encodings_fragment: encodings_fragment,
  10286. encodings_pars_fragment: encodings_pars_fragment,
  10287. envmap_fragment: envmap_fragment,
  10288. envmap_common_pars_fragment: envmap_common_pars_fragment,
  10289. envmap_pars_fragment: envmap_pars_fragment,
  10290. envmap_pars_vertex: envmap_pars_vertex,
  10291. envmap_physical_pars_fragment: envmap_physical_pars_fragment,
  10292. envmap_vertex: envmap_vertex,
  10293. fog_vertex: fog_vertex,
  10294. fog_pars_vertex: fog_pars_vertex,
  10295. fog_fragment: fog_fragment,
  10296. fog_pars_fragment: fog_pars_fragment,
  10297. gradientmap_pars_fragment: gradientmap_pars_fragment,
  10298. lightmap_fragment: lightmap_fragment,
  10299. lightmap_pars_fragment: lightmap_pars_fragment,
  10300. lights_lambert_vertex: lights_lambert_vertex,
  10301. lights_pars_begin: lights_pars_begin,
  10302. lights_phong_fragment: lights_phong_fragment,
  10303. lights_phong_pars_fragment: lights_phong_pars_fragment,
  10304. lights_physical_fragment: lights_physical_fragment,
  10305. lights_physical_pars_fragment: lights_physical_pars_fragment,
  10306. lights_fragment_begin: lights_fragment_begin,
  10307. lights_fragment_maps: lights_fragment_maps,
  10308. lights_fragment_end: lights_fragment_end,
  10309. logdepthbuf_fragment: logdepthbuf_fragment,
  10310. logdepthbuf_pars_fragment: logdepthbuf_pars_fragment,
  10311. logdepthbuf_pars_vertex: logdepthbuf_pars_vertex,
  10312. logdepthbuf_vertex: logdepthbuf_vertex,
  10313. map_fragment: map_fragment,
  10314. map_pars_fragment: map_pars_fragment,
  10315. map_particle_fragment: map_particle_fragment,
  10316. map_particle_pars_fragment: map_particle_pars_fragment,
  10317. metalnessmap_fragment: metalnessmap_fragment,
  10318. metalnessmap_pars_fragment: metalnessmap_pars_fragment,
  10319. morphnormal_vertex: morphnormal_vertex,
  10320. morphtarget_pars_vertex: morphtarget_pars_vertex,
  10321. morphtarget_vertex: morphtarget_vertex,
  10322. normal_fragment_begin: normal_fragment_begin,
  10323. normal_fragment_maps: normal_fragment_maps,
  10324. normalmap_pars_fragment: normalmap_pars_fragment,
  10325. clearcoat_normal_fragment_begin: clearcoat_normal_fragment_begin,
  10326. clearcoat_normal_fragment_maps: clearcoat_normal_fragment_maps,
  10327. clearcoat_normalmap_pars_fragment: clearcoat_normalmap_pars_fragment,
  10328. packing: packing,
  10329. premultiplied_alpha_fragment: premultiplied_alpha_fragment,
  10330. project_vertex: project_vertex,
  10331. dithering_fragment: dithering_fragment,
  10332. dithering_pars_fragment: dithering_pars_fragment,
  10333. roughnessmap_fragment: roughnessmap_fragment,
  10334. roughnessmap_pars_fragment: roughnessmap_pars_fragment,
  10335. shadowmap_pars_fragment: shadowmap_pars_fragment,
  10336. shadowmap_pars_vertex: shadowmap_pars_vertex,
  10337. shadowmap_vertex: shadowmap_vertex,
  10338. shadowmask_pars_fragment: shadowmask_pars_fragment,
  10339. skinbase_vertex: skinbase_vertex,
  10340. skinning_pars_vertex: skinning_pars_vertex,
  10341. skinning_vertex: skinning_vertex,
  10342. skinnormal_vertex: skinnormal_vertex,
  10343. specularmap_fragment: specularmap_fragment,
  10344. specularmap_pars_fragment: specularmap_pars_fragment,
  10345. tonemapping_fragment: tonemapping_fragment,
  10346. tonemapping_pars_fragment: tonemapping_pars_fragment,
  10347. uv_pars_fragment: uv_pars_fragment,
  10348. uv_pars_vertex: uv_pars_vertex,
  10349. uv_vertex: uv_vertex,
  10350. uv2_pars_fragment: uv2_pars_fragment,
  10351. uv2_pars_vertex: uv2_pars_vertex,
  10352. uv2_vertex: uv2_vertex,
  10353. worldpos_vertex: worldpos_vertex,
  10354. background_frag: background_frag,
  10355. background_vert: background_vert,
  10356. cube_frag: cube_frag,
  10357. cube_vert: cube_vert,
  10358. depth_frag: depth_frag,
  10359. depth_vert: depth_vert,
  10360. distanceRGBA_frag: distanceRGBA_frag,
  10361. distanceRGBA_vert: distanceRGBA_vert,
  10362. equirect_frag: equirect_frag,
  10363. equirect_vert: equirect_vert,
  10364. linedashed_frag: linedashed_frag,
  10365. linedashed_vert: linedashed_vert,
  10366. meshbasic_frag: meshbasic_frag,
  10367. meshbasic_vert: meshbasic_vert,
  10368. meshlambert_frag: meshlambert_frag,
  10369. meshlambert_vert: meshlambert_vert,
  10370. meshmatcap_frag: meshmatcap_frag,
  10371. meshmatcap_vert: meshmatcap_vert,
  10372. meshphong_frag: meshphong_frag,
  10373. meshphong_vert: meshphong_vert,
  10374. meshphysical_frag: meshphysical_frag,
  10375. meshphysical_vert: meshphysical_vert,
  10376. normal_frag: normal_frag,
  10377. normal_vert: normal_vert,
  10378. points_frag: points_frag,
  10379. points_vert: points_vert,
  10380. shadow_frag: shadow_frag,
  10381. shadow_vert: shadow_vert,
  10382. sprite_frag: sprite_frag,
  10383. sprite_vert: sprite_vert
  10384. };
  10385. /**
  10386. * Uniforms library for shared webgl shaders
  10387. */
  10388. exports.ShaderChunk = ShaderChunk;
  10389. var UniformsLib = {
  10390. common: {
  10391. diffuse: {
  10392. value: new Color(0xeeeeee)
  10393. },
  10394. opacity: {
  10395. value: 1.0
  10396. },
  10397. map: {
  10398. value: null
  10399. },
  10400. uvTransform: {
  10401. value: new Matrix3()
  10402. },
  10403. alphaMap: {
  10404. value: null
  10405. }
  10406. },
  10407. specularmap: {
  10408. specularMap: {
  10409. value: null
  10410. }
  10411. },
  10412. envmap: {
  10413. envMap: {
  10414. value: null
  10415. },
  10416. flipEnvMap: {
  10417. value: -1
  10418. },
  10419. reflectivity: {
  10420. value: 1.0
  10421. },
  10422. refractionRatio: {
  10423. value: 0.98
  10424. },
  10425. maxMipLevel: {
  10426. value: 0
  10427. }
  10428. },
  10429. aomap: {
  10430. aoMap: {
  10431. value: null
  10432. },
  10433. aoMapIntensity: {
  10434. value: 1
  10435. }
  10436. },
  10437. lightmap: {
  10438. lightMap: {
  10439. value: null
  10440. },
  10441. lightMapIntensity: {
  10442. value: 1
  10443. }
  10444. },
  10445. emissivemap: {
  10446. emissiveMap: {
  10447. value: null
  10448. }
  10449. },
  10450. bumpmap: {
  10451. bumpMap: {
  10452. value: null
  10453. },
  10454. bumpScale: {
  10455. value: 1
  10456. }
  10457. },
  10458. normalmap: {
  10459. normalMap: {
  10460. value: null
  10461. },
  10462. normalScale: {
  10463. value: new Vector2(1, 1)
  10464. }
  10465. },
  10466. displacementmap: {
  10467. displacementMap: {
  10468. value: null
  10469. },
  10470. displacementScale: {
  10471. value: 1
  10472. },
  10473. displacementBias: {
  10474. value: 0
  10475. }
  10476. },
  10477. roughnessmap: {
  10478. roughnessMap: {
  10479. value: null
  10480. }
  10481. },
  10482. metalnessmap: {
  10483. metalnessMap: {
  10484. value: null
  10485. }
  10486. },
  10487. gradientmap: {
  10488. gradientMap: {
  10489. value: null
  10490. }
  10491. },
  10492. fog: {
  10493. fogDensity: {
  10494. value: 0.00025
  10495. },
  10496. fogNear: {
  10497. value: 1
  10498. },
  10499. fogFar: {
  10500. value: 2000
  10501. },
  10502. fogColor: {
  10503. value: new Color(0xffffff)
  10504. }
  10505. },
  10506. lights: {
  10507. ambientLightColor: {
  10508. value: []
  10509. },
  10510. lightProbe: {
  10511. value: []
  10512. },
  10513. directionalLights: {
  10514. value: [],
  10515. properties: {
  10516. direction: {},
  10517. color: {},
  10518. shadow: {},
  10519. shadowBias: {},
  10520. shadowRadius: {},
  10521. shadowMapSize: {}
  10522. }
  10523. },
  10524. directionalShadowMap: {
  10525. value: []
  10526. },
  10527. directionalShadowMatrix: {
  10528. value: []
  10529. },
  10530. spotLights: {
  10531. value: [],
  10532. properties: {
  10533. color: {},
  10534. position: {},
  10535. direction: {},
  10536. distance: {},
  10537. coneCos: {},
  10538. penumbraCos: {},
  10539. decay: {},
  10540. shadow: {},
  10541. shadowBias: {},
  10542. shadowRadius: {},
  10543. shadowMapSize: {}
  10544. }
  10545. },
  10546. spotShadowMap: {
  10547. value: []
  10548. },
  10549. spotShadowMatrix: {
  10550. value: []
  10551. },
  10552. pointLights: {
  10553. value: [],
  10554. properties: {
  10555. color: {},
  10556. position: {},
  10557. decay: {},
  10558. distance: {},
  10559. shadow: {},
  10560. shadowBias: {},
  10561. shadowRadius: {},
  10562. shadowMapSize: {},
  10563. shadowCameraNear: {},
  10564. shadowCameraFar: {}
  10565. }
  10566. },
  10567. pointShadowMap: {
  10568. value: []
  10569. },
  10570. pointShadowMatrix: {
  10571. value: []
  10572. },
  10573. hemisphereLights: {
  10574. value: [],
  10575. properties: {
  10576. direction: {},
  10577. skyColor: {},
  10578. groundColor: {}
  10579. }
  10580. },
  10581. // TODO (abelnation): RectAreaLight BRDF data needs to be moved from example to main src
  10582. rectAreaLights: {
  10583. value: [],
  10584. properties: {
  10585. color: {},
  10586. position: {},
  10587. width: {},
  10588. height: {}
  10589. }
  10590. }
  10591. },
  10592. points: {
  10593. diffuse: {
  10594. value: new Color(0xeeeeee)
  10595. },
  10596. opacity: {
  10597. value: 1.0
  10598. },
  10599. size: {
  10600. value: 1.0
  10601. },
  10602. scale: {
  10603. value: 1.0
  10604. },
  10605. map: {
  10606. value: null
  10607. },
  10608. uvTransform: {
  10609. value: new Matrix3()
  10610. }
  10611. },
  10612. sprite: {
  10613. diffuse: {
  10614. value: new Color(0xeeeeee)
  10615. },
  10616. opacity: {
  10617. value: 1.0
  10618. },
  10619. center: {
  10620. value: new Vector2(0.5, 0.5)
  10621. },
  10622. rotation: {
  10623. value: 0.0
  10624. },
  10625. map: {
  10626. value: null
  10627. },
  10628. uvTransform: {
  10629. value: new Matrix3()
  10630. }
  10631. }
  10632. };
  10633. /**
  10634. * @author alteredq / http://alteredqualia.com/
  10635. * @author mrdoob / http://mrdoob.com/
  10636. * @author mikael emtinger / http://gomo.se/
  10637. */
  10638. exports.UniformsLib = UniformsLib;
  10639. var ShaderLib = {
  10640. basic: {
  10641. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.specularmap, UniformsLib.envmap, UniformsLib.aomap, UniformsLib.lightmap, UniformsLib.fog]),
  10642. vertexShader: ShaderChunk.meshbasic_vert,
  10643. fragmentShader: ShaderChunk.meshbasic_frag
  10644. },
  10645. lambert: {
  10646. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.specularmap, UniformsLib.envmap, UniformsLib.aomap, UniformsLib.lightmap, UniformsLib.emissivemap, UniformsLib.fog, UniformsLib.lights, {
  10647. emissive: {
  10648. value: new Color(0x000000)
  10649. }
  10650. }]),
  10651. vertexShader: ShaderChunk.meshlambert_vert,
  10652. fragmentShader: ShaderChunk.meshlambert_frag
  10653. },
  10654. phong: {
  10655. 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, {
  10656. emissive: {
  10657. value: new Color(0x000000)
  10658. },
  10659. specular: {
  10660. value: new Color(0x111111)
  10661. },
  10662. shininess: {
  10663. value: 30
  10664. }
  10665. }]),
  10666. vertexShader: ShaderChunk.meshphong_vert,
  10667. fragmentShader: ShaderChunk.meshphong_frag
  10668. },
  10669. standard: {
  10670. 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, {
  10671. emissive: {
  10672. value: new Color(0x000000)
  10673. },
  10674. roughness: {
  10675. value: 0.5
  10676. },
  10677. metalness: {
  10678. value: 0.5
  10679. },
  10680. envMapIntensity: {
  10681. value: 1
  10682. } // temporary
  10683. }]),
  10684. vertexShader: ShaderChunk.meshphysical_vert,
  10685. fragmentShader: ShaderChunk.meshphysical_frag
  10686. },
  10687. matcap: {
  10688. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, UniformsLib.fog, {
  10689. matcap: {
  10690. value: null
  10691. }
  10692. }]),
  10693. vertexShader: ShaderChunk.meshmatcap_vert,
  10694. fragmentShader: ShaderChunk.meshmatcap_frag
  10695. },
  10696. points: {
  10697. uniforms: mergeUniforms([UniformsLib.points, UniformsLib.fog]),
  10698. vertexShader: ShaderChunk.points_vert,
  10699. fragmentShader: ShaderChunk.points_frag
  10700. },
  10701. dashed: {
  10702. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.fog, {
  10703. scale: {
  10704. value: 1
  10705. },
  10706. dashSize: {
  10707. value: 1
  10708. },
  10709. totalSize: {
  10710. value: 2
  10711. }
  10712. }]),
  10713. vertexShader: ShaderChunk.linedashed_vert,
  10714. fragmentShader: ShaderChunk.linedashed_frag
  10715. },
  10716. depth: {
  10717. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.displacementmap]),
  10718. vertexShader: ShaderChunk.depth_vert,
  10719. fragmentShader: ShaderChunk.depth_frag
  10720. },
  10721. normal: {
  10722. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, {
  10723. opacity: {
  10724. value: 1.0
  10725. }
  10726. }]),
  10727. vertexShader: ShaderChunk.normal_vert,
  10728. fragmentShader: ShaderChunk.normal_frag
  10729. },
  10730. sprite: {
  10731. uniforms: mergeUniforms([UniformsLib.sprite, UniformsLib.fog]),
  10732. vertexShader: ShaderChunk.sprite_vert,
  10733. fragmentShader: ShaderChunk.sprite_frag
  10734. },
  10735. background: {
  10736. uniforms: {
  10737. uvTransform: {
  10738. value: new Matrix3()
  10739. },
  10740. t2D: {
  10741. value: null
  10742. }
  10743. },
  10744. vertexShader: ShaderChunk.background_vert,
  10745. fragmentShader: ShaderChunk.background_frag
  10746. },
  10747. /* -------------------------------------------------------------------------
  10748. // Cube map shader
  10749. ------------------------------------------------------------------------- */
  10750. cube: {
  10751. uniforms: {
  10752. tCube: {
  10753. value: null
  10754. },
  10755. tFlip: {
  10756. value: -1
  10757. },
  10758. opacity: {
  10759. value: 1.0
  10760. }
  10761. },
  10762. vertexShader: ShaderChunk.cube_vert,
  10763. fragmentShader: ShaderChunk.cube_frag
  10764. },
  10765. equirect: {
  10766. uniforms: {
  10767. tEquirect: {
  10768. value: null
  10769. }
  10770. },
  10771. vertexShader: ShaderChunk.equirect_vert,
  10772. fragmentShader: ShaderChunk.equirect_frag
  10773. },
  10774. distanceRGBA: {
  10775. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.displacementmap, {
  10776. referencePosition: {
  10777. value: new Vector3()
  10778. },
  10779. nearDistance: {
  10780. value: 1
  10781. },
  10782. farDistance: {
  10783. value: 1000
  10784. }
  10785. }]),
  10786. vertexShader: ShaderChunk.distanceRGBA_vert,
  10787. fragmentShader: ShaderChunk.distanceRGBA_frag
  10788. },
  10789. shadow: {
  10790. uniforms: mergeUniforms([UniformsLib.lights, UniformsLib.fog, {
  10791. color: {
  10792. value: new Color(0x00000)
  10793. },
  10794. opacity: {
  10795. value: 1.0
  10796. }
  10797. }]),
  10798. vertexShader: ShaderChunk.shadow_vert,
  10799. fragmentShader: ShaderChunk.shadow_frag
  10800. }
  10801. };
  10802. exports.ShaderLib = ShaderLib;
  10803. ShaderLib.physical = {
  10804. uniforms: mergeUniforms([ShaderLib.standard.uniforms, {
  10805. transparency: {
  10806. value: 0
  10807. },
  10808. clearcoat: {
  10809. value: 0
  10810. },
  10811. clearcoatRoughness: {
  10812. value: 0
  10813. },
  10814. sheen: {
  10815. value: new Color(0x000000)
  10816. },
  10817. clearcoatNormalScale: {
  10818. value: new Vector2(1, 1)
  10819. },
  10820. clearcoatNormalMap: {
  10821. value: null
  10822. }
  10823. }]),
  10824. vertexShader: ShaderChunk.meshphysical_vert,
  10825. fragmentShader: ShaderChunk.meshphysical_frag
  10826. };
  10827. /**
  10828. * @author mrdoob / http://mrdoob.com/
  10829. */
  10830. function WebGLAnimation() {
  10831. var context = null;
  10832. var isAnimating = false;
  10833. var animationLoop = null;
  10834. function onAnimationFrame(time, frame) {
  10835. if (isAnimating === false) return;
  10836. animationLoop(time, frame);
  10837. context.requestAnimationFrame(onAnimationFrame);
  10838. }
  10839. return {
  10840. start: function () {
  10841. if (isAnimating === true) return;
  10842. if (animationLoop === null) return;
  10843. context.requestAnimationFrame(onAnimationFrame);
  10844. isAnimating = true;
  10845. },
  10846. stop: function () {
  10847. isAnimating = false;
  10848. },
  10849. setAnimationLoop: function (callback) {
  10850. animationLoop = callback;
  10851. },
  10852. setContext: function (value) {
  10853. context = value;
  10854. }
  10855. };
  10856. }
  10857. /**
  10858. * @author mrdoob / http://mrdoob.com/
  10859. */
  10860. function WebGLAttributes(gl) {
  10861. var buffers = new WeakMap();
  10862. function createBuffer(attribute, bufferType) {
  10863. var array = attribute.array;
  10864. var usage = attribute.dynamic ? 35048 : 35044;
  10865. var buffer = gl.createBuffer();
  10866. gl.bindBuffer(bufferType, buffer);
  10867. gl.bufferData(bufferType, array, usage);
  10868. attribute.onUploadCallback();
  10869. var type = 5126;
  10870. if (array instanceof Float32Array) {
  10871. type = 5126;
  10872. } else if (array instanceof Float64Array) {
  10873. console.warn('THREE.WebGLAttributes: Unsupported data buffer format: Float64Array.');
  10874. } else if (array instanceof Uint16Array) {
  10875. type = 5123;
  10876. } else if (array instanceof Int16Array) {
  10877. type = 5122;
  10878. } else if (array instanceof Uint32Array) {
  10879. type = 5125;
  10880. } else if (array instanceof Int32Array) {
  10881. type = 5124;
  10882. } else if (array instanceof Int8Array) {
  10883. type = 5120;
  10884. } else if (array instanceof Uint8Array) {
  10885. type = 5121;
  10886. }
  10887. return {
  10888. buffer: buffer,
  10889. type: type,
  10890. bytesPerElement: array.BYTES_PER_ELEMENT,
  10891. version: attribute.version
  10892. };
  10893. }
  10894. function updateBuffer(buffer, attribute, bufferType) {
  10895. var array = attribute.array;
  10896. var updateRange = attribute.updateRange;
  10897. gl.bindBuffer(bufferType, buffer);
  10898. if (attribute.dynamic === false) {
  10899. gl.bufferData(bufferType, array, 35044);
  10900. } else if (updateRange.count === -1) {
  10901. // Not using update ranges
  10902. gl.bufferSubData(bufferType, 0, array);
  10903. } else if (updateRange.count === 0) {
  10904. 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.');
  10905. } else {
  10906. gl.bufferSubData(bufferType, updateRange.offset * array.BYTES_PER_ELEMENT, array.subarray(updateRange.offset, updateRange.offset + updateRange.count));
  10907. updateRange.count = -1; // reset range
  10908. }
  10909. } //
  10910. function get(attribute) {
  10911. if (attribute.isInterleavedBufferAttribute) attribute = attribute.data;
  10912. return buffers.get(attribute);
  10913. }
  10914. function remove(attribute) {
  10915. if (attribute.isInterleavedBufferAttribute) attribute = attribute.data;
  10916. var data = buffers.get(attribute);
  10917. if (data) {
  10918. gl.deleteBuffer(data.buffer);
  10919. buffers.delete(attribute);
  10920. }
  10921. }
  10922. function update(attribute, bufferType) {
  10923. if (attribute.isInterleavedBufferAttribute) attribute = attribute.data;
  10924. var data = buffers.get(attribute);
  10925. if (data === undefined) {
  10926. buffers.set(attribute, createBuffer(attribute, bufferType));
  10927. } else if (data.version < attribute.version) {
  10928. updateBuffer(data.buffer, attribute, bufferType);
  10929. data.version = attribute.version;
  10930. }
  10931. }
  10932. return {
  10933. get: get,
  10934. remove: remove,
  10935. update: update
  10936. };
  10937. }
  10938. /**
  10939. * @author mrdoob / http://mrdoob.com/
  10940. * @author Mugen87 / https://github.com/Mugen87
  10941. */
  10942. // PlaneGeometry
  10943. function PlaneGeometry(width, height, widthSegments, heightSegments) {
  10944. Geometry.call(this);
  10945. this.type = 'PlaneGeometry';
  10946. this.parameters = {
  10947. width: width,
  10948. height: height,
  10949. widthSegments: widthSegments,
  10950. heightSegments: heightSegments
  10951. };
  10952. this.fromBufferGeometry(new PlaneBufferGeometry(width, height, widthSegments, heightSegments));
  10953. this.mergeVertices();
  10954. }
  10955. PlaneGeometry.prototype = Object.create(Geometry.prototype);
  10956. PlaneGeometry.prototype.constructor = PlaneGeometry; // PlaneBufferGeometry
  10957. function PlaneBufferGeometry(width, height, widthSegments, heightSegments) {
  10958. BufferGeometry.call(this);
  10959. this.type = 'PlaneBufferGeometry';
  10960. this.parameters = {
  10961. width: width,
  10962. height: height,
  10963. widthSegments: widthSegments,
  10964. heightSegments: heightSegments
  10965. };
  10966. width = width || 1;
  10967. height = height || 1;
  10968. var width_half = width / 2;
  10969. var height_half = height / 2;
  10970. var gridX = Math.floor(widthSegments) || 1;
  10971. var gridY = Math.floor(heightSegments) || 1;
  10972. var gridX1 = gridX + 1;
  10973. var gridY1 = gridY + 1;
  10974. var segment_width = width / gridX;
  10975. var segment_height = height / gridY;
  10976. var ix, iy; // buffers
  10977. var indices = [];
  10978. var vertices = [];
  10979. var normals = [];
  10980. var uvs = []; // generate vertices, normals and uvs
  10981. for (iy = 0; iy < gridY1; iy++) {
  10982. var y = iy * segment_height - height_half;
  10983. for (ix = 0; ix < gridX1; ix++) {
  10984. var x = ix * segment_width - width_half;
  10985. vertices.push(x, -y, 0);
  10986. normals.push(0, 0, 1);
  10987. uvs.push(ix / gridX);
  10988. uvs.push(1 - iy / gridY);
  10989. }
  10990. } // indices
  10991. for (iy = 0; iy < gridY; iy++) {
  10992. for (ix = 0; ix < gridX; ix++) {
  10993. var a = ix + gridX1 * iy;
  10994. var b = ix + gridX1 * (iy + 1);
  10995. var c = ix + 1 + gridX1 * (iy + 1);
  10996. var d = ix + 1 + gridX1 * iy; // faces
  10997. indices.push(a, b, d);
  10998. indices.push(b, c, d);
  10999. }
  11000. } // build geometry
  11001. this.setIndex(indices);
  11002. this.addAttribute('position', new Float32BufferAttribute(vertices, 3));
  11003. this.addAttribute('normal', new Float32BufferAttribute(normals, 3));
  11004. this.addAttribute('uv', new Float32BufferAttribute(uvs, 2));
  11005. }
  11006. PlaneBufferGeometry.prototype = Object.create(BufferGeometry.prototype);
  11007. PlaneBufferGeometry.prototype.constructor = PlaneBufferGeometry;
  11008. /**
  11009. * @author mrdoob / http://mrdoob.com/
  11010. */
  11011. function WebGLBackground(renderer, state, objects, premultipliedAlpha) {
  11012. var clearColor = new Color(0x000000);
  11013. var clearAlpha = 0;
  11014. var planeMesh;
  11015. var boxMesh; // Store the current background texture and its `version`
  11016. // so we can recompile the material accordingly.
  11017. var currentBackground = null;
  11018. var currentBackgroundVersion = 0;
  11019. function render(renderList, scene, camera, forceClear) {
  11020. var background = scene.background; // Ignore background in AR
  11021. // TODO: Reconsider this.
  11022. var vr = renderer.vr;
  11023. var session = vr.getSession && vr.getSession();
  11024. if (session && session.environmentBlendMode === 'additive') {
  11025. background = null;
  11026. }
  11027. if (background === null) {
  11028. setClear(clearColor, clearAlpha);
  11029. currentBackground = null;
  11030. currentBackgroundVersion = 0;
  11031. } else if (background && background.isColor) {
  11032. setClear(background, 1);
  11033. forceClear = true;
  11034. currentBackground = null;
  11035. currentBackgroundVersion = 0;
  11036. }
  11037. if (renderer.autoClear || forceClear) {
  11038. renderer.clear(renderer.autoClearColor, renderer.autoClearDepth, renderer.autoClearStencil);
  11039. }
  11040. if (background && (background.isCubeTexture || background.isWebGLRenderTargetCube)) {
  11041. if (boxMesh === undefined) {
  11042. boxMesh = new Mesh(new BoxBufferGeometry(1, 1, 1), new ShaderMaterial({
  11043. type: 'BackgroundCubeMaterial',
  11044. uniforms: cloneUniforms(ShaderLib.cube.uniforms),
  11045. vertexShader: ShaderLib.cube.vertexShader,
  11046. fragmentShader: ShaderLib.cube.fragmentShader,
  11047. side: BackSide,
  11048. depthTest: false,
  11049. depthWrite: false,
  11050. fog: false
  11051. }));
  11052. boxMesh.geometry.removeAttribute('normal');
  11053. boxMesh.geometry.removeAttribute('uv');
  11054. boxMesh.onBeforeRender = function (renderer, scene, camera) {
  11055. this.matrixWorld.copyPosition(camera.matrixWorld);
  11056. }; // enable code injection for non-built-in material
  11057. Object.defineProperty(boxMesh.material, 'map', {
  11058. get: function () {
  11059. return this.uniforms.tCube.value;
  11060. }
  11061. });
  11062. objects.update(boxMesh);
  11063. }
  11064. var texture = background.isWebGLRenderTargetCube ? background.texture : background;
  11065. boxMesh.material.uniforms.tCube.value = texture;
  11066. boxMesh.material.uniforms.tFlip.value = background.isWebGLRenderTargetCube ? 1 : -1;
  11067. if (currentBackground !== background || currentBackgroundVersion !== texture.version) {
  11068. boxMesh.material.needsUpdate = true;
  11069. currentBackground = background;
  11070. currentBackgroundVersion = texture.version;
  11071. } // push to the pre-sorted opaque render list
  11072. renderList.unshift(boxMesh, boxMesh.geometry, boxMesh.material, 0, 0, null);
  11073. } else if (background && background.isTexture) {
  11074. if (planeMesh === undefined) {
  11075. planeMesh = new Mesh(new PlaneBufferGeometry(2, 2), new ShaderMaterial({
  11076. type: 'BackgroundMaterial',
  11077. uniforms: cloneUniforms(ShaderLib.background.uniforms),
  11078. vertexShader: ShaderLib.background.vertexShader,
  11079. fragmentShader: ShaderLib.background.fragmentShader,
  11080. side: FrontSide,
  11081. depthTest: false,
  11082. depthWrite: false,
  11083. fog: false
  11084. }));
  11085. planeMesh.geometry.removeAttribute('normal'); // enable code injection for non-built-in material
  11086. Object.defineProperty(planeMesh.material, 'map', {
  11087. get: function () {
  11088. return this.uniforms.t2D.value;
  11089. }
  11090. });
  11091. objects.update(planeMesh);
  11092. }
  11093. planeMesh.material.uniforms.t2D.value = background;
  11094. if (background.matrixAutoUpdate === true) {
  11095. background.updateMatrix();
  11096. }
  11097. planeMesh.material.uniforms.uvTransform.value.copy(background.matrix);
  11098. if (currentBackground !== background || currentBackgroundVersion !== background.version) {
  11099. planeMesh.material.needsUpdate = true;
  11100. currentBackground = background;
  11101. currentBackgroundVersion = background.version;
  11102. } // push to the pre-sorted opaque render list
  11103. renderList.unshift(planeMesh, planeMesh.geometry, planeMesh.material, 0, 0, null);
  11104. }
  11105. }
  11106. function setClear(color, alpha) {
  11107. state.buffers.color.setClear(color.r, color.g, color.b, alpha, premultipliedAlpha);
  11108. }
  11109. return {
  11110. getClearColor: function () {
  11111. return clearColor;
  11112. },
  11113. setClearColor: function (color, alpha) {
  11114. clearColor.set(color);
  11115. clearAlpha = alpha !== undefined ? alpha : 1;
  11116. setClear(clearColor, clearAlpha);
  11117. },
  11118. getClearAlpha: function () {
  11119. return clearAlpha;
  11120. },
  11121. setClearAlpha: function (alpha) {
  11122. clearAlpha = alpha;
  11123. setClear(clearColor, clearAlpha);
  11124. },
  11125. render: render
  11126. };
  11127. }
  11128. /**
  11129. * @author mrdoob / http://mrdoob.com/
  11130. */
  11131. function WebGLBufferRenderer(gl, extensions, info, capabilities) {
  11132. var mode;
  11133. function setMode(value) {
  11134. mode = value;
  11135. }
  11136. function render(start, count) {
  11137. gl.drawArrays(mode, start, count);
  11138. info.update(count, mode);
  11139. }
  11140. function renderInstances(geometry, start, count, primcount) {
  11141. if (primcount === 0) return;
  11142. var extension, methodName;
  11143. if (capabilities.isWebGL2) {
  11144. extension = gl;
  11145. methodName = 'drawArraysInstanced';
  11146. } else {
  11147. extension = extensions.get('ANGLE_instanced_arrays');
  11148. methodName = 'drawArraysInstancedANGLE';
  11149. if (extension === null) {
  11150. console.error('THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.');
  11151. return;
  11152. }
  11153. }
  11154. extension[methodName](mode, start, count, primcount);
  11155. info.update(count, mode, primcount);
  11156. } //
  11157. this.setMode = setMode;
  11158. this.render = render;
  11159. this.renderInstances = renderInstances;
  11160. }
  11161. /**
  11162. * @author mrdoob / http://mrdoob.com/
  11163. */
  11164. function WebGLCapabilities(gl, extensions, parameters) {
  11165. var maxAnisotropy;
  11166. function getMaxAnisotropy() {
  11167. if (maxAnisotropy !== undefined) return maxAnisotropy;
  11168. var extension = extensions.get('EXT_texture_filter_anisotropic');
  11169. if (extension !== null) {
  11170. maxAnisotropy = gl.getParameter(extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT);
  11171. } else {
  11172. maxAnisotropy = 0;
  11173. }
  11174. return maxAnisotropy;
  11175. }
  11176. function getMaxPrecision(precision) {
  11177. if (precision === 'highp') {
  11178. if (gl.getShaderPrecisionFormat(35633, 36338).precision > 0 && gl.getShaderPrecisionFormat(35632, 36338).precision > 0) {
  11179. return 'highp';
  11180. }
  11181. precision = 'mediump';
  11182. }
  11183. if (precision === 'mediump') {
  11184. if (gl.getShaderPrecisionFormat(35633, 36337).precision > 0 && gl.getShaderPrecisionFormat(35632, 36337).precision > 0) {
  11185. return 'mediump';
  11186. }
  11187. }
  11188. return 'lowp';
  11189. }
  11190. var isWebGL2 = typeof WebGL2RenderingContext !== 'undefined' && gl instanceof WebGL2RenderingContext;
  11191. var precision = parameters.precision !== undefined ? parameters.precision : 'highp';
  11192. var maxPrecision = getMaxPrecision(precision);
  11193. if (maxPrecision !== precision) {
  11194. console.warn('THREE.WebGLRenderer:', precision, 'not supported, using', maxPrecision, 'instead.');
  11195. precision = maxPrecision;
  11196. }
  11197. var logarithmicDepthBuffer = parameters.logarithmicDepthBuffer === true;
  11198. var maxTextures = gl.getParameter(34930);
  11199. var maxVertexTextures = gl.getParameter(35660);
  11200. var maxTextureSize = gl.getParameter(3379);
  11201. var maxCubemapSize = gl.getParameter(34076);
  11202. var maxAttributes = gl.getParameter(34921);
  11203. var maxVertexUniforms = gl.getParameter(36347);
  11204. var maxVaryings = gl.getParameter(36348);
  11205. var maxFragmentUniforms = gl.getParameter(36349);
  11206. var vertexTextures = maxVertexTextures > 0;
  11207. var floatFragmentTextures = isWebGL2 || !!extensions.get('OES_texture_float');
  11208. var floatVertexTextures = vertexTextures && floatFragmentTextures;
  11209. var maxSamples = isWebGL2 ? gl.getParameter(36183) : 0;
  11210. return {
  11211. isWebGL2: isWebGL2,
  11212. getMaxAnisotropy: getMaxAnisotropy,
  11213. getMaxPrecision: getMaxPrecision,
  11214. precision: precision,
  11215. logarithmicDepthBuffer: logarithmicDepthBuffer,
  11216. maxTextures: maxTextures,
  11217. maxVertexTextures: maxVertexTextures,
  11218. maxTextureSize: maxTextureSize,
  11219. maxCubemapSize: maxCubemapSize,
  11220. maxAttributes: maxAttributes,
  11221. maxVertexUniforms: maxVertexUniforms,
  11222. maxVaryings: maxVaryings,
  11223. maxFragmentUniforms: maxFragmentUniforms,
  11224. vertexTextures: vertexTextures,
  11225. floatFragmentTextures: floatFragmentTextures,
  11226. floatVertexTextures: floatVertexTextures,
  11227. maxSamples: maxSamples
  11228. };
  11229. }
  11230. /**
  11231. * @author tschw
  11232. */
  11233. function WebGLClipping() {
  11234. var scope = this,
  11235. globalState = null,
  11236. numGlobalPlanes = 0,
  11237. localClippingEnabled = false,
  11238. renderingShadows = false,
  11239. plane = new Plane(),
  11240. viewNormalMatrix = new Matrix3(),
  11241. uniform = {
  11242. value: null,
  11243. needsUpdate: false
  11244. };
  11245. this.uniform = uniform;
  11246. this.numPlanes = 0;
  11247. this.numIntersection = 0;
  11248. this.init = function (planes, enableLocalClipping, camera) {
  11249. var enabled = planes.length !== 0 || enableLocalClipping || // enable state of previous frame - the clipping code has to
  11250. // run another frame in order to reset the state:
  11251. numGlobalPlanes !== 0 || localClippingEnabled;
  11252. localClippingEnabled = enableLocalClipping;
  11253. globalState = projectPlanes(planes, camera, 0);
  11254. numGlobalPlanes = planes.length;
  11255. return enabled;
  11256. };
  11257. this.beginShadows = function () {
  11258. renderingShadows = true;
  11259. projectPlanes(null);
  11260. };
  11261. this.endShadows = function () {
  11262. renderingShadows = false;
  11263. resetGlobalState();
  11264. };
  11265. this.setState = function (planes, clipIntersection, clipShadows, camera, cache, fromCache) {
  11266. if (!localClippingEnabled || planes === null || planes.length === 0 || renderingShadows && !clipShadows) {
  11267. // there's no local clipping
  11268. if (renderingShadows) {
  11269. // there's no global clipping
  11270. projectPlanes(null);
  11271. } else {
  11272. resetGlobalState();
  11273. }
  11274. } else {
  11275. var nGlobal = renderingShadows ? 0 : numGlobalPlanes,
  11276. lGlobal = nGlobal * 4,
  11277. dstArray = cache.clippingState || null;
  11278. uniform.value = dstArray; // ensure unique state
  11279. dstArray = projectPlanes(planes, camera, lGlobal, fromCache);
  11280. for (var i = 0; i !== lGlobal; ++i) {
  11281. dstArray[i] = globalState[i];
  11282. }
  11283. cache.clippingState = dstArray;
  11284. this.numIntersection = clipIntersection ? this.numPlanes : 0;
  11285. this.numPlanes += nGlobal;
  11286. }
  11287. };
  11288. function resetGlobalState() {
  11289. if (uniform.value !== globalState) {
  11290. uniform.value = globalState;
  11291. uniform.needsUpdate = numGlobalPlanes > 0;
  11292. }
  11293. scope.numPlanes = numGlobalPlanes;
  11294. scope.numIntersection = 0;
  11295. }
  11296. function projectPlanes(planes, camera, dstOffset, skipTransform) {
  11297. var nPlanes = planes !== null ? planes.length : 0,
  11298. dstArray = null;
  11299. if (nPlanes !== 0) {
  11300. dstArray = uniform.value;
  11301. if (skipTransform !== true || dstArray === null) {
  11302. var flatSize = dstOffset + nPlanes * 4,
  11303. viewMatrix = camera.matrixWorldInverse;
  11304. viewNormalMatrix.getNormalMatrix(viewMatrix);
  11305. if (dstArray === null || dstArray.length < flatSize) {
  11306. dstArray = new Float32Array(flatSize);
  11307. }
  11308. for (var i = 0, i4 = dstOffset; i !== nPlanes; ++i, i4 += 4) {
  11309. plane.copy(planes[i]).applyMatrix4(viewMatrix, viewNormalMatrix);
  11310. plane.normal.toArray(dstArray, i4);
  11311. dstArray[i4 + 3] = plane.constant;
  11312. }
  11313. }
  11314. uniform.value = dstArray;
  11315. uniform.needsUpdate = true;
  11316. }
  11317. scope.numPlanes = nPlanes;
  11318. return dstArray;
  11319. }
  11320. }
  11321. /**
  11322. * @author mrdoob / http://mrdoob.com/
  11323. */
  11324. function WebGLExtensions(gl) {
  11325. var extensions = {};
  11326. return {
  11327. get: function (name) {
  11328. if (extensions[name] !== undefined) {
  11329. return extensions[name];
  11330. }
  11331. var extension;
  11332. switch (name) {
  11333. case 'WEBGL_depth_texture':
  11334. extension = gl.getExtension('WEBGL_depth_texture') || gl.getExtension('MOZ_WEBGL_depth_texture') || gl.getExtension('WEBKIT_WEBGL_depth_texture');
  11335. break;
  11336. case 'EXT_texture_filter_anisotropic':
  11337. extension = gl.getExtension('EXT_texture_filter_anisotropic') || gl.getExtension('MOZ_EXT_texture_filter_anisotropic') || gl.getExtension('WEBKIT_EXT_texture_filter_anisotropic');
  11338. break;
  11339. case 'WEBGL_compressed_texture_s3tc':
  11340. extension = gl.getExtension('WEBGL_compressed_texture_s3tc') || gl.getExtension('MOZ_WEBGL_compressed_texture_s3tc') || gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  11341. break;
  11342. case 'WEBGL_compressed_texture_pvrtc':
  11343. extension = gl.getExtension('WEBGL_compressed_texture_pvrtc') || gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  11344. break;
  11345. default:
  11346. extension = gl.getExtension(name);
  11347. }
  11348. if (extension === null) {
  11349. console.warn('THREE.WebGLRenderer: ' + name + ' extension not supported.');
  11350. }
  11351. extensions[name] = extension;
  11352. return extension;
  11353. }
  11354. };
  11355. }
  11356. /**
  11357. * @author mrdoob / http://mrdoob.com/
  11358. */
  11359. function WebGLGeometries(gl, attributes, info) {
  11360. var geometries = new WeakMap();
  11361. var wireframeAttributes = new WeakMap();
  11362. function onGeometryDispose(event) {
  11363. var geometry = event.target;
  11364. var buffergeometry = geometries.get(geometry);
  11365. if (buffergeometry.index !== null) {
  11366. attributes.remove(buffergeometry.index);
  11367. }
  11368. for (var name in buffergeometry.attributes) {
  11369. attributes.remove(buffergeometry.attributes[name]);
  11370. }
  11371. geometry.removeEventListener('dispose', onGeometryDispose);
  11372. geometries.delete(geometry);
  11373. var attribute = wireframeAttributes.get(buffergeometry);
  11374. if (attribute) {
  11375. attributes.remove(attribute);
  11376. wireframeAttributes.delete(buffergeometry);
  11377. } //
  11378. info.memory.geometries--;
  11379. }
  11380. function get(object, geometry) {
  11381. var buffergeometry = geometries.get(geometry);
  11382. if (buffergeometry) return buffergeometry;
  11383. geometry.addEventListener('dispose', onGeometryDispose);
  11384. if (geometry.isBufferGeometry) {
  11385. buffergeometry = geometry;
  11386. } else if (geometry.isGeometry) {
  11387. if (geometry._bufferGeometry === undefined) {
  11388. geometry._bufferGeometry = new BufferGeometry().setFromObject(object);
  11389. }
  11390. buffergeometry = geometry._bufferGeometry;
  11391. }
  11392. geometries.set(geometry, buffergeometry);
  11393. info.memory.geometries++;
  11394. return buffergeometry;
  11395. }
  11396. function update(geometry) {
  11397. var index = geometry.index;
  11398. var geometryAttributes = geometry.attributes;
  11399. if (index !== null) {
  11400. attributes.update(index, 34963);
  11401. }
  11402. for (var name in geometryAttributes) {
  11403. attributes.update(geometryAttributes[name], 34962);
  11404. } // morph targets
  11405. var morphAttributes = geometry.morphAttributes;
  11406. for (var name in morphAttributes) {
  11407. var array = morphAttributes[name];
  11408. for (var i = 0, l = array.length; i < l; i++) {
  11409. attributes.update(array[i], 34962);
  11410. }
  11411. }
  11412. }
  11413. function updateWireframeAttribute(geometry) {
  11414. var indices = [];
  11415. var geometryIndex = geometry.index;
  11416. var geometryPosition = geometry.attributes.position;
  11417. var version = 0;
  11418. if (geometryIndex !== null) {
  11419. var array = geometryIndex.array;
  11420. version = geometryIndex.version;
  11421. for (var i = 0, l = array.length; i < l; i += 3) {
  11422. var a = array[i + 0];
  11423. var b = array[i + 1];
  11424. var c = array[i + 2];
  11425. indices.push(a, b, b, c, c, a);
  11426. }
  11427. } else {
  11428. var array = geometryPosition.array;
  11429. version = geometryPosition.version;
  11430. for (var i = 0, l = array.length / 3 - 1; i < l; i += 3) {
  11431. var a = i + 0;
  11432. var b = i + 1;
  11433. var c = i + 2;
  11434. indices.push(a, b, b, c, c, a);
  11435. }
  11436. }
  11437. var attribute = new (arrayMax(indices) > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute)(indices, 1);
  11438. attribute.version = version;
  11439. attributes.update(attribute, 34963); //
  11440. var previousAttribute = wireframeAttributes.get(geometry);
  11441. if (previousAttribute) attributes.remove(previousAttribute); //
  11442. wireframeAttributes.set(geometry, attribute);
  11443. }
  11444. function getWireframeAttribute(geometry) {
  11445. var currentAttribute = wireframeAttributes.get(geometry);
  11446. if (currentAttribute) {
  11447. var geometryIndex = geometry.index;
  11448. if (geometryIndex !== null) {
  11449. // if the attribute is obsolete, create a new one
  11450. if (currentAttribute.version < geometryIndex.version) {
  11451. updateWireframeAttribute(geometry);
  11452. }
  11453. }
  11454. } else {
  11455. updateWireframeAttribute(geometry);
  11456. }
  11457. return wireframeAttributes.get(geometry);
  11458. }
  11459. return {
  11460. get: get,
  11461. update: update,
  11462. getWireframeAttribute: getWireframeAttribute
  11463. };
  11464. }
  11465. /**
  11466. * @author mrdoob / http://mrdoob.com/
  11467. */
  11468. function WebGLIndexedBufferRenderer(gl, extensions, info, capabilities) {
  11469. var mode;
  11470. function setMode(value) {
  11471. mode = value;
  11472. }
  11473. var type, bytesPerElement;
  11474. function setIndex(value) {
  11475. type = value.type;
  11476. bytesPerElement = value.bytesPerElement;
  11477. }
  11478. function render(start, count) {
  11479. gl.drawElements(mode, count, type, start * bytesPerElement);
  11480. info.update(count, mode);
  11481. }
  11482. function renderInstances(geometry, start, count, primcount) {
  11483. if (primcount === 0) return;
  11484. var extension, methodName;
  11485. if (capabilities.isWebGL2) {
  11486. extension = gl;
  11487. methodName = 'drawElementsInstanced';
  11488. } else {
  11489. extension = extensions.get('ANGLE_instanced_arrays');
  11490. methodName = 'drawElementsInstancedANGLE';
  11491. if (extension === null) {
  11492. console.error('THREE.WebGLIndexedBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.');
  11493. return;
  11494. }
  11495. }
  11496. extension[methodName](mode, count, type, start * bytesPerElement, primcount);
  11497. info.update(count, mode, primcount);
  11498. } //
  11499. this.setMode = setMode;
  11500. this.setIndex = setIndex;
  11501. this.render = render;
  11502. this.renderInstances = renderInstances;
  11503. }
  11504. /**
  11505. * @author Mugen87 / https://github.com/Mugen87
  11506. */
  11507. function WebGLInfo(gl) {
  11508. var memory = {
  11509. geometries: 0,
  11510. textures: 0
  11511. };
  11512. var render = {
  11513. frame: 0,
  11514. calls: 0,
  11515. triangles: 0,
  11516. points: 0,
  11517. lines: 0
  11518. };
  11519. function update(count, mode, instanceCount) {
  11520. instanceCount = instanceCount || 1;
  11521. render.calls++;
  11522. switch (mode) {
  11523. case 4:
  11524. render.triangles += instanceCount * (count / 3);
  11525. break;
  11526. case 5:
  11527. case 6:
  11528. render.triangles += instanceCount * (count - 2);
  11529. break;
  11530. case 1:
  11531. render.lines += instanceCount * (count / 2);
  11532. break;
  11533. case 3:
  11534. render.lines += instanceCount * (count - 1);
  11535. break;
  11536. case 2:
  11537. render.lines += instanceCount * count;
  11538. break;
  11539. case 0:
  11540. render.points += instanceCount * count;
  11541. break;
  11542. default:
  11543. console.error('THREE.WebGLInfo: Unknown draw mode:', mode);
  11544. break;
  11545. }
  11546. }
  11547. function reset() {
  11548. render.frame++;
  11549. render.calls = 0;
  11550. render.triangles = 0;
  11551. render.points = 0;
  11552. render.lines = 0;
  11553. }
  11554. return {
  11555. memory: memory,
  11556. render: render,
  11557. programs: null,
  11558. autoReset: true,
  11559. reset: reset,
  11560. update: update
  11561. };
  11562. }
  11563. /**
  11564. * @author mrdoob / http://mrdoob.com/
  11565. */
  11566. function absNumericalSort(a, b) {
  11567. return Math.abs(b[1]) - Math.abs(a[1]);
  11568. }
  11569. function WebGLMorphtargets(gl) {
  11570. var influencesList = {};
  11571. var morphInfluences = new Float32Array(8);
  11572. function update(object, geometry, material, program) {
  11573. var objectInfluences = object.morphTargetInfluences;
  11574. var length = objectInfluences.length;
  11575. var influences = influencesList[geometry.id];
  11576. if (influences === undefined) {
  11577. // initialise list
  11578. influences = [];
  11579. for (var i = 0; i < length; i++) {
  11580. influences[i] = [i, 0];
  11581. }
  11582. influencesList[geometry.id] = influences;
  11583. }
  11584. var morphTargets = material.morphTargets && geometry.morphAttributes.position;
  11585. var morphNormals = material.morphNormals && geometry.morphAttributes.normal; // Remove current morphAttributes
  11586. for (var i = 0; i < length; i++) {
  11587. var influence = influences[i];
  11588. if (influence[1] !== 0) {
  11589. if (morphTargets) geometry.removeAttribute('morphTarget' + i);
  11590. if (morphNormals) geometry.removeAttribute('morphNormal' + i);
  11591. }
  11592. } // Collect influences
  11593. for (var i = 0; i < length; i++) {
  11594. var influence = influences[i];
  11595. influence[0] = i;
  11596. influence[1] = objectInfluences[i];
  11597. }
  11598. influences.sort(absNumericalSort); // Add morphAttributes
  11599. for (var i = 0; i < 8; i++) {
  11600. var influence = influences[i];
  11601. if (influence) {
  11602. var index = influence[0];
  11603. var value = influence[1];
  11604. if (value) {
  11605. if (morphTargets) geometry.addAttribute('morphTarget' + i, morphTargets[index]);
  11606. if (morphNormals) geometry.addAttribute('morphNormal' + i, morphNormals[index]);
  11607. morphInfluences[i] = value;
  11608. continue;
  11609. }
  11610. }
  11611. morphInfluences[i] = 0;
  11612. }
  11613. program.getUniforms().setValue(gl, 'morphTargetInfluences', morphInfluences);
  11614. }
  11615. return {
  11616. update: update
  11617. };
  11618. }
  11619. /**
  11620. * @author mrdoob / http://mrdoob.com/
  11621. */
  11622. function WebGLObjects(gl, geometries, attributes, info) {
  11623. var updateList = {};
  11624. function update(object) {
  11625. var frame = info.render.frame;
  11626. var geometry = object.geometry;
  11627. var buffergeometry = geometries.get(object, geometry); // Update once per frame
  11628. if (updateList[buffergeometry.id] !== frame) {
  11629. if (geometry.isGeometry) {
  11630. buffergeometry.updateFromObject(object);
  11631. }
  11632. geometries.update(buffergeometry);
  11633. updateList[buffergeometry.id] = frame;
  11634. }
  11635. if (object.isInstancedMesh) {
  11636. attributes.update(object.instanceMatrix, 34962);
  11637. }
  11638. return buffergeometry;
  11639. }
  11640. function dispose() {
  11641. updateList = {};
  11642. }
  11643. return {
  11644. update: update,
  11645. dispose: dispose
  11646. };
  11647. }
  11648. /**
  11649. * @author mrdoob / http://mrdoob.com/
  11650. */
  11651. function CubeTexture(images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding) {
  11652. images = images !== undefined ? images : [];
  11653. mapping = mapping !== undefined ? mapping : CubeReflectionMapping;
  11654. format = format !== undefined ? format : RGBFormat;
  11655. Texture.call(this, images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding);
  11656. this.flipY = false;
  11657. }
  11658. CubeTexture.prototype = Object.create(Texture.prototype);
  11659. CubeTexture.prototype.constructor = CubeTexture;
  11660. CubeTexture.prototype.isCubeTexture = true;
  11661. Object.defineProperty(CubeTexture.prototype, 'images', {
  11662. get: function () {
  11663. return this.image;
  11664. },
  11665. set: function (value) {
  11666. this.image = value;
  11667. }
  11668. });
  11669. /**
  11670. * @author Takahiro https://github.com/takahirox
  11671. */
  11672. function DataTexture2DArray(data, width, height, depth) {
  11673. Texture.call(this, null);
  11674. this.image = {
  11675. data: data || null,
  11676. width: width || 1,
  11677. height: height || 1,
  11678. depth: depth || 1
  11679. };
  11680. this.magFilter = NearestFilter;
  11681. this.minFilter = NearestFilter;
  11682. this.wrapR = ClampToEdgeWrapping;
  11683. this.generateMipmaps = false;
  11684. this.flipY = false;
  11685. this.needsUpdate = true;
  11686. }
  11687. DataTexture2DArray.prototype = Object.create(Texture.prototype);
  11688. DataTexture2DArray.prototype.constructor = DataTexture2DArray;
  11689. DataTexture2DArray.prototype.isDataTexture2DArray = true;
  11690. /**
  11691. * @author Artur Trzesiok
  11692. */
  11693. function DataTexture3D(data, width, height, depth) {
  11694. // We're going to add .setXXX() methods for setting properties later.
  11695. // Users can still set in DataTexture3D directly.
  11696. //
  11697. // var texture = new THREE.DataTexture3D( data, width, height, depth );
  11698. // texture.anisotropy = 16;
  11699. //
  11700. // See #14839
  11701. Texture.call(this, null);
  11702. this.image = {
  11703. data: data || null,
  11704. width: width || 1,
  11705. height: height || 1,
  11706. depth: depth || 1
  11707. };
  11708. this.magFilter = NearestFilter;
  11709. this.minFilter = NearestFilter;
  11710. this.wrapR = ClampToEdgeWrapping;
  11711. this.generateMipmaps = false;
  11712. this.flipY = false;
  11713. this.needsUpdate = true;
  11714. }
  11715. DataTexture3D.prototype = Object.create(Texture.prototype);
  11716. DataTexture3D.prototype.constructor = DataTexture3D;
  11717. DataTexture3D.prototype.isDataTexture3D = true;
  11718. /**
  11719. * @author tschw
  11720. * @author Mugen87 / https://github.com/Mugen87
  11721. * @author mrdoob / http://mrdoob.com/
  11722. *
  11723. * Uniforms of a program.
  11724. * Those form a tree structure with a special top-level container for the root,
  11725. * which you get by calling 'new WebGLUniforms( gl, program )'.
  11726. *
  11727. *
  11728. * Properties of inner nodes including the top-level container:
  11729. *
  11730. * .seq - array of nested uniforms
  11731. * .map - nested uniforms by name
  11732. *
  11733. *
  11734. * Methods of all nodes except the top-level container:
  11735. *
  11736. * .setValue( gl, value, [textures] )
  11737. *
  11738. * uploads a uniform value(s)
  11739. * the 'textures' parameter is needed for sampler uniforms
  11740. *
  11741. *
  11742. * Static methods of the top-level container (textures factorizations):
  11743. *
  11744. * .upload( gl, seq, values, textures )
  11745. *
  11746. * sets uniforms in 'seq' to 'values[id].value'
  11747. *
  11748. * .seqWithValue( seq, values ) : filteredSeq
  11749. *
  11750. * filters 'seq' entries with corresponding entry in values
  11751. *
  11752. *
  11753. * Methods of the top-level container (textures factorizations):
  11754. *
  11755. * .setValue( gl, name, value, textures )
  11756. *
  11757. * sets uniform with name 'name' to 'value'
  11758. *
  11759. * .setOptional( gl, obj, prop )
  11760. *
  11761. * like .set for an optional property of the object
  11762. *
  11763. */
  11764. var emptyTexture = new Texture();
  11765. var emptyTexture2dArray = new DataTexture2DArray();
  11766. var emptyTexture3d = new DataTexture3D();
  11767. var emptyCubeTexture = new CubeTexture(); // --- Utilities ---
  11768. // Array Caches (provide typed arrays for temporary by size)
  11769. var arrayCacheF32 = [];
  11770. var arrayCacheI32 = []; // Float32Array caches used for uploading Matrix uniforms
  11771. var mat4array = new Float32Array(16);
  11772. var mat3array = new Float32Array(9);
  11773. var mat2array = new Float32Array(4); // Flattening for arrays of vectors and matrices
  11774. function flatten(array, nBlocks, blockSize) {
  11775. var firstElem = array[0];
  11776. if (firstElem <= 0 || firstElem > 0) return array; // unoptimized: ! isNaN( firstElem )
  11777. // see http://jacksondunstan.com/articles/983
  11778. var n = nBlocks * blockSize,
  11779. r = arrayCacheF32[n];
  11780. if (r === undefined) {
  11781. r = new Float32Array(n);
  11782. arrayCacheF32[n] = r;
  11783. }
  11784. if (nBlocks !== 0) {
  11785. firstElem.toArray(r, 0);
  11786. for (var i = 1, offset = 0; i !== nBlocks; ++i) {
  11787. offset += blockSize;
  11788. array[i].toArray(r, offset);
  11789. }
  11790. }
  11791. return r;
  11792. }
  11793. function arraysEqual(a, b) {
  11794. if (a.length !== b.length) return false;
  11795. for (var i = 0, l = a.length; i < l; i++) {
  11796. if (a[i] !== b[i]) return false;
  11797. }
  11798. return true;
  11799. }
  11800. function copyArray(a, b) {
  11801. for (var i = 0, l = b.length; i < l; i++) {
  11802. a[i] = b[i];
  11803. }
  11804. } // Texture unit allocation
  11805. function allocTexUnits(textures, n) {
  11806. var r = arrayCacheI32[n];
  11807. if (r === undefined) {
  11808. r = new Int32Array(n);
  11809. arrayCacheI32[n] = r;
  11810. }
  11811. for (var i = 0; i !== n; ++i) r[i] = textures.allocateTextureUnit();
  11812. return r;
  11813. } // --- Setters ---
  11814. // Note: Defining these methods externally, because they come in a bunch
  11815. // and this way their names minify.
  11816. // Single scalar
  11817. function setValueV1f(gl, v) {
  11818. var cache = this.cache;
  11819. if (cache[0] === v) return;
  11820. gl.uniform1f(this.addr, v);
  11821. cache[0] = v;
  11822. } // Single float vector (from flat array or THREE.VectorN)
  11823. function setValueV2f(gl, v) {
  11824. var cache = this.cache;
  11825. if (v.x !== undefined) {
  11826. if (cache[0] !== v.x || cache[1] !== v.y) {
  11827. gl.uniform2f(this.addr, v.x, v.y);
  11828. cache[0] = v.x;
  11829. cache[1] = v.y;
  11830. }
  11831. } else {
  11832. if (arraysEqual(cache, v)) return;
  11833. gl.uniform2fv(this.addr, v);
  11834. copyArray(cache, v);
  11835. }
  11836. }
  11837. function setValueV3f(gl, v) {
  11838. var cache = this.cache;
  11839. if (v.x !== undefined) {
  11840. if (cache[0] !== v.x || cache[1] !== v.y || cache[2] !== v.z) {
  11841. gl.uniform3f(this.addr, v.x, v.y, v.z);
  11842. cache[0] = v.x;
  11843. cache[1] = v.y;
  11844. cache[2] = v.z;
  11845. }
  11846. } else if (v.r !== undefined) {
  11847. if (cache[0] !== v.r || cache[1] !== v.g || cache[2] !== v.b) {
  11848. gl.uniform3f(this.addr, v.r, v.g, v.b);
  11849. cache[0] = v.r;
  11850. cache[1] = v.g;
  11851. cache[2] = v.b;
  11852. }
  11853. } else {
  11854. if (arraysEqual(cache, v)) return;
  11855. gl.uniform3fv(this.addr, v);
  11856. copyArray(cache, v);
  11857. }
  11858. }
  11859. function setValueV4f(gl, v) {
  11860. var cache = this.cache;
  11861. if (v.x !== undefined) {
  11862. if (cache[0] !== v.x || cache[1] !== v.y || cache[2] !== v.z || cache[3] !== v.w) {
  11863. gl.uniform4f(this.addr, v.x, v.y, v.z, v.w);
  11864. cache[0] = v.x;
  11865. cache[1] = v.y;
  11866. cache[2] = v.z;
  11867. cache[3] = v.w;
  11868. }
  11869. } else {
  11870. if (arraysEqual(cache, v)) return;
  11871. gl.uniform4fv(this.addr, v);
  11872. copyArray(cache, v);
  11873. }
  11874. } // Single matrix (from flat array or MatrixN)
  11875. function setValueM2(gl, v) {
  11876. var cache = this.cache;
  11877. var elements = v.elements;
  11878. if (elements === undefined) {
  11879. if (arraysEqual(cache, v)) return;
  11880. gl.uniformMatrix2fv(this.addr, false, v);
  11881. copyArray(cache, v);
  11882. } else {
  11883. if (arraysEqual(cache, elements)) return;
  11884. mat2array.set(elements);
  11885. gl.uniformMatrix2fv(this.addr, false, mat2array);
  11886. copyArray(cache, elements);
  11887. }
  11888. }
  11889. function setValueM3(gl, v) {
  11890. var cache = this.cache;
  11891. var elements = v.elements;
  11892. if (elements === undefined) {
  11893. if (arraysEqual(cache, v)) return;
  11894. gl.uniformMatrix3fv(this.addr, false, v);
  11895. copyArray(cache, v);
  11896. } else {
  11897. if (arraysEqual(cache, elements)) return;
  11898. mat3array.set(elements);
  11899. gl.uniformMatrix3fv(this.addr, false, mat3array);
  11900. copyArray(cache, elements);
  11901. }
  11902. }
  11903. function setValueM4(gl, v) {
  11904. var cache = this.cache;
  11905. var elements = v.elements;
  11906. if (elements === undefined) {
  11907. if (arraysEqual(cache, v)) return;
  11908. gl.uniformMatrix4fv(this.addr, false, v);
  11909. copyArray(cache, v);
  11910. } else {
  11911. if (arraysEqual(cache, elements)) return;
  11912. mat4array.set(elements);
  11913. gl.uniformMatrix4fv(this.addr, false, mat4array);
  11914. copyArray(cache, elements);
  11915. }
  11916. } // Single texture (2D / Cube)
  11917. function setValueT1(gl, v, textures) {
  11918. var cache = this.cache;
  11919. var unit = textures.allocateTextureUnit();
  11920. if (cache[0] !== unit) {
  11921. gl.uniform1i(this.addr, unit);
  11922. cache[0] = unit;
  11923. }
  11924. textures.safeSetTexture2D(v || emptyTexture, unit);
  11925. }
  11926. function setValueT2DArray1(gl, v, textures) {
  11927. var cache = this.cache;
  11928. var unit = textures.allocateTextureUnit();
  11929. if (cache[0] !== unit) {
  11930. gl.uniform1i(this.addr, unit);
  11931. cache[0] = unit;
  11932. }
  11933. textures.setTexture2DArray(v || emptyTexture2dArray, unit);
  11934. }
  11935. function setValueT3D1(gl, v, textures) {
  11936. var cache = this.cache;
  11937. var unit = textures.allocateTextureUnit();
  11938. if (cache[0] !== unit) {
  11939. gl.uniform1i(this.addr, unit);
  11940. cache[0] = unit;
  11941. }
  11942. textures.setTexture3D(v || emptyTexture3d, unit);
  11943. }
  11944. function setValueT6(gl, v, textures) {
  11945. var cache = this.cache;
  11946. var unit = textures.allocateTextureUnit();
  11947. if (cache[0] !== unit) {
  11948. gl.uniform1i(this.addr, unit);
  11949. cache[0] = unit;
  11950. }
  11951. textures.safeSetTextureCube(v || emptyCubeTexture, unit);
  11952. } // Integer / Boolean vectors or arrays thereof (always flat arrays)
  11953. function setValueV1i(gl, v) {
  11954. var cache = this.cache;
  11955. if (cache[0] === v) return;
  11956. gl.uniform1i(this.addr, v);
  11957. cache[0] = v;
  11958. }
  11959. function setValueV2i(gl, v) {
  11960. var cache = this.cache;
  11961. if (arraysEqual(cache, v)) return;
  11962. gl.uniform2iv(this.addr, v);
  11963. copyArray(cache, v);
  11964. }
  11965. function setValueV3i(gl, v) {
  11966. var cache = this.cache;
  11967. if (arraysEqual(cache, v)) return;
  11968. gl.uniform3iv(this.addr, v);
  11969. copyArray(cache, v);
  11970. }
  11971. function setValueV4i(gl, v) {
  11972. var cache = this.cache;
  11973. if (arraysEqual(cache, v)) return;
  11974. gl.uniform4iv(this.addr, v);
  11975. copyArray(cache, v);
  11976. } // Helper to pick the right setter for the singular case
  11977. function getSingularSetter(type) {
  11978. switch (type) {
  11979. case 0x1406:
  11980. return setValueV1f;
  11981. // FLOAT
  11982. case 0x8b50:
  11983. return setValueV2f;
  11984. // _VEC2
  11985. case 0x8b51:
  11986. return setValueV3f;
  11987. // _VEC3
  11988. case 0x8b52:
  11989. return setValueV4f;
  11990. // _VEC4
  11991. case 0x8b5a:
  11992. return setValueM2;
  11993. // _MAT2
  11994. case 0x8b5b:
  11995. return setValueM3;
  11996. // _MAT3
  11997. case 0x8b5c:
  11998. return setValueM4;
  11999. // _MAT4
  12000. case 0x8b5e:
  12001. case 0x8d66:
  12002. return setValueT1;
  12003. // SAMPLER_2D, SAMPLER_EXTERNAL_OES
  12004. case 0x8b5f:
  12005. return setValueT3D1;
  12006. // SAMPLER_3D
  12007. case 0x8b60:
  12008. return setValueT6;
  12009. // SAMPLER_CUBE
  12010. case 0x8DC1:
  12011. return setValueT2DArray1;
  12012. // SAMPLER_2D_ARRAY
  12013. case 0x1404:
  12014. case 0x8b56:
  12015. return setValueV1i;
  12016. // INT, BOOL
  12017. case 0x8b53:
  12018. case 0x8b57:
  12019. return setValueV2i;
  12020. // _VEC2
  12021. case 0x8b54:
  12022. case 0x8b58:
  12023. return setValueV3i;
  12024. // _VEC3
  12025. case 0x8b55:
  12026. case 0x8b59:
  12027. return setValueV4i;
  12028. // _VEC4
  12029. }
  12030. } // Array of scalars
  12031. function setValueV1fArray(gl, v) {
  12032. gl.uniform1fv(this.addr, v);
  12033. } // Integer / Boolean vectors or arrays thereof (always flat arrays)
  12034. function setValueV1iArray(gl, v) {
  12035. gl.uniform1iv(this.addr, v);
  12036. }
  12037. function setValueV2iArray(gl, v) {
  12038. gl.uniform2iv(this.addr, v);
  12039. }
  12040. function setValueV3iArray(gl, v) {
  12041. gl.uniform3iv(this.addr, v);
  12042. }
  12043. function setValueV4iArray(gl, v) {
  12044. gl.uniform4iv(this.addr, v);
  12045. } // Array of vectors (flat or from THREE classes)
  12046. function setValueV2fArray(gl, v) {
  12047. var data = flatten(v, this.size, 2);
  12048. gl.uniform2fv(this.addr, data);
  12049. }
  12050. function setValueV3fArray(gl, v) {
  12051. var data = flatten(v, this.size, 3);
  12052. gl.uniform3fv(this.addr, data);
  12053. }
  12054. function setValueV4fArray(gl, v) {
  12055. var data = flatten(v, this.size, 4);
  12056. gl.uniform4fv(this.addr, data);
  12057. } // Array of matrices (flat or from THREE clases)
  12058. function setValueM2Array(gl, v) {
  12059. var data = flatten(v, this.size, 4);
  12060. gl.uniformMatrix2fv(this.addr, false, data);
  12061. }
  12062. function setValueM3Array(gl, v) {
  12063. var data = flatten(v, this.size, 9);
  12064. gl.uniformMatrix3fv(this.addr, false, data);
  12065. }
  12066. function setValueM4Array(gl, v) {
  12067. var data = flatten(v, this.size, 16);
  12068. gl.uniformMatrix4fv(this.addr, false, data);
  12069. } // Array of textures (2D / Cube)
  12070. function setValueT1Array(gl, v, textures) {
  12071. var n = v.length;
  12072. var units = allocTexUnits(textures, n);
  12073. gl.uniform1iv(this.addr, units);
  12074. for (var i = 0; i !== n; ++i) {
  12075. textures.safeSetTexture2D(v[i] || emptyTexture, units[i]);
  12076. }
  12077. }
  12078. function setValueT6Array(gl, v, textures) {
  12079. var n = v.length;
  12080. var units = allocTexUnits(textures, n);
  12081. gl.uniform1iv(this.addr, units);
  12082. for (var i = 0; i !== n; ++i) {
  12083. textures.safeSetTextureCube(v[i] || emptyCubeTexture, units[i]);
  12084. }
  12085. } // Helper to pick the right setter for a pure (bottom-level) array
  12086. function getPureArraySetter(type) {
  12087. switch (type) {
  12088. case 0x1406:
  12089. return setValueV1fArray;
  12090. // FLOAT
  12091. case 0x8b50:
  12092. return setValueV2fArray;
  12093. // _VEC2
  12094. case 0x8b51:
  12095. return setValueV3fArray;
  12096. // _VEC3
  12097. case 0x8b52:
  12098. return setValueV4fArray;
  12099. // _VEC4
  12100. case 0x8b5a:
  12101. return setValueM2Array;
  12102. // _MAT2
  12103. case 0x8b5b:
  12104. return setValueM3Array;
  12105. // _MAT3
  12106. case 0x8b5c:
  12107. return setValueM4Array;
  12108. // _MAT4
  12109. case 0x8b5e:
  12110. return setValueT1Array;
  12111. // SAMPLER_2D
  12112. case 0x8b60:
  12113. return setValueT6Array;
  12114. // SAMPLER_CUBE
  12115. case 0x1404:
  12116. case 0x8b56:
  12117. return setValueV1iArray;
  12118. // INT, BOOL
  12119. case 0x8b53:
  12120. case 0x8b57:
  12121. return setValueV2iArray;
  12122. // _VEC2
  12123. case 0x8b54:
  12124. case 0x8b58:
  12125. return setValueV3iArray;
  12126. // _VEC3
  12127. case 0x8b55:
  12128. case 0x8b59:
  12129. return setValueV4iArray;
  12130. // _VEC4
  12131. }
  12132. } // --- Uniform Classes ---
  12133. function SingleUniform(id, activeInfo, addr) {
  12134. this.id = id;
  12135. this.addr = addr;
  12136. this.cache = [];
  12137. this.setValue = getSingularSetter(activeInfo.type); // this.path = activeInfo.name; // DEBUG
  12138. }
  12139. function PureArrayUniform(id, activeInfo, addr) {
  12140. this.id = id;
  12141. this.addr = addr;
  12142. this.cache = [];
  12143. this.size = activeInfo.size;
  12144. this.setValue = getPureArraySetter(activeInfo.type); // this.path = activeInfo.name; // DEBUG
  12145. }
  12146. PureArrayUniform.prototype.updateCache = function (data) {
  12147. var cache = this.cache;
  12148. if (data instanceof Float32Array && cache.length !== data.length) {
  12149. this.cache = new Float32Array(data.length);
  12150. }
  12151. copyArray(cache, data);
  12152. };
  12153. function StructuredUniform(id) {
  12154. this.id = id;
  12155. this.seq = [];
  12156. this.map = {};
  12157. }
  12158. StructuredUniform.prototype.setValue = function (gl, value, textures) {
  12159. var seq = this.seq;
  12160. for (var i = 0, n = seq.length; i !== n; ++i) {
  12161. var u = seq[i];
  12162. u.setValue(gl, value[u.id], textures);
  12163. }
  12164. }; // --- Top-level ---
  12165. // Parser - builds up the property tree from the path strings
  12166. var RePathPart = /([\w\d_]+)(\])?(\[|\.)?/g; // extracts
  12167. // - the identifier (member name or array index)
  12168. // - followed by an optional right bracket (found when array index)
  12169. // - followed by an optional left bracket or dot (type of subscript)
  12170. //
  12171. // Note: These portions can be read in a non-overlapping fashion and
  12172. // allow straightforward parsing of the hierarchy that WebGL encodes
  12173. // in the uniform names.
  12174. function addUniform(container, uniformObject) {
  12175. container.seq.push(uniformObject);
  12176. container.map[uniformObject.id] = uniformObject;
  12177. }
  12178. function parseUniform(activeInfo, addr, container) {
  12179. var path = activeInfo.name,
  12180. pathLength = path.length; // reset RegExp object, because of the early exit of a previous run
  12181. RePathPart.lastIndex = 0;
  12182. while (true) {
  12183. var match = RePathPart.exec(path),
  12184. matchEnd = RePathPart.lastIndex,
  12185. id = match[1],
  12186. idIsIndex = match[2] === ']',
  12187. subscript = match[3];
  12188. if (idIsIndex) id = id | 0; // convert to integer
  12189. if (subscript === undefined || subscript === '[' && matchEnd + 2 === pathLength) {
  12190. // bare name or "pure" bottom-level array "[0]" suffix
  12191. addUniform(container, subscript === undefined ? new SingleUniform(id, activeInfo, addr) : new PureArrayUniform(id, activeInfo, addr));
  12192. break;
  12193. } else {
  12194. // step into inner node / create it in case it doesn't exist
  12195. var map = container.map,
  12196. next = map[id];
  12197. if (next === undefined) {
  12198. next = new StructuredUniform(id);
  12199. addUniform(container, next);
  12200. }
  12201. container = next;
  12202. }
  12203. }
  12204. } // Root Container
  12205. function WebGLUniforms(gl, program) {
  12206. this.seq = [];
  12207. this.map = {};
  12208. var n = gl.getProgramParameter(program, 35718);
  12209. for (var i = 0; i < n; ++i) {
  12210. var info = gl.getActiveUniform(program, i),
  12211. addr = gl.getUniformLocation(program, info.name);
  12212. parseUniform(info, addr, this);
  12213. }
  12214. }
  12215. WebGLUniforms.prototype.setValue = function (gl, name, value, textures) {
  12216. var u = this.map[name];
  12217. if (u !== undefined) u.setValue(gl, value, textures);
  12218. };
  12219. WebGLUniforms.prototype.setOptional = function (gl, object, name) {
  12220. var v = object[name];
  12221. if (v !== undefined) this.setValue(gl, name, v);
  12222. }; // Static interface
  12223. WebGLUniforms.upload = function (gl, seq, values, textures) {
  12224. for (var i = 0, n = seq.length; i !== n; ++i) {
  12225. var u = seq[i],
  12226. v = values[u.id];
  12227. if (v.needsUpdate !== false) {
  12228. // note: always updating when .needsUpdate is undefined
  12229. u.setValue(gl, v.value, textures);
  12230. }
  12231. }
  12232. };
  12233. WebGLUniforms.seqWithValue = function (seq, values) {
  12234. var r = [];
  12235. for (var i = 0, n = seq.length; i !== n; ++i) {
  12236. var u = seq[i];
  12237. if (u.id in values) r.push(u);
  12238. }
  12239. return r;
  12240. };
  12241. /**
  12242. * @author mrdoob / http://mrdoob.com/
  12243. */
  12244. function WebGLShader(gl, type, string) {
  12245. var shader = gl.createShader(type);
  12246. gl.shaderSource(shader, string);
  12247. gl.compileShader(shader);
  12248. return shader;
  12249. }
  12250. /**
  12251. * @author mrdoob / http://mrdoob.com/
  12252. */
  12253. var programIdCount = 0;
  12254. function addLineNumbers(string) {
  12255. var lines = string.split('\n');
  12256. for (var i = 0; i < lines.length; i++) {
  12257. lines[i] = i + 1 + ': ' + lines[i];
  12258. }
  12259. return lines.join('\n');
  12260. }
  12261. function getEncodingComponents(encoding) {
  12262. switch (encoding) {
  12263. case LinearEncoding:
  12264. return ['Linear', '( value )'];
  12265. case sRGBEncoding:
  12266. return ['sRGB', '( value )'];
  12267. case RGBEEncoding:
  12268. return ['RGBE', '( value )'];
  12269. case RGBM7Encoding:
  12270. return ['RGBM', '( value, 7.0 )'];
  12271. case RGBM16Encoding:
  12272. return ['RGBM', '( value, 16.0 )'];
  12273. case RGBDEncoding:
  12274. return ['RGBD', '( value, 256.0 )'];
  12275. case GammaEncoding:
  12276. return ['Gamma', '( value, float( GAMMA_FACTOR ) )'];
  12277. case LogLuvEncoding:
  12278. return ['LogLuv', '( value )'];
  12279. default:
  12280. throw new Error('unsupported encoding: ' + encoding);
  12281. }
  12282. }
  12283. function getShaderErrors(gl, shader, type) {
  12284. var status = gl.getShaderParameter(shader, 35713);
  12285. var log = gl.getShaderInfoLog(shader).trim();
  12286. if (status && log === '') return ''; // --enable-privileged-webgl-extension
  12287. // console.log( '**' + type + '**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) );
  12288. var source = gl.getShaderSource(shader);
  12289. return 'THREE.WebGLShader: gl.getShaderInfoLog() ' + type + '\n' + log + addLineNumbers(source);
  12290. }
  12291. function getTexelDecodingFunction(functionName, encoding) {
  12292. var components = getEncodingComponents(encoding);
  12293. return 'vec4 ' + functionName + '( vec4 value ) { return ' + components[0] + 'ToLinear' + components[1] + '; }';
  12294. }
  12295. function getTexelEncodingFunction(functionName, encoding) {
  12296. var components = getEncodingComponents(encoding);
  12297. return 'vec4 ' + functionName + '( vec4 value ) { return LinearTo' + components[0] + components[1] + '; }';
  12298. }
  12299. function getToneMappingFunction(functionName, toneMapping) {
  12300. var toneMappingName;
  12301. switch (toneMapping) {
  12302. case LinearToneMapping:
  12303. toneMappingName = 'Linear';
  12304. break;
  12305. case ReinhardToneMapping:
  12306. toneMappingName = 'Reinhard';
  12307. break;
  12308. case Uncharted2ToneMapping:
  12309. toneMappingName = 'Uncharted2';
  12310. break;
  12311. case CineonToneMapping:
  12312. toneMappingName = 'OptimizedCineon';
  12313. break;
  12314. case ACESFilmicToneMapping:
  12315. toneMappingName = 'ACESFilmic';
  12316. break;
  12317. default:
  12318. throw new Error('unsupported toneMapping: ' + toneMapping);
  12319. }
  12320. return 'vec3 ' + functionName + '( vec3 color ) { return ' + toneMappingName + 'ToneMapping( color ); }';
  12321. }
  12322. function generateExtensions(extensions, parameters, rendererExtensions) {
  12323. extensions = extensions || {};
  12324. 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' : ''];
  12325. return chunks.filter(filterEmptyLine).join('\n');
  12326. }
  12327. function generateDefines(defines) {
  12328. var chunks = [];
  12329. for (var name in defines) {
  12330. var value = defines[name];
  12331. if (value === false) continue;
  12332. chunks.push('#define ' + name + ' ' + value);
  12333. }
  12334. return chunks.join('\n');
  12335. }
  12336. function fetchAttributeLocations(gl, program) {
  12337. var attributes = {};
  12338. var n = gl.getProgramParameter(program, 35721);
  12339. for (var i = 0; i < n; i++) {
  12340. var info = gl.getActiveAttrib(program, i);
  12341. var name = info.name; // console.log( 'THREE.WebGLProgram: ACTIVE VERTEX ATTRIBUTE:', name, i );
  12342. attributes[name] = gl.getAttribLocation(program, name);
  12343. }
  12344. return attributes;
  12345. }
  12346. function filterEmptyLine(string) {
  12347. return string !== '';
  12348. }
  12349. function replaceLightNums(string, parameters) {
  12350. 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);
  12351. }
  12352. function replaceClippingPlaneNums(string, parameters) {
  12353. return string.replace(/NUM_CLIPPING_PLANES/g, parameters.numClippingPlanes).replace(/UNION_CLIPPING_PLANES/g, parameters.numClippingPlanes - parameters.numClipIntersection);
  12354. } // Resolve Includes
  12355. var includePattern = /^[ \t]*#include +<([\w\d./]+)>/gm;
  12356. function resolveIncludes(string) {
  12357. return string.replace(includePattern, includeReplacer);
  12358. }
  12359. function includeReplacer(match, include) {
  12360. var string = ShaderChunk[include];
  12361. if (string === undefined) {
  12362. throw new Error('Can not resolve #include <' + include + '>');
  12363. }
  12364. return resolveIncludes(string);
  12365. } // Unroll Loops
  12366. var loopPattern = /#pragma unroll_loop[\s]+?for \( int i \= (\d+)\; i < (\d+)\; i \+\+ \) \{([\s\S]+?)(?=\})\}/g;
  12367. function unrollLoops(string) {
  12368. return string.replace(loopPattern, loopReplacer);
  12369. }
  12370. function loopReplacer(match, start, end, snippet) {
  12371. var string = '';
  12372. for (var i = parseInt(start); i < parseInt(end); i++) {
  12373. string += snippet.replace(/\[ i \]/g, '[ ' + i + ' ]').replace(/UNROLLED_LOOP_INDEX/g, i);
  12374. }
  12375. return string;
  12376. } //
  12377. function generatePrecision(parameters) {
  12378. var precisionstring = "precision " + parameters.precision + " float;\nprecision " + parameters.precision + " int;";
  12379. if (parameters.precision === "highp") {
  12380. precisionstring += "\n#define HIGH_PRECISION";
  12381. } else if (parameters.precision === "mediump") {
  12382. precisionstring += "\n#define MEDIUM_PRECISION";
  12383. } else if (parameters.precision === "lowp") {
  12384. precisionstring += "\n#define LOW_PRECISION";
  12385. }
  12386. return precisionstring;
  12387. }
  12388. function generateShadowMapTypeDefine(parameters) {
  12389. var shadowMapTypeDefine = 'SHADOWMAP_TYPE_BASIC';
  12390. if (parameters.shadowMapType === PCFShadowMap) {
  12391. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF';
  12392. } else if (parameters.shadowMapType === PCFSoftShadowMap) {
  12393. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF_SOFT';
  12394. } else if (parameters.shadowMapType === VSMShadowMap) {
  12395. shadowMapTypeDefine = 'SHADOWMAP_TYPE_VSM';
  12396. }
  12397. return shadowMapTypeDefine;
  12398. }
  12399. function generateEnvMapTypeDefine(parameters, material) {
  12400. var envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  12401. if (parameters.envMap) {
  12402. switch (material.envMap.mapping) {
  12403. case CubeReflectionMapping:
  12404. case CubeRefractionMapping:
  12405. envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  12406. break;
  12407. case CubeUVReflectionMapping:
  12408. case CubeUVRefractionMapping:
  12409. envMapTypeDefine = 'ENVMAP_TYPE_CUBE_UV';
  12410. break;
  12411. case EquirectangularReflectionMapping:
  12412. case EquirectangularRefractionMapping:
  12413. envMapTypeDefine = 'ENVMAP_TYPE_EQUIREC';
  12414. break;
  12415. case SphericalReflectionMapping:
  12416. envMapTypeDefine = 'ENVMAP_TYPE_SPHERE';
  12417. break;
  12418. }
  12419. }
  12420. return envMapTypeDefine;
  12421. }
  12422. function generateEnvMapModeDefine(parameters, material) {
  12423. var envMapModeDefine = 'ENVMAP_MODE_REFLECTION';
  12424. if (parameters.envMap) {
  12425. switch (material.envMap.mapping) {
  12426. case CubeRefractionMapping:
  12427. case EquirectangularRefractionMapping:
  12428. envMapModeDefine = 'ENVMAP_MODE_REFRACTION';
  12429. break;
  12430. }
  12431. }
  12432. return envMapModeDefine;
  12433. }
  12434. function generateEnvMapBlendingDefine(parameters, material) {
  12435. var envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  12436. if (parameters.envMap) {
  12437. switch (material.combine) {
  12438. case MultiplyOperation:
  12439. envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  12440. break;
  12441. case MixOperation:
  12442. envMapBlendingDefine = 'ENVMAP_BLENDING_MIX';
  12443. break;
  12444. case AddOperation:
  12445. envMapBlendingDefine = 'ENVMAP_BLENDING_ADD';
  12446. break;
  12447. }
  12448. }
  12449. return envMapBlendingDefine;
  12450. }
  12451. function WebGLProgram(renderer, extensions, code, material, shader, parameters) {
  12452. var gl = renderer.getContext();
  12453. var defines = material.defines;
  12454. var vertexShader = shader.vertexShader;
  12455. var fragmentShader = shader.fragmentShader;
  12456. var shadowMapTypeDefine = generateShadowMapTypeDefine(parameters);
  12457. var envMapTypeDefine = generateEnvMapTypeDefine(parameters, material);
  12458. var envMapModeDefine = generateEnvMapModeDefine(parameters, material);
  12459. var envMapBlendingDefine = generateEnvMapBlendingDefine(parameters, material);
  12460. var gammaFactorDefine = renderer.gammaFactor > 0 ? renderer.gammaFactor : 1.0;
  12461. var customExtensions = parameters.isWebGL2 ? '' : generateExtensions(material.extensions, parameters, extensions);
  12462. var customDefines = generateDefines(defines);
  12463. var program = gl.createProgram();
  12464. var prefixVertex, prefixFragment;
  12465. var renderTarget = renderer.getRenderTarget();
  12466. var numMultiviewViews = renderTarget && renderTarget.isWebGLMultiviewRenderTarget ? renderTarget.numViews : 0;
  12467. if (material.isRawShaderMaterial) {
  12468. prefixVertex = [customDefines].filter(filterEmptyLine).join('\n');
  12469. if (prefixVertex.length > 0) {
  12470. prefixVertex += '\n';
  12471. }
  12472. prefixFragment = [customExtensions, customDefines].filter(filterEmptyLine).join('\n');
  12473. if (prefixFragment.length > 0) {
  12474. prefixFragment += '\n';
  12475. }
  12476. } else {
  12477. 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');
  12478. prefixFragment = [customExtensions, generatePrecision(parameters), '#define SHADER_NAME ' + shader.name, customDefines, parameters.alphaTest ? '#define ALPHATEST ' + parameters.alphaTest + (parameters.alphaTest % 1 ? '' : '.0') : '', // add '.0' if integer
  12479. '#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
  12480. 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
  12481. 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');
  12482. }
  12483. vertexShader = resolveIncludes(vertexShader);
  12484. vertexShader = replaceLightNums(vertexShader, parameters);
  12485. vertexShader = replaceClippingPlaneNums(vertexShader, parameters);
  12486. fragmentShader = resolveIncludes(fragmentShader);
  12487. fragmentShader = replaceLightNums(fragmentShader, parameters);
  12488. fragmentShader = replaceClippingPlaneNums(fragmentShader, parameters);
  12489. vertexShader = unrollLoops(vertexShader);
  12490. fragmentShader = unrollLoops(fragmentShader);
  12491. if (parameters.isWebGL2 && !material.isRawShaderMaterial) {
  12492. var isGLSL3ShaderMaterial = false;
  12493. var versionRegex = /^\s*#version\s+300\s+es\s*\n/;
  12494. if (material.isShaderMaterial && vertexShader.match(versionRegex) !== null && fragmentShader.match(versionRegex) !== null) {
  12495. isGLSL3ShaderMaterial = true;
  12496. vertexShader = vertexShader.replace(versionRegex, '');
  12497. fragmentShader = fragmentShader.replace(versionRegex, '');
  12498. } // GLSL 3.0 conversion
  12499. prefixVertex = ['#version 300 es\n', '#define attribute in', '#define varying out', '#define texture2D texture'].join('\n') + '\n' + prefixVertex;
  12500. 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
  12501. if (numMultiviewViews > 0) {
  12502. 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'));
  12503. 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'));
  12504. prefixFragment = prefixFragment.replace('#version 300 es\n', ['#version 300 es\n', '#extension GL_OVR_multiview2 : require', '#define VIEW_ID gl_ViewID_OVR'].join('\n'));
  12505. prefixFragment = prefixFragment.replace('uniform mat4 viewMatrix;', ['uniform mat4 viewMatrices[' + numMultiviewViews + '];', '#define viewMatrix viewMatrices[VIEW_ID]'].join('\n'));
  12506. }
  12507. }
  12508. var vertexGlsl = prefixVertex + vertexShader;
  12509. var fragmentGlsl = prefixFragment + fragmentShader; // console.log( '*VERTEX*', vertexGlsl );
  12510. // console.log( '*FRAGMENT*', fragmentGlsl );
  12511. var glVertexShader = WebGLShader(gl, 35633, vertexGlsl);
  12512. var glFragmentShader = WebGLShader(gl, 35632, fragmentGlsl);
  12513. gl.attachShader(program, glVertexShader);
  12514. gl.attachShader(program, glFragmentShader); // Force a particular attribute to index 0.
  12515. if (material.index0AttributeName !== undefined) {
  12516. gl.bindAttribLocation(program, 0, material.index0AttributeName);
  12517. } else if (parameters.morphTargets === true) {
  12518. // programs with morphTargets displace position out of attribute 0
  12519. gl.bindAttribLocation(program, 0, 'position');
  12520. }
  12521. gl.linkProgram(program); // check for link errors
  12522. if (renderer.debug.checkShaderErrors) {
  12523. var programLog = gl.getProgramInfoLog(program).trim();
  12524. var vertexLog = gl.getShaderInfoLog(glVertexShader).trim();
  12525. var fragmentLog = gl.getShaderInfoLog(glFragmentShader).trim();
  12526. var runnable = true;
  12527. var haveDiagnostics = true;
  12528. if (gl.getProgramParameter(program, 35714) === false) {
  12529. runnable = false;
  12530. var vertexErrors = getShaderErrors(gl, glVertexShader, 'vertex');
  12531. var fragmentErrors = getShaderErrors(gl, glFragmentShader, 'fragment');
  12532. console.error('THREE.WebGLProgram: shader error: ', gl.getError(), '35715', gl.getProgramParameter(program, 35715), 'gl.getProgramInfoLog', programLog, vertexErrors, fragmentErrors);
  12533. } else if (programLog !== '') {
  12534. console.warn('THREE.WebGLProgram: gl.getProgramInfoLog()', programLog);
  12535. } else if (vertexLog === '' || fragmentLog === '') {
  12536. haveDiagnostics = false;
  12537. }
  12538. if (haveDiagnostics) {
  12539. this.diagnostics = {
  12540. runnable: runnable,
  12541. material: material,
  12542. programLog: programLog,
  12543. vertexShader: {
  12544. log: vertexLog,
  12545. prefix: prefixVertex
  12546. },
  12547. fragmentShader: {
  12548. log: fragmentLog,
  12549. prefix: prefixFragment
  12550. }
  12551. };
  12552. }
  12553. } // clean up
  12554. gl.deleteShader(glVertexShader);
  12555. gl.deleteShader(glFragmentShader); // set up caching for uniform locations
  12556. var cachedUniforms;
  12557. this.getUniforms = function () {
  12558. if (cachedUniforms === undefined) {
  12559. cachedUniforms = new WebGLUniforms(gl, program);
  12560. }
  12561. return cachedUniforms;
  12562. }; // set up caching for attribute locations
  12563. var cachedAttributes;
  12564. this.getAttributes = function () {
  12565. if (cachedAttributes === undefined) {
  12566. cachedAttributes = fetchAttributeLocations(gl, program);
  12567. }
  12568. return cachedAttributes;
  12569. }; // free resource
  12570. this.destroy = function () {
  12571. gl.deleteProgram(program);
  12572. this.program = undefined;
  12573. }; //
  12574. this.name = shader.name;
  12575. this.id = programIdCount++;
  12576. this.code = code;
  12577. this.usedTimes = 1;
  12578. this.program = program;
  12579. this.vertexShader = glVertexShader;
  12580. this.fragmentShader = glFragmentShader;
  12581. this.numMultiviewViews = numMultiviewViews;
  12582. return this;
  12583. }
  12584. /**
  12585. * @author mrdoob / http://mrdoob.com/
  12586. */
  12587. function WebGLPrograms(renderer, extensions, capabilities) {
  12588. var programs = [];
  12589. var shaderIDs = {
  12590. MeshDepthMaterial: 'depth',
  12591. MeshDistanceMaterial: 'distanceRGBA',
  12592. MeshNormalMaterial: 'normal',
  12593. MeshBasicMaterial: 'basic',
  12594. MeshLambertMaterial: 'lambert',
  12595. MeshPhongMaterial: 'phong',
  12596. MeshToonMaterial: 'phong',
  12597. MeshStandardMaterial: 'physical',
  12598. MeshPhysicalMaterial: 'physical',
  12599. MeshMatcapMaterial: 'matcap',
  12600. LineBasicMaterial: 'basic',
  12601. LineDashedMaterial: 'dashed',
  12602. PointsMaterial: 'points',
  12603. ShadowMaterial: 'shadow',
  12604. SpriteMaterial: 'sprite'
  12605. };
  12606. 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"];
  12607. function allocateBones(object) {
  12608. var skeleton = object.skeleton;
  12609. var bones = skeleton.bones;
  12610. if (capabilities.floatVertexTextures) {
  12611. return 1024;
  12612. } else {
  12613. // default for when object is not specified
  12614. // ( for example when prebuilding shader to be used with multiple objects )
  12615. //
  12616. // - leave some extra space for other uniforms
  12617. // - limit here is ANGLE's 254 max uniform vectors
  12618. // (up to 54 should be safe)
  12619. var nVertexUniforms = capabilities.maxVertexUniforms;
  12620. var nVertexMatrices = Math.floor((nVertexUniforms - 20) / 4);
  12621. var maxBones = Math.min(nVertexMatrices, bones.length);
  12622. if (maxBones < bones.length) {
  12623. console.warn('THREE.WebGLRenderer: Skeleton has ' + bones.length + ' bones. This GPU supports ' + maxBones + '.');
  12624. return 0;
  12625. }
  12626. return maxBones;
  12627. }
  12628. }
  12629. function getTextureEncodingFromMap(map, gammaOverrideLinear) {
  12630. var encoding;
  12631. if (!map) {
  12632. encoding = LinearEncoding;
  12633. } else if (map.isTexture) {
  12634. encoding = map.encoding;
  12635. } else if (map.isWebGLRenderTarget) {
  12636. console.warn("THREE.WebGLPrograms.getTextureEncodingFromMap: don't use render targets as textures. Use their .texture property instead.");
  12637. encoding = map.texture.encoding;
  12638. } // add backwards compatibility for WebGLRenderer.gammaInput/gammaOutput parameter, should probably be removed at some point.
  12639. if (encoding === LinearEncoding && gammaOverrideLinear) {
  12640. encoding = GammaEncoding;
  12641. }
  12642. return encoding;
  12643. }
  12644. this.getParameters = function (material, lights, shadows, fog, nClipPlanes, nClipIntersection, object) {
  12645. var shaderID = shaderIDs[material.type]; // heuristics to create shader parameters according to lights in the scene
  12646. // (not to blow over maxLights budget)
  12647. var maxBones = object.isSkinnedMesh ? allocateBones(object) : 0;
  12648. var precision = capabilities.precision;
  12649. if (material.precision !== null) {
  12650. precision = capabilities.getMaxPrecision(material.precision);
  12651. if (precision !== material.precision) {
  12652. console.warn('THREE.WebGLProgram.getParameters:', material.precision, 'not supported, using', precision, 'instead.');
  12653. }
  12654. }
  12655. var currentRenderTarget = renderer.getRenderTarget();
  12656. var parameters = {
  12657. isWebGL2: capabilities.isWebGL2,
  12658. shaderID: shaderID,
  12659. precision: precision,
  12660. instancing: object.isInstancedMesh === true,
  12661. supportsVertexTextures: capabilities.vertexTextures,
  12662. outputEncoding: getTextureEncodingFromMap(!currentRenderTarget ? null : currentRenderTarget.texture, renderer.gammaOutput),
  12663. map: !!material.map,
  12664. mapEncoding: getTextureEncodingFromMap(material.map, renderer.gammaInput),
  12665. matcap: !!material.matcap,
  12666. matcapEncoding: getTextureEncodingFromMap(material.matcap, renderer.gammaInput),
  12667. envMap: !!material.envMap,
  12668. envMapMode: material.envMap && material.envMap.mapping,
  12669. envMapEncoding: getTextureEncodingFromMap(material.envMap, renderer.gammaInput),
  12670. envMapCubeUV: !!material.envMap && (material.envMap.mapping === CubeUVReflectionMapping || material.envMap.mapping === CubeUVRefractionMapping),
  12671. lightMap: !!material.lightMap,
  12672. aoMap: !!material.aoMap,
  12673. emissiveMap: !!material.emissiveMap,
  12674. emissiveMapEncoding: getTextureEncodingFromMap(material.emissiveMap, renderer.gammaInput),
  12675. bumpMap: !!material.bumpMap,
  12676. normalMap: !!material.normalMap,
  12677. objectSpaceNormalMap: material.normalMapType === ObjectSpaceNormalMap,
  12678. tangentSpaceNormalMap: material.normalMapType === TangentSpaceNormalMap,
  12679. clearcoatNormalMap: !!material.clearcoatNormalMap,
  12680. displacementMap: !!material.displacementMap,
  12681. roughnessMap: !!material.roughnessMap,
  12682. metalnessMap: !!material.metalnessMap,
  12683. specularMap: !!material.specularMap,
  12684. alphaMap: !!material.alphaMap,
  12685. gradientMap: !!material.gradientMap,
  12686. sheen: !!material.sheen,
  12687. combine: material.combine,
  12688. vertexTangents: material.normalMap && material.vertexTangents,
  12689. vertexColors: material.vertexColors,
  12690. vertexUvs: !!material.map || !!material.bumpMap || !!material.normalMap || !!material.specularMap || !!material.alphaMap || !!material.emissiveMap || !!material.roughnessMap || !!material.metalnessMap || !!material.clearcoatNormalMap,
  12691. fog: !!fog,
  12692. useFog: material.fog,
  12693. fogExp2: fog && fog.isFogExp2,
  12694. flatShading: material.flatShading,
  12695. sizeAttenuation: material.sizeAttenuation,
  12696. logarithmicDepthBuffer: capabilities.logarithmicDepthBuffer,
  12697. skinning: material.skinning && maxBones > 0,
  12698. maxBones: maxBones,
  12699. useVertexTexture: capabilities.floatVertexTextures,
  12700. morphTargets: material.morphTargets,
  12701. morphNormals: material.morphNormals,
  12702. maxMorphTargets: renderer.maxMorphTargets,
  12703. maxMorphNormals: renderer.maxMorphNormals,
  12704. numDirLights: lights.directional.length,
  12705. numPointLights: lights.point.length,
  12706. numSpotLights: lights.spot.length,
  12707. numRectAreaLights: lights.rectArea.length,
  12708. numHemiLights: lights.hemi.length,
  12709. numDirLightShadows: lights.directionalShadowMap.length,
  12710. numPointLightShadows: lights.pointShadowMap.length,
  12711. numSpotLightShadows: lights.spotShadowMap.length,
  12712. numClippingPlanes: nClipPlanes,
  12713. numClipIntersection: nClipIntersection,
  12714. dithering: material.dithering,
  12715. shadowMapEnabled: renderer.shadowMap.enabled && shadows.length > 0,
  12716. shadowMapType: renderer.shadowMap.type,
  12717. toneMapping: material.toneMapped ? renderer.toneMapping : NoToneMapping,
  12718. physicallyCorrectLights: renderer.physicallyCorrectLights,
  12719. premultipliedAlpha: material.premultipliedAlpha,
  12720. alphaTest: material.alphaTest,
  12721. doubleSided: material.side === DoubleSide,
  12722. flipSided: material.side === BackSide,
  12723. depthPacking: material.depthPacking !== undefined ? material.depthPacking : false
  12724. };
  12725. return parameters;
  12726. };
  12727. this.getProgramCode = function (material, parameters) {
  12728. var array = [];
  12729. if (parameters.shaderID) {
  12730. array.push(parameters.shaderID);
  12731. } else {
  12732. array.push(material.fragmentShader);
  12733. array.push(material.vertexShader);
  12734. }
  12735. if (material.defines !== undefined) {
  12736. for (var name in material.defines) {
  12737. array.push(name);
  12738. array.push(material.defines[name]);
  12739. }
  12740. }
  12741. for (var i = 0; i < parameterNames.length; i++) {
  12742. array.push(parameters[parameterNames[i]]);
  12743. }
  12744. array.push(material.onBeforeCompile.toString());
  12745. array.push(renderer.gammaOutput);
  12746. array.push(renderer.gammaFactor);
  12747. return array.join();
  12748. };
  12749. this.acquireProgram = function (material, shader, parameters, code) {
  12750. var program; // Check if code has been already compiled
  12751. for (var p = 0, pl = programs.length; p < pl; p++) {
  12752. var programInfo = programs[p];
  12753. if (programInfo.code === code) {
  12754. program = programInfo;
  12755. ++program.usedTimes;
  12756. break;
  12757. }
  12758. }
  12759. if (program === undefined) {
  12760. program = new WebGLProgram(renderer, extensions, code, material, shader, parameters);
  12761. programs.push(program);
  12762. }
  12763. return program;
  12764. };
  12765. this.releaseProgram = function (program) {
  12766. if (--program.usedTimes === 0) {
  12767. // Remove from unordered set
  12768. var i = programs.indexOf(program);
  12769. programs[i] = programs[programs.length - 1];
  12770. programs.pop(); // Free WebGL resources
  12771. program.destroy();
  12772. }
  12773. }; // Exposed for resource monitoring & error feedback via renderer.info:
  12774. this.programs = programs;
  12775. }
  12776. /**
  12777. * @author fordacious / fordacious.github.io
  12778. */
  12779. function WebGLProperties() {
  12780. var properties = new WeakMap();
  12781. function get(object) {
  12782. var map = properties.get(object);
  12783. if (map === undefined) {
  12784. map = {};
  12785. properties.set(object, map);
  12786. }
  12787. return map;
  12788. }
  12789. function remove(object) {
  12790. properties.delete(object);
  12791. }
  12792. function update(object, key, value) {
  12793. properties.get(object)[key] = value;
  12794. }
  12795. function dispose() {
  12796. properties = new WeakMap();
  12797. }
  12798. return {
  12799. get: get,
  12800. remove: remove,
  12801. update: update,
  12802. dispose: dispose
  12803. };
  12804. }
  12805. /**
  12806. * @author mrdoob / http://mrdoob.com/
  12807. */
  12808. function painterSortStable(a, b) {
  12809. if (a.groupOrder !== b.groupOrder) {
  12810. return a.groupOrder - b.groupOrder;
  12811. } else if (a.renderOrder !== b.renderOrder) {
  12812. return a.renderOrder - b.renderOrder;
  12813. } else if (a.program !== b.program) {
  12814. return a.program.id - b.program.id;
  12815. } else if (a.material.id !== b.material.id) {
  12816. return a.material.id - b.material.id;
  12817. } else if (a.z !== b.z) {
  12818. return a.z - b.z;
  12819. } else {
  12820. return a.id - b.id;
  12821. }
  12822. }
  12823. function reversePainterSortStable(a, b) {
  12824. if (a.groupOrder !== b.groupOrder) {
  12825. return a.groupOrder - b.groupOrder;
  12826. } else if (a.renderOrder !== b.renderOrder) {
  12827. return a.renderOrder - b.renderOrder;
  12828. } else if (a.z !== b.z) {
  12829. return b.z - a.z;
  12830. } else {
  12831. return a.id - b.id;
  12832. }
  12833. }
  12834. function WebGLRenderList() {
  12835. var renderItems = [];
  12836. var renderItemsIndex = 0;
  12837. var opaque = [];
  12838. var transparent = [];
  12839. var defaultProgram = {
  12840. id: -1
  12841. };
  12842. function init() {
  12843. renderItemsIndex = 0;
  12844. opaque.length = 0;
  12845. transparent.length = 0;
  12846. }
  12847. function getNextRenderItem(object, geometry, material, groupOrder, z, group) {
  12848. var renderItem = renderItems[renderItemsIndex];
  12849. if (renderItem === undefined) {
  12850. renderItem = {
  12851. id: object.id,
  12852. object: object,
  12853. geometry: geometry,
  12854. material: material,
  12855. program: material.program || defaultProgram,
  12856. groupOrder: groupOrder,
  12857. renderOrder: object.renderOrder,
  12858. z: z,
  12859. group: group
  12860. };
  12861. renderItems[renderItemsIndex] = renderItem;
  12862. } else {
  12863. renderItem.id = object.id;
  12864. renderItem.object = object;
  12865. renderItem.geometry = geometry;
  12866. renderItem.material = material;
  12867. renderItem.program = material.program || defaultProgram;
  12868. renderItem.groupOrder = groupOrder;
  12869. renderItem.renderOrder = object.renderOrder;
  12870. renderItem.z = z;
  12871. renderItem.group = group;
  12872. }
  12873. renderItemsIndex++;
  12874. return renderItem;
  12875. }
  12876. function push(object, geometry, material, groupOrder, z, group) {
  12877. var renderItem = getNextRenderItem(object, geometry, material, groupOrder, z, group);
  12878. (material.transparent === true ? transparent : opaque).push(renderItem);
  12879. }
  12880. function unshift(object, geometry, material, groupOrder, z, group) {
  12881. var renderItem = getNextRenderItem(object, geometry, material, groupOrder, z, group);
  12882. (material.transparent === true ? transparent : opaque).unshift(renderItem);
  12883. }
  12884. function sort() {
  12885. if (opaque.length > 1) opaque.sort(painterSortStable);
  12886. if (transparent.length > 1) transparent.sort(reversePainterSortStable);
  12887. }
  12888. return {
  12889. opaque: opaque,
  12890. transparent: transparent,
  12891. init: init,
  12892. push: push,
  12893. unshift: unshift,
  12894. sort: sort
  12895. };
  12896. }
  12897. function WebGLRenderLists() {
  12898. var lists = new WeakMap();
  12899. function onSceneDispose(event) {
  12900. var scene = event.target;
  12901. scene.removeEventListener('dispose', onSceneDispose);
  12902. lists.delete(scene);
  12903. }
  12904. function get(scene, camera) {
  12905. var cameras = lists.get(scene);
  12906. var list;
  12907. if (cameras === undefined) {
  12908. list = new WebGLRenderList();
  12909. lists.set(scene, new WeakMap());
  12910. lists.get(scene).set(camera, list);
  12911. scene.addEventListener('dispose', onSceneDispose);
  12912. } else {
  12913. list = cameras.get(camera);
  12914. if (list === undefined) {
  12915. list = new WebGLRenderList();
  12916. cameras.set(camera, list);
  12917. }
  12918. }
  12919. return list;
  12920. }
  12921. function dispose() {
  12922. lists = new WeakMap();
  12923. }
  12924. return {
  12925. get: get,
  12926. dispose: dispose
  12927. };
  12928. }
  12929. /**
  12930. * @author mrdoob / http://mrdoob.com/
  12931. */
  12932. function UniformsCache() {
  12933. var lights = {};
  12934. return {
  12935. get: function (light) {
  12936. if (lights[light.id] !== undefined) {
  12937. return lights[light.id];
  12938. }
  12939. var uniforms;
  12940. switch (light.type) {
  12941. case 'DirectionalLight':
  12942. uniforms = {
  12943. direction: new Vector3(),
  12944. color: new Color(),
  12945. shadow: false,
  12946. shadowBias: 0,
  12947. shadowRadius: 1,
  12948. shadowMapSize: new Vector2()
  12949. };
  12950. break;
  12951. case 'SpotLight':
  12952. uniforms = {
  12953. position: new Vector3(),
  12954. direction: new Vector3(),
  12955. color: new Color(),
  12956. distance: 0,
  12957. coneCos: 0,
  12958. penumbraCos: 0,
  12959. decay: 0,
  12960. shadow: false,
  12961. shadowBias: 0,
  12962. shadowRadius: 1,
  12963. shadowMapSize: new Vector2()
  12964. };
  12965. break;
  12966. case 'PointLight':
  12967. uniforms = {
  12968. position: new Vector3(),
  12969. color: new Color(),
  12970. distance: 0,
  12971. decay: 0,
  12972. shadow: false,
  12973. shadowBias: 0,
  12974. shadowRadius: 1,
  12975. shadowMapSize: new Vector2(),
  12976. shadowCameraNear: 1,
  12977. shadowCameraFar: 1000
  12978. };
  12979. break;
  12980. case 'HemisphereLight':
  12981. uniforms = {
  12982. direction: new Vector3(),
  12983. skyColor: new Color(),
  12984. groundColor: new Color()
  12985. };
  12986. break;
  12987. case 'RectAreaLight':
  12988. uniforms = {
  12989. color: new Color(),
  12990. position: new Vector3(),
  12991. halfWidth: new Vector3(),
  12992. halfHeight: new Vector3() // TODO (abelnation): set RectAreaLight shadow uniforms
  12993. };
  12994. break;
  12995. }
  12996. lights[light.id] = uniforms;
  12997. return uniforms;
  12998. }
  12999. };
  13000. }
  13001. var nextVersion = 0;
  13002. function shadowCastingLightsFirst(lightA, lightB) {
  13003. return (lightB.castShadow ? 1 : 0) - (lightA.castShadow ? 1 : 0);
  13004. }
  13005. function WebGLLights() {
  13006. var cache = new UniformsCache();
  13007. var state = {
  13008. version: 0,
  13009. hash: {
  13010. directionalLength: -1,
  13011. pointLength: -1,
  13012. spotLength: -1,
  13013. rectAreaLength: -1,
  13014. hemiLength: -1,
  13015. numDirectionalShadows: -1,
  13016. numPointShadows: -1,
  13017. numSpotShadows: -1
  13018. },
  13019. ambient: [0, 0, 0],
  13020. probe: [],
  13021. directional: [],
  13022. directionalShadowMap: [],
  13023. directionalShadowMatrix: [],
  13024. spot: [],
  13025. spotShadowMap: [],
  13026. spotShadowMatrix: [],
  13027. rectArea: [],
  13028. point: [],
  13029. pointShadowMap: [],
  13030. pointShadowMatrix: [],
  13031. hemi: [],
  13032. numDirectionalShadows: -1,
  13033. numPointShadows: -1,
  13034. numSpotShadows: -1
  13035. };
  13036. for (var i = 0; i < 9; i++) state.probe.push(new Vector3());
  13037. var vector3 = new Vector3();
  13038. var matrix4 = new Matrix4();
  13039. var matrix42 = new Matrix4();
  13040. function setup(lights, shadows, camera) {
  13041. var r = 0,
  13042. g = 0,
  13043. b = 0;
  13044. for (var i = 0; i < 9; i++) state.probe[i].set(0, 0, 0);
  13045. var directionalLength = 0;
  13046. var pointLength = 0;
  13047. var spotLength = 0;
  13048. var rectAreaLength = 0;
  13049. var hemiLength = 0;
  13050. var numDirectionalShadows = 0;
  13051. var numPointShadows = 0;
  13052. var numSpotShadows = 0;
  13053. var viewMatrix = camera.matrixWorldInverse;
  13054. lights.sort(shadowCastingLightsFirst);
  13055. for (var i = 0, l = lights.length; i < l; i++) {
  13056. var light = lights[i];
  13057. var color = light.color;
  13058. var intensity = light.intensity;
  13059. var distance = light.distance;
  13060. var shadowMap = light.shadow && light.shadow.map ? light.shadow.map.texture : null;
  13061. if (light.isAmbientLight) {
  13062. r += color.r * intensity;
  13063. g += color.g * intensity;
  13064. b += color.b * intensity;
  13065. } else if (light.isLightProbe) {
  13066. for (var j = 0; j < 9; j++) {
  13067. state.probe[j].addScaledVector(light.sh.coefficients[j], intensity);
  13068. }
  13069. } else if (light.isDirectionalLight) {
  13070. var uniforms = cache.get(light);
  13071. uniforms.color.copy(light.color).multiplyScalar(light.intensity);
  13072. uniforms.direction.setFromMatrixPosition(light.matrixWorld);
  13073. vector3.setFromMatrixPosition(light.target.matrixWorld);
  13074. uniforms.direction.sub(vector3);
  13075. uniforms.direction.transformDirection(viewMatrix);
  13076. uniforms.shadow = light.castShadow;
  13077. if (light.castShadow) {
  13078. var shadow = light.shadow;
  13079. uniforms.shadowBias = shadow.bias;
  13080. uniforms.shadowRadius = shadow.radius;
  13081. uniforms.shadowMapSize = shadow.mapSize;
  13082. state.directionalShadowMap[directionalLength] = shadowMap;
  13083. state.directionalShadowMatrix[directionalLength] = light.shadow.matrix;
  13084. numDirectionalShadows++;
  13085. }
  13086. state.directional[directionalLength] = uniforms;
  13087. directionalLength++;
  13088. } else if (light.isSpotLight) {
  13089. var uniforms = cache.get(light);
  13090. uniforms.position.setFromMatrixPosition(light.matrixWorld);
  13091. uniforms.position.applyMatrix4(viewMatrix);
  13092. uniforms.color.copy(color).multiplyScalar(intensity);
  13093. uniforms.distance = distance;
  13094. uniforms.direction.setFromMatrixPosition(light.matrixWorld);
  13095. vector3.setFromMatrixPosition(light.target.matrixWorld);
  13096. uniforms.direction.sub(vector3);
  13097. uniforms.direction.transformDirection(viewMatrix);
  13098. uniforms.coneCos = Math.cos(light.angle);
  13099. uniforms.penumbraCos = Math.cos(light.angle * (1 - light.penumbra));
  13100. uniforms.decay = light.decay;
  13101. uniforms.shadow = light.castShadow;
  13102. if (light.castShadow) {
  13103. var shadow = light.shadow;
  13104. uniforms.shadowBias = shadow.bias;
  13105. uniforms.shadowRadius = shadow.radius;
  13106. uniforms.shadowMapSize = shadow.mapSize;
  13107. state.spotShadowMap[spotLength] = shadowMap;
  13108. state.spotShadowMatrix[spotLength] = light.shadow.matrix;
  13109. numSpotShadows++;
  13110. }
  13111. state.spot[spotLength] = uniforms;
  13112. spotLength++;
  13113. } else if (light.isRectAreaLight) {
  13114. var uniforms = cache.get(light); // (a) intensity is the total visible light emitted
  13115. //uniforms.color.copy( color ).multiplyScalar( intensity / ( light.width * light.height * Math.PI ) );
  13116. // (b) intensity is the brightness of the light
  13117. uniforms.color.copy(color).multiplyScalar(intensity);
  13118. uniforms.position.setFromMatrixPosition(light.matrixWorld);
  13119. uniforms.position.applyMatrix4(viewMatrix); // extract local rotation of light to derive width/height half vectors
  13120. matrix42.identity();
  13121. matrix4.copy(light.matrixWorld);
  13122. matrix4.premultiply(viewMatrix);
  13123. matrix42.extractRotation(matrix4);
  13124. uniforms.halfWidth.set(light.width * 0.5, 0.0, 0.0);
  13125. uniforms.halfHeight.set(0.0, light.height * 0.5, 0.0);
  13126. uniforms.halfWidth.applyMatrix4(matrix42);
  13127. uniforms.halfHeight.applyMatrix4(matrix42); // TODO (abelnation): RectAreaLight distance?
  13128. // uniforms.distance = distance;
  13129. state.rectArea[rectAreaLength] = uniforms;
  13130. rectAreaLength++;
  13131. } else if (light.isPointLight) {
  13132. var uniforms = cache.get(light);
  13133. uniforms.position.setFromMatrixPosition(light.matrixWorld);
  13134. uniforms.position.applyMatrix4(viewMatrix);
  13135. uniforms.color.copy(light.color).multiplyScalar(light.intensity);
  13136. uniforms.distance = light.distance;
  13137. uniforms.decay = light.decay;
  13138. uniforms.shadow = light.castShadow;
  13139. if (light.castShadow) {
  13140. var shadow = light.shadow;
  13141. uniforms.shadowBias = shadow.bias;
  13142. uniforms.shadowRadius = shadow.radius;
  13143. uniforms.shadowMapSize = shadow.mapSize;
  13144. uniforms.shadowCameraNear = shadow.camera.near;
  13145. uniforms.shadowCameraFar = shadow.camera.far;
  13146. state.pointShadowMap[pointLength] = shadowMap;
  13147. state.pointShadowMatrix[pointLength] = light.shadow.matrix;
  13148. numPointShadows++;
  13149. }
  13150. state.point[pointLength] = uniforms;
  13151. pointLength++;
  13152. } else if (light.isHemisphereLight) {
  13153. var uniforms = cache.get(light);
  13154. uniforms.direction.setFromMatrixPosition(light.matrixWorld);
  13155. uniforms.direction.transformDirection(viewMatrix);
  13156. uniforms.direction.normalize();
  13157. uniforms.skyColor.copy(light.color).multiplyScalar(intensity);
  13158. uniforms.groundColor.copy(light.groundColor).multiplyScalar(intensity);
  13159. state.hemi[hemiLength] = uniforms;
  13160. hemiLength++;
  13161. }
  13162. }
  13163. state.ambient[0] = r;
  13164. state.ambient[1] = g;
  13165. state.ambient[2] = b;
  13166. var hash = state.hash;
  13167. 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) {
  13168. state.directional.length = directionalLength;
  13169. state.spot.length = spotLength;
  13170. state.rectArea.length = rectAreaLength;
  13171. state.point.length = pointLength;
  13172. state.hemi.length = hemiLength;
  13173. state.directionalShadowMap.length = numDirectionalShadows;
  13174. state.pointShadowMap.length = numPointShadows;
  13175. state.spotShadowMap.length = numSpotShadows;
  13176. state.directionalShadowMatrix.length = numDirectionalShadows;
  13177. state.pointShadowMatrix.length = numPointShadows;
  13178. state.spotShadowMatrix.length = numSpotShadows;
  13179. hash.directionalLength = directionalLength;
  13180. hash.pointLength = pointLength;
  13181. hash.spotLength = spotLength;
  13182. hash.rectAreaLength = rectAreaLength;
  13183. hash.hemiLength = hemiLength;
  13184. hash.numDirectionalShadows = numDirectionalShadows;
  13185. hash.numPointShadows = numPointShadows;
  13186. hash.numSpotShadows = numSpotShadows;
  13187. state.version = nextVersion++;
  13188. }
  13189. }
  13190. return {
  13191. setup: setup,
  13192. state: state
  13193. };
  13194. }
  13195. /**
  13196. * @author Mugen87 / https://github.com/Mugen87
  13197. */
  13198. function WebGLRenderState() {
  13199. var lights = new WebGLLights();
  13200. var lightsArray = [];
  13201. var shadowsArray = [];
  13202. function init() {
  13203. lightsArray.length = 0;
  13204. shadowsArray.length = 0;
  13205. }
  13206. function pushLight(light) {
  13207. lightsArray.push(light);
  13208. }
  13209. function pushShadow(shadowLight) {
  13210. shadowsArray.push(shadowLight);
  13211. }
  13212. function setupLights(camera) {
  13213. lights.setup(lightsArray, shadowsArray, camera);
  13214. }
  13215. var state = {
  13216. lightsArray: lightsArray,
  13217. shadowsArray: shadowsArray,
  13218. lights: lights
  13219. };
  13220. return {
  13221. init: init,
  13222. state: state,
  13223. setupLights: setupLights,
  13224. pushLight: pushLight,
  13225. pushShadow: pushShadow
  13226. };
  13227. }
  13228. function WebGLRenderStates() {
  13229. var renderStates = new WeakMap();
  13230. function onSceneDispose(event) {
  13231. var scene = event.target;
  13232. scene.removeEventListener('dispose', onSceneDispose);
  13233. renderStates.delete(scene);
  13234. }
  13235. function get(scene, camera) {
  13236. var renderState;
  13237. if (renderStates.has(scene) === false) {
  13238. renderState = new WebGLRenderState();
  13239. renderStates.set(scene, new WeakMap());
  13240. renderStates.get(scene).set(camera, renderState);
  13241. scene.addEventListener('dispose', onSceneDispose);
  13242. } else {
  13243. if (renderStates.get(scene).has(camera) === false) {
  13244. renderState = new WebGLRenderState();
  13245. renderStates.get(scene).set(camera, renderState);
  13246. } else {
  13247. renderState = renderStates.get(scene).get(camera);
  13248. }
  13249. }
  13250. return renderState;
  13251. }
  13252. function dispose() {
  13253. renderStates = new WeakMap();
  13254. }
  13255. return {
  13256. get: get,
  13257. dispose: dispose
  13258. };
  13259. }
  13260. /**
  13261. * @author mrdoob / http://mrdoob.com/
  13262. * @author alteredq / http://alteredqualia.com/
  13263. * @author bhouston / https://clara.io
  13264. * @author WestLangley / http://github.com/WestLangley
  13265. *
  13266. * parameters = {
  13267. *
  13268. * opacity: <float>,
  13269. *
  13270. * map: new THREE.Texture( <Image> ),
  13271. *
  13272. * alphaMap: new THREE.Texture( <Image> ),
  13273. *
  13274. * displacementMap: new THREE.Texture( <Image> ),
  13275. * displacementScale: <float>,
  13276. * displacementBias: <float>,
  13277. *
  13278. * wireframe: <boolean>,
  13279. * wireframeLinewidth: <float>
  13280. * }
  13281. */
  13282. function MeshDepthMaterial(parameters) {
  13283. Material.call(this);
  13284. this.type = 'MeshDepthMaterial';
  13285. this.depthPacking = BasicDepthPacking;
  13286. this.skinning = false;
  13287. this.morphTargets = false;
  13288. this.map = null;
  13289. this.alphaMap = null;
  13290. this.displacementMap = null;
  13291. this.displacementScale = 1;
  13292. this.displacementBias = 0;
  13293. this.wireframe = false;
  13294. this.wireframeLinewidth = 1;
  13295. this.fog = false;
  13296. this.setValues(parameters);
  13297. }
  13298. MeshDepthMaterial.prototype = Object.create(Material.prototype);
  13299. MeshDepthMaterial.prototype.constructor = MeshDepthMaterial;
  13300. MeshDepthMaterial.prototype.isMeshDepthMaterial = true;
  13301. MeshDepthMaterial.prototype.copy = function (source) {
  13302. Material.prototype.copy.call(this, source);
  13303. this.depthPacking = source.depthPacking;
  13304. this.skinning = source.skinning;
  13305. this.morphTargets = source.morphTargets;
  13306. this.map = source.map;
  13307. this.alphaMap = source.alphaMap;
  13308. this.displacementMap = source.displacementMap;
  13309. this.displacementScale = source.displacementScale;
  13310. this.displacementBias = source.displacementBias;
  13311. this.wireframe = source.wireframe;
  13312. this.wireframeLinewidth = source.wireframeLinewidth;
  13313. return this;
  13314. };
  13315. /**
  13316. * @author WestLangley / http://github.com/WestLangley
  13317. *
  13318. * parameters = {
  13319. *
  13320. * referencePosition: <float>,
  13321. * nearDistance: <float>,
  13322. * farDistance: <float>,
  13323. *
  13324. * skinning: <bool>,
  13325. * morphTargets: <bool>,
  13326. *
  13327. * map: new THREE.Texture( <Image> ),
  13328. *
  13329. * alphaMap: new THREE.Texture( <Image> ),
  13330. *
  13331. * displacementMap: new THREE.Texture( <Image> ),
  13332. * displacementScale: <float>,
  13333. * displacementBias: <float>
  13334. *
  13335. * }
  13336. */
  13337. function MeshDistanceMaterial(parameters) {
  13338. Material.call(this);
  13339. this.type = 'MeshDistanceMaterial';
  13340. this.referencePosition = new Vector3();
  13341. this.nearDistance = 1;
  13342. this.farDistance = 1000;
  13343. this.skinning = false;
  13344. this.morphTargets = false;
  13345. this.map = null;
  13346. this.alphaMap = null;
  13347. this.displacementMap = null;
  13348. this.displacementScale = 1;
  13349. this.displacementBias = 0;
  13350. this.fog = false;
  13351. this.setValues(parameters);
  13352. }
  13353. MeshDistanceMaterial.prototype = Object.create(Material.prototype);
  13354. MeshDistanceMaterial.prototype.constructor = MeshDistanceMaterial;
  13355. MeshDistanceMaterial.prototype.isMeshDistanceMaterial = true;
  13356. MeshDistanceMaterial.prototype.copy = function (source) {
  13357. Material.prototype.copy.call(this, source);
  13358. this.referencePosition.copy(source.referencePosition);
  13359. this.nearDistance = source.nearDistance;
  13360. this.farDistance = source.farDistance;
  13361. this.skinning = source.skinning;
  13362. this.morphTargets = source.morphTargets;
  13363. this.map = source.map;
  13364. this.alphaMap = source.alphaMap;
  13365. this.displacementMap = source.displacementMap;
  13366. this.displacementScale = source.displacementScale;
  13367. this.displacementBias = source.displacementBias;
  13368. return this;
  13369. };
  13370. 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}";
  13371. var vsm_vert = "void main() {\n\tgl_Position = vec4( position, 1.0 );\n}";
  13372. /**
  13373. * @author alteredq / http://alteredqualia.com/
  13374. * @author mrdoob / http://mrdoob.com/
  13375. */
  13376. function WebGLShadowMap(_renderer, _objects, maxTextureSize) {
  13377. var _frustum = new Frustum(),
  13378. _shadowMapSize = new Vector2(),
  13379. _viewportSize = new Vector2(),
  13380. _viewport = new Vector4(),
  13381. _MorphingFlag = 1,
  13382. _SkinningFlag = 2,
  13383. _NumberOfMaterialVariants = (_MorphingFlag | _SkinningFlag) + 1,
  13384. _depthMaterials = new Array(_NumberOfMaterialVariants),
  13385. _distanceMaterials = new Array(_NumberOfMaterialVariants),
  13386. _materialCache = {};
  13387. var shadowSide = {
  13388. 0: BackSide,
  13389. 1: FrontSide,
  13390. 2: DoubleSide
  13391. };
  13392. var shadowMaterialVertical = new ShaderMaterial({
  13393. defines: {
  13394. SAMPLE_RATE: 2.0 / 8.0,
  13395. HALF_SAMPLE_RATE: 1.0 / 8.0
  13396. },
  13397. uniforms: {
  13398. shadow_pass: {
  13399. value: null
  13400. },
  13401. resolution: {
  13402. value: new Vector2()
  13403. },
  13404. radius: {
  13405. value: 4.0
  13406. }
  13407. },
  13408. vertexShader: vsm_vert,
  13409. fragmentShader: vsm_frag
  13410. });
  13411. var shadowMaterialHorizonal = shadowMaterialVertical.clone();
  13412. shadowMaterialHorizonal.defines.HORIZONAL_PASS = 1;
  13413. var fullScreenTri = new BufferGeometry();
  13414. fullScreenTri.addAttribute("position", new BufferAttribute(new Float32Array([-1, -1, 0.5, 3, -1, 0.5, -1, 3, 0.5]), 3));
  13415. var fullScreenMesh = new Mesh(fullScreenTri, shadowMaterialVertical); // init
  13416. for (var i = 0; i !== _NumberOfMaterialVariants; ++i) {
  13417. var useMorphing = (i & _MorphingFlag) !== 0;
  13418. var useSkinning = (i & _SkinningFlag) !== 0;
  13419. var depthMaterial = new MeshDepthMaterial({
  13420. depthPacking: RGBADepthPacking,
  13421. morphTargets: useMorphing,
  13422. skinning: useSkinning
  13423. });
  13424. _depthMaterials[i] = depthMaterial;
  13425. var distanceMaterial = new MeshDistanceMaterial({
  13426. morphTargets: useMorphing,
  13427. skinning: useSkinning
  13428. });
  13429. _distanceMaterials[i] = distanceMaterial;
  13430. }
  13431. var scope = this;
  13432. this.enabled = false;
  13433. this.autoUpdate = true;
  13434. this.needsUpdate = false;
  13435. this.type = PCFShadowMap;
  13436. this.render = function (lights, scene, camera) {
  13437. if (scope.enabled === false) return;
  13438. if (scope.autoUpdate === false && scope.needsUpdate === false) return;
  13439. if (lights.length === 0) return;
  13440. var currentRenderTarget = _renderer.getRenderTarget();
  13441. var activeCubeFace = _renderer.getActiveCubeFace();
  13442. var activeMipmapLevel = _renderer.getActiveMipmapLevel();
  13443. var _state = _renderer.state; // Set GL state for depth map.
  13444. _state.setBlending(NoBlending);
  13445. _state.buffers.color.setClear(1, 1, 1, 1);
  13446. _state.buffers.depth.setTest(true);
  13447. _state.setScissorTest(false); // render depth map
  13448. for (var i = 0, il = lights.length; i < il; i++) {
  13449. var light = lights[i];
  13450. var shadow = light.shadow;
  13451. if (shadow === undefined) {
  13452. console.warn('THREE.WebGLShadowMap:', light, 'has no shadow.');
  13453. continue;
  13454. }
  13455. _shadowMapSize.copy(shadow.mapSize);
  13456. var shadowFrameExtents = shadow.getFrameExtents();
  13457. _shadowMapSize.multiply(shadowFrameExtents);
  13458. _viewportSize.copy(shadow.mapSize);
  13459. if (_shadowMapSize.x > maxTextureSize || _shadowMapSize.y > maxTextureSize) {
  13460. console.warn('THREE.WebGLShadowMap:', light, 'has shadow exceeding max texture size, reducing');
  13461. if (_shadowMapSize.x > maxTextureSize) {
  13462. _viewportSize.x = Math.floor(maxTextureSize / shadowFrameExtents.x);
  13463. _shadowMapSize.x = _viewportSize.x * shadowFrameExtents.x;
  13464. shadow.mapSize.x = _viewportSize.x;
  13465. }
  13466. if (_shadowMapSize.y > maxTextureSize) {
  13467. _viewportSize.y = Math.floor(maxTextureSize / shadowFrameExtents.y);
  13468. _shadowMapSize.y = _viewportSize.y * shadowFrameExtents.y;
  13469. shadow.mapSize.y = _viewportSize.y;
  13470. }
  13471. }
  13472. if (shadow.map === null && !shadow.isPointLightShadow && this.type === VSMShadowMap) {
  13473. var pars = {
  13474. minFilter: LinearFilter,
  13475. magFilter: LinearFilter,
  13476. format: RGBAFormat
  13477. };
  13478. shadow.map = new WebGLRenderTarget(_shadowMapSize.x, _shadowMapSize.y, pars);
  13479. shadow.map.texture.name = light.name + ".shadowMap";
  13480. shadow.mapPass = new WebGLRenderTarget(_shadowMapSize.x, _shadowMapSize.y, pars);
  13481. shadow.camera.updateProjectionMatrix();
  13482. }
  13483. if (shadow.map === null) {
  13484. var pars = {
  13485. minFilter: NearestFilter,
  13486. magFilter: NearestFilter,
  13487. format: RGBAFormat
  13488. };
  13489. shadow.map = new WebGLRenderTarget(_shadowMapSize.x, _shadowMapSize.y, pars);
  13490. shadow.map.texture.name = light.name + ".shadowMap";
  13491. shadow.camera.updateProjectionMatrix();
  13492. }
  13493. _renderer.setRenderTarget(shadow.map);
  13494. _renderer.clear();
  13495. var viewportCount = shadow.getViewportCount();
  13496. for (var vp = 0; vp < viewportCount; vp++) {
  13497. var viewport = shadow.getViewport(vp);
  13498. _viewport.set(_viewportSize.x * viewport.x, _viewportSize.y * viewport.y, _viewportSize.x * viewport.z, _viewportSize.y * viewport.w);
  13499. _state.viewport(_viewport);
  13500. shadow.updateMatrices(light, camera, vp);
  13501. _frustum = shadow.getFrustum();
  13502. renderObject(scene, camera, shadow.camera, light, this.type);
  13503. } // do blur pass for VSM
  13504. if (!shadow.isPointLightShadow && this.type === VSMShadowMap) {
  13505. VSMPass(shadow, camera);
  13506. }
  13507. }
  13508. scope.needsUpdate = false;
  13509. _renderer.setRenderTarget(currentRenderTarget, activeCubeFace, activeMipmapLevel);
  13510. };
  13511. function VSMPass(shadow, camera) {
  13512. var geometry = _objects.update(fullScreenMesh); // vertical pass
  13513. shadowMaterialVertical.uniforms.shadow_pass.value = shadow.map.texture;
  13514. shadowMaterialVertical.uniforms.resolution.value = shadow.mapSize;
  13515. shadowMaterialVertical.uniforms.radius.value = shadow.radius;
  13516. _renderer.setRenderTarget(shadow.mapPass);
  13517. _renderer.clear();
  13518. _renderer.renderBufferDirect(camera, null, geometry, shadowMaterialVertical, fullScreenMesh, null); // horizonal pass
  13519. shadowMaterialHorizonal.uniforms.shadow_pass.value = shadow.mapPass.texture;
  13520. shadowMaterialHorizonal.uniforms.resolution.value = shadow.mapSize;
  13521. shadowMaterialHorizonal.uniforms.radius.value = shadow.radius;
  13522. _renderer.setRenderTarget(shadow.map);
  13523. _renderer.clear();
  13524. _renderer.renderBufferDirect(camera, null, geometry, shadowMaterialHorizonal, fullScreenMesh, null);
  13525. }
  13526. function getDepthMaterial(object, material, light, shadowCameraNear, shadowCameraFar, type) {
  13527. var geometry = object.geometry;
  13528. var result = null;
  13529. var materialVariants = _depthMaterials;
  13530. var customMaterial = object.customDepthMaterial;
  13531. if (light.isPointLight) {
  13532. materialVariants = _distanceMaterials;
  13533. customMaterial = object.customDistanceMaterial;
  13534. }
  13535. if (!customMaterial) {
  13536. var useMorphing = false;
  13537. if (material.morphTargets) {
  13538. if (geometry && geometry.isBufferGeometry) {
  13539. useMorphing = geometry.morphAttributes && geometry.morphAttributes.position && geometry.morphAttributes.position.length > 0;
  13540. } else if (geometry && geometry.isGeometry) {
  13541. useMorphing = geometry.morphTargets && geometry.morphTargets.length > 0;
  13542. }
  13543. }
  13544. if (object.isSkinnedMesh && material.skinning === false) {
  13545. console.warn('THREE.WebGLShadowMap: THREE.SkinnedMesh with material.skinning set to false:', object);
  13546. }
  13547. var useSkinning = object.isSkinnedMesh && material.skinning;
  13548. var variantIndex = 0;
  13549. if (useMorphing) variantIndex |= _MorphingFlag;
  13550. if (useSkinning) variantIndex |= _SkinningFlag;
  13551. result = materialVariants[variantIndex];
  13552. } else {
  13553. result = customMaterial;
  13554. }
  13555. if (_renderer.localClippingEnabled && material.clipShadows === true && material.clippingPlanes.length !== 0) {
  13556. // in this case we need a unique material instance reflecting the
  13557. // appropriate state
  13558. var keyA = result.uuid,
  13559. keyB = material.uuid;
  13560. var materialsForVariant = _materialCache[keyA];
  13561. if (materialsForVariant === undefined) {
  13562. materialsForVariant = {};
  13563. _materialCache[keyA] = materialsForVariant;
  13564. }
  13565. var cachedMaterial = materialsForVariant[keyB];
  13566. if (cachedMaterial === undefined) {
  13567. cachedMaterial = result.clone();
  13568. materialsForVariant[keyB] = cachedMaterial;
  13569. }
  13570. result = cachedMaterial;
  13571. }
  13572. result.visible = material.visible;
  13573. result.wireframe = material.wireframe;
  13574. if (type === VSMShadowMap) {
  13575. result.side = material.shadowSide != null ? material.shadowSide : material.side;
  13576. } else {
  13577. result.side = material.shadowSide != null ? material.shadowSide : shadowSide[material.side];
  13578. }
  13579. result.clipShadows = material.clipShadows;
  13580. result.clippingPlanes = material.clippingPlanes;
  13581. result.clipIntersection = material.clipIntersection;
  13582. result.wireframeLinewidth = material.wireframeLinewidth;
  13583. result.linewidth = material.linewidth;
  13584. if (light.isPointLight && result.isMeshDistanceMaterial) {
  13585. result.referencePosition.setFromMatrixPosition(light.matrixWorld);
  13586. result.nearDistance = shadowCameraNear;
  13587. result.farDistance = shadowCameraFar;
  13588. }
  13589. return result;
  13590. }
  13591. function renderObject(object, camera, shadowCamera, light, type) {
  13592. if (object.visible === false) return;
  13593. var visible = object.layers.test(camera.layers);
  13594. if (visible && (object.isMesh || object.isLine || object.isPoints)) {
  13595. if ((object.castShadow || object.receiveShadow && type === VSMShadowMap) && (!object.frustumCulled || _frustum.intersectsObject(object))) {
  13596. object.modelViewMatrix.multiplyMatrices(shadowCamera.matrixWorldInverse, object.matrixWorld);
  13597. var geometry = _objects.update(object);
  13598. var material = object.material;
  13599. if (Array.isArray(material)) {
  13600. var groups = geometry.groups;
  13601. for (var k = 0, kl = groups.length; k < kl; k++) {
  13602. var group = groups[k];
  13603. var groupMaterial = material[group.materialIndex];
  13604. if (groupMaterial && groupMaterial.visible) {
  13605. var depthMaterial = getDepthMaterial(object, groupMaterial, light, shadowCamera.near, shadowCamera.far, type);
  13606. _renderer.renderBufferDirect(shadowCamera, null, geometry, depthMaterial, object, group);
  13607. }
  13608. }
  13609. } else if (material.visible) {
  13610. var depthMaterial = getDepthMaterial(object, material, light, shadowCamera.near, shadowCamera.far, type);
  13611. _renderer.renderBufferDirect(shadowCamera, null, geometry, depthMaterial, object, null);
  13612. }
  13613. }
  13614. }
  13615. var children = object.children;
  13616. for (var i = 0, l = children.length; i < l; i++) {
  13617. renderObject(children[i], camera, shadowCamera, light, type);
  13618. }
  13619. }
  13620. }
  13621. /**
  13622. * @author mrdoob / http://mrdoob.com/
  13623. */
  13624. function WebGLState(gl, extensions, utils, capabilities) {
  13625. function ColorBuffer() {
  13626. var locked = false;
  13627. var color = new Vector4();
  13628. var currentColorMask = null;
  13629. var currentColorClear = new Vector4(0, 0, 0, 0);
  13630. return {
  13631. setMask: function (colorMask) {
  13632. if (currentColorMask !== colorMask && !locked) {
  13633. gl.colorMask(colorMask, colorMask, colorMask, colorMask);
  13634. currentColorMask = colorMask;
  13635. }
  13636. },
  13637. setLocked: function (lock) {
  13638. locked = lock;
  13639. },
  13640. setClear: function (r, g, b, a, premultipliedAlpha) {
  13641. if (premultipliedAlpha === true) {
  13642. r *= a;
  13643. g *= a;
  13644. b *= a;
  13645. }
  13646. color.set(r, g, b, a);
  13647. if (currentColorClear.equals(color) === false) {
  13648. gl.clearColor(r, g, b, a);
  13649. currentColorClear.copy(color);
  13650. }
  13651. },
  13652. reset: function () {
  13653. locked = false;
  13654. currentColorMask = null;
  13655. currentColorClear.set(-1, 0, 0, 0); // set to invalid state
  13656. }
  13657. };
  13658. }
  13659. function DepthBuffer() {
  13660. var locked = false;
  13661. var currentDepthMask = null;
  13662. var currentDepthFunc = null;
  13663. var currentDepthClear = null;
  13664. return {
  13665. setTest: function (depthTest) {
  13666. if (depthTest) {
  13667. enable(2929);
  13668. } else {
  13669. disable(2929);
  13670. }
  13671. },
  13672. setMask: function (depthMask) {
  13673. if (currentDepthMask !== depthMask && !locked) {
  13674. gl.depthMask(depthMask);
  13675. currentDepthMask = depthMask;
  13676. }
  13677. },
  13678. setFunc: function (depthFunc) {
  13679. if (currentDepthFunc !== depthFunc) {
  13680. if (depthFunc) {
  13681. switch (depthFunc) {
  13682. case NeverDepth:
  13683. gl.depthFunc(512);
  13684. break;
  13685. case AlwaysDepth:
  13686. gl.depthFunc(519);
  13687. break;
  13688. case LessDepth:
  13689. gl.depthFunc(513);
  13690. break;
  13691. case LessEqualDepth:
  13692. gl.depthFunc(515);
  13693. break;
  13694. case EqualDepth:
  13695. gl.depthFunc(514);
  13696. break;
  13697. case GreaterEqualDepth:
  13698. gl.depthFunc(518);
  13699. break;
  13700. case GreaterDepth:
  13701. gl.depthFunc(516);
  13702. break;
  13703. case NotEqualDepth:
  13704. gl.depthFunc(517);
  13705. break;
  13706. default:
  13707. gl.depthFunc(515);
  13708. }
  13709. } else {
  13710. gl.depthFunc(515);
  13711. }
  13712. currentDepthFunc = depthFunc;
  13713. }
  13714. },
  13715. setLocked: function (lock) {
  13716. locked = lock;
  13717. },
  13718. setClear: function (depth) {
  13719. if (currentDepthClear !== depth) {
  13720. gl.clearDepth(depth);
  13721. currentDepthClear = depth;
  13722. }
  13723. },
  13724. reset: function () {
  13725. locked = false;
  13726. currentDepthMask = null;
  13727. currentDepthFunc = null;
  13728. currentDepthClear = null;
  13729. }
  13730. };
  13731. }
  13732. function StencilBuffer() {
  13733. var locked = false;
  13734. var currentStencilMask = null;
  13735. var currentStencilFunc = null;
  13736. var currentStencilRef = null;
  13737. var currentStencilFuncMask = null;
  13738. var currentStencilFail = null;
  13739. var currentStencilZFail = null;
  13740. var currentStencilZPass = null;
  13741. var currentStencilClear = null;
  13742. return {
  13743. setTest: function (stencilTest) {
  13744. if (!locked) {
  13745. if (stencilTest) {
  13746. enable(2960);
  13747. } else {
  13748. disable(2960);
  13749. }
  13750. }
  13751. },
  13752. setMask: function (stencilMask) {
  13753. if (currentStencilMask !== stencilMask && !locked) {
  13754. gl.stencilMask(stencilMask);
  13755. currentStencilMask = stencilMask;
  13756. }
  13757. },
  13758. setFunc: function (stencilFunc, stencilRef, stencilMask) {
  13759. if (currentStencilFunc !== stencilFunc || currentStencilRef !== stencilRef || currentStencilFuncMask !== stencilMask) {
  13760. gl.stencilFunc(stencilFunc, stencilRef, stencilMask);
  13761. currentStencilFunc = stencilFunc;
  13762. currentStencilRef = stencilRef;
  13763. currentStencilFuncMask = stencilMask;
  13764. }
  13765. },
  13766. setOp: function (stencilFail, stencilZFail, stencilZPass) {
  13767. if (currentStencilFail !== stencilFail || currentStencilZFail !== stencilZFail || currentStencilZPass !== stencilZPass) {
  13768. gl.stencilOp(stencilFail, stencilZFail, stencilZPass);
  13769. currentStencilFail = stencilFail;
  13770. currentStencilZFail = stencilZFail;
  13771. currentStencilZPass = stencilZPass;
  13772. }
  13773. },
  13774. setLocked: function (lock) {
  13775. locked = lock;
  13776. },
  13777. setClear: function (stencil) {
  13778. if (currentStencilClear !== stencil) {
  13779. gl.clearStencil(stencil);
  13780. currentStencilClear = stencil;
  13781. }
  13782. },
  13783. reset: function () {
  13784. locked = false;
  13785. currentStencilMask = null;
  13786. currentStencilFunc = null;
  13787. currentStencilRef = null;
  13788. currentStencilFuncMask = null;
  13789. currentStencilFail = null;
  13790. currentStencilZFail = null;
  13791. currentStencilZPass = null;
  13792. currentStencilClear = null;
  13793. }
  13794. };
  13795. } //
  13796. var colorBuffer = new ColorBuffer();
  13797. var depthBuffer = new DepthBuffer();
  13798. var stencilBuffer = new StencilBuffer();
  13799. var maxVertexAttributes = gl.getParameter(34921);
  13800. var newAttributes = new Uint8Array(maxVertexAttributes);
  13801. var enabledAttributes = new Uint8Array(maxVertexAttributes);
  13802. var attributeDivisors = new Uint8Array(maxVertexAttributes);
  13803. var enabledCapabilities = {};
  13804. var compressedTextureFormats = null;
  13805. var currentProgram = null;
  13806. var currentBlendingEnabled = null;
  13807. var currentBlending = null;
  13808. var currentBlendEquation = null;
  13809. var currentBlendSrc = null;
  13810. var currentBlendDst = null;
  13811. var currentBlendEquationAlpha = null;
  13812. var currentBlendSrcAlpha = null;
  13813. var currentBlendDstAlpha = null;
  13814. var currentPremultipledAlpha = false;
  13815. var currentFlipSided = null;
  13816. var currentCullFace = null;
  13817. var currentLineWidth = null;
  13818. var currentPolygonOffsetFactor = null;
  13819. var currentPolygonOffsetUnits = null;
  13820. var maxTextures = gl.getParameter(35661);
  13821. var lineWidthAvailable = false;
  13822. var version = 0;
  13823. var glVersion = gl.getParameter(7938);
  13824. if (glVersion.indexOf('WebGL') !== -1) {
  13825. version = parseFloat(/^WebGL\ ([0-9])/.exec(glVersion)[1]);
  13826. lineWidthAvailable = version >= 1.0;
  13827. } else if (glVersion.indexOf('OpenGL ES') !== -1) {
  13828. version = parseFloat(/^OpenGL\ ES\ ([0-9])/.exec(glVersion)[1]);
  13829. lineWidthAvailable = version >= 2.0;
  13830. }
  13831. var currentTextureSlot = null;
  13832. var currentBoundTextures = {};
  13833. var currentScissor = new Vector4();
  13834. var currentViewport = new Vector4();
  13835. function createTexture(type, target, count) {
  13836. var data = new Uint8Array(4); // 4 is required to match default unpack alignment of 4.
  13837. var texture = gl.createTexture();
  13838. gl.bindTexture(type, texture);
  13839. gl.texParameteri(type, 10241, 9728);
  13840. gl.texParameteri(type, 10240, 9728);
  13841. for (var i = 0; i < count; i++) {
  13842. gl.texImage2D(target + i, 0, 6408, 1, 1, 0, 6408, 5121, data);
  13843. }
  13844. return texture;
  13845. }
  13846. var emptyTextures = {};
  13847. emptyTextures[3553] = createTexture(3553, 3553, 1);
  13848. emptyTextures[34067] = createTexture(34067, 34069, 6); // init
  13849. colorBuffer.setClear(0, 0, 0, 1);
  13850. depthBuffer.setClear(1);
  13851. stencilBuffer.setClear(0);
  13852. enable(2929);
  13853. depthBuffer.setFunc(LessEqualDepth);
  13854. setFlipSided(false);
  13855. setCullFace(CullFaceBack);
  13856. enable(2884);
  13857. setBlending(NoBlending); //
  13858. function initAttributes() {
  13859. for (var i = 0, l = newAttributes.length; i < l; i++) {
  13860. newAttributes[i] = 0;
  13861. }
  13862. }
  13863. function enableAttribute(attribute) {
  13864. enableAttributeAndDivisor(attribute, 0);
  13865. }
  13866. function enableAttributeAndDivisor(attribute, meshPerAttribute) {
  13867. newAttributes[attribute] = 1;
  13868. if (enabledAttributes[attribute] === 0) {
  13869. gl.enableVertexAttribArray(attribute);
  13870. enabledAttributes[attribute] = 1;
  13871. }
  13872. if (attributeDivisors[attribute] !== meshPerAttribute) {
  13873. var extension = capabilities.isWebGL2 ? gl : extensions.get('ANGLE_instanced_arrays');
  13874. extension[capabilities.isWebGL2 ? 'vertexAttribDivisor' : 'vertexAttribDivisorANGLE'](attribute, meshPerAttribute);
  13875. attributeDivisors[attribute] = meshPerAttribute;
  13876. }
  13877. }
  13878. function disableUnusedAttributes() {
  13879. for (var i = 0, l = enabledAttributes.length; i !== l; ++i) {
  13880. if (enabledAttributes[i] !== newAttributes[i]) {
  13881. gl.disableVertexAttribArray(i);
  13882. enabledAttributes[i] = 0;
  13883. }
  13884. }
  13885. }
  13886. function enable(id) {
  13887. if (enabledCapabilities[id] !== true) {
  13888. gl.enable(id);
  13889. enabledCapabilities[id] = true;
  13890. }
  13891. }
  13892. function disable(id) {
  13893. if (enabledCapabilities[id] !== false) {
  13894. gl.disable(id);
  13895. enabledCapabilities[id] = false;
  13896. }
  13897. }
  13898. function getCompressedTextureFormats() {
  13899. if (compressedTextureFormats === null) {
  13900. compressedTextureFormats = [];
  13901. 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')) {
  13902. var formats = gl.getParameter(34467);
  13903. for (var i = 0; i < formats.length; i++) {
  13904. compressedTextureFormats.push(formats[i]);
  13905. }
  13906. }
  13907. }
  13908. return compressedTextureFormats;
  13909. }
  13910. function useProgram(program) {
  13911. if (currentProgram !== program) {
  13912. gl.useProgram(program);
  13913. currentProgram = program;
  13914. return true;
  13915. }
  13916. return false;
  13917. }
  13918. function setBlending(blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha) {
  13919. if (blending === NoBlending) {
  13920. if (currentBlendingEnabled) {
  13921. disable(3042);
  13922. currentBlendingEnabled = false;
  13923. }
  13924. return;
  13925. }
  13926. if (!currentBlendingEnabled) {
  13927. enable(3042);
  13928. currentBlendingEnabled = true;
  13929. }
  13930. if (blending !== CustomBlending) {
  13931. if (blending !== currentBlending || premultipliedAlpha !== currentPremultipledAlpha) {
  13932. if (currentBlendEquation !== AddEquation || currentBlendEquationAlpha !== AddEquation) {
  13933. gl.blendEquation(32774);
  13934. currentBlendEquation = AddEquation;
  13935. currentBlendEquationAlpha = AddEquation;
  13936. }
  13937. if (premultipliedAlpha) {
  13938. switch (blending) {
  13939. case NormalBlending:
  13940. gl.blendFuncSeparate(1, 771, 1, 771);
  13941. break;
  13942. case AdditiveBlending:
  13943. gl.blendFunc(1, 1);
  13944. break;
  13945. case SubtractiveBlending:
  13946. gl.blendFuncSeparate(0, 0, 769, 771);
  13947. break;
  13948. case MultiplyBlending:
  13949. gl.blendFuncSeparate(0, 768, 0, 770);
  13950. break;
  13951. default:
  13952. console.error('THREE.WebGLState: Invalid blending: ', blending);
  13953. break;
  13954. }
  13955. } else {
  13956. switch (blending) {
  13957. case NormalBlending:
  13958. gl.blendFuncSeparate(770, 771, 1, 771);
  13959. break;
  13960. case AdditiveBlending:
  13961. gl.blendFunc(770, 1);
  13962. break;
  13963. case SubtractiveBlending:
  13964. gl.blendFunc(0, 769);
  13965. break;
  13966. case MultiplyBlending:
  13967. gl.blendFunc(0, 768);
  13968. break;
  13969. default:
  13970. console.error('THREE.WebGLState: Invalid blending: ', blending);
  13971. break;
  13972. }
  13973. }
  13974. currentBlendSrc = null;
  13975. currentBlendDst = null;
  13976. currentBlendSrcAlpha = null;
  13977. currentBlendDstAlpha = null;
  13978. currentBlending = blending;
  13979. currentPremultipledAlpha = premultipliedAlpha;
  13980. }
  13981. return;
  13982. } // custom blending
  13983. blendEquationAlpha = blendEquationAlpha || blendEquation;
  13984. blendSrcAlpha = blendSrcAlpha || blendSrc;
  13985. blendDstAlpha = blendDstAlpha || blendDst;
  13986. if (blendEquation !== currentBlendEquation || blendEquationAlpha !== currentBlendEquationAlpha) {
  13987. gl.blendEquationSeparate(utils.convert(blendEquation), utils.convert(blendEquationAlpha));
  13988. currentBlendEquation = blendEquation;
  13989. currentBlendEquationAlpha = blendEquationAlpha;
  13990. }
  13991. if (blendSrc !== currentBlendSrc || blendDst !== currentBlendDst || blendSrcAlpha !== currentBlendSrcAlpha || blendDstAlpha !== currentBlendDstAlpha) {
  13992. gl.blendFuncSeparate(utils.convert(blendSrc), utils.convert(blendDst), utils.convert(blendSrcAlpha), utils.convert(blendDstAlpha));
  13993. currentBlendSrc = blendSrc;
  13994. currentBlendDst = blendDst;
  13995. currentBlendSrcAlpha = blendSrcAlpha;
  13996. currentBlendDstAlpha = blendDstAlpha;
  13997. }
  13998. currentBlending = blending;
  13999. currentPremultipledAlpha = null;
  14000. }
  14001. function setMaterial(material, frontFaceCW) {
  14002. material.side === DoubleSide ? disable(2884) : enable(2884);
  14003. var flipSided = material.side === BackSide;
  14004. if (frontFaceCW) flipSided = !flipSided;
  14005. setFlipSided(flipSided);
  14006. 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);
  14007. depthBuffer.setFunc(material.depthFunc);
  14008. depthBuffer.setTest(material.depthTest);
  14009. depthBuffer.setMask(material.depthWrite);
  14010. colorBuffer.setMask(material.colorWrite);
  14011. var stencilWrite = material.stencilWrite;
  14012. stencilBuffer.setTest(stencilWrite);
  14013. if (stencilWrite) {
  14014. stencilBuffer.setMask(material.stencilWriteMask);
  14015. stencilBuffer.setFunc(material.stencilFunc, material.stencilRef, material.stencilFuncMask);
  14016. stencilBuffer.setOp(material.stencilFail, material.stencilZFail, material.stencilZPass);
  14017. }
  14018. setPolygonOffset(material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits);
  14019. } //
  14020. function setFlipSided(flipSided) {
  14021. if (currentFlipSided !== flipSided) {
  14022. if (flipSided) {
  14023. gl.frontFace(2304);
  14024. } else {
  14025. gl.frontFace(2305);
  14026. }
  14027. currentFlipSided = flipSided;
  14028. }
  14029. }
  14030. function setCullFace(cullFace) {
  14031. if (cullFace !== CullFaceNone) {
  14032. enable(2884);
  14033. if (cullFace !== currentCullFace) {
  14034. if (cullFace === CullFaceBack) {
  14035. gl.cullFace(1029);
  14036. } else if (cullFace === CullFaceFront) {
  14037. gl.cullFace(1028);
  14038. } else {
  14039. gl.cullFace(1032);
  14040. }
  14041. }
  14042. } else {
  14043. disable(2884);
  14044. }
  14045. currentCullFace = cullFace;
  14046. }
  14047. function setLineWidth(width) {
  14048. if (width !== currentLineWidth) {
  14049. if (lineWidthAvailable) gl.lineWidth(width);
  14050. currentLineWidth = width;
  14051. }
  14052. }
  14053. function setPolygonOffset(polygonOffset, factor, units) {
  14054. if (polygonOffset) {
  14055. enable(32823);
  14056. if (currentPolygonOffsetFactor !== factor || currentPolygonOffsetUnits !== units) {
  14057. gl.polygonOffset(factor, units);
  14058. currentPolygonOffsetFactor = factor;
  14059. currentPolygonOffsetUnits = units;
  14060. }
  14061. } else {
  14062. disable(32823);
  14063. }
  14064. }
  14065. function setScissorTest(scissorTest) {
  14066. if (scissorTest) {
  14067. enable(3089);
  14068. } else {
  14069. disable(3089);
  14070. }
  14071. } // texture
  14072. function activeTexture(webglSlot) {
  14073. if (webglSlot === undefined) webglSlot = 33984 + maxTextures - 1;
  14074. if (currentTextureSlot !== webglSlot) {
  14075. gl.activeTexture(webglSlot);
  14076. currentTextureSlot = webglSlot;
  14077. }
  14078. }
  14079. function bindTexture(webglType, webglTexture) {
  14080. if (currentTextureSlot === null) {
  14081. activeTexture();
  14082. }
  14083. var boundTexture = currentBoundTextures[currentTextureSlot];
  14084. if (boundTexture === undefined) {
  14085. boundTexture = {
  14086. type: undefined,
  14087. texture: undefined
  14088. };
  14089. currentBoundTextures[currentTextureSlot] = boundTexture;
  14090. }
  14091. if (boundTexture.type !== webglType || boundTexture.texture !== webglTexture) {
  14092. gl.bindTexture(webglType, webglTexture || emptyTextures[webglType]);
  14093. boundTexture.type = webglType;
  14094. boundTexture.texture = webglTexture;
  14095. }
  14096. }
  14097. function compressedTexImage2D() {
  14098. try {
  14099. gl.compressedTexImage2D.apply(gl, arguments);
  14100. } catch (error) {
  14101. console.error('THREE.WebGLState:', error);
  14102. }
  14103. }
  14104. function texImage2D() {
  14105. try {
  14106. gl.texImage2D.apply(gl, arguments);
  14107. } catch (error) {
  14108. console.error('THREE.WebGLState:', error);
  14109. }
  14110. }
  14111. function texImage3D() {
  14112. try {
  14113. gl.texImage3D.apply(gl, arguments);
  14114. } catch (error) {
  14115. console.error('THREE.WebGLState:', error);
  14116. }
  14117. } //
  14118. function scissor(scissor) {
  14119. if (currentScissor.equals(scissor) === false) {
  14120. gl.scissor(scissor.x, scissor.y, scissor.z, scissor.w);
  14121. currentScissor.copy(scissor);
  14122. }
  14123. }
  14124. function viewport(viewport) {
  14125. if (currentViewport.equals(viewport) === false) {
  14126. gl.viewport(viewport.x, viewport.y, viewport.z, viewport.w);
  14127. currentViewport.copy(viewport);
  14128. }
  14129. } //
  14130. function reset() {
  14131. for (var i = 0; i < enabledAttributes.length; i++) {
  14132. if (enabledAttributes[i] === 1) {
  14133. gl.disableVertexAttribArray(i);
  14134. enabledAttributes[i] = 0;
  14135. }
  14136. }
  14137. enabledCapabilities = {};
  14138. compressedTextureFormats = null;
  14139. currentTextureSlot = null;
  14140. currentBoundTextures = {};
  14141. currentProgram = null;
  14142. currentBlending = null;
  14143. currentFlipSided = null;
  14144. currentCullFace = null;
  14145. colorBuffer.reset();
  14146. depthBuffer.reset();
  14147. stencilBuffer.reset();
  14148. }
  14149. return {
  14150. buffers: {
  14151. color: colorBuffer,
  14152. depth: depthBuffer,
  14153. stencil: stencilBuffer
  14154. },
  14155. initAttributes: initAttributes,
  14156. enableAttribute: enableAttribute,
  14157. enableAttributeAndDivisor: enableAttributeAndDivisor,
  14158. disableUnusedAttributes: disableUnusedAttributes,
  14159. enable: enable,
  14160. disable: disable,
  14161. getCompressedTextureFormats: getCompressedTextureFormats,
  14162. useProgram: useProgram,
  14163. setBlending: setBlending,
  14164. setMaterial: setMaterial,
  14165. setFlipSided: setFlipSided,
  14166. setCullFace: setCullFace,
  14167. setLineWidth: setLineWidth,
  14168. setPolygonOffset: setPolygonOffset,
  14169. setScissorTest: setScissorTest,
  14170. activeTexture: activeTexture,
  14171. bindTexture: bindTexture,
  14172. compressedTexImage2D: compressedTexImage2D,
  14173. texImage2D: texImage2D,
  14174. texImage3D: texImage3D,
  14175. scissor: scissor,
  14176. viewport: viewport,
  14177. reset: reset
  14178. };
  14179. }
  14180. /**
  14181. * @author mrdoob / http://mrdoob.com/
  14182. */
  14183. function WebGLTextures(_gl, extensions, state, properties, capabilities, utils, info) {
  14184. var _videoTextures = new WeakMap();
  14185. var _canvas; // cordova iOS (as of 5.0) still uses UIWebView, which provides OffscreenCanvas,
  14186. // also OffscreenCanvas.getContext("webgl"), but not OffscreenCanvas.getContext("2d")!
  14187. var useOffscreenCanvas = typeof OffscreenCanvas !== 'undefined' && new OffscreenCanvas(1, 1).getContext("2d") !== null;
  14188. function createCanvas(width, height) {
  14189. // Use OffscreenCanvas when available. Specially needed in web workers
  14190. return useOffscreenCanvas ? new OffscreenCanvas(width, height) : document.createElementNS('http://www.w3.org/1999/xhtml', 'canvas');
  14191. }
  14192. function resizeImage(image, needsPowerOfTwo, needsNewCanvas, maxSize) {
  14193. var scale = 1; // handle case if texture exceeds max size
  14194. if (image.width > maxSize || image.height > maxSize) {
  14195. scale = maxSize / Math.max(image.width, image.height);
  14196. } // only perform resize if necessary
  14197. if (scale < 1 || needsPowerOfTwo === true) {
  14198. // only perform resize for certain image types
  14199. if (typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement || typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement || typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap) {
  14200. var floor = needsPowerOfTwo ? _Math.floorPowerOfTwo : Math.floor;
  14201. var width = floor(scale * image.width);
  14202. var height = floor(scale * image.height);
  14203. if (_canvas === undefined) _canvas = createCanvas(width, height); // cube textures can't reuse the same canvas
  14204. var canvas = needsNewCanvas ? createCanvas(width, height) : _canvas;
  14205. canvas.width = width;
  14206. canvas.height = height;
  14207. var context = canvas.getContext('2d');
  14208. context.drawImage(image, 0, 0, width, height);
  14209. console.warn('THREE.WebGLRenderer: Texture has been resized from (' + image.width + 'x' + image.height + ') to (' + width + 'x' + height + ').');
  14210. return canvas;
  14211. } else {
  14212. if ('data' in image) {
  14213. console.warn('THREE.WebGLRenderer: Image in DataTexture is too big (' + image.width + 'x' + image.height + ').');
  14214. }
  14215. return image;
  14216. }
  14217. }
  14218. return image;
  14219. }
  14220. function isPowerOfTwo(image) {
  14221. return _Math.isPowerOfTwo(image.width) && _Math.isPowerOfTwo(image.height);
  14222. }
  14223. function textureNeedsPowerOfTwo(texture) {
  14224. if (capabilities.isWebGL2) return false;
  14225. return texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping || texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter;
  14226. }
  14227. function textureNeedsGenerateMipmaps(texture, supportsMips) {
  14228. return texture.generateMipmaps && supportsMips && texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter;
  14229. }
  14230. function generateMipmap(target, texture, width, height) {
  14231. _gl.generateMipmap(target);
  14232. var textureProperties = properties.get(texture); // Note: Math.log( x ) * Math.LOG2E used instead of Math.log2( x ) which is not supported by IE11
  14233. textureProperties.__maxMipLevel = Math.log(Math.max(width, height)) * Math.LOG2E;
  14234. }
  14235. function getInternalFormat(glFormat, glType) {
  14236. if (!capabilities.isWebGL2) return glFormat;
  14237. var internalFormat = glFormat;
  14238. if (glFormat === 6403) {
  14239. if (glType === 5126) internalFormat = 33326;
  14240. if (glType === 5131) internalFormat = 33325;
  14241. if (glType === 5121) internalFormat = 33321;
  14242. }
  14243. if (glFormat === 6407) {
  14244. if (glType === 5126) internalFormat = 34837;
  14245. if (glType === 5131) internalFormat = 34843;
  14246. if (glType === 5121) internalFormat = 32849;
  14247. }
  14248. if (glFormat === 6408) {
  14249. if (glType === 5126) internalFormat = 34836;
  14250. if (glType === 5131) internalFormat = 34842;
  14251. if (glType === 5121) internalFormat = 32856;
  14252. }
  14253. if (internalFormat === 33325 || internalFormat === 33326 || internalFormat === 34842 || internalFormat === 34836) {
  14254. extensions.get('EXT_color_buffer_float');
  14255. } else if (internalFormat === 34843 || internalFormat === 34837) {
  14256. console.warn('THREE.WebGLRenderer: Floating point textures with RGB format not supported. Please use RGBA instead.');
  14257. }
  14258. return internalFormat;
  14259. } // Fallback filters for non-power-of-2 textures
  14260. function filterFallback(f) {
  14261. if (f === NearestFilter || f === NearestMipmapNearestFilter || f === NearestMipmapLinearFilter) {
  14262. return 9728;
  14263. }
  14264. return 9729;
  14265. } //
  14266. function onTextureDispose(event) {
  14267. var texture = event.target;
  14268. texture.removeEventListener('dispose', onTextureDispose);
  14269. deallocateTexture(texture);
  14270. if (texture.isVideoTexture) {
  14271. _videoTextures.delete(texture);
  14272. }
  14273. info.memory.textures--;
  14274. }
  14275. function onRenderTargetDispose(event) {
  14276. var renderTarget = event.target;
  14277. renderTarget.removeEventListener('dispose', onRenderTargetDispose);
  14278. deallocateRenderTarget(renderTarget);
  14279. info.memory.textures--;
  14280. } //
  14281. function deallocateTexture(texture) {
  14282. var textureProperties = properties.get(texture);
  14283. if (textureProperties.__webglInit === undefined) return;
  14284. _gl.deleteTexture(textureProperties.__webglTexture);
  14285. properties.remove(texture);
  14286. }
  14287. function deallocateRenderTarget(renderTarget) {
  14288. var renderTargetProperties = properties.get(renderTarget);
  14289. var textureProperties = properties.get(renderTarget.texture);
  14290. if (!renderTarget) return;
  14291. if (textureProperties.__webglTexture !== undefined) {
  14292. _gl.deleteTexture(textureProperties.__webglTexture);
  14293. }
  14294. if (renderTarget.depthTexture) {
  14295. renderTarget.depthTexture.dispose();
  14296. }
  14297. if (renderTarget.isWebGLRenderTargetCube) {
  14298. for (var i = 0; i < 6; i++) {
  14299. _gl.deleteFramebuffer(renderTargetProperties.__webglFramebuffer[i]);
  14300. if (renderTargetProperties.__webglDepthbuffer) _gl.deleteRenderbuffer(renderTargetProperties.__webglDepthbuffer[i]);
  14301. }
  14302. } else {
  14303. _gl.deleteFramebuffer(renderTargetProperties.__webglFramebuffer);
  14304. if (renderTargetProperties.__webglDepthbuffer) _gl.deleteRenderbuffer(renderTargetProperties.__webglDepthbuffer);
  14305. }
  14306. if (renderTarget.isWebGLMultiviewRenderTarget) {
  14307. _gl.deleteTexture(renderTargetProperties.__webglColorTexture);
  14308. _gl.deleteTexture(renderTargetProperties.__webglDepthStencilTexture);
  14309. info.memory.textures -= 2;
  14310. for (var i = 0, il = renderTargetProperties.__webglViewFramebuffers.length; i < il; i++) {
  14311. _gl.deleteFramebuffer(renderTargetProperties.__webglViewFramebuffers[i]);
  14312. }
  14313. }
  14314. properties.remove(renderTarget.texture);
  14315. properties.remove(renderTarget);
  14316. } //
  14317. var textureUnits = 0;
  14318. function resetTextureUnits() {
  14319. textureUnits = 0;
  14320. }
  14321. function allocateTextureUnit() {
  14322. var textureUnit = textureUnits;
  14323. if (textureUnit >= capabilities.maxTextures) {
  14324. console.warn('THREE.WebGLTextures: Trying to use ' + textureUnit + ' texture units while this GPU supports only ' + capabilities.maxTextures);
  14325. }
  14326. textureUnits += 1;
  14327. return textureUnit;
  14328. } //
  14329. function setTexture2D(texture, slot) {
  14330. var textureProperties = properties.get(texture);
  14331. if (texture.isVideoTexture) updateVideoTexture(texture);
  14332. if (texture.version > 0 && textureProperties.__version !== texture.version) {
  14333. var image = texture.image;
  14334. if (image === undefined) {
  14335. console.warn('THREE.WebGLRenderer: Texture marked for update but image is undefined');
  14336. } else if (image.complete === false) {
  14337. console.warn('THREE.WebGLRenderer: Texture marked for update but image is incomplete');
  14338. } else {
  14339. uploadTexture(textureProperties, texture, slot);
  14340. return;
  14341. }
  14342. }
  14343. state.activeTexture(33984 + slot);
  14344. state.bindTexture(3553, textureProperties.__webglTexture);
  14345. }
  14346. function setTexture2DArray(texture, slot) {
  14347. var textureProperties = properties.get(texture);
  14348. if (texture.version > 0 && textureProperties.__version !== texture.version) {
  14349. uploadTexture(textureProperties, texture, slot);
  14350. return;
  14351. }
  14352. state.activeTexture(33984 + slot);
  14353. state.bindTexture(35866, textureProperties.__webglTexture);
  14354. }
  14355. function setTexture3D(texture, slot) {
  14356. var textureProperties = properties.get(texture);
  14357. if (texture.version > 0 && textureProperties.__version !== texture.version) {
  14358. uploadTexture(textureProperties, texture, slot);
  14359. return;
  14360. }
  14361. state.activeTexture(33984 + slot);
  14362. state.bindTexture(32879, textureProperties.__webglTexture);
  14363. }
  14364. function setTextureCube(texture, slot) {
  14365. if (texture.image.length !== 6) return;
  14366. var textureProperties = properties.get(texture);
  14367. if (texture.version > 0 && textureProperties.__version !== texture.version) {
  14368. initTexture(textureProperties, texture);
  14369. state.activeTexture(33984 + slot);
  14370. state.bindTexture(34067, textureProperties.__webglTexture);
  14371. _gl.pixelStorei(37440, texture.flipY);
  14372. var isCompressed = texture && texture.isCompressedTexture;
  14373. var isDataTexture = texture.image[0] && texture.image[0].isDataTexture;
  14374. var cubeImage = [];
  14375. for (var i = 0; i < 6; i++) {
  14376. if (!isCompressed && !isDataTexture) {
  14377. cubeImage[i] = resizeImage(texture.image[i], false, true, capabilities.maxCubemapSize);
  14378. } else {
  14379. cubeImage[i] = isDataTexture ? texture.image[i].image : texture.image[i];
  14380. }
  14381. }
  14382. var image = cubeImage[0],
  14383. supportsMips = isPowerOfTwo(image) || capabilities.isWebGL2,
  14384. glFormat = utils.convert(texture.format),
  14385. glType = utils.convert(texture.type),
  14386. glInternalFormat = getInternalFormat(glFormat, glType);
  14387. setTextureParameters(34067, texture, supportsMips);
  14388. var mipmaps;
  14389. if (isCompressed) {
  14390. for (var i = 0; i < 6; i++) {
  14391. mipmaps = cubeImage[i].mipmaps;
  14392. for (var j = 0; j < mipmaps.length; j++) {
  14393. var mipmap = mipmaps[j];
  14394. if (texture.format !== RGBAFormat && texture.format !== RGBFormat) {
  14395. if (state.getCompressedTextureFormats().indexOf(glFormat) > -1) {
  14396. state.compressedTexImage2D(34069 + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data);
  14397. } else {
  14398. console.warn('THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()');
  14399. }
  14400. } else {
  14401. state.texImage2D(34069 + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data);
  14402. }
  14403. }
  14404. }
  14405. textureProperties.__maxMipLevel = mipmaps.length - 1;
  14406. } else {
  14407. mipmaps = texture.mipmaps;
  14408. for (var i = 0; i < 6; i++) {
  14409. if (isDataTexture) {
  14410. state.texImage2D(34069 + i, 0, glInternalFormat, cubeImage[i].width, cubeImage[i].height, 0, glFormat, glType, cubeImage[i].data);
  14411. for (var j = 0; j < mipmaps.length; j++) {
  14412. var mipmap = mipmaps[j];
  14413. var mipmapImage = mipmap.image[i].image;
  14414. state.texImage2D(34069 + i, j + 1, glInternalFormat, mipmapImage.width, mipmapImage.height, 0, glFormat, glType, mipmapImage.data);
  14415. }
  14416. } else {
  14417. state.texImage2D(34069 + i, 0, glInternalFormat, glFormat, glType, cubeImage[i]);
  14418. for (var j = 0; j < mipmaps.length; j++) {
  14419. var mipmap = mipmaps[j];
  14420. state.texImage2D(34069 + i, j + 1, glInternalFormat, glFormat, glType, mipmap.image[i]);
  14421. }
  14422. }
  14423. }
  14424. textureProperties.__maxMipLevel = mipmaps.length;
  14425. }
  14426. if (textureNeedsGenerateMipmaps(texture, supportsMips)) {
  14427. // We assume images for cube map have the same size.
  14428. generateMipmap(34067, texture, image.width, image.height);
  14429. }
  14430. textureProperties.__version = texture.version;
  14431. if (texture.onUpdate) texture.onUpdate(texture);
  14432. } else {
  14433. state.activeTexture(33984 + slot);
  14434. state.bindTexture(34067, textureProperties.__webglTexture);
  14435. }
  14436. }
  14437. function setTextureCubeDynamic(texture, slot) {
  14438. state.activeTexture(33984 + slot);
  14439. state.bindTexture(34067, properties.get(texture).__webglTexture);
  14440. }
  14441. function setTextureParameters(textureType, texture, supportsMips) {
  14442. var extension;
  14443. if (supportsMips) {
  14444. _gl.texParameteri(textureType, 10242, utils.convert(texture.wrapS));
  14445. _gl.texParameteri(textureType, 10243, utils.convert(texture.wrapT));
  14446. if (textureType === 32879 || textureType === 35866) {
  14447. _gl.texParameteri(textureType, 32882, utils.convert(texture.wrapR));
  14448. }
  14449. _gl.texParameteri(textureType, 10240, utils.convert(texture.magFilter));
  14450. _gl.texParameteri(textureType, 10241, utils.convert(texture.minFilter));
  14451. } else {
  14452. _gl.texParameteri(textureType, 10242, 33071);
  14453. _gl.texParameteri(textureType, 10243, 33071);
  14454. if (textureType === 32879 || textureType === 35866) {
  14455. _gl.texParameteri(textureType, 32882, 33071);
  14456. }
  14457. if (texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping) {
  14458. console.warn('THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping.');
  14459. }
  14460. _gl.texParameteri(textureType, 10240, filterFallback(texture.magFilter));
  14461. _gl.texParameteri(textureType, 10241, filterFallback(texture.minFilter));
  14462. if (texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter) {
  14463. console.warn('THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.');
  14464. }
  14465. }
  14466. extension = extensions.get('EXT_texture_filter_anisotropic');
  14467. if (extension) {
  14468. if (texture.type === FloatType && extensions.get('OES_texture_float_linear') === null) return;
  14469. if (texture.type === HalfFloatType && (capabilities.isWebGL2 || extensions.get('OES_texture_half_float_linear')) === null) return;
  14470. if (texture.anisotropy > 1 || properties.get(texture).__currentAnisotropy) {
  14471. _gl.texParameterf(textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(texture.anisotropy, capabilities.getMaxAnisotropy()));
  14472. properties.get(texture).__currentAnisotropy = texture.anisotropy;
  14473. }
  14474. }
  14475. }
  14476. function initTexture(textureProperties, texture) {
  14477. if (textureProperties.__webglInit === undefined) {
  14478. textureProperties.__webglInit = true;
  14479. texture.addEventListener('dispose', onTextureDispose);
  14480. textureProperties.__webglTexture = _gl.createTexture();
  14481. info.memory.textures++;
  14482. }
  14483. }
  14484. function uploadTexture(textureProperties, texture, slot) {
  14485. var textureType = 3553;
  14486. if (texture.isDataTexture2DArray) textureType = 35866;
  14487. if (texture.isDataTexture3D) textureType = 32879;
  14488. initTexture(textureProperties, texture);
  14489. state.activeTexture(33984 + slot);
  14490. state.bindTexture(textureType, textureProperties.__webglTexture);
  14491. _gl.pixelStorei(37440, texture.flipY);
  14492. _gl.pixelStorei(37441, texture.premultiplyAlpha);
  14493. _gl.pixelStorei(3317, texture.unpackAlignment);
  14494. var needsPowerOfTwo = textureNeedsPowerOfTwo(texture) && isPowerOfTwo(texture.image) === false;
  14495. var image = resizeImage(texture.image, needsPowerOfTwo, false, capabilities.maxTextureSize);
  14496. var supportsMips = isPowerOfTwo(image) || capabilities.isWebGL2,
  14497. glFormat = utils.convert(texture.format),
  14498. glType = utils.convert(texture.type),
  14499. glInternalFormat = getInternalFormat(glFormat, glType);
  14500. setTextureParameters(textureType, texture, supportsMips);
  14501. var mipmap,
  14502. mipmaps = texture.mipmaps;
  14503. if (texture.isDepthTexture) {
  14504. // populate depth texture with dummy data
  14505. glInternalFormat = 6402;
  14506. if (texture.type === FloatType) {
  14507. if (!capabilities.isWebGL2) throw new Error('Float Depth Texture only supported in WebGL2.0');
  14508. glInternalFormat = 36012;
  14509. } else if (capabilities.isWebGL2) {
  14510. // WebGL 2.0 requires signed internalformat for glTexImage2D
  14511. glInternalFormat = 33189;
  14512. }
  14513. if (texture.format === DepthFormat && glInternalFormat === 6402) {
  14514. // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  14515. // DEPTH_COMPONENT and type is not UNSIGNED_SHORT or UNSIGNED_INT
  14516. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  14517. if (texture.type !== UnsignedShortType && texture.type !== UnsignedIntType) {
  14518. console.warn('THREE.WebGLRenderer: Use UnsignedShortType or UnsignedIntType for DepthFormat DepthTexture.');
  14519. texture.type = UnsignedShortType;
  14520. glType = utils.convert(texture.type);
  14521. }
  14522. } // Depth stencil textures need the DEPTH_STENCIL internal format
  14523. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  14524. if (texture.format === DepthStencilFormat) {
  14525. glInternalFormat = 34041; // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  14526. // DEPTH_STENCIL and type is not UNSIGNED_INT_24_8_WEBGL.
  14527. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  14528. if (texture.type !== UnsignedInt248Type) {
  14529. console.warn('THREE.WebGLRenderer: Use UnsignedInt248Type for DepthStencilFormat DepthTexture.');
  14530. texture.type = UnsignedInt248Type;
  14531. glType = utils.convert(texture.type);
  14532. }
  14533. }
  14534. state.texImage2D(3553, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, null);
  14535. } else if (texture.isDataTexture) {
  14536. // use manually created mipmaps if available
  14537. // if there are no manual mipmaps
  14538. // set 0 level mipmap and then use GL to generate other mipmap levels
  14539. if (mipmaps.length > 0 && supportsMips) {
  14540. for (var i = 0, il = mipmaps.length; i < il; i++) {
  14541. mipmap = mipmaps[i];
  14542. state.texImage2D(3553, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data);
  14543. }
  14544. texture.generateMipmaps = false;
  14545. textureProperties.__maxMipLevel = mipmaps.length - 1;
  14546. } else {
  14547. state.texImage2D(3553, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, image.data);
  14548. textureProperties.__maxMipLevel = 0;
  14549. }
  14550. } else if (texture.isCompressedTexture) {
  14551. for (var i = 0, il = mipmaps.length; i < il; i++) {
  14552. mipmap = mipmaps[i];
  14553. if (texture.format !== RGBAFormat && texture.format !== RGBFormat) {
  14554. if (state.getCompressedTextureFormats().indexOf(glFormat) > -1) {
  14555. state.compressedTexImage2D(3553, i, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data);
  14556. } else {
  14557. console.warn('THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()');
  14558. }
  14559. } else {
  14560. state.texImage2D(3553, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data);
  14561. }
  14562. }
  14563. textureProperties.__maxMipLevel = mipmaps.length - 1;
  14564. } else if (texture.isDataTexture2DArray) {
  14565. state.texImage3D(35866, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data);
  14566. textureProperties.__maxMipLevel = 0;
  14567. } else if (texture.isDataTexture3D) {
  14568. state.texImage3D(32879, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data);
  14569. textureProperties.__maxMipLevel = 0;
  14570. } else {
  14571. // regular Texture (image, video, canvas)
  14572. // use manually created mipmaps if available
  14573. // if there are no manual mipmaps
  14574. // set 0 level mipmap and then use GL to generate other mipmap levels
  14575. if (mipmaps.length > 0 && supportsMips) {
  14576. for (var i = 0, il = mipmaps.length; i < il; i++) {
  14577. mipmap = mipmaps[i];
  14578. state.texImage2D(3553, i, glInternalFormat, glFormat, glType, mipmap);
  14579. }
  14580. texture.generateMipmaps = false;
  14581. textureProperties.__maxMipLevel = mipmaps.length - 1;
  14582. } else {
  14583. state.texImage2D(3553, 0, glInternalFormat, glFormat, glType, image);
  14584. textureProperties.__maxMipLevel = 0;
  14585. }
  14586. }
  14587. if (textureNeedsGenerateMipmaps(texture, supportsMips)) {
  14588. generateMipmap(3553, texture, image.width, image.height);
  14589. }
  14590. textureProperties.__version = texture.version;
  14591. if (texture.onUpdate) texture.onUpdate(texture);
  14592. } // Render targets
  14593. // Setup storage for target texture and bind it to correct framebuffer
  14594. function setupFrameBufferTexture(framebuffer, renderTarget, attachment, textureTarget) {
  14595. var glFormat = utils.convert(renderTarget.texture.format);
  14596. var glType = utils.convert(renderTarget.texture.type);
  14597. var glInternalFormat = getInternalFormat(glFormat, glType);
  14598. state.texImage2D(textureTarget, 0, glInternalFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null);
  14599. _gl.bindFramebuffer(36160, framebuffer);
  14600. _gl.framebufferTexture2D(36160, attachment, textureTarget, properties.get(renderTarget.texture).__webglTexture, 0);
  14601. _gl.bindFramebuffer(36160, null);
  14602. } // Setup storage for internal depth/stencil buffers and bind to correct framebuffer
  14603. function setupRenderBufferStorage(renderbuffer, renderTarget, isMultisample) {
  14604. _gl.bindRenderbuffer(36161, renderbuffer);
  14605. if (renderTarget.depthBuffer && !renderTarget.stencilBuffer) {
  14606. if (isMultisample) {
  14607. var samples = getRenderTargetSamples(renderTarget);
  14608. _gl.renderbufferStorageMultisample(36161, samples, 33189, renderTarget.width, renderTarget.height);
  14609. } else {
  14610. _gl.renderbufferStorage(36161, 33189, renderTarget.width, renderTarget.height);
  14611. }
  14612. _gl.framebufferRenderbuffer(36160, 36096, 36161, renderbuffer);
  14613. } else if (renderTarget.depthBuffer && renderTarget.stencilBuffer) {
  14614. if (isMultisample) {
  14615. var samples = getRenderTargetSamples(renderTarget);
  14616. _gl.renderbufferStorageMultisample(36161, samples, 35056, renderTarget.width, renderTarget.height);
  14617. } else {
  14618. _gl.renderbufferStorage(36161, 34041, renderTarget.width, renderTarget.height);
  14619. }
  14620. _gl.framebufferRenderbuffer(36160, 33306, 36161, renderbuffer);
  14621. } else {
  14622. var glFormat = utils.convert(renderTarget.texture.format);
  14623. var glType = utils.convert(renderTarget.texture.type);
  14624. var glInternalFormat = getInternalFormat(glFormat, glType);
  14625. if (isMultisample) {
  14626. var samples = getRenderTargetSamples(renderTarget);
  14627. _gl.renderbufferStorageMultisample(36161, samples, glInternalFormat, renderTarget.width, renderTarget.height);
  14628. } else {
  14629. _gl.renderbufferStorage(36161, glInternalFormat, renderTarget.width, renderTarget.height);
  14630. }
  14631. }
  14632. _gl.bindRenderbuffer(36161, null);
  14633. } // Setup resources for a Depth Texture for a FBO (needs an extension)
  14634. function setupDepthTexture(framebuffer, renderTarget) {
  14635. var isCube = renderTarget && renderTarget.isWebGLRenderTargetCube;
  14636. if (isCube) throw new Error('Depth Texture with cube render targets is not supported');
  14637. _gl.bindFramebuffer(36160, framebuffer);
  14638. if (!(renderTarget.depthTexture && renderTarget.depthTexture.isDepthTexture)) {
  14639. throw new Error('renderTarget.depthTexture must be an instance of THREE.DepthTexture');
  14640. } // upload an empty depth texture with framebuffer size
  14641. if (!properties.get(renderTarget.depthTexture).__webglTexture || renderTarget.depthTexture.image.width !== renderTarget.width || renderTarget.depthTexture.image.height !== renderTarget.height) {
  14642. renderTarget.depthTexture.image.width = renderTarget.width;
  14643. renderTarget.depthTexture.image.height = renderTarget.height;
  14644. renderTarget.depthTexture.needsUpdate = true;
  14645. }
  14646. setTexture2D(renderTarget.depthTexture, 0);
  14647. var webglDepthTexture = properties.get(renderTarget.depthTexture).__webglTexture;
  14648. if (renderTarget.depthTexture.format === DepthFormat) {
  14649. _gl.framebufferTexture2D(36160, 36096, 3553, webglDepthTexture, 0);
  14650. } else if (renderTarget.depthTexture.format === DepthStencilFormat) {
  14651. _gl.framebufferTexture2D(36160, 33306, 3553, webglDepthTexture, 0);
  14652. } else {
  14653. throw new Error('Unknown depthTexture format');
  14654. }
  14655. } // Setup GL resources for a non-texture depth buffer
  14656. function setupDepthRenderbuffer(renderTarget) {
  14657. var renderTargetProperties = properties.get(renderTarget);
  14658. var isCube = renderTarget.isWebGLRenderTargetCube === true;
  14659. if (renderTarget.depthTexture) {
  14660. if (isCube) throw new Error('target.depthTexture not supported in Cube render targets');
  14661. setupDepthTexture(renderTargetProperties.__webglFramebuffer, renderTarget);
  14662. } else {
  14663. if (isCube) {
  14664. renderTargetProperties.__webglDepthbuffer = [];
  14665. for (var i = 0; i < 6; i++) {
  14666. _gl.bindFramebuffer(36160, renderTargetProperties.__webglFramebuffer[i]);
  14667. renderTargetProperties.__webglDepthbuffer[i] = _gl.createRenderbuffer();
  14668. setupRenderBufferStorage(renderTargetProperties.__webglDepthbuffer[i], renderTarget);
  14669. }
  14670. } else {
  14671. _gl.bindFramebuffer(36160, renderTargetProperties.__webglFramebuffer);
  14672. renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer();
  14673. setupRenderBufferStorage(renderTargetProperties.__webglDepthbuffer, renderTarget);
  14674. }
  14675. }
  14676. _gl.bindFramebuffer(36160, null);
  14677. } // Set up GL resources for the render target
  14678. function setupRenderTarget(renderTarget) {
  14679. var renderTargetProperties = properties.get(renderTarget);
  14680. var textureProperties = properties.get(renderTarget.texture);
  14681. renderTarget.addEventListener('dispose', onRenderTargetDispose);
  14682. textureProperties.__webglTexture = _gl.createTexture();
  14683. info.memory.textures++;
  14684. var isCube = renderTarget.isWebGLRenderTargetCube === true;
  14685. var isMultisample = renderTarget.isWebGLMultisampleRenderTarget === true;
  14686. var isMultiview = renderTarget.isWebGLMultiviewRenderTarget === true;
  14687. var supportsMips = isPowerOfTwo(renderTarget) || capabilities.isWebGL2; // Setup framebuffer
  14688. if (isCube) {
  14689. renderTargetProperties.__webglFramebuffer = [];
  14690. for (var i = 0; i < 6; i++) {
  14691. renderTargetProperties.__webglFramebuffer[i] = _gl.createFramebuffer();
  14692. }
  14693. } else {
  14694. renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer();
  14695. if (isMultisample) {
  14696. if (capabilities.isWebGL2) {
  14697. renderTargetProperties.__webglMultisampledFramebuffer = _gl.createFramebuffer();
  14698. renderTargetProperties.__webglColorRenderbuffer = _gl.createRenderbuffer();
  14699. _gl.bindRenderbuffer(36161, renderTargetProperties.__webglColorRenderbuffer);
  14700. var glFormat = utils.convert(renderTarget.texture.format);
  14701. var glType = utils.convert(renderTarget.texture.type);
  14702. var glInternalFormat = getInternalFormat(glFormat, glType);
  14703. var samples = getRenderTargetSamples(renderTarget);
  14704. _gl.renderbufferStorageMultisample(36161, samples, glInternalFormat, renderTarget.width, renderTarget.height);
  14705. _gl.bindFramebuffer(36160, renderTargetProperties.__webglMultisampledFramebuffer);
  14706. _gl.framebufferRenderbuffer(36160, 36064, 36161, renderTargetProperties.__webglColorRenderbuffer);
  14707. _gl.bindRenderbuffer(36161, null);
  14708. if (renderTarget.depthBuffer) {
  14709. renderTargetProperties.__webglDepthRenderbuffer = _gl.createRenderbuffer();
  14710. setupRenderBufferStorage(renderTargetProperties.__webglDepthRenderbuffer, renderTarget, true);
  14711. }
  14712. _gl.bindFramebuffer(36160, null);
  14713. } else {
  14714. console.warn('THREE.WebGLRenderer: WebGLMultisampleRenderTarget can only be used with WebGL2.');
  14715. }
  14716. } else if (isMultiview) {
  14717. var width = renderTarget.width;
  14718. var height = renderTarget.height;
  14719. var numViews = renderTarget.numViews;
  14720. _gl.bindFramebuffer(36160, renderTargetProperties.__webglFramebuffer);
  14721. var ext = extensions.get('OVR_multiview2');
  14722. info.memory.textures += 2;
  14723. var colorTexture = _gl.createTexture();
  14724. _gl.bindTexture(35866, colorTexture);
  14725. _gl.texParameteri(35866, 10240, 9728);
  14726. _gl.texParameteri(35866, 10241, 9728);
  14727. _gl.texImage3D(35866, 0, 32856, width, height, numViews, 0, 6408, 5121, null);
  14728. ext.framebufferTextureMultiviewOVR(36160, 36064, colorTexture, 0, 0, numViews);
  14729. var depthStencilTexture = _gl.createTexture();
  14730. _gl.bindTexture(35866, depthStencilTexture);
  14731. _gl.texParameteri(35866, 10240, 9728);
  14732. _gl.texParameteri(35866, 10241, 9728);
  14733. _gl.texImage3D(35866, 0, 35056, width, height, numViews, 0, 34041, 34042, null);
  14734. ext.framebufferTextureMultiviewOVR(36160, 33306, depthStencilTexture, 0, 0, numViews);
  14735. var viewFramebuffers = new Array(numViews);
  14736. for (var i = 0; i < numViews; ++i) {
  14737. viewFramebuffers[i] = _gl.createFramebuffer();
  14738. _gl.bindFramebuffer(36160, viewFramebuffers[i]);
  14739. _gl.framebufferTextureLayer(36160, 36064, colorTexture, 0, i);
  14740. }
  14741. renderTargetProperties.__webglColorTexture = colorTexture;
  14742. renderTargetProperties.__webglDepthStencilTexture = depthStencilTexture;
  14743. renderTargetProperties.__webglViewFramebuffers = viewFramebuffers;
  14744. _gl.bindFramebuffer(36160, null);
  14745. _gl.bindTexture(35866, null);
  14746. }
  14747. } // Setup color buffer
  14748. if (isCube) {
  14749. state.bindTexture(34067, textureProperties.__webglTexture);
  14750. setTextureParameters(34067, renderTarget.texture, supportsMips);
  14751. for (var i = 0; i < 6; i++) {
  14752. setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer[i], renderTarget, 36064, 34069 + i);
  14753. }
  14754. if (textureNeedsGenerateMipmaps(renderTarget.texture, supportsMips)) {
  14755. generateMipmap(34067, renderTarget.texture, renderTarget.width, renderTarget.height);
  14756. }
  14757. state.bindTexture(34067, null);
  14758. } else if (!isMultiview) {
  14759. state.bindTexture(3553, textureProperties.__webglTexture);
  14760. setTextureParameters(3553, renderTarget.texture, supportsMips);
  14761. setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer, renderTarget, 36064, 3553);
  14762. if (textureNeedsGenerateMipmaps(renderTarget.texture, supportsMips)) {
  14763. generateMipmap(3553, renderTarget.texture, renderTarget.width, renderTarget.height);
  14764. }
  14765. state.bindTexture(3553, null);
  14766. } // Setup depth and stencil buffers
  14767. if (renderTarget.depthBuffer) {
  14768. setupDepthRenderbuffer(renderTarget);
  14769. }
  14770. }
  14771. function updateRenderTargetMipmap(renderTarget) {
  14772. var texture = renderTarget.texture;
  14773. var supportsMips = isPowerOfTwo(renderTarget) || capabilities.isWebGL2;
  14774. if (textureNeedsGenerateMipmaps(texture, supportsMips)) {
  14775. var target = renderTarget.isWebGLRenderTargetCube ? 34067 : 3553;
  14776. var webglTexture = properties.get(texture).__webglTexture;
  14777. state.bindTexture(target, webglTexture);
  14778. generateMipmap(target, texture, renderTarget.width, renderTarget.height);
  14779. state.bindTexture(target, null);
  14780. }
  14781. }
  14782. function updateMultisampleRenderTarget(renderTarget) {
  14783. if (renderTarget.isWebGLMultisampleRenderTarget) {
  14784. if (capabilities.isWebGL2) {
  14785. var renderTargetProperties = properties.get(renderTarget);
  14786. _gl.bindFramebuffer(36008, renderTargetProperties.__webglMultisampledFramebuffer);
  14787. _gl.bindFramebuffer(36009, renderTargetProperties.__webglFramebuffer);
  14788. var width = renderTarget.width;
  14789. var height = renderTarget.height;
  14790. var mask = 16384;
  14791. if (renderTarget.depthBuffer) mask |= 256;
  14792. if (renderTarget.stencilBuffer) mask |= 1024;
  14793. _gl.blitFramebuffer(0, 0, width, height, 0, 0, width, height, mask, 9728);
  14794. } else {
  14795. console.warn('THREE.WebGLRenderer: WebGLMultisampleRenderTarget can only be used with WebGL2.');
  14796. }
  14797. }
  14798. }
  14799. function getRenderTargetSamples(renderTarget) {
  14800. return capabilities.isWebGL2 && renderTarget.isWebGLMultisampleRenderTarget ? Math.min(capabilities.maxSamples, renderTarget.samples) : 0;
  14801. }
  14802. function updateVideoTexture(texture) {
  14803. var frame = info.render.frame; // Check the last frame we updated the VideoTexture
  14804. if (_videoTextures.get(texture) !== frame) {
  14805. _videoTextures.set(texture, frame);
  14806. texture.update();
  14807. }
  14808. } // backwards compatibility
  14809. var warnedTexture2D = false;
  14810. var warnedTextureCube = false;
  14811. function safeSetTexture2D(texture, slot) {
  14812. if (texture && texture.isWebGLRenderTarget) {
  14813. if (warnedTexture2D === false) {
  14814. console.warn("THREE.WebGLTextures.safeSetTexture2D: don't use render targets as textures. Use their .texture property instead.");
  14815. warnedTexture2D = true;
  14816. }
  14817. texture = texture.texture;
  14818. }
  14819. setTexture2D(texture, slot);
  14820. }
  14821. function safeSetTextureCube(texture, slot) {
  14822. if (texture && texture.isWebGLRenderTargetCube) {
  14823. if (warnedTextureCube === false) {
  14824. console.warn("THREE.WebGLTextures.safeSetTextureCube: don't use cube render targets as textures. Use their .texture property instead.");
  14825. warnedTextureCube = true;
  14826. }
  14827. texture = texture.texture;
  14828. } // currently relying on the fact that WebGLRenderTargetCube.texture is a Texture and NOT a CubeTexture
  14829. // TODO: unify these code paths
  14830. if (texture && texture.isCubeTexture || Array.isArray(texture.image) && texture.image.length === 6) {
  14831. // CompressedTexture can have Array in image :/
  14832. // this function alone should take care of cube textures
  14833. setTextureCube(texture, slot);
  14834. } else {
  14835. // assumed: texture property of THREE.WebGLRenderTargetCube
  14836. setTextureCubeDynamic(texture, slot);
  14837. }
  14838. } //
  14839. this.allocateTextureUnit = allocateTextureUnit;
  14840. this.resetTextureUnits = resetTextureUnits;
  14841. this.setTexture2D = setTexture2D;
  14842. this.setTexture2DArray = setTexture2DArray;
  14843. this.setTexture3D = setTexture3D;
  14844. this.setTextureCube = setTextureCube;
  14845. this.setTextureCubeDynamic = setTextureCubeDynamic;
  14846. this.setupRenderTarget = setupRenderTarget;
  14847. this.updateRenderTargetMipmap = updateRenderTargetMipmap;
  14848. this.updateMultisampleRenderTarget = updateMultisampleRenderTarget;
  14849. this.safeSetTexture2D = safeSetTexture2D;
  14850. this.safeSetTextureCube = safeSetTextureCube;
  14851. }
  14852. /**
  14853. * @author thespite / http://www.twitter.com/thespite
  14854. */
  14855. function WebGLUtils(gl, extensions, capabilities) {
  14856. function convert(p) {
  14857. var extension;
  14858. if (p === RepeatWrapping) return 10497;
  14859. if (p === ClampToEdgeWrapping) return 33071;
  14860. if (p === MirroredRepeatWrapping) return 33648;
  14861. if (p === NearestFilter) return 9728;
  14862. if (p === NearestMipmapNearestFilter) return 9984;
  14863. if (p === NearestMipmapLinearFilter) return 9986;
  14864. if (p === LinearFilter) return 9729;
  14865. if (p === LinearMipmapNearestFilter) return 9985;
  14866. if (p === LinearMipmapLinearFilter) return 9987;
  14867. if (p === UnsignedByteType) return 5121;
  14868. if (p === UnsignedShort4444Type) return 32819;
  14869. if (p === UnsignedShort5551Type) return 32820;
  14870. if (p === UnsignedShort565Type) return 33635;
  14871. if (p === ByteType) return 5120;
  14872. if (p === ShortType) return 5122;
  14873. if (p === UnsignedShortType) return 5123;
  14874. if (p === IntType) return 5124;
  14875. if (p === UnsignedIntType) return 5125;
  14876. if (p === FloatType) return 5126;
  14877. if (p === HalfFloatType) {
  14878. if (capabilities.isWebGL2) return 5131;
  14879. extension = extensions.get('OES_texture_half_float');
  14880. if (extension !== null) return extension.HALF_FLOAT_OES;
  14881. }
  14882. if (p === AlphaFormat) return 6406;
  14883. if (p === RGBFormat) return 6407;
  14884. if (p === RGBAFormat) return 6408;
  14885. if (p === LuminanceFormat) return 6409;
  14886. if (p === LuminanceAlphaFormat) return 6410;
  14887. if (p === DepthFormat) return 6402;
  14888. if (p === DepthStencilFormat) return 34041;
  14889. if (p === RedFormat) return 6403;
  14890. if (p === AddEquation) return 32774;
  14891. if (p === SubtractEquation) return 32778;
  14892. if (p === ReverseSubtractEquation) return 32779;
  14893. if (p === ZeroFactor) return 0;
  14894. if (p === OneFactor) return 1;
  14895. if (p === SrcColorFactor) return 768;
  14896. if (p === OneMinusSrcColorFactor) return 769;
  14897. if (p === SrcAlphaFactor) return 770;
  14898. if (p === OneMinusSrcAlphaFactor) return 771;
  14899. if (p === DstAlphaFactor) return 772;
  14900. if (p === OneMinusDstAlphaFactor) return 773;
  14901. if (p === DstColorFactor) return 774;
  14902. if (p === OneMinusDstColorFactor) return 775;
  14903. if (p === SrcAlphaSaturateFactor) return 776;
  14904. if (p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format) {
  14905. extension = extensions.get('WEBGL_compressed_texture_s3tc');
  14906. if (extension !== null) {
  14907. if (p === RGB_S3TC_DXT1_Format) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  14908. if (p === RGBA_S3TC_DXT1_Format) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  14909. if (p === RGBA_S3TC_DXT3_Format) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  14910. if (p === RGBA_S3TC_DXT5_Format) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  14911. }
  14912. }
  14913. if (p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format) {
  14914. extension = extensions.get('WEBGL_compressed_texture_pvrtc');
  14915. if (extension !== null) {
  14916. if (p === RGB_PVRTC_4BPPV1_Format) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  14917. if (p === RGB_PVRTC_2BPPV1_Format) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  14918. if (p === RGBA_PVRTC_4BPPV1_Format) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  14919. if (p === RGBA_PVRTC_2BPPV1_Format) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  14920. }
  14921. }
  14922. if (p === RGB_ETC1_Format) {
  14923. extension = extensions.get('WEBGL_compressed_texture_etc1');
  14924. if (extension !== null) return extension.COMPRESSED_RGB_ETC1_WEBGL;
  14925. }
  14926. 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) {
  14927. extension = extensions.get('WEBGL_compressed_texture_astc');
  14928. if (extension !== null) {
  14929. return p;
  14930. }
  14931. }
  14932. if (p === MinEquation || p === MaxEquation) {
  14933. if (capabilities.isWebGL2) {
  14934. if (p === MinEquation) return 32775;
  14935. if (p === MaxEquation) return 32776;
  14936. }
  14937. extension = extensions.get('EXT_blend_minmax');
  14938. if (extension !== null) {
  14939. if (p === MinEquation) return extension.MIN_EXT;
  14940. if (p === MaxEquation) return extension.MAX_EXT;
  14941. }
  14942. }
  14943. if (p === UnsignedInt248Type) {
  14944. if (capabilities.isWebGL2) return 34042;
  14945. extension = extensions.get('WEBGL_depth_texture');
  14946. if (extension !== null) return extension.UNSIGNED_INT_24_8_WEBGL;
  14947. }
  14948. return 0;
  14949. }
  14950. return {
  14951. convert: convert
  14952. };
  14953. }
  14954. /**
  14955. * @author fernandojsg / http://fernandojsg.com
  14956. * @author Takahiro https://github.com/takahirox
  14957. */
  14958. function WebGLMultiviewRenderTarget(width, height, numViews, options) {
  14959. WebGLRenderTarget.call(this, width, height, options);
  14960. this.depthBuffer = false;
  14961. this.stencilBuffer = false;
  14962. this.numViews = numViews;
  14963. }
  14964. WebGLMultiviewRenderTarget.prototype = Object.assign(Object.create(WebGLRenderTarget.prototype), {
  14965. constructor: WebGLMultiviewRenderTarget,
  14966. isWebGLMultiviewRenderTarget: true,
  14967. copy: function (source) {
  14968. WebGLRenderTarget.prototype.copy.call(this, source);
  14969. this.numViews = source.numViews;
  14970. return this;
  14971. },
  14972. setNumViews: function (numViews) {
  14973. if (this.numViews !== numViews) {
  14974. this.numViews = numViews;
  14975. this.dispose();
  14976. }
  14977. return this;
  14978. }
  14979. });
  14980. /**
  14981. * @author fernandojsg / http://fernandojsg.com
  14982. * @author Takahiro https://github.com/takahirox
  14983. */
  14984. function WebGLMultiview(renderer, gl) {
  14985. var DEFAULT_NUMVIEWS = 2;
  14986. var extensions = renderer.extensions;
  14987. var properties = renderer.properties;
  14988. var renderTarget, currentRenderTarget;
  14989. var mat3, mat4, cameraArray, renderSize;
  14990. var available;
  14991. var maxNumViews = 0; //
  14992. function isAvailable() {
  14993. if (available === undefined) {
  14994. var extension = extensions.get('OVR_multiview2');
  14995. available = extension !== null && gl.getContextAttributes().antialias === false;
  14996. if (available) {
  14997. maxNumViews = gl.getParameter(extension.MAX_VIEWS_OVR);
  14998. renderTarget = new WebGLMultiviewRenderTarget(0, 0, DEFAULT_NUMVIEWS);
  14999. renderSize = new Vector2();
  15000. mat4 = [];
  15001. mat3 = [];
  15002. cameraArray = [];
  15003. for (var i = 0; i < maxNumViews; i++) {
  15004. mat4[i] = new Matrix4();
  15005. mat3[i] = new Matrix3();
  15006. }
  15007. }
  15008. }
  15009. return available;
  15010. }
  15011. function getCameraArray(camera) {
  15012. if (camera.isArrayCamera) return camera.cameras;
  15013. cameraArray[0] = camera;
  15014. return cameraArray;
  15015. }
  15016. function updateCameraProjectionMatricesUniform(camera, uniforms) {
  15017. var cameras = getCameraArray(camera);
  15018. for (var i = 0; i < cameras.length; i++) {
  15019. mat4[i].copy(cameras[i].projectionMatrix);
  15020. }
  15021. uniforms.setValue(gl, 'projectionMatrices', mat4);
  15022. }
  15023. function updateCameraViewMatricesUniform(camera, uniforms) {
  15024. var cameras = getCameraArray(camera);
  15025. for (var i = 0; i < cameras.length; i++) {
  15026. mat4[i].copy(cameras[i].matrixWorldInverse);
  15027. }
  15028. uniforms.setValue(gl, 'viewMatrices', mat4);
  15029. }
  15030. function updateObjectMatricesUniforms(object, camera, uniforms) {
  15031. var cameras = getCameraArray(camera);
  15032. for (var i = 0; i < cameras.length; i++) {
  15033. mat4[i].multiplyMatrices(cameras[i].matrixWorldInverse, object.matrixWorld);
  15034. mat3[i].getNormalMatrix(mat4[i]);
  15035. }
  15036. uniforms.setValue(gl, 'modelViewMatrices', mat4);
  15037. uniforms.setValue(gl, 'normalMatrices', mat3);
  15038. }
  15039. function isMultiviewCompatible(camera) {
  15040. if (camera.isArrayCamera === undefined) return true;
  15041. var cameras = camera.cameras;
  15042. if (cameras.length > maxNumViews) return false;
  15043. for (var i = 1, il = cameras.length; i < il; i++) {
  15044. if (cameras[0].viewport.z !== cameras[i].viewport.z || cameras[0].viewport.w !== cameras[i].viewport.w) return false;
  15045. }
  15046. return true;
  15047. }
  15048. function resizeRenderTarget(camera) {
  15049. if (currentRenderTarget) {
  15050. renderSize.set(currentRenderTarget.width, currentRenderTarget.height);
  15051. } else {
  15052. renderer.getDrawingBufferSize(renderSize);
  15053. }
  15054. if (camera.isArrayCamera) {
  15055. var viewport = camera.cameras[0].viewport;
  15056. renderTarget.setSize(viewport.z, viewport.w);
  15057. renderTarget.setNumViews(camera.cameras.length);
  15058. } else {
  15059. renderTarget.setSize(renderSize.x, renderSize.y);
  15060. renderTarget.setNumViews(DEFAULT_NUMVIEWS);
  15061. }
  15062. }
  15063. function attachCamera(camera) {
  15064. if (isMultiviewCompatible(camera) === false) return;
  15065. currentRenderTarget = renderer.getRenderTarget();
  15066. resizeRenderTarget(camera);
  15067. renderer.setRenderTarget(renderTarget);
  15068. }
  15069. function detachCamera(camera) {
  15070. if (renderTarget !== renderer.getRenderTarget()) return;
  15071. renderer.setRenderTarget(currentRenderTarget);
  15072. flush(camera);
  15073. }
  15074. function flush(camera) {
  15075. var srcRenderTarget = renderTarget;
  15076. var numViews = srcRenderTarget.numViews;
  15077. var srcFramebuffers = properties.get(srcRenderTarget).__webglViewFramebuffers;
  15078. var viewWidth = srcRenderTarget.width;
  15079. var viewHeight = srcRenderTarget.height;
  15080. if (camera.isArrayCamera) {
  15081. for (var i = 0; i < numViews; i++) {
  15082. var viewport = camera.cameras[i].viewport;
  15083. var x1 = viewport.x;
  15084. var y1 = viewport.y;
  15085. var x2 = x1 + viewport.z;
  15086. var y2 = y1 + viewport.w;
  15087. gl.bindFramebuffer(36008, srcFramebuffers[i]);
  15088. gl.blitFramebuffer(0, 0, viewWidth, viewHeight, x1, y1, x2, y2, 16384, 9728);
  15089. }
  15090. } else {
  15091. gl.bindFramebuffer(36008, srcFramebuffers[0]);
  15092. gl.blitFramebuffer(0, 0, viewWidth, viewHeight, 0, 0, renderSize.x, renderSize.y, 16384, 9728);
  15093. }
  15094. }
  15095. this.isAvailable = isAvailable;
  15096. this.attachCamera = attachCamera;
  15097. this.detachCamera = detachCamera;
  15098. this.updateCameraProjectionMatricesUniform = updateCameraProjectionMatricesUniform;
  15099. this.updateCameraViewMatricesUniform = updateCameraViewMatricesUniform;
  15100. this.updateObjectMatricesUniforms = updateObjectMatricesUniforms;
  15101. }
  15102. /**
  15103. * @author mrdoob / http://mrdoob.com/
  15104. */
  15105. function Group() {
  15106. Object3D.call(this);
  15107. this.type = 'Group';
  15108. }
  15109. Group.prototype = Object.assign(Object.create(Object3D.prototype), {
  15110. constructor: Group,
  15111. isGroup: true
  15112. });
  15113. /**
  15114. * @author mrdoob / http://mrdoob.com/
  15115. */
  15116. function ArrayCamera(array) {
  15117. PerspectiveCamera.call(this);
  15118. this.cameras = array || [];
  15119. }
  15120. ArrayCamera.prototype = Object.assign(Object.create(PerspectiveCamera.prototype), {
  15121. constructor: ArrayCamera,
  15122. isArrayCamera: true
  15123. });
  15124. /**
  15125. * @author jsantell / https://www.jsantell.com/
  15126. * @author mrdoob / http://mrdoob.com/
  15127. */
  15128. var cameraLPos = new Vector3();
  15129. var cameraRPos = new Vector3();
  15130. /**
  15131. * Assumes 2 cameras that are parallel and share an X-axis, and that
  15132. * the cameras' projection and world matrices have already been set.
  15133. * And that near and far planes are identical for both cameras.
  15134. * Visualization of this technique: https://computergraphics.stackexchange.com/a/4765
  15135. */
  15136. function setProjectionFromUnion(camera, cameraL, cameraR) {
  15137. cameraLPos.setFromMatrixPosition(cameraL.matrixWorld);
  15138. cameraRPos.setFromMatrixPosition(cameraR.matrixWorld);
  15139. var ipd = cameraLPos.distanceTo(cameraRPos);
  15140. var projL = cameraL.projectionMatrix.elements;
  15141. var projR = cameraR.projectionMatrix.elements; // VR systems will have identical far and near planes, and
  15142. // most likely identical top and bottom frustum extents.
  15143. // Use the left camera for these values.
  15144. var near = projL[14] / (projL[10] - 1);
  15145. var far = projL[14] / (projL[10] + 1);
  15146. var topFov = (projL[9] + 1) / projL[5];
  15147. var bottomFov = (projL[9] - 1) / projL[5];
  15148. var leftFov = (projL[8] - 1) / projL[0];
  15149. var rightFov = (projR[8] + 1) / projR[0];
  15150. var left = near * leftFov;
  15151. var right = near * rightFov; // Calculate the new camera's position offset from the
  15152. // left camera. xOffset should be roughly half `ipd`.
  15153. var zOffset = ipd / (-leftFov + rightFov);
  15154. var xOffset = zOffset * -leftFov; // TODO: Better way to apply this offset?
  15155. cameraL.matrixWorld.decompose(camera.position, camera.quaternion, camera.scale);
  15156. camera.translateX(xOffset);
  15157. camera.translateZ(zOffset);
  15158. camera.matrixWorld.compose(camera.position, camera.quaternion, camera.scale);
  15159. camera.matrixWorldInverse.getInverse(camera.matrixWorld); // Find the union of the frustum values of the cameras and scale
  15160. // the values so that the near plane's position does not change in world space,
  15161. // although must now be relative to the new union camera.
  15162. var near2 = near + zOffset;
  15163. var far2 = far + zOffset;
  15164. var left2 = left - xOffset;
  15165. var right2 = right + (ipd - xOffset);
  15166. var top2 = topFov * far / far2 * near2;
  15167. var bottom2 = bottomFov * far / far2 * near2;
  15168. camera.projectionMatrix.makePerspective(left2, right2, top2, bottom2, near2, far2);
  15169. }
  15170. /**
  15171. * @author mrdoob / http://mrdoob.com/
  15172. */
  15173. function WebVRManager(renderer) {
  15174. var renderWidth, renderHeight;
  15175. var scope = this;
  15176. var device = null;
  15177. var frameData = null;
  15178. var poseTarget = null;
  15179. var controllers = [];
  15180. var standingMatrix = new Matrix4();
  15181. var standingMatrixInverse = new Matrix4();
  15182. var framebufferScaleFactor = 1.0;
  15183. var referenceSpaceType = 'local-floor';
  15184. if (typeof window !== 'undefined' && 'VRFrameData' in window) {
  15185. frameData = new window.VRFrameData();
  15186. window.addEventListener('vrdisplaypresentchange', onVRDisplayPresentChange, false);
  15187. }
  15188. var matrixWorldInverse = new Matrix4();
  15189. var tempQuaternion = new Quaternion();
  15190. var tempPosition = new Vector3();
  15191. var cameraL = new PerspectiveCamera();
  15192. cameraL.viewport = new Vector4();
  15193. cameraL.layers.enable(1);
  15194. var cameraR = new PerspectiveCamera();
  15195. cameraR.viewport = new Vector4();
  15196. cameraR.layers.enable(2);
  15197. var cameraVR = new ArrayCamera([cameraL, cameraR]);
  15198. cameraVR.layers.enable(1);
  15199. cameraVR.layers.enable(2); //
  15200. function isPresenting() {
  15201. return device !== null && device.isPresenting === true;
  15202. }
  15203. var currentSize = new Vector2(),
  15204. currentPixelRatio;
  15205. function onVRDisplayPresentChange() {
  15206. if (isPresenting()) {
  15207. var eyeParameters = device.getEyeParameters('left');
  15208. renderWidth = 2 * eyeParameters.renderWidth * framebufferScaleFactor;
  15209. renderHeight = eyeParameters.renderHeight * framebufferScaleFactor;
  15210. currentPixelRatio = renderer.getPixelRatio();
  15211. renderer.getSize(currentSize);
  15212. renderer.setDrawingBufferSize(renderWidth, renderHeight, 1);
  15213. cameraL.viewport.set(0, 0, renderWidth / 2, renderHeight);
  15214. cameraR.viewport.set(renderWidth / 2, 0, renderWidth / 2, renderHeight);
  15215. animation.start();
  15216. scope.dispatchEvent({
  15217. type: 'sessionstart'
  15218. });
  15219. } else {
  15220. if (scope.enabled) {
  15221. renderer.setDrawingBufferSize(currentSize.width, currentSize.height, currentPixelRatio);
  15222. }
  15223. animation.stop();
  15224. scope.dispatchEvent({
  15225. type: 'sessionend'
  15226. });
  15227. }
  15228. } //
  15229. var triggers = [];
  15230. function findGamepad(id) {
  15231. var gamepads = navigator.getGamepads && navigator.getGamepads();
  15232. for (var i = 0, j = 0, l = gamepads.length; i < l; i++) {
  15233. var gamepad = gamepads[i];
  15234. 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'))) {
  15235. if (j === id) return gamepad;
  15236. j++;
  15237. }
  15238. }
  15239. }
  15240. function updateControllers() {
  15241. for (var i = 0; i < controllers.length; i++) {
  15242. var controller = controllers[i];
  15243. var gamepad = findGamepad(i);
  15244. if (gamepad !== undefined && gamepad.pose !== undefined) {
  15245. if (gamepad.pose === null) return; // Pose
  15246. var pose = gamepad.pose;
  15247. if (pose.hasPosition === false) controller.position.set(0.2, -0.6, -0.05);
  15248. if (pose.position !== null) controller.position.fromArray(pose.position);
  15249. if (pose.orientation !== null) controller.quaternion.fromArray(pose.orientation);
  15250. controller.matrix.compose(controller.position, controller.quaternion, controller.scale);
  15251. controller.matrix.premultiply(standingMatrix);
  15252. controller.matrix.decompose(controller.position, controller.quaternion, controller.scale);
  15253. controller.matrixWorldNeedsUpdate = true;
  15254. controller.visible = true; // Trigger
  15255. var buttonId = gamepad.id === 'Daydream Controller' ? 0 : 1;
  15256. if (triggers[i] === undefined) triggers[i] = false;
  15257. if (triggers[i] !== gamepad.buttons[buttonId].pressed) {
  15258. triggers[i] = gamepad.buttons[buttonId].pressed;
  15259. if (triggers[i] === true) {
  15260. controller.dispatchEvent({
  15261. type: 'selectstart'
  15262. });
  15263. } else {
  15264. controller.dispatchEvent({
  15265. type: 'selectend'
  15266. });
  15267. controller.dispatchEvent({
  15268. type: 'select'
  15269. });
  15270. }
  15271. }
  15272. } else {
  15273. controller.visible = false;
  15274. }
  15275. }
  15276. }
  15277. function updateViewportFromBounds(viewport, bounds) {
  15278. if (bounds !== null && bounds.length === 4) {
  15279. viewport.set(bounds[0] * renderWidth, bounds[1] * renderHeight, bounds[2] * renderWidth, bounds[3] * renderHeight);
  15280. }
  15281. } //
  15282. this.enabled = false;
  15283. this.getController = function (id) {
  15284. var controller = controllers[id];
  15285. if (controller === undefined) {
  15286. controller = new Group();
  15287. controller.matrixAutoUpdate = false;
  15288. controller.visible = false;
  15289. controllers[id] = controller;
  15290. }
  15291. return controller;
  15292. };
  15293. this.getDevice = function () {
  15294. return device;
  15295. };
  15296. this.setDevice = function (value) {
  15297. if (value !== undefined) device = value;
  15298. animation.setContext(value);
  15299. };
  15300. this.setFramebufferScaleFactor = function (value) {
  15301. framebufferScaleFactor = value;
  15302. };
  15303. this.setReferenceSpaceType = function (value) {
  15304. referenceSpaceType = value;
  15305. };
  15306. this.setPoseTarget = function (object) {
  15307. if (object !== undefined) poseTarget = object;
  15308. };
  15309. this.getCamera = function (camera) {
  15310. var userHeight = referenceSpaceType === 'local-floor' ? 1.6 : 0;
  15311. if (isPresenting() === false) {
  15312. camera.position.set(0, userHeight, 0);
  15313. camera.rotation.set(0, 0, 0);
  15314. return camera;
  15315. }
  15316. device.depthNear = camera.near;
  15317. device.depthFar = camera.far;
  15318. device.getFrameData(frameData); //
  15319. if (referenceSpaceType === 'local-floor') {
  15320. var stageParameters = device.stageParameters;
  15321. if (stageParameters) {
  15322. standingMatrix.fromArray(stageParameters.sittingToStandingTransform);
  15323. } else {
  15324. standingMatrix.makeTranslation(0, userHeight, 0);
  15325. }
  15326. }
  15327. var pose = frameData.pose;
  15328. var poseObject = poseTarget !== null ? poseTarget : camera; // We want to manipulate poseObject by its position and quaternion components since users may rely on them.
  15329. poseObject.matrix.copy(standingMatrix);
  15330. poseObject.matrix.decompose(poseObject.position, poseObject.quaternion, poseObject.scale);
  15331. if (pose.orientation !== null) {
  15332. tempQuaternion.fromArray(pose.orientation);
  15333. poseObject.quaternion.multiply(tempQuaternion);
  15334. }
  15335. if (pose.position !== null) {
  15336. tempQuaternion.setFromRotationMatrix(standingMatrix);
  15337. tempPosition.fromArray(pose.position);
  15338. tempPosition.applyQuaternion(tempQuaternion);
  15339. poseObject.position.add(tempPosition);
  15340. }
  15341. poseObject.updateMatrixWorld(); //
  15342. cameraL.near = camera.near;
  15343. cameraR.near = camera.near;
  15344. cameraL.far = camera.far;
  15345. cameraR.far = camera.far;
  15346. cameraL.matrixWorldInverse.fromArray(frameData.leftViewMatrix);
  15347. cameraR.matrixWorldInverse.fromArray(frameData.rightViewMatrix); // TODO (mrdoob) Double check this code
  15348. standingMatrixInverse.getInverse(standingMatrix);
  15349. if (referenceSpaceType === 'local-floor') {
  15350. cameraL.matrixWorldInverse.multiply(standingMatrixInverse);
  15351. cameraR.matrixWorldInverse.multiply(standingMatrixInverse);
  15352. }
  15353. var parent = poseObject.parent;
  15354. if (parent !== null) {
  15355. matrixWorldInverse.getInverse(parent.matrixWorld);
  15356. cameraL.matrixWorldInverse.multiply(matrixWorldInverse);
  15357. cameraR.matrixWorldInverse.multiply(matrixWorldInverse);
  15358. } // envMap and Mirror needs camera.matrixWorld
  15359. cameraL.matrixWorld.getInverse(cameraL.matrixWorldInverse);
  15360. cameraR.matrixWorld.getInverse(cameraR.matrixWorldInverse);
  15361. cameraL.projectionMatrix.fromArray(frameData.leftProjectionMatrix);
  15362. cameraR.projectionMatrix.fromArray(frameData.rightProjectionMatrix);
  15363. setProjectionFromUnion(cameraVR, cameraL, cameraR); //
  15364. var layers = device.getLayers();
  15365. if (layers.length) {
  15366. var layer = layers[0];
  15367. updateViewportFromBounds(cameraL.viewport, layer.leftBounds);
  15368. updateViewportFromBounds(cameraR.viewport, layer.rightBounds);
  15369. }
  15370. updateControllers();
  15371. return cameraVR;
  15372. };
  15373. this.getStandingMatrix = function () {
  15374. return standingMatrix;
  15375. };
  15376. this.isPresenting = isPresenting; // Animation Loop
  15377. var animation = new WebGLAnimation();
  15378. this.setAnimationLoop = function (callback) {
  15379. animation.setAnimationLoop(callback);
  15380. if (isPresenting()) animation.start();
  15381. };
  15382. this.submitFrame = function () {
  15383. if (isPresenting()) device.submitFrame();
  15384. };
  15385. this.dispose = function () {
  15386. if (typeof window !== 'undefined') {
  15387. window.removeEventListener('vrdisplaypresentchange', onVRDisplayPresentChange);
  15388. }
  15389. }; // DEPRECATED
  15390. this.setFrameOfReferenceType = function () {
  15391. console.warn('THREE.WebVRManager: setFrameOfReferenceType() has been deprecated.');
  15392. };
  15393. }
  15394. Object.assign(WebVRManager.prototype, EventDispatcher.prototype);
  15395. /**
  15396. * @author mrdoob / http://mrdoob.com/
  15397. */
  15398. function WebXRManager(renderer, gl) {
  15399. var scope = this;
  15400. var session = null; // var framebufferScaleFactor = 1.0;
  15401. var referenceSpace = null;
  15402. var referenceSpaceType = 'local-floor';
  15403. var pose = null;
  15404. var controllers = [];
  15405. var inputSources = [];
  15406. function isPresenting() {
  15407. return session !== null && referenceSpace !== null;
  15408. } //
  15409. var cameraL = new PerspectiveCamera();
  15410. cameraL.layers.enable(1);
  15411. cameraL.viewport = new Vector4();
  15412. var cameraR = new PerspectiveCamera();
  15413. cameraR.layers.enable(2);
  15414. cameraR.viewport = new Vector4();
  15415. var cameraVR = new ArrayCamera([cameraL, cameraR]);
  15416. cameraVR.layers.enable(1);
  15417. cameraVR.layers.enable(2); //
  15418. this.enabled = false;
  15419. this.getController = function (id) {
  15420. var controller = controllers[id];
  15421. if (controller === undefined) {
  15422. controller = new Group();
  15423. controller.matrixAutoUpdate = false;
  15424. controller.visible = false;
  15425. controllers[id] = controller;
  15426. }
  15427. return controller;
  15428. }; //
  15429. function onSessionEvent(event) {
  15430. for (var i = 0; i < controllers.length; i++) {
  15431. if (inputSources[i] === event.inputSource) {
  15432. controllers[i].dispatchEvent({
  15433. type: event.type
  15434. });
  15435. }
  15436. }
  15437. }
  15438. function onSessionEnd() {
  15439. renderer.setFramebuffer(null);
  15440. renderer.setRenderTarget(renderer.getRenderTarget()); // Hack #15830
  15441. animation.stop();
  15442. scope.dispatchEvent({
  15443. type: 'sessionend'
  15444. });
  15445. }
  15446. function onRequestReferenceSpace(value) {
  15447. referenceSpace = value;
  15448. animation.setContext(session);
  15449. animation.start();
  15450. scope.dispatchEvent({
  15451. type: 'sessionstart'
  15452. });
  15453. }
  15454. this.setFramebufferScaleFactor = function ()
  15455. /* value */
  15456. {// framebufferScaleFactor = value;
  15457. };
  15458. this.setReferenceSpaceType = function (value) {
  15459. referenceSpaceType = value;
  15460. };
  15461. this.getSession = function () {
  15462. return session;
  15463. };
  15464. this.setSession = function (value) {
  15465. session = value;
  15466. if (session !== null) {
  15467. session.addEventListener('select', onSessionEvent);
  15468. session.addEventListener('selectstart', onSessionEvent);
  15469. session.addEventListener('selectend', onSessionEvent);
  15470. session.addEventListener('end', onSessionEnd); // eslint-disable-next-line no-undef
  15471. session.updateRenderState({
  15472. baseLayer: new XRWebGLLayer(session, gl)
  15473. });
  15474. session.requestReferenceSpace(referenceSpaceType).then(onRequestReferenceSpace); //
  15475. inputSources = session.inputSources;
  15476. session.addEventListener('inputsourceschange', function () {
  15477. inputSources = session.inputSources;
  15478. console.log(inputSources);
  15479. for (var i = 0; i < controllers.length; i++) {
  15480. var controller = controllers[i];
  15481. controller.userData.inputSource = inputSources[i];
  15482. }
  15483. });
  15484. }
  15485. };
  15486. function updateCamera(camera, parent) {
  15487. if (parent === null) {
  15488. camera.matrixWorld.copy(camera.matrix);
  15489. } else {
  15490. camera.matrixWorld.multiplyMatrices(parent.matrixWorld, camera.matrix);
  15491. }
  15492. camera.matrixWorldInverse.getInverse(camera.matrixWorld);
  15493. }
  15494. this.getCamera = function (camera) {
  15495. if (isPresenting()) {
  15496. var parent = camera.parent;
  15497. var cameras = cameraVR.cameras;
  15498. updateCamera(cameraVR, parent);
  15499. for (var i = 0; i < cameras.length; i++) {
  15500. updateCamera(cameras[i], parent);
  15501. } // update camera and its children
  15502. camera.matrixWorld.copy(cameraVR.matrixWorld);
  15503. var children = camera.children;
  15504. for (var i = 0, l = children.length; i < l; i++) {
  15505. children[i].updateMatrixWorld(true);
  15506. }
  15507. setProjectionFromUnion(cameraVR, cameraL, cameraR);
  15508. return cameraVR;
  15509. }
  15510. return camera;
  15511. };
  15512. this.isPresenting = isPresenting; // Animation Loop
  15513. var onAnimationFrameCallback = null;
  15514. function onAnimationFrame(time, frame) {
  15515. pose = frame.getViewerPose(referenceSpace);
  15516. if (pose !== null) {
  15517. var views = pose.views;
  15518. var baseLayer = session.renderState.baseLayer;
  15519. renderer.setFramebuffer(baseLayer.framebuffer);
  15520. for (var i = 0; i < views.length; i++) {
  15521. var view = views[i];
  15522. var viewport = baseLayer.getViewport(view);
  15523. var viewMatrix = view.transform.inverse.matrix;
  15524. var camera = cameraVR.cameras[i];
  15525. camera.matrix.fromArray(viewMatrix).getInverse(camera.matrix);
  15526. camera.projectionMatrix.fromArray(view.projectionMatrix);
  15527. camera.viewport.set(viewport.x, viewport.y, viewport.width, viewport.height);
  15528. if (i === 0) {
  15529. cameraVR.matrix.copy(camera.matrix);
  15530. }
  15531. }
  15532. } //
  15533. for (var i = 0; i < controllers.length; i++) {
  15534. var controller = controllers[i];
  15535. var inputSource = inputSources[i];
  15536. if (inputSource) {
  15537. var inputPose = frame.getPose(inputSource.targetRaySpace, referenceSpace);
  15538. if (inputPose !== null) {
  15539. controller.matrix.fromArray(inputPose.transform.matrix);
  15540. controller.matrix.decompose(controller.position, controller.rotation, controller.scale);
  15541. controller.visible = true;
  15542. continue;
  15543. }
  15544. }
  15545. controller.visible = false;
  15546. }
  15547. if (onAnimationFrameCallback) onAnimationFrameCallback(time);
  15548. }
  15549. var animation = new WebGLAnimation();
  15550. animation.setAnimationLoop(onAnimationFrame);
  15551. this.setAnimationLoop = function (callback) {
  15552. onAnimationFrameCallback = callback;
  15553. };
  15554. this.dispose = function () {}; // DEPRECATED
  15555. this.getStandingMatrix = function () {
  15556. console.warn('THREE.WebXRManager: getStandingMatrix() is no longer needed.');
  15557. return new Matrix4();
  15558. };
  15559. this.getDevice = function () {
  15560. console.warn('THREE.WebXRManager: getDevice() has been deprecated.');
  15561. };
  15562. this.setDevice = function () {
  15563. console.warn('THREE.WebXRManager: setDevice() has been deprecated.');
  15564. };
  15565. this.setFrameOfReferenceType = function () {
  15566. console.warn('THREE.WebXRManager: setFrameOfReferenceType() has been deprecated.');
  15567. };
  15568. this.submitFrame = function () {};
  15569. }
  15570. Object.assign(WebXRManager.prototype, EventDispatcher.prototype);
  15571. /**
  15572. * @author supereggbert / http://www.paulbrunt.co.uk/
  15573. * @author mrdoob / http://mrdoob.com/
  15574. * @author alteredq / http://alteredqualia.com/
  15575. * @author szimek / https://github.com/szimek/
  15576. * @author tschw
  15577. */
  15578. function WebGLRenderer(parameters) {
  15579. parameters = parameters || {};
  15580. var _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElementNS('http://www.w3.org/1999/xhtml', 'canvas'),
  15581. _context = parameters.context !== undefined ? parameters.context : null,
  15582. _alpha = parameters.alpha !== undefined ? parameters.alpha : false,
  15583. _depth = parameters.depth !== undefined ? parameters.depth : true,
  15584. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  15585. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  15586. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  15587. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false,
  15588. _powerPreference = parameters.powerPreference !== undefined ? parameters.powerPreference : 'default',
  15589. _failIfMajorPerformanceCaveat = parameters.failIfMajorPerformanceCaveat !== undefined ? parameters.failIfMajorPerformanceCaveat : false;
  15590. var currentRenderList = null;
  15591. var currentRenderState = null; // public properties
  15592. this.domElement = _canvas; // Debug configuration container
  15593. this.debug = {
  15594. /**
  15595. * Enables error checking and reporting when shader programs are being compiled
  15596. * @type {boolean}
  15597. */
  15598. checkShaderErrors: true
  15599. }; // clearing
  15600. this.autoClear = true;
  15601. this.autoClearColor = true;
  15602. this.autoClearDepth = true;
  15603. this.autoClearStencil = true; // scene graph
  15604. this.sortObjects = true; // user-defined clipping
  15605. this.clippingPlanes = [];
  15606. this.localClippingEnabled = false; // physically based shading
  15607. this.gammaFactor = 2.0; // for backwards compatibility
  15608. this.gammaInput = false;
  15609. this.gammaOutput = false; // physical lights
  15610. this.physicallyCorrectLights = false; // tone mapping
  15611. this.toneMapping = LinearToneMapping;
  15612. this.toneMappingExposure = 1.0;
  15613. this.toneMappingWhitePoint = 1.0; // morphs
  15614. this.maxMorphTargets = 8;
  15615. this.maxMorphNormals = 4; // internal properties
  15616. var _this = this,
  15617. _isContextLost = false,
  15618. // internal state cache
  15619. _framebuffer = null,
  15620. _currentActiveCubeFace = 0,
  15621. _currentActiveMipmapLevel = 0,
  15622. _currentRenderTarget = null,
  15623. _currentFramebuffer = null,
  15624. _currentMaterialId = -1,
  15625. // geometry and program caching
  15626. _currentGeometryProgram = {
  15627. geometry: null,
  15628. program: null,
  15629. wireframe: false
  15630. },
  15631. _currentCamera = null,
  15632. _currentArrayCamera = null,
  15633. _currentViewport = new Vector4(),
  15634. _currentScissor = new Vector4(),
  15635. _currentScissorTest = null,
  15636. //
  15637. _width = _canvas.width,
  15638. _height = _canvas.height,
  15639. _pixelRatio = 1,
  15640. _viewport = new Vector4(0, 0, _width, _height),
  15641. _scissor = new Vector4(0, 0, _width, _height),
  15642. _scissorTest = false,
  15643. // frustum
  15644. _frustum = new Frustum(),
  15645. // clipping
  15646. _clipping = new WebGLClipping(),
  15647. _clippingEnabled = false,
  15648. _localClippingEnabled = false,
  15649. // camera matrices cache
  15650. _projScreenMatrix = new Matrix4(),
  15651. _vector3 = new Vector3();
  15652. function getTargetPixelRatio() {
  15653. return _currentRenderTarget === null ? _pixelRatio : 1;
  15654. } // initialize
  15655. var _gl;
  15656. try {
  15657. var contextAttributes = {
  15658. alpha: _alpha,
  15659. depth: _depth,
  15660. stencil: _stencil,
  15661. antialias: _antialias,
  15662. premultipliedAlpha: _premultipliedAlpha,
  15663. preserveDrawingBuffer: _preserveDrawingBuffer,
  15664. powerPreference: _powerPreference,
  15665. failIfMajorPerformanceCaveat: _failIfMajorPerformanceCaveat,
  15666. xrCompatible: true
  15667. }; // event listeners must be registered before WebGL context is created, see #12753
  15668. _canvas.addEventListener('webglcontextlost', onContextLost, false);
  15669. _canvas.addEventListener('webglcontextrestored', onContextRestore, false);
  15670. _gl = _context || _canvas.getContext('webgl', contextAttributes) || _canvas.getContext('experimental-webgl', contextAttributes);
  15671. if (_gl === null) {
  15672. if (_canvas.getContext('webgl') !== null) {
  15673. throw new Error('Error creating WebGL context with your selected attributes.');
  15674. } else {
  15675. throw new Error('Error creating WebGL context.');
  15676. }
  15677. } // Some experimental-webgl implementations do not have getShaderPrecisionFormat
  15678. if (_gl.getShaderPrecisionFormat === undefined) {
  15679. _gl.getShaderPrecisionFormat = function () {
  15680. return {
  15681. 'rangeMin': 1,
  15682. 'rangeMax': 1,
  15683. 'precision': 1
  15684. };
  15685. };
  15686. }
  15687. } catch (error) {
  15688. console.error('THREE.WebGLRenderer: ' + error.message);
  15689. throw error;
  15690. }
  15691. var extensions, capabilities, state, info;
  15692. var properties, textures, attributes, geometries, objects;
  15693. var programCache, renderLists, renderStates;
  15694. var background, morphtargets, bufferRenderer, indexedBufferRenderer;
  15695. var utils;
  15696. function initGLContext() {
  15697. extensions = new WebGLExtensions(_gl);
  15698. capabilities = new WebGLCapabilities(_gl, extensions, parameters);
  15699. if (capabilities.isWebGL2 === false) {
  15700. extensions.get('WEBGL_depth_texture');
  15701. extensions.get('OES_texture_float');
  15702. extensions.get('OES_texture_half_float');
  15703. extensions.get('OES_texture_half_float_linear');
  15704. extensions.get('OES_standard_derivatives');
  15705. extensions.get('OES_element_index_uint');
  15706. extensions.get('ANGLE_instanced_arrays');
  15707. }
  15708. extensions.get('OES_texture_float_linear');
  15709. utils = new WebGLUtils(_gl, extensions, capabilities);
  15710. state = new WebGLState(_gl, extensions, utils, capabilities);
  15711. state.scissor(_currentScissor.copy(_scissor).multiplyScalar(_pixelRatio).floor());
  15712. state.viewport(_currentViewport.copy(_viewport).multiplyScalar(_pixelRatio).floor());
  15713. info = new WebGLInfo(_gl);
  15714. properties = new WebGLProperties();
  15715. textures = new WebGLTextures(_gl, extensions, state, properties, capabilities, utils, info);
  15716. attributes = new WebGLAttributes(_gl);
  15717. geometries = new WebGLGeometries(_gl, attributes, info);
  15718. objects = new WebGLObjects(_gl, geometries, attributes, info);
  15719. morphtargets = new WebGLMorphtargets(_gl);
  15720. programCache = new WebGLPrograms(_this, extensions, capabilities);
  15721. renderLists = new WebGLRenderLists();
  15722. renderStates = new WebGLRenderStates();
  15723. background = new WebGLBackground(_this, state, objects, _premultipliedAlpha);
  15724. bufferRenderer = new WebGLBufferRenderer(_gl, extensions, info, capabilities);
  15725. indexedBufferRenderer = new WebGLIndexedBufferRenderer(_gl, extensions, info, capabilities);
  15726. info.programs = programCache.programs;
  15727. _this.capabilities = capabilities;
  15728. _this.extensions = extensions;
  15729. _this.properties = properties;
  15730. _this.renderLists = renderLists;
  15731. _this.state = state;
  15732. _this.info = info;
  15733. }
  15734. initGLContext(); // vr
  15735. var vr = typeof navigator !== 'undefined' && 'xr' in navigator && 'supportsSession' in navigator.xr ? new WebXRManager(_this, _gl) : new WebVRManager(_this);
  15736. this.vr = vr; // Multiview
  15737. var multiview = new WebGLMultiview(_this, _gl); // shadow map
  15738. var shadowMap = new WebGLShadowMap(_this, objects, capabilities.maxTextureSize);
  15739. this.shadowMap = shadowMap; // API
  15740. this.getContext = function () {
  15741. return _gl;
  15742. };
  15743. this.getContextAttributes = function () {
  15744. return _gl.getContextAttributes();
  15745. };
  15746. this.forceContextLoss = function () {
  15747. var extension = extensions.get('WEBGL_lose_context');
  15748. if (extension) extension.loseContext();
  15749. };
  15750. this.forceContextRestore = function () {
  15751. var extension = extensions.get('WEBGL_lose_context');
  15752. if (extension) extension.restoreContext();
  15753. };
  15754. this.getPixelRatio = function () {
  15755. return _pixelRatio;
  15756. };
  15757. this.setPixelRatio = function (value) {
  15758. if (value === undefined) return;
  15759. _pixelRatio = value;
  15760. this.setSize(_width, _height, false);
  15761. };
  15762. this.getSize = function (target) {
  15763. if (target === undefined) {
  15764. console.warn('WebGLRenderer: .getsize() now requires a Vector2 as an argument');
  15765. target = new Vector2();
  15766. }
  15767. return target.set(_width, _height);
  15768. };
  15769. this.setSize = function (width, height, updateStyle) {
  15770. if (vr.isPresenting()) {
  15771. console.warn('THREE.WebGLRenderer: Can\'t change size while VR device is presenting.');
  15772. return;
  15773. }
  15774. _width = width;
  15775. _height = height;
  15776. _canvas.width = Math.floor(width * _pixelRatio);
  15777. _canvas.height = Math.floor(height * _pixelRatio);
  15778. if (updateStyle !== false) {
  15779. _canvas.style.width = width + 'px';
  15780. _canvas.style.height = height + 'px';
  15781. }
  15782. this.setViewport(0, 0, width, height);
  15783. };
  15784. this.getDrawingBufferSize = function (target) {
  15785. if (target === undefined) {
  15786. console.warn('WebGLRenderer: .getdrawingBufferSize() now requires a Vector2 as an argument');
  15787. target = new Vector2();
  15788. }
  15789. return target.set(_width * _pixelRatio, _height * _pixelRatio).floor();
  15790. };
  15791. this.setDrawingBufferSize = function (width, height, pixelRatio) {
  15792. _width = width;
  15793. _height = height;
  15794. _pixelRatio = pixelRatio;
  15795. _canvas.width = Math.floor(width * pixelRatio);
  15796. _canvas.height = Math.floor(height * pixelRatio);
  15797. this.setViewport(0, 0, width, height);
  15798. };
  15799. this.getCurrentViewport = function (target) {
  15800. if (target === undefined) {
  15801. console.warn('WebGLRenderer: .getCurrentViewport() now requires a Vector4 as an argument');
  15802. target = new Vector4();
  15803. }
  15804. return target.copy(_currentViewport);
  15805. };
  15806. this.getViewport = function (target) {
  15807. return target.copy(_viewport);
  15808. };
  15809. this.setViewport = function (x, y, width, height) {
  15810. if (x.isVector4) {
  15811. _viewport.set(x.x, x.y, x.z, x.w);
  15812. } else {
  15813. _viewport.set(x, y, width, height);
  15814. }
  15815. state.viewport(_currentViewport.copy(_viewport).multiplyScalar(_pixelRatio).floor());
  15816. };
  15817. this.getScissor = function (target) {
  15818. return target.copy(_scissor);
  15819. };
  15820. this.setScissor = function (x, y, width, height) {
  15821. if (x.isVector4) {
  15822. _scissor.set(x.x, x.y, x.z, x.w);
  15823. } else {
  15824. _scissor.set(x, y, width, height);
  15825. }
  15826. state.scissor(_currentScissor.copy(_scissor).multiplyScalar(_pixelRatio).floor());
  15827. };
  15828. this.getScissorTest = function () {
  15829. return _scissorTest;
  15830. };
  15831. this.setScissorTest = function (boolean) {
  15832. state.setScissorTest(_scissorTest = boolean);
  15833. }; // Clearing
  15834. this.getClearColor = function () {
  15835. return background.getClearColor();
  15836. };
  15837. this.setClearColor = function () {
  15838. background.setClearColor.apply(background, arguments);
  15839. };
  15840. this.getClearAlpha = function () {
  15841. return background.getClearAlpha();
  15842. };
  15843. this.setClearAlpha = function () {
  15844. background.setClearAlpha.apply(background, arguments);
  15845. };
  15846. this.clear = function (color, depth, stencil) {
  15847. var bits = 0;
  15848. if (color === undefined || color) bits |= 16384;
  15849. if (depth === undefined || depth) bits |= 256;
  15850. if (stencil === undefined || stencil) bits |= 1024;
  15851. _gl.clear(bits);
  15852. };
  15853. this.clearColor = function () {
  15854. this.clear(true, false, false);
  15855. };
  15856. this.clearDepth = function () {
  15857. this.clear(false, true, false);
  15858. };
  15859. this.clearStencil = function () {
  15860. this.clear(false, false, true);
  15861. }; //
  15862. this.dispose = function () {
  15863. _canvas.removeEventListener('webglcontextlost', onContextLost, false);
  15864. _canvas.removeEventListener('webglcontextrestored', onContextRestore, false);
  15865. renderLists.dispose();
  15866. renderStates.dispose();
  15867. properties.dispose();
  15868. objects.dispose();
  15869. vr.dispose();
  15870. animation.stop();
  15871. }; // Events
  15872. function onContextLost(event) {
  15873. event.preventDefault();
  15874. console.log('THREE.WebGLRenderer: Context Lost.');
  15875. _isContextLost = true;
  15876. }
  15877. function onContextRestore()
  15878. /* event */
  15879. {
  15880. console.log('THREE.WebGLRenderer: Context Restored.');
  15881. _isContextLost = false;
  15882. initGLContext();
  15883. }
  15884. function onMaterialDispose(event) {
  15885. var material = event.target;
  15886. material.removeEventListener('dispose', onMaterialDispose);
  15887. deallocateMaterial(material);
  15888. } // Buffer deallocation
  15889. function deallocateMaterial(material) {
  15890. releaseMaterialProgramReference(material);
  15891. properties.remove(material);
  15892. }
  15893. function releaseMaterialProgramReference(material) {
  15894. var programInfo = properties.get(material).program;
  15895. material.program = undefined;
  15896. if (programInfo !== undefined) {
  15897. programCache.releaseProgram(programInfo);
  15898. }
  15899. } // Buffer rendering
  15900. function renderObjectImmediate(object, program) {
  15901. object.render(function (object) {
  15902. _this.renderBufferImmediate(object, program);
  15903. });
  15904. }
  15905. this.renderBufferImmediate = function (object, program) {
  15906. state.initAttributes();
  15907. var buffers = properties.get(object);
  15908. if (object.hasPositions && !buffers.position) buffers.position = _gl.createBuffer();
  15909. if (object.hasNormals && !buffers.normal) buffers.normal = _gl.createBuffer();
  15910. if (object.hasUvs && !buffers.uv) buffers.uv = _gl.createBuffer();
  15911. if (object.hasColors && !buffers.color) buffers.color = _gl.createBuffer();
  15912. var programAttributes = program.getAttributes();
  15913. if (object.hasPositions) {
  15914. _gl.bindBuffer(34962, buffers.position);
  15915. _gl.bufferData(34962, object.positionArray, 35048);
  15916. state.enableAttribute(programAttributes.position);
  15917. _gl.vertexAttribPointer(programAttributes.position, 3, 5126, false, 0, 0);
  15918. }
  15919. if (object.hasNormals) {
  15920. _gl.bindBuffer(34962, buffers.normal);
  15921. _gl.bufferData(34962, object.normalArray, 35048);
  15922. state.enableAttribute(programAttributes.normal);
  15923. _gl.vertexAttribPointer(programAttributes.normal, 3, 5126, false, 0, 0);
  15924. }
  15925. if (object.hasUvs) {
  15926. _gl.bindBuffer(34962, buffers.uv);
  15927. _gl.bufferData(34962, object.uvArray, 35048);
  15928. state.enableAttribute(programAttributes.uv);
  15929. _gl.vertexAttribPointer(programAttributes.uv, 2, 5126, false, 0, 0);
  15930. }
  15931. if (object.hasColors) {
  15932. _gl.bindBuffer(34962, buffers.color);
  15933. _gl.bufferData(34962, object.colorArray, 35048);
  15934. state.enableAttribute(programAttributes.color);
  15935. _gl.vertexAttribPointer(programAttributes.color, 3, 5126, false, 0, 0);
  15936. }
  15937. state.disableUnusedAttributes();
  15938. _gl.drawArrays(4, 0, object.count);
  15939. object.count = 0;
  15940. };
  15941. this.renderBufferDirect = function (camera, fog, geometry, material, object, group) {
  15942. var frontFaceCW = object.isMesh && object.matrixWorld.determinant() < 0;
  15943. state.setMaterial(material, frontFaceCW);
  15944. var program = setProgram(camera, fog, material, object);
  15945. var updateBuffers = false;
  15946. if (_currentGeometryProgram.geometry !== geometry.id || _currentGeometryProgram.program !== program.id || _currentGeometryProgram.wireframe !== (material.wireframe === true)) {
  15947. _currentGeometryProgram.geometry = geometry.id;
  15948. _currentGeometryProgram.program = program.id;
  15949. _currentGeometryProgram.wireframe = material.wireframe === true;
  15950. updateBuffers = true;
  15951. }
  15952. if (object.morphTargetInfluences) {
  15953. morphtargets.update(object, geometry, material, program);
  15954. updateBuffers = true;
  15955. } //
  15956. var index = geometry.index;
  15957. var position = geometry.attributes.position;
  15958. var rangeFactor = 1;
  15959. if (material.wireframe === true) {
  15960. index = geometries.getWireframeAttribute(geometry);
  15961. rangeFactor = 2;
  15962. }
  15963. var attribute;
  15964. var renderer = bufferRenderer;
  15965. if (index !== null) {
  15966. attribute = attributes.get(index);
  15967. renderer = indexedBufferRenderer;
  15968. renderer.setIndex(attribute);
  15969. }
  15970. if (updateBuffers) {
  15971. setupVertexAttributes(object, geometry, material, program);
  15972. if (index !== null) {
  15973. _gl.bindBuffer(34963, attribute.buffer);
  15974. }
  15975. } //
  15976. var dataCount = Infinity;
  15977. if (index !== null) {
  15978. dataCount = index.count;
  15979. } else if (position !== undefined) {
  15980. dataCount = position.count;
  15981. }
  15982. var rangeStart = geometry.drawRange.start * rangeFactor;
  15983. var rangeCount = geometry.drawRange.count * rangeFactor;
  15984. var groupStart = group !== null ? group.start * rangeFactor : 0;
  15985. var groupCount = group !== null ? group.count * rangeFactor : Infinity;
  15986. var drawStart = Math.max(rangeStart, groupStart);
  15987. var drawEnd = Math.min(dataCount, rangeStart + rangeCount, groupStart + groupCount) - 1;
  15988. var drawCount = Math.max(0, drawEnd - drawStart + 1);
  15989. if (drawCount === 0) return; //
  15990. if (object.isMesh) {
  15991. if (material.wireframe === true) {
  15992. state.setLineWidth(material.wireframeLinewidth * getTargetPixelRatio());
  15993. renderer.setMode(1);
  15994. } else {
  15995. switch (object.drawMode) {
  15996. case TrianglesDrawMode:
  15997. renderer.setMode(4);
  15998. break;
  15999. case TriangleStripDrawMode:
  16000. renderer.setMode(5);
  16001. break;
  16002. case TriangleFanDrawMode:
  16003. renderer.setMode(6);
  16004. break;
  16005. }
  16006. }
  16007. } else if (object.isLine) {
  16008. var lineWidth = material.linewidth;
  16009. if (lineWidth === undefined) lineWidth = 1; // Not using Line*Material
  16010. state.setLineWidth(lineWidth * getTargetPixelRatio());
  16011. if (object.isLineSegments) {
  16012. renderer.setMode(1);
  16013. } else if (object.isLineLoop) {
  16014. renderer.setMode(2);
  16015. } else {
  16016. renderer.setMode(3);
  16017. }
  16018. } else if (object.isPoints) {
  16019. renderer.setMode(0);
  16020. } else if (object.isSprite) {
  16021. renderer.setMode(4);
  16022. }
  16023. if (object.isInstancedMesh) {
  16024. renderer.renderInstances(geometry, drawStart, drawCount, object.count);
  16025. } else if (geometry.isInstancedBufferGeometry) {
  16026. renderer.renderInstances(geometry, drawStart, drawCount, geometry.maxInstancedCount);
  16027. } else {
  16028. renderer.render(drawStart, drawCount);
  16029. }
  16030. };
  16031. function setupVertexAttributes(object, geometry, material, program) {
  16032. if (capabilities.isWebGL2 === false && (object.isInstancedMesh || geometry.isInstancedBufferGeometry)) {
  16033. if (extensions.get('ANGLE_instanced_arrays') === null) return;
  16034. }
  16035. state.initAttributes();
  16036. var geometryAttributes = geometry.attributes;
  16037. var programAttributes = program.getAttributes();
  16038. var materialDefaultAttributeValues = material.defaultAttributeValues;
  16039. for (var name in programAttributes) {
  16040. var programAttribute = programAttributes[name];
  16041. if (programAttribute >= 0) {
  16042. var geometryAttribute = geometryAttributes[name];
  16043. if (geometryAttribute !== undefined) {
  16044. var normalized = geometryAttribute.normalized;
  16045. var size = geometryAttribute.itemSize;
  16046. var attribute = attributes.get(geometryAttribute); // TODO Attribute may not be available on context restore
  16047. if (attribute === undefined) continue;
  16048. var buffer = attribute.buffer;
  16049. var type = attribute.type;
  16050. var bytesPerElement = attribute.bytesPerElement;
  16051. if (geometryAttribute.isInterleavedBufferAttribute) {
  16052. var data = geometryAttribute.data;
  16053. var stride = data.stride;
  16054. var offset = geometryAttribute.offset;
  16055. if (data && data.isInstancedInterleavedBuffer) {
  16056. state.enableAttributeAndDivisor(programAttribute, data.meshPerAttribute);
  16057. if (geometry.maxInstancedCount === undefined) {
  16058. geometry.maxInstancedCount = data.meshPerAttribute * data.count;
  16059. }
  16060. } else {
  16061. state.enableAttribute(programAttribute);
  16062. }
  16063. _gl.bindBuffer(34962, buffer);
  16064. _gl.vertexAttribPointer(programAttribute, size, type, normalized, stride * bytesPerElement, offset * bytesPerElement);
  16065. } else {
  16066. if (geometryAttribute.isInstancedBufferAttribute) {
  16067. state.enableAttributeAndDivisor(programAttribute, geometryAttribute.meshPerAttribute);
  16068. if (geometry.maxInstancedCount === undefined) {
  16069. geometry.maxInstancedCount = geometryAttribute.meshPerAttribute * geometryAttribute.count;
  16070. }
  16071. } else {
  16072. state.enableAttribute(programAttribute);
  16073. }
  16074. _gl.bindBuffer(34962, buffer);
  16075. _gl.vertexAttribPointer(programAttribute, size, type, normalized, 0, 0);
  16076. }
  16077. } else if (name === 'instanceMatrix') {
  16078. var attribute = attributes.get(object.instanceMatrix); // TODO Attribute may not be available on context restore
  16079. if (attribute === undefined) continue;
  16080. var buffer = attribute.buffer;
  16081. var type = attribute.type;
  16082. state.enableAttributeAndDivisor(programAttribute + 0, 1);
  16083. state.enableAttributeAndDivisor(programAttribute + 1, 1);
  16084. state.enableAttributeAndDivisor(programAttribute + 2, 1);
  16085. state.enableAttributeAndDivisor(programAttribute + 3, 1);
  16086. _gl.bindBuffer(34962, buffer);
  16087. _gl.vertexAttribPointer(programAttribute + 0, 4, type, false, 64, 0);
  16088. _gl.vertexAttribPointer(programAttribute + 1, 4, type, false, 64, 16);
  16089. _gl.vertexAttribPointer(programAttribute + 2, 4, type, false, 64, 32);
  16090. _gl.vertexAttribPointer(programAttribute + 3, 4, type, false, 64, 48);
  16091. } else if (materialDefaultAttributeValues !== undefined) {
  16092. var value = materialDefaultAttributeValues[name];
  16093. if (value !== undefined) {
  16094. switch (value.length) {
  16095. case 2:
  16096. _gl.vertexAttrib2fv(programAttribute, value);
  16097. break;
  16098. case 3:
  16099. _gl.vertexAttrib3fv(programAttribute, value);
  16100. break;
  16101. case 4:
  16102. _gl.vertexAttrib4fv(programAttribute, value);
  16103. break;
  16104. default:
  16105. _gl.vertexAttrib1fv(programAttribute, value);
  16106. }
  16107. }
  16108. }
  16109. }
  16110. }
  16111. state.disableUnusedAttributes();
  16112. } // Compile
  16113. this.compile = function (scene, camera) {
  16114. currentRenderState = renderStates.get(scene, camera);
  16115. currentRenderState.init();
  16116. scene.traverse(function (object) {
  16117. if (object.isLight) {
  16118. currentRenderState.pushLight(object);
  16119. if (object.castShadow) {
  16120. currentRenderState.pushShadow(object);
  16121. }
  16122. }
  16123. });
  16124. currentRenderState.setupLights(camera);
  16125. scene.traverse(function (object) {
  16126. if (object.material) {
  16127. if (Array.isArray(object.material)) {
  16128. for (var i = 0; i < object.material.length; i++) {
  16129. initMaterial(object.material[i], scene.fog, object);
  16130. }
  16131. } else {
  16132. initMaterial(object.material, scene.fog, object);
  16133. }
  16134. }
  16135. });
  16136. }; // Animation Loop
  16137. var onAnimationFrameCallback = null;
  16138. function onAnimationFrame(time) {
  16139. if (vr.isPresenting()) return;
  16140. if (onAnimationFrameCallback) onAnimationFrameCallback(time);
  16141. }
  16142. var animation = new WebGLAnimation();
  16143. animation.setAnimationLoop(onAnimationFrame);
  16144. if (typeof window !== 'undefined') animation.setContext(window);
  16145. this.setAnimationLoop = function (callback) {
  16146. onAnimationFrameCallback = callback;
  16147. vr.setAnimationLoop(callback);
  16148. animation.start();
  16149. }; // Rendering
  16150. this.render = function (scene, camera) {
  16151. var renderTarget, forceClear;
  16152. if (arguments[2] !== undefined) {
  16153. console.warn('THREE.WebGLRenderer.render(): the renderTarget argument has been removed. Use .setRenderTarget() instead.');
  16154. renderTarget = arguments[2];
  16155. }
  16156. if (arguments[3] !== undefined) {
  16157. console.warn('THREE.WebGLRenderer.render(): the forceClear argument has been removed. Use .clear() instead.');
  16158. forceClear = arguments[3];
  16159. }
  16160. if (!(camera && camera.isCamera)) {
  16161. console.error('THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.');
  16162. return;
  16163. }
  16164. if (_isContextLost) return; // reset caching for this frame
  16165. _currentGeometryProgram.geometry = null;
  16166. _currentGeometryProgram.program = null;
  16167. _currentGeometryProgram.wireframe = false;
  16168. _currentMaterialId = -1;
  16169. _currentCamera = null; // update scene graph
  16170. if (scene.autoUpdate === true) scene.updateMatrixWorld(); // update camera matrices and frustum
  16171. if (camera.parent === null) camera.updateMatrixWorld();
  16172. if (vr.enabled) {
  16173. camera = vr.getCamera(camera);
  16174. } //
  16175. currentRenderState = renderStates.get(scene, camera);
  16176. currentRenderState.init();
  16177. scene.onBeforeRender(_this, scene, camera, renderTarget || _currentRenderTarget);
  16178. _projScreenMatrix.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse);
  16179. _frustum.setFromMatrix(_projScreenMatrix);
  16180. _localClippingEnabled = this.localClippingEnabled;
  16181. _clippingEnabled = _clipping.init(this.clippingPlanes, _localClippingEnabled, camera);
  16182. currentRenderList = renderLists.get(scene, camera);
  16183. currentRenderList.init();
  16184. projectObject(scene, camera, 0, _this.sortObjects);
  16185. if (_this.sortObjects === true) {
  16186. currentRenderList.sort();
  16187. } //
  16188. if (_clippingEnabled) _clipping.beginShadows();
  16189. var shadowsArray = currentRenderState.state.shadowsArray;
  16190. shadowMap.render(shadowsArray, scene, camera);
  16191. currentRenderState.setupLights(camera);
  16192. if (_clippingEnabled) _clipping.endShadows(); //
  16193. if (this.info.autoReset) this.info.reset();
  16194. if (renderTarget !== undefined) {
  16195. this.setRenderTarget(renderTarget);
  16196. }
  16197. if (vr.enabled && multiview.isAvailable()) {
  16198. multiview.attachCamera(camera);
  16199. } //
  16200. background.render(currentRenderList, scene, camera, forceClear); // render scene
  16201. var opaqueObjects = currentRenderList.opaque;
  16202. var transparentObjects = currentRenderList.transparent;
  16203. if (scene.overrideMaterial) {
  16204. var overrideMaterial = scene.overrideMaterial;
  16205. if (opaqueObjects.length) renderObjects(opaqueObjects, scene, camera, overrideMaterial);
  16206. if (transparentObjects.length) renderObjects(transparentObjects, scene, camera, overrideMaterial);
  16207. } else {
  16208. // opaque pass (front-to-back order)
  16209. if (opaqueObjects.length) renderObjects(opaqueObjects, scene, camera); // transparent pass (back-to-front order)
  16210. if (transparentObjects.length) renderObjects(transparentObjects, scene, camera);
  16211. } //
  16212. scene.onAfterRender(_this, scene, camera); //
  16213. if (_currentRenderTarget !== null) {
  16214. // Generate mipmap if we're using any kind of mipmap filtering
  16215. textures.updateRenderTargetMipmap(_currentRenderTarget); // resolve multisample renderbuffers to a single-sample texture if necessary
  16216. textures.updateMultisampleRenderTarget(_currentRenderTarget);
  16217. } // Ensure depth buffer writing is enabled so it can be cleared on next render
  16218. state.buffers.depth.setTest(true);
  16219. state.buffers.depth.setMask(true);
  16220. state.buffers.color.setMask(true);
  16221. state.setPolygonOffset(false);
  16222. if (vr.enabled) {
  16223. if (multiview.isAvailable()) {
  16224. multiview.detachCamera(camera);
  16225. }
  16226. vr.submitFrame();
  16227. } // _gl.finish();
  16228. currentRenderList = null;
  16229. currentRenderState = null;
  16230. };
  16231. function projectObject(object, camera, groupOrder, sortObjects) {
  16232. if (object.visible === false) return;
  16233. var visible = object.layers.test(camera.layers);
  16234. if (visible) {
  16235. if (object.isGroup) {
  16236. groupOrder = object.renderOrder;
  16237. } else if (object.isLOD) {
  16238. if (object.autoUpdate === true) object.update(camera);
  16239. } else if (object.isLight) {
  16240. currentRenderState.pushLight(object);
  16241. if (object.castShadow) {
  16242. currentRenderState.pushShadow(object);
  16243. }
  16244. } else if (object.isSprite) {
  16245. if (!object.frustumCulled || _frustum.intersectsSprite(object)) {
  16246. if (sortObjects) {
  16247. _vector3.setFromMatrixPosition(object.matrixWorld).applyMatrix4(_projScreenMatrix);
  16248. }
  16249. var geometry = objects.update(object);
  16250. var material = object.material;
  16251. if (material.visible) {
  16252. currentRenderList.push(object, geometry, material, groupOrder, _vector3.z, null);
  16253. }
  16254. }
  16255. } else if (object.isImmediateRenderObject) {
  16256. if (sortObjects) {
  16257. _vector3.setFromMatrixPosition(object.matrixWorld).applyMatrix4(_projScreenMatrix);
  16258. }
  16259. currentRenderList.push(object, null, object.material, groupOrder, _vector3.z, null);
  16260. } else if (object.isMesh || object.isLine || object.isPoints) {
  16261. if (object.isSkinnedMesh) {
  16262. // update skeleton only once in a frame
  16263. if (object.skeleton.frame !== info.render.frame) {
  16264. object.skeleton.update();
  16265. object.skeleton.frame = info.render.frame;
  16266. }
  16267. }
  16268. if (!object.frustumCulled || _frustum.intersectsObject(object)) {
  16269. if (sortObjects) {
  16270. _vector3.setFromMatrixPosition(object.matrixWorld).applyMatrix4(_projScreenMatrix);
  16271. }
  16272. var geometry = objects.update(object);
  16273. var material = object.material;
  16274. if (Array.isArray(material)) {
  16275. var groups = geometry.groups;
  16276. for (var i = 0, l = groups.length; i < l; i++) {
  16277. var group = groups[i];
  16278. var groupMaterial = material[group.materialIndex];
  16279. if (groupMaterial && groupMaterial.visible) {
  16280. currentRenderList.push(object, geometry, groupMaterial, groupOrder, _vector3.z, group);
  16281. }
  16282. }
  16283. } else if (material.visible) {
  16284. currentRenderList.push(object, geometry, material, groupOrder, _vector3.z, null);
  16285. }
  16286. }
  16287. }
  16288. }
  16289. var children = object.children;
  16290. for (var i = 0, l = children.length; i < l; i++) {
  16291. projectObject(children[i], camera, groupOrder, sortObjects);
  16292. }
  16293. }
  16294. function renderObjects(renderList, scene, camera, overrideMaterial) {
  16295. for (var i = 0, l = renderList.length; i < l; i++) {
  16296. var renderItem = renderList[i];
  16297. var object = renderItem.object;
  16298. var geometry = renderItem.geometry;
  16299. var material = overrideMaterial === undefined ? renderItem.material : overrideMaterial;
  16300. var group = renderItem.group;
  16301. if (camera.isArrayCamera) {
  16302. _currentArrayCamera = camera;
  16303. if (vr.enabled && multiview.isAvailable()) {
  16304. renderObject(object, scene, camera, geometry, material, group);
  16305. } else {
  16306. var cameras = camera.cameras;
  16307. for (var j = 0, jl = cameras.length; j < jl; j++) {
  16308. var camera2 = cameras[j];
  16309. if (object.layers.test(camera2.layers)) {
  16310. state.viewport(_currentViewport.copy(camera2.viewport));
  16311. currentRenderState.setupLights(camera2);
  16312. renderObject(object, scene, camera2, geometry, material, group);
  16313. }
  16314. }
  16315. }
  16316. } else {
  16317. _currentArrayCamera = null;
  16318. renderObject(object, scene, camera, geometry, material, group);
  16319. }
  16320. }
  16321. }
  16322. function renderObject(object, scene, camera, geometry, material, group) {
  16323. object.onBeforeRender(_this, scene, camera, geometry, material, group);
  16324. currentRenderState = renderStates.get(scene, _currentArrayCamera || camera);
  16325. object.modelViewMatrix.multiplyMatrices(camera.matrixWorldInverse, object.matrixWorld);
  16326. object.normalMatrix.getNormalMatrix(object.modelViewMatrix);
  16327. if (object.isImmediateRenderObject) {
  16328. state.setMaterial(material);
  16329. var program = setProgram(camera, scene.fog, material, object);
  16330. _currentGeometryProgram.geometry = null;
  16331. _currentGeometryProgram.program = null;
  16332. _currentGeometryProgram.wireframe = false;
  16333. renderObjectImmediate(object, program);
  16334. } else {
  16335. _this.renderBufferDirect(camera, scene.fog, geometry, material, object, group);
  16336. }
  16337. object.onAfterRender(_this, scene, camera, geometry, material, group);
  16338. currentRenderState = renderStates.get(scene, _currentArrayCamera || camera);
  16339. }
  16340. function initMaterial(material, fog, object) {
  16341. var materialProperties = properties.get(material);
  16342. var lights = currentRenderState.state.lights;
  16343. var shadowsArray = currentRenderState.state.shadowsArray;
  16344. var lightsStateVersion = lights.state.version;
  16345. var parameters = programCache.getParameters(material, lights.state, shadowsArray, fog, _clipping.numPlanes, _clipping.numIntersection, object);
  16346. var code = programCache.getProgramCode(material, parameters);
  16347. var program = materialProperties.program;
  16348. var programChange = true;
  16349. if (program === undefined) {
  16350. // new material
  16351. material.addEventListener('dispose', onMaterialDispose);
  16352. } else if (program.code !== code) {
  16353. // changed glsl or parameters
  16354. releaseMaterialProgramReference(material);
  16355. } else if (materialProperties.lightsStateVersion !== lightsStateVersion) {
  16356. materialProperties.lightsStateVersion = lightsStateVersion;
  16357. programChange = false;
  16358. } else if (parameters.shaderID !== undefined) {
  16359. // same glsl and uniform list
  16360. return;
  16361. } else {
  16362. // only rebuild uniform list
  16363. programChange = false;
  16364. }
  16365. if (programChange) {
  16366. if (parameters.shaderID) {
  16367. var shader = ShaderLib[parameters.shaderID];
  16368. materialProperties.shader = {
  16369. name: material.type,
  16370. uniforms: cloneUniforms(shader.uniforms),
  16371. vertexShader: shader.vertexShader,
  16372. fragmentShader: shader.fragmentShader
  16373. };
  16374. } else {
  16375. materialProperties.shader = {
  16376. name: material.type,
  16377. uniforms: material.uniforms,
  16378. vertexShader: material.vertexShader,
  16379. fragmentShader: material.fragmentShader
  16380. };
  16381. }
  16382. material.onBeforeCompile(materialProperties.shader, _this); // Computing code again as onBeforeCompile may have changed the shaders
  16383. code = programCache.getProgramCode(material, parameters);
  16384. program = programCache.acquireProgram(material, materialProperties.shader, parameters, code);
  16385. materialProperties.program = program;
  16386. material.program = program;
  16387. }
  16388. var programAttributes = program.getAttributes();
  16389. if (material.morphTargets) {
  16390. material.numSupportedMorphTargets = 0;
  16391. for (var i = 0; i < _this.maxMorphTargets; i++) {
  16392. if (programAttributes['morphTarget' + i] >= 0) {
  16393. material.numSupportedMorphTargets++;
  16394. }
  16395. }
  16396. }
  16397. if (material.morphNormals) {
  16398. material.numSupportedMorphNormals = 0;
  16399. for (var i = 0; i < _this.maxMorphNormals; i++) {
  16400. if (programAttributes['morphNormal' + i] >= 0) {
  16401. material.numSupportedMorphNormals++;
  16402. }
  16403. }
  16404. }
  16405. var uniforms = materialProperties.shader.uniforms;
  16406. if (!material.isShaderMaterial && !material.isRawShaderMaterial || material.clipping === true) {
  16407. materialProperties.numClippingPlanes = _clipping.numPlanes;
  16408. materialProperties.numIntersection = _clipping.numIntersection;
  16409. uniforms.clippingPlanes = _clipping.uniform;
  16410. }
  16411. materialProperties.fog = fog; // store the light setup it was created for
  16412. materialProperties.needsLights = materialNeedsLights(material);
  16413. materialProperties.lightsStateVersion = lightsStateVersion;
  16414. if (materialProperties.needsLights) {
  16415. // wire up the material to this renderer's lighting state
  16416. uniforms.ambientLightColor.value = lights.state.ambient;
  16417. uniforms.lightProbe.value = lights.state.probe;
  16418. uniforms.directionalLights.value = lights.state.directional;
  16419. uniforms.spotLights.value = lights.state.spot;
  16420. uniforms.rectAreaLights.value = lights.state.rectArea;
  16421. uniforms.pointLights.value = lights.state.point;
  16422. uniforms.hemisphereLights.value = lights.state.hemi;
  16423. uniforms.directionalShadowMap.value = lights.state.directionalShadowMap;
  16424. uniforms.directionalShadowMatrix.value = lights.state.directionalShadowMatrix;
  16425. uniforms.spotShadowMap.value = lights.state.spotShadowMap;
  16426. uniforms.spotShadowMatrix.value = lights.state.spotShadowMatrix;
  16427. uniforms.pointShadowMap.value = lights.state.pointShadowMap;
  16428. uniforms.pointShadowMatrix.value = lights.state.pointShadowMatrix; // TODO (abelnation): add area lights shadow info to uniforms
  16429. }
  16430. var progUniforms = materialProperties.program.getUniforms(),
  16431. uniformsList = WebGLUniforms.seqWithValue(progUniforms.seq, uniforms);
  16432. materialProperties.uniformsList = uniformsList;
  16433. }
  16434. function setProgram(camera, fog, material, object) {
  16435. textures.resetTextureUnits();
  16436. var materialProperties = properties.get(material);
  16437. var lights = currentRenderState.state.lights;
  16438. if (_clippingEnabled) {
  16439. if (_localClippingEnabled || camera !== _currentCamera) {
  16440. var useCache = camera === _currentCamera && material.id === _currentMaterialId; // we might want to call this function with some ClippingGroup
  16441. // object instead of the material, once it becomes feasible
  16442. // (#8465, #8379)
  16443. _clipping.setState(material.clippingPlanes, material.clipIntersection, material.clipShadows, camera, materialProperties, useCache);
  16444. }
  16445. }
  16446. if (material.needsUpdate === false) {
  16447. if (materialProperties.program === undefined) {
  16448. material.needsUpdate = true;
  16449. } else if (material.fog && materialProperties.fog !== fog) {
  16450. material.needsUpdate = true;
  16451. } else if (materialProperties.needsLights && materialProperties.lightsStateVersion !== lights.state.version) {
  16452. material.needsUpdate = true;
  16453. } else if (materialProperties.numClippingPlanes !== undefined && (materialProperties.numClippingPlanes !== _clipping.numPlanes || materialProperties.numIntersection !== _clipping.numIntersection)) {
  16454. material.needsUpdate = true;
  16455. }
  16456. }
  16457. if (material.needsUpdate) {
  16458. initMaterial(material, fog, object);
  16459. material.needsUpdate = false;
  16460. }
  16461. var refreshProgram = false;
  16462. var refreshMaterial = false;
  16463. var refreshLights = false;
  16464. var program = materialProperties.program,
  16465. p_uniforms = program.getUniforms(),
  16466. m_uniforms = materialProperties.shader.uniforms;
  16467. if (state.useProgram(program.program)) {
  16468. refreshProgram = true;
  16469. refreshMaterial = true;
  16470. refreshLights = true;
  16471. }
  16472. if (material.id !== _currentMaterialId) {
  16473. _currentMaterialId = material.id;
  16474. refreshMaterial = true;
  16475. }
  16476. if (refreshProgram || _currentCamera !== camera) {
  16477. if (program.numMultiviewViews > 0) {
  16478. multiview.updateCameraProjectionMatricesUniform(camera, p_uniforms);
  16479. } else {
  16480. p_uniforms.setValue(_gl, 'projectionMatrix', camera.projectionMatrix);
  16481. }
  16482. if (capabilities.logarithmicDepthBuffer) {
  16483. p_uniforms.setValue(_gl, 'logDepthBufFC', 2.0 / (Math.log(camera.far + 1.0) / Math.LN2));
  16484. }
  16485. if (_currentCamera !== camera) {
  16486. _currentCamera = camera; // lighting uniforms depend on the camera so enforce an update
  16487. // now, in case this material supports lights - or later, when
  16488. // the next material that does gets activated:
  16489. refreshMaterial = true; // set to true on material change
  16490. refreshLights = true; // remains set until update done
  16491. } // load material specific uniforms
  16492. // (shader material also gets them for the sake of genericity)
  16493. if (material.isShaderMaterial || material.isMeshPhongMaterial || material.isMeshStandardMaterial || material.envMap) {
  16494. var uCamPos = p_uniforms.map.cameraPosition;
  16495. if (uCamPos !== undefined) {
  16496. uCamPos.setValue(_gl, _vector3.setFromMatrixPosition(camera.matrixWorld));
  16497. }
  16498. }
  16499. if (material.isMeshPhongMaterial || material.isMeshLambertMaterial || material.isMeshBasicMaterial || material.isMeshStandardMaterial || material.isShaderMaterial || material.skinning) {
  16500. if (program.numMultiviewViews > 0) {
  16501. multiview.updateCameraViewMatricesUniform(camera, p_uniforms);
  16502. } else {
  16503. p_uniforms.setValue(_gl, 'viewMatrix', camera.matrixWorldInverse);
  16504. }
  16505. }
  16506. } // skinning uniforms must be set even if material didn't change
  16507. // auto-setting of texture unit for bone texture must go before other textures
  16508. // not sure why, but otherwise weird things happen
  16509. if (material.skinning) {
  16510. p_uniforms.setOptional(_gl, object, 'bindMatrix');
  16511. p_uniforms.setOptional(_gl, object, 'bindMatrixInverse');
  16512. var skeleton = object.skeleton;
  16513. if (skeleton) {
  16514. var bones = skeleton.bones;
  16515. if (capabilities.floatVertexTextures) {
  16516. if (skeleton.boneTexture === undefined) {
  16517. // layout (1 matrix = 4 pixels)
  16518. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  16519. // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8)
  16520. // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16)
  16521. // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32)
  16522. // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64)
  16523. var size = Math.sqrt(bones.length * 4); // 4 pixels needed for 1 matrix
  16524. size = _Math.ceilPowerOfTwo(size);
  16525. size = Math.max(size, 4);
  16526. var boneMatrices = new Float32Array(size * size * 4); // 4 floats per RGBA pixel
  16527. boneMatrices.set(skeleton.boneMatrices); // copy current values
  16528. var boneTexture = new DataTexture(boneMatrices, size, size, RGBAFormat, FloatType);
  16529. skeleton.boneMatrices = boneMatrices;
  16530. skeleton.boneTexture = boneTexture;
  16531. skeleton.boneTextureSize = size;
  16532. }
  16533. p_uniforms.setValue(_gl, 'boneTexture', skeleton.boneTexture, textures);
  16534. p_uniforms.setValue(_gl, 'boneTextureSize', skeleton.boneTextureSize);
  16535. } else {
  16536. p_uniforms.setOptional(_gl, skeleton, 'boneMatrices');
  16537. }
  16538. }
  16539. }
  16540. if (refreshMaterial || materialProperties.receiveShadow !== object.receiveShadow) {
  16541. materialProperties.receiveShadow = object.receiveShadow;
  16542. p_uniforms.setValue(_gl, 'receiveShadow', object.receiveShadow);
  16543. }
  16544. if (refreshMaterial) {
  16545. p_uniforms.setValue(_gl, 'toneMappingExposure', _this.toneMappingExposure);
  16546. p_uniforms.setValue(_gl, 'toneMappingWhitePoint', _this.toneMappingWhitePoint);
  16547. if (materialProperties.needsLights) {
  16548. // the current material requires lighting info
  16549. // note: all lighting uniforms are always set correctly
  16550. // they simply reference the renderer's state for their
  16551. // values
  16552. //
  16553. // use the current material's .needsUpdate flags to set
  16554. // the GL state when required
  16555. markUniformsLightsNeedsUpdate(m_uniforms, refreshLights);
  16556. } // refresh uniforms common to several materials
  16557. if (fog && material.fog) {
  16558. refreshUniformsFog(m_uniforms, fog);
  16559. }
  16560. if (material.isMeshBasicMaterial) {
  16561. refreshUniformsCommon(m_uniforms, material);
  16562. } else if (material.isMeshLambertMaterial) {
  16563. refreshUniformsCommon(m_uniforms, material);
  16564. refreshUniformsLambert(m_uniforms, material);
  16565. } else if (material.isMeshPhongMaterial) {
  16566. refreshUniformsCommon(m_uniforms, material);
  16567. if (material.isMeshToonMaterial) {
  16568. refreshUniformsToon(m_uniforms, material);
  16569. } else {
  16570. refreshUniformsPhong(m_uniforms, material);
  16571. }
  16572. } else if (material.isMeshStandardMaterial) {
  16573. refreshUniformsCommon(m_uniforms, material);
  16574. if (material.isMeshPhysicalMaterial) {
  16575. refreshUniformsPhysical(m_uniforms, material);
  16576. } else {
  16577. refreshUniformsStandard(m_uniforms, material);
  16578. }
  16579. } else if (material.isMeshMatcapMaterial) {
  16580. refreshUniformsCommon(m_uniforms, material);
  16581. refreshUniformsMatcap(m_uniforms, material);
  16582. } else if (material.isMeshDepthMaterial) {
  16583. refreshUniformsCommon(m_uniforms, material);
  16584. refreshUniformsDepth(m_uniforms, material);
  16585. } else if (material.isMeshDistanceMaterial) {
  16586. refreshUniformsCommon(m_uniforms, material);
  16587. refreshUniformsDistance(m_uniforms, material);
  16588. } else if (material.isMeshNormalMaterial) {
  16589. refreshUniformsCommon(m_uniforms, material);
  16590. refreshUniformsNormal(m_uniforms, material);
  16591. } else if (material.isLineBasicMaterial) {
  16592. refreshUniformsLine(m_uniforms, material);
  16593. if (material.isLineDashedMaterial) {
  16594. refreshUniformsDash(m_uniforms, material);
  16595. }
  16596. } else if (material.isPointsMaterial) {
  16597. refreshUniformsPoints(m_uniforms, material);
  16598. } else if (material.isSpriteMaterial) {
  16599. refreshUniformsSprites(m_uniforms, material);
  16600. } else if (material.isShadowMaterial) {
  16601. m_uniforms.color.value.copy(material.color);
  16602. m_uniforms.opacity.value = material.opacity;
  16603. } // RectAreaLight Texture
  16604. // TODO (mrdoob): Find a nicer implementation
  16605. if (m_uniforms.ltc_1 !== undefined) m_uniforms.ltc_1.value = UniformsLib.LTC_1;
  16606. if (m_uniforms.ltc_2 !== undefined) m_uniforms.ltc_2.value = UniformsLib.LTC_2;
  16607. WebGLUniforms.upload(_gl, materialProperties.uniformsList, m_uniforms, textures);
  16608. }
  16609. if (material.isShaderMaterial && material.uniformsNeedUpdate === true) {
  16610. WebGLUniforms.upload(_gl, materialProperties.uniformsList, m_uniforms, textures);
  16611. material.uniformsNeedUpdate = false;
  16612. }
  16613. if (material.isSpriteMaterial) {
  16614. p_uniforms.setValue(_gl, 'center', object.center);
  16615. } // common matrices
  16616. if (program.numMultiviewViews > 0) {
  16617. multiview.updateObjectMatricesUniforms(object, camera, p_uniforms);
  16618. } else {
  16619. p_uniforms.setValue(_gl, 'modelViewMatrix', object.modelViewMatrix);
  16620. p_uniforms.setValue(_gl, 'normalMatrix', object.normalMatrix);
  16621. }
  16622. p_uniforms.setValue(_gl, 'modelMatrix', object.matrixWorld);
  16623. return program;
  16624. } // Uniforms (refresh uniforms objects)
  16625. function refreshUniformsCommon(uniforms, material) {
  16626. uniforms.opacity.value = material.opacity;
  16627. if (material.color) {
  16628. uniforms.diffuse.value.copy(material.color);
  16629. }
  16630. if (material.emissive) {
  16631. uniforms.emissive.value.copy(material.emissive).multiplyScalar(material.emissiveIntensity);
  16632. }
  16633. if (material.map) {
  16634. uniforms.map.value = material.map;
  16635. }
  16636. if (material.alphaMap) {
  16637. uniforms.alphaMap.value = material.alphaMap;
  16638. }
  16639. if (material.specularMap) {
  16640. uniforms.specularMap.value = material.specularMap;
  16641. }
  16642. if (material.envMap) {
  16643. uniforms.envMap.value = material.envMap; // don't flip CubeTexture envMaps, flip everything else:
  16644. // WebGLRenderTargetCube will be flipped for backwards compatibility
  16645. // WebGLRenderTargetCube.texture will be flipped because it's a Texture and NOT a CubeTexture
  16646. // this check must be handled differently, or removed entirely, if WebGLRenderTargetCube uses a CubeTexture in the future
  16647. uniforms.flipEnvMap.value = material.envMap.isCubeTexture ? -1 : 1;
  16648. uniforms.reflectivity.value = material.reflectivity;
  16649. uniforms.refractionRatio.value = material.refractionRatio;
  16650. uniforms.maxMipLevel.value = properties.get(material.envMap).__maxMipLevel;
  16651. }
  16652. if (material.lightMap) {
  16653. uniforms.lightMap.value = material.lightMap;
  16654. uniforms.lightMapIntensity.value = material.lightMapIntensity;
  16655. }
  16656. if (material.aoMap) {
  16657. uniforms.aoMap.value = material.aoMap;
  16658. uniforms.aoMapIntensity.value = material.aoMapIntensity;
  16659. } // uv repeat and offset setting priorities
  16660. // 1. color map
  16661. // 2. specular map
  16662. // 3. normal map
  16663. // 4. bump map
  16664. // 5. alpha map
  16665. // 6. emissive map
  16666. var uvScaleMap;
  16667. if (material.map) {
  16668. uvScaleMap = material.map;
  16669. } else if (material.specularMap) {
  16670. uvScaleMap = material.specularMap;
  16671. } else if (material.displacementMap) {
  16672. uvScaleMap = material.displacementMap;
  16673. } else if (material.normalMap) {
  16674. uvScaleMap = material.normalMap;
  16675. } else if (material.bumpMap) {
  16676. uvScaleMap = material.bumpMap;
  16677. } else if (material.roughnessMap) {
  16678. uvScaleMap = material.roughnessMap;
  16679. } else if (material.metalnessMap) {
  16680. uvScaleMap = material.metalnessMap;
  16681. } else if (material.alphaMap) {
  16682. uvScaleMap = material.alphaMap;
  16683. } else if (material.emissiveMap) {
  16684. uvScaleMap = material.emissiveMap;
  16685. }
  16686. if (uvScaleMap !== undefined) {
  16687. // backwards compatibility
  16688. if (uvScaleMap.isWebGLRenderTarget) {
  16689. uvScaleMap = uvScaleMap.texture;
  16690. }
  16691. if (uvScaleMap.matrixAutoUpdate === true) {
  16692. uvScaleMap.updateMatrix();
  16693. }
  16694. uniforms.uvTransform.value.copy(uvScaleMap.matrix);
  16695. }
  16696. }
  16697. function refreshUniformsLine(uniforms, material) {
  16698. uniforms.diffuse.value.copy(material.color);
  16699. uniforms.opacity.value = material.opacity;
  16700. }
  16701. function refreshUniformsDash(uniforms, material) {
  16702. uniforms.dashSize.value = material.dashSize;
  16703. uniforms.totalSize.value = material.dashSize + material.gapSize;
  16704. uniforms.scale.value = material.scale;
  16705. }
  16706. function refreshUniformsPoints(uniforms, material) {
  16707. uniforms.diffuse.value.copy(material.color);
  16708. uniforms.opacity.value = material.opacity;
  16709. uniforms.size.value = material.size * _pixelRatio;
  16710. uniforms.scale.value = _height * 0.5;
  16711. uniforms.map.value = material.map;
  16712. if (material.map !== null) {
  16713. if (material.map.matrixAutoUpdate === true) {
  16714. material.map.updateMatrix();
  16715. }
  16716. uniforms.uvTransform.value.copy(material.map.matrix);
  16717. }
  16718. }
  16719. function refreshUniformsSprites(uniforms, material) {
  16720. uniforms.diffuse.value.copy(material.color);
  16721. uniforms.opacity.value = material.opacity;
  16722. uniforms.rotation.value = material.rotation;
  16723. uniforms.map.value = material.map;
  16724. if (material.map !== null) {
  16725. if (material.map.matrixAutoUpdate === true) {
  16726. material.map.updateMatrix();
  16727. }
  16728. uniforms.uvTransform.value.copy(material.map.matrix);
  16729. }
  16730. }
  16731. function refreshUniformsFog(uniforms, fog) {
  16732. uniforms.fogColor.value.copy(fog.color);
  16733. if (fog.isFog) {
  16734. uniforms.fogNear.value = fog.near;
  16735. uniforms.fogFar.value = fog.far;
  16736. } else if (fog.isFogExp2) {
  16737. uniforms.fogDensity.value = fog.density;
  16738. }
  16739. }
  16740. function refreshUniformsLambert(uniforms, material) {
  16741. if (material.emissiveMap) {
  16742. uniforms.emissiveMap.value = material.emissiveMap;
  16743. }
  16744. }
  16745. function refreshUniformsPhong(uniforms, material) {
  16746. uniforms.specular.value.copy(material.specular);
  16747. uniforms.shininess.value = Math.max(material.shininess, 1e-4); // to prevent pow( 0.0, 0.0 )
  16748. if (material.emissiveMap) {
  16749. uniforms.emissiveMap.value = material.emissiveMap;
  16750. }
  16751. if (material.bumpMap) {
  16752. uniforms.bumpMap.value = material.bumpMap;
  16753. uniforms.bumpScale.value = material.bumpScale;
  16754. if (material.side === BackSide) uniforms.bumpScale.value *= -1;
  16755. }
  16756. if (material.normalMap) {
  16757. uniforms.normalMap.value = material.normalMap;
  16758. uniforms.normalScale.value.copy(material.normalScale);
  16759. if (material.side === BackSide) uniforms.normalScale.value.negate();
  16760. }
  16761. if (material.displacementMap) {
  16762. uniforms.displacementMap.value = material.displacementMap;
  16763. uniforms.displacementScale.value = material.displacementScale;
  16764. uniforms.displacementBias.value = material.displacementBias;
  16765. }
  16766. }
  16767. function refreshUniformsToon(uniforms, material) {
  16768. refreshUniformsPhong(uniforms, material);
  16769. if (material.gradientMap) {
  16770. uniforms.gradientMap.value = material.gradientMap;
  16771. }
  16772. }
  16773. function refreshUniformsStandard(uniforms, material) {
  16774. uniforms.roughness.value = material.roughness;
  16775. uniforms.metalness.value = material.metalness;
  16776. if (material.roughnessMap) {
  16777. uniforms.roughnessMap.value = material.roughnessMap;
  16778. }
  16779. if (material.metalnessMap) {
  16780. uniforms.metalnessMap.value = material.metalnessMap;
  16781. }
  16782. if (material.emissiveMap) {
  16783. uniforms.emissiveMap.value = material.emissiveMap;
  16784. }
  16785. if (material.bumpMap) {
  16786. uniforms.bumpMap.value = material.bumpMap;
  16787. uniforms.bumpScale.value = material.bumpScale;
  16788. if (material.side === BackSide) uniforms.bumpScale.value *= -1;
  16789. }
  16790. if (material.normalMap) {
  16791. uniforms.normalMap.value = material.normalMap;
  16792. uniforms.normalScale.value.copy(material.normalScale);
  16793. if (material.side === BackSide) uniforms.normalScale.value.negate();
  16794. }
  16795. if (material.displacementMap) {
  16796. uniforms.displacementMap.value = material.displacementMap;
  16797. uniforms.displacementScale.value = material.displacementScale;
  16798. uniforms.displacementBias.value = material.displacementBias;
  16799. }
  16800. if (material.envMap) {
  16801. //uniforms.envMap.value = material.envMap; // part of uniforms common
  16802. uniforms.envMapIntensity.value = material.envMapIntensity;
  16803. }
  16804. }
  16805. function refreshUniformsPhysical(uniforms, material) {
  16806. refreshUniformsStandard(uniforms, material);
  16807. uniforms.reflectivity.value = material.reflectivity; // also part of uniforms common
  16808. uniforms.clearcoat.value = material.clearcoat;
  16809. uniforms.clearcoatRoughness.value = material.clearcoatRoughness;
  16810. if (material.sheen) uniforms.sheen.value.copy(material.sheen);
  16811. if (material.clearcoatNormalMap) {
  16812. uniforms.clearcoatNormalScale.value.copy(material.clearcoatNormalScale);
  16813. uniforms.clearcoatNormalMap.value = material.clearcoatNormalMap;
  16814. if (material.side === BackSide) {
  16815. uniforms.clearcoatNormalScale.value.negate();
  16816. }
  16817. }
  16818. uniforms.transparency.value = material.transparency;
  16819. }
  16820. function refreshUniformsMatcap(uniforms, material) {
  16821. if (material.matcap) {
  16822. uniforms.matcap.value = material.matcap;
  16823. }
  16824. if (material.bumpMap) {
  16825. uniforms.bumpMap.value = material.bumpMap;
  16826. uniforms.bumpScale.value = material.bumpScale;
  16827. if (material.side === BackSide) uniforms.bumpScale.value *= -1;
  16828. }
  16829. if (material.normalMap) {
  16830. uniforms.normalMap.value = material.normalMap;
  16831. uniforms.normalScale.value.copy(material.normalScale);
  16832. if (material.side === BackSide) uniforms.normalScale.value.negate();
  16833. }
  16834. if (material.displacementMap) {
  16835. uniforms.displacementMap.value = material.displacementMap;
  16836. uniforms.displacementScale.value = material.displacementScale;
  16837. uniforms.displacementBias.value = material.displacementBias;
  16838. }
  16839. }
  16840. function refreshUniformsDepth(uniforms, material) {
  16841. if (material.displacementMap) {
  16842. uniforms.displacementMap.value = material.displacementMap;
  16843. uniforms.displacementScale.value = material.displacementScale;
  16844. uniforms.displacementBias.value = material.displacementBias;
  16845. }
  16846. }
  16847. function refreshUniformsDistance(uniforms, material) {
  16848. if (material.displacementMap) {
  16849. uniforms.displacementMap.value = material.displacementMap;
  16850. uniforms.displacementScale.value = material.displacementScale;
  16851. uniforms.displacementBias.value = material.displacementBias;
  16852. }
  16853. uniforms.referencePosition.value.copy(material.referencePosition);
  16854. uniforms.nearDistance.value = material.nearDistance;
  16855. uniforms.farDistance.value = material.farDistance;
  16856. }
  16857. function refreshUniformsNormal(uniforms, material) {
  16858. if (material.bumpMap) {
  16859. uniforms.bumpMap.value = material.bumpMap;
  16860. uniforms.bumpScale.value = material.bumpScale;
  16861. if (material.side === BackSide) uniforms.bumpScale.value *= -1;
  16862. }
  16863. if (material.normalMap) {
  16864. uniforms.normalMap.value = material.normalMap;
  16865. uniforms.normalScale.value.copy(material.normalScale);
  16866. if (material.side === BackSide) uniforms.normalScale.value.negate();
  16867. }
  16868. if (material.displacementMap) {
  16869. uniforms.displacementMap.value = material.displacementMap;
  16870. uniforms.displacementScale.value = material.displacementScale;
  16871. uniforms.displacementBias.value = material.displacementBias;
  16872. }
  16873. } // If uniforms are marked as clean, they don't need to be loaded to the GPU.
  16874. function markUniformsLightsNeedsUpdate(uniforms, value) {
  16875. uniforms.ambientLightColor.needsUpdate = value;
  16876. uniforms.lightProbe.needsUpdate = value;
  16877. uniforms.directionalLights.needsUpdate = value;
  16878. uniforms.pointLights.needsUpdate = value;
  16879. uniforms.spotLights.needsUpdate = value;
  16880. uniforms.rectAreaLights.needsUpdate = value;
  16881. uniforms.hemisphereLights.needsUpdate = value;
  16882. }
  16883. function materialNeedsLights(material) {
  16884. return material.isMeshLambertMaterial || material.isMeshPhongMaterial || material.isMeshStandardMaterial || material.isShadowMaterial || material.isShaderMaterial && material.lights === true;
  16885. } //
  16886. this.setFramebuffer = function (value) {
  16887. if (_framebuffer !== value) _gl.bindFramebuffer(36160, value);
  16888. _framebuffer = value;
  16889. };
  16890. this.getActiveCubeFace = function () {
  16891. return _currentActiveCubeFace;
  16892. };
  16893. this.getActiveMipmapLevel = function () {
  16894. return _currentActiveMipmapLevel;
  16895. };
  16896. this.getRenderTarget = function () {
  16897. return _currentRenderTarget;
  16898. };
  16899. this.setRenderTarget = function (renderTarget, activeCubeFace, activeMipmapLevel) {
  16900. _currentRenderTarget = renderTarget;
  16901. _currentActiveCubeFace = activeCubeFace;
  16902. _currentActiveMipmapLevel = activeMipmapLevel;
  16903. if (renderTarget && properties.get(renderTarget).__webglFramebuffer === undefined) {
  16904. textures.setupRenderTarget(renderTarget);
  16905. }
  16906. var framebuffer = _framebuffer;
  16907. var isCube = false;
  16908. if (renderTarget) {
  16909. var __webglFramebuffer = properties.get(renderTarget).__webglFramebuffer;
  16910. if (renderTarget.isWebGLRenderTargetCube) {
  16911. framebuffer = __webglFramebuffer[activeCubeFace || 0];
  16912. isCube = true;
  16913. } else if (renderTarget.isWebGLMultisampleRenderTarget) {
  16914. framebuffer = properties.get(renderTarget).__webglMultisampledFramebuffer;
  16915. } else {
  16916. framebuffer = __webglFramebuffer;
  16917. }
  16918. _currentViewport.copy(renderTarget.viewport);
  16919. _currentScissor.copy(renderTarget.scissor);
  16920. _currentScissorTest = renderTarget.scissorTest;
  16921. } else {
  16922. _currentViewport.copy(_viewport).multiplyScalar(_pixelRatio).floor();
  16923. _currentScissor.copy(_scissor).multiplyScalar(_pixelRatio).floor();
  16924. _currentScissorTest = _scissorTest;
  16925. }
  16926. if (_currentFramebuffer !== framebuffer) {
  16927. _gl.bindFramebuffer(36160, framebuffer);
  16928. _currentFramebuffer = framebuffer;
  16929. }
  16930. state.viewport(_currentViewport);
  16931. state.scissor(_currentScissor);
  16932. state.setScissorTest(_currentScissorTest);
  16933. if (isCube) {
  16934. var textureProperties = properties.get(renderTarget.texture);
  16935. _gl.framebufferTexture2D(36160, 36064, 34069 + (activeCubeFace || 0), textureProperties.__webglTexture, activeMipmapLevel || 0);
  16936. }
  16937. };
  16938. this.readRenderTargetPixels = function (renderTarget, x, y, width, height, buffer, activeCubeFaceIndex) {
  16939. if (!(renderTarget && renderTarget.isWebGLRenderTarget)) {
  16940. console.error('THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.');
  16941. return;
  16942. }
  16943. var framebuffer = properties.get(renderTarget).__webglFramebuffer;
  16944. if (renderTarget.isWebGLRenderTargetCube && activeCubeFaceIndex !== undefined) {
  16945. framebuffer = framebuffer[activeCubeFaceIndex];
  16946. }
  16947. if (framebuffer) {
  16948. var restore = false;
  16949. if (framebuffer !== _currentFramebuffer) {
  16950. _gl.bindFramebuffer(36160, framebuffer);
  16951. restore = true;
  16952. }
  16953. try {
  16954. var texture = renderTarget.texture;
  16955. var textureFormat = texture.format;
  16956. var textureType = texture.type;
  16957. if (textureFormat !== RGBAFormat && utils.convert(textureFormat) !== _gl.getParameter(35739)) {
  16958. console.error('THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.');
  16959. return;
  16960. }
  16961. if (textureType !== UnsignedByteType && utils.convert(textureType) !== _gl.getParameter(35738) && // IE11, Edge and Chrome Mac < 52 (#9513)
  16962. !(textureType === FloatType && (capabilities.isWebGL2 || extensions.get('OES_texture_float') || extensions.get('WEBGL_color_buffer_float'))) && // Chrome Mac >= 52 and Firefox
  16963. !(textureType === HalfFloatType && (capabilities.isWebGL2 ? extensions.get('EXT_color_buffer_float') : extensions.get('EXT_color_buffer_half_float')))) {
  16964. console.error('THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.');
  16965. return;
  16966. }
  16967. if (_gl.checkFramebufferStatus(36160) === 36053) {
  16968. // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604)
  16969. if (x >= 0 && x <= renderTarget.width - width && y >= 0 && y <= renderTarget.height - height) {
  16970. _gl.readPixels(x, y, width, height, utils.convert(textureFormat), utils.convert(textureType), buffer);
  16971. }
  16972. } else {
  16973. console.error('THREE.WebGLRenderer.readRenderTargetPixels: readPixels from renderTarget failed. Framebuffer not complete.');
  16974. }
  16975. } finally {
  16976. if (restore) {
  16977. _gl.bindFramebuffer(36160, _currentFramebuffer);
  16978. }
  16979. }
  16980. }
  16981. };
  16982. this.copyFramebufferToTexture = function (position, texture, level) {
  16983. var width = texture.image.width;
  16984. var height = texture.image.height;
  16985. var glFormat = utils.convert(texture.format);
  16986. textures.setTexture2D(texture, 0);
  16987. _gl.copyTexImage2D(3553, level || 0, glFormat, position.x, position.y, width, height, 0);
  16988. };
  16989. this.copyTextureToTexture = function (position, srcTexture, dstTexture, level) {
  16990. var width = srcTexture.image.width;
  16991. var height = srcTexture.image.height;
  16992. var glFormat = utils.convert(dstTexture.format);
  16993. var glType = utils.convert(dstTexture.type);
  16994. textures.setTexture2D(dstTexture, 0);
  16995. if (srcTexture.isDataTexture) {
  16996. _gl.texSubImage2D(3553, level || 0, position.x, position.y, width, height, glFormat, glType, srcTexture.image.data);
  16997. } else {
  16998. _gl.texSubImage2D(3553, level || 0, position.x, position.y, glFormat, glType, srcTexture.image);
  16999. }
  17000. };
  17001. if (typeof __THREE_DEVTOOLS__ !== 'undefined') {
  17002. __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent('observe', {
  17003. detail: this
  17004. })); // eslint-disable-line no-undef
  17005. }
  17006. }
  17007. /**
  17008. * @author mrdoob / http://mrdoob.com/
  17009. * @author alteredq / http://alteredqualia.com/
  17010. */
  17011. function FogExp2(color, density) {
  17012. this.name = '';
  17013. this.color = new Color(color);
  17014. this.density = density !== undefined ? density : 0.00025;
  17015. }
  17016. Object.assign(FogExp2.prototype, {
  17017. isFogExp2: true,
  17018. clone: function () {
  17019. return new FogExp2(this.color, this.density);
  17020. },
  17021. toJSON: function ()
  17022. /* meta */
  17023. {
  17024. return {
  17025. type: 'FogExp2',
  17026. color: this.color.getHex(),
  17027. density: this.density
  17028. };
  17029. }
  17030. });
  17031. /**
  17032. * @author mrdoob / http://mrdoob.com/
  17033. * @author alteredq / http://alteredqualia.com/
  17034. */
  17035. function Fog(color, near, far) {
  17036. this.name = '';
  17037. this.color = new Color(color);
  17038. this.near = near !== undefined ? near : 1;
  17039. this.far = far !== undefined ? far : 1000;
  17040. }
  17041. Object.assign(Fog.prototype, {
  17042. isFog: true,
  17043. clone: function () {
  17044. return new Fog(this.color, this.near, this.far);
  17045. },
  17046. toJSON: function ()
  17047. /* meta */
  17048. {
  17049. return {
  17050. type: 'Fog',
  17051. color: this.color.getHex(),
  17052. near: this.near,
  17053. far: this.far
  17054. };
  17055. }
  17056. });
  17057. /**
  17058. * @author benaadams / https://twitter.com/ben_a_adams
  17059. */
  17060. function InterleavedBuffer(array, stride) {
  17061. this.array = array;
  17062. this.stride = stride;
  17063. this.count = array !== undefined ? array.length / stride : 0;
  17064. this.dynamic = false;
  17065. this.updateRange = {
  17066. offset: 0,
  17067. count: -1
  17068. };
  17069. this.version = 0;
  17070. }
  17071. Object.defineProperty(InterleavedBuffer.prototype, 'needsUpdate', {
  17072. set: function (value) {
  17073. if (value === true) this.version++;
  17074. }
  17075. });
  17076. Object.assign(InterleavedBuffer.prototype, {
  17077. isInterleavedBuffer: true,
  17078. onUploadCallback: function () {},
  17079. setDynamic: function (value) {
  17080. this.dynamic = value;
  17081. return this;
  17082. },
  17083. copy: function (source) {
  17084. this.array = new source.array.constructor(source.array);
  17085. this.count = source.count;
  17086. this.stride = source.stride;
  17087. this.dynamic = source.dynamic;
  17088. return this;
  17089. },
  17090. copyAt: function (index1, attribute, index2) {
  17091. index1 *= this.stride;
  17092. index2 *= attribute.stride;
  17093. for (var i = 0, l = this.stride; i < l; i++) {
  17094. this.array[index1 + i] = attribute.array[index2 + i];
  17095. }
  17096. return this;
  17097. },
  17098. set: function (value, offset) {
  17099. if (offset === undefined) offset = 0;
  17100. this.array.set(value, offset);
  17101. return this;
  17102. },
  17103. clone: function () {
  17104. return new this.constructor().copy(this);
  17105. },
  17106. onUpload: function (callback) {
  17107. this.onUploadCallback = callback;
  17108. return this;
  17109. }
  17110. });
  17111. /**
  17112. * @author benaadams / https://twitter.com/ben_a_adams
  17113. */
  17114. function InterleavedBufferAttribute(interleavedBuffer, itemSize, offset, normalized) {
  17115. this.data = interleavedBuffer;
  17116. this.itemSize = itemSize;
  17117. this.offset = offset;
  17118. this.normalized = normalized === true;
  17119. }
  17120. Object.defineProperties(InterleavedBufferAttribute.prototype, {
  17121. count: {
  17122. get: function () {
  17123. return this.data.count;
  17124. }
  17125. },
  17126. array: {
  17127. get: function () {
  17128. return this.data.array;
  17129. }
  17130. }
  17131. });
  17132. Object.assign(InterleavedBufferAttribute.prototype, {
  17133. isInterleavedBufferAttribute: true,
  17134. setX: function (index, x) {
  17135. this.data.array[index * this.data.stride + this.offset] = x;
  17136. return this;
  17137. },
  17138. setY: function (index, y) {
  17139. this.data.array[index * this.data.stride + this.offset + 1] = y;
  17140. return this;
  17141. },
  17142. setZ: function (index, z) {
  17143. this.data.array[index * this.data.stride + this.offset + 2] = z;
  17144. return this;
  17145. },
  17146. setW: function (index, w) {
  17147. this.data.array[index * this.data.stride + this.offset + 3] = w;
  17148. return this;
  17149. },
  17150. getX: function (index) {
  17151. return this.data.array[index * this.data.stride + this.offset];
  17152. },
  17153. getY: function (index) {
  17154. return this.data.array[index * this.data.stride + this.offset + 1];
  17155. },
  17156. getZ: function (index) {
  17157. return this.data.array[index * this.data.stride + this.offset + 2];
  17158. },
  17159. getW: function (index) {
  17160. return this.data.array[index * this.data.stride + this.offset + 3];
  17161. },
  17162. setXY: function (index, x, y) {
  17163. index = index * this.data.stride + this.offset;
  17164. this.data.array[index + 0] = x;
  17165. this.data.array[index + 1] = y;
  17166. return this;
  17167. },
  17168. setXYZ: function (index, x, y, z) {
  17169. index = index * this.data.stride + this.offset;
  17170. this.data.array[index + 0] = x;
  17171. this.data.array[index + 1] = y;
  17172. this.data.array[index + 2] = z;
  17173. return this;
  17174. },
  17175. setXYZW: function (index, x, y, z, w) {
  17176. index = index * this.data.stride + this.offset;
  17177. this.data.array[index + 0] = x;
  17178. this.data.array[index + 1] = y;
  17179. this.data.array[index + 2] = z;
  17180. this.data.array[index + 3] = w;
  17181. return this;
  17182. }
  17183. });
  17184. /**
  17185. * @author alteredq / http://alteredqualia.com/
  17186. *
  17187. * parameters = {
  17188. * color: <hex>,
  17189. * map: new THREE.Texture( <Image> ),
  17190. * rotation: <float>,
  17191. * sizeAttenuation: <bool>
  17192. * }
  17193. */
  17194. function SpriteMaterial(parameters) {
  17195. Material.call(this);
  17196. this.type = 'SpriteMaterial';
  17197. this.color = new Color(0xffffff);
  17198. this.map = null;
  17199. this.rotation = 0;
  17200. this.sizeAttenuation = true;
  17201. this.transparent = true;
  17202. this.setValues(parameters);
  17203. }
  17204. SpriteMaterial.prototype = Object.create(Material.prototype);
  17205. SpriteMaterial.prototype.constructor = SpriteMaterial;
  17206. SpriteMaterial.prototype.isSpriteMaterial = true;
  17207. SpriteMaterial.prototype.copy = function (source) {
  17208. Material.prototype.copy.call(this, source);
  17209. this.color.copy(source.color);
  17210. this.map = source.map;
  17211. this.rotation = source.rotation;
  17212. this.sizeAttenuation = source.sizeAttenuation;
  17213. return this;
  17214. };
  17215. /**
  17216. * @author mikael emtinger / http://gomo.se/
  17217. * @author alteredq / http://alteredqualia.com/
  17218. */
  17219. var _geometry;
  17220. var _intersectPoint = new Vector3();
  17221. var _worldScale = new Vector3();
  17222. var _mvPosition = new Vector3();
  17223. var _alignedPosition = new Vector2();
  17224. var _rotatedPosition = new Vector2();
  17225. var _viewWorldMatrix = new Matrix4();
  17226. var _vA$1 = new Vector3();
  17227. var _vB$1 = new Vector3();
  17228. var _vC$1 = new Vector3();
  17229. var _uvA$1 = new Vector2();
  17230. var _uvB$1 = new Vector2();
  17231. var _uvC$1 = new Vector2();
  17232. function Sprite(material) {
  17233. Object3D.call(this);
  17234. this.type = 'Sprite';
  17235. if (_geometry === undefined) {
  17236. _geometry = new BufferGeometry();
  17237. 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]);
  17238. var interleavedBuffer = new InterleavedBuffer(float32Array, 5);
  17239. _geometry.setIndex([0, 1, 2, 0, 2, 3]);
  17240. _geometry.addAttribute('position', new InterleavedBufferAttribute(interleavedBuffer, 3, 0, false));
  17241. _geometry.addAttribute('uv', new InterleavedBufferAttribute(interleavedBuffer, 2, 3, false));
  17242. }
  17243. this.geometry = _geometry;
  17244. this.material = material !== undefined ? material : new SpriteMaterial();
  17245. this.center = new Vector2(0.5, 0.5);
  17246. }
  17247. Sprite.prototype = Object.assign(Object.create(Object3D.prototype), {
  17248. constructor: Sprite,
  17249. isSprite: true,
  17250. raycast: function (raycaster, intersects) {
  17251. if (raycaster.camera === null) {
  17252. console.error('THREE.Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.');
  17253. }
  17254. _worldScale.setFromMatrixScale(this.matrixWorld);
  17255. _viewWorldMatrix.copy(raycaster.camera.matrixWorld);
  17256. this.modelViewMatrix.multiplyMatrices(raycaster.camera.matrixWorldInverse, this.matrixWorld);
  17257. _mvPosition.setFromMatrixPosition(this.modelViewMatrix);
  17258. if (raycaster.camera.isPerspectiveCamera && this.material.sizeAttenuation === false) {
  17259. _worldScale.multiplyScalar(-_mvPosition.z);
  17260. }
  17261. var rotation = this.material.rotation;
  17262. var sin, cos;
  17263. if (rotation !== 0) {
  17264. cos = Math.cos(rotation);
  17265. sin = Math.sin(rotation);
  17266. }
  17267. var center = this.center;
  17268. transformVertex(_vA$1.set(-0.5, -0.5, 0), _mvPosition, center, _worldScale, sin, cos);
  17269. transformVertex(_vB$1.set(0.5, -0.5, 0), _mvPosition, center, _worldScale, sin, cos);
  17270. transformVertex(_vC$1.set(0.5, 0.5, 0), _mvPosition, center, _worldScale, sin, cos);
  17271. _uvA$1.set(0, 0);
  17272. _uvB$1.set(1, 0);
  17273. _uvC$1.set(1, 1); // check first triangle
  17274. var intersect = raycaster.ray.intersectTriangle(_vA$1, _vB$1, _vC$1, false, _intersectPoint);
  17275. if (intersect === null) {
  17276. // check second triangle
  17277. transformVertex(_vB$1.set(-0.5, 0.5, 0), _mvPosition, center, _worldScale, sin, cos);
  17278. _uvB$1.set(0, 1);
  17279. intersect = raycaster.ray.intersectTriangle(_vA$1, _vC$1, _vB$1, false, _intersectPoint);
  17280. if (intersect === null) {
  17281. return;
  17282. }
  17283. }
  17284. var distance = raycaster.ray.origin.distanceTo(_intersectPoint);
  17285. if (distance < raycaster.near || distance > raycaster.far) return;
  17286. intersects.push({
  17287. distance: distance,
  17288. point: _intersectPoint.clone(),
  17289. uv: Triangle.getUV(_intersectPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2()),
  17290. face: null,
  17291. object: this
  17292. });
  17293. },
  17294. clone: function () {
  17295. return new this.constructor(this.material).copy(this);
  17296. },
  17297. copy: function (source) {
  17298. Object3D.prototype.copy.call(this, source);
  17299. if (source.center !== undefined) this.center.copy(source.center);
  17300. return this;
  17301. }
  17302. });
  17303. function transformVertex(vertexPosition, mvPosition, center, scale, sin, cos) {
  17304. // compute position in camera space
  17305. _alignedPosition.subVectors(vertexPosition, center).addScalar(0.5).multiply(scale); // to check if rotation is not zero
  17306. if (sin !== undefined) {
  17307. _rotatedPosition.x = cos * _alignedPosition.x - sin * _alignedPosition.y;
  17308. _rotatedPosition.y = sin * _alignedPosition.x + cos * _alignedPosition.y;
  17309. } else {
  17310. _rotatedPosition.copy(_alignedPosition);
  17311. }
  17312. vertexPosition.copy(mvPosition);
  17313. vertexPosition.x += _rotatedPosition.x;
  17314. vertexPosition.y += _rotatedPosition.y; // transform to world space
  17315. vertexPosition.applyMatrix4(_viewWorldMatrix);
  17316. }
  17317. /**
  17318. * @author mikael emtinger / http://gomo.se/
  17319. * @author alteredq / http://alteredqualia.com/
  17320. * @author mrdoob / http://mrdoob.com/
  17321. */
  17322. var _v1$4 = new Vector3();
  17323. var _v2$2 = new Vector3();
  17324. function LOD() {
  17325. Object3D.call(this);
  17326. this.type = 'LOD';
  17327. Object.defineProperties(this, {
  17328. levels: {
  17329. enumerable: true,
  17330. value: []
  17331. }
  17332. });
  17333. this.autoUpdate = true;
  17334. }
  17335. LOD.prototype = Object.assign(Object.create(Object3D.prototype), {
  17336. constructor: LOD,
  17337. isLOD: true,
  17338. copy: function (source) {
  17339. Object3D.prototype.copy.call(this, source, false);
  17340. var levels = source.levels;
  17341. for (var i = 0, l = levels.length; i < l; i++) {
  17342. var level = levels[i];
  17343. this.addLevel(level.object.clone(), level.distance);
  17344. }
  17345. return this;
  17346. },
  17347. addLevel: function (object, distance) {
  17348. if (distance === undefined) distance = 0;
  17349. distance = Math.abs(distance);
  17350. var levels = this.levels;
  17351. for (var l = 0; l < levels.length; l++) {
  17352. if (distance < levels[l].distance) {
  17353. break;
  17354. }
  17355. }
  17356. levels.splice(l, 0, {
  17357. distance: distance,
  17358. object: object
  17359. });
  17360. this.add(object);
  17361. return this;
  17362. },
  17363. getObjectForDistance: function (distance) {
  17364. var levels = this.levels;
  17365. for (var i = 1, l = levels.length; i < l; i++) {
  17366. if (distance < levels[i].distance) {
  17367. break;
  17368. }
  17369. }
  17370. return levels[i - 1].object;
  17371. },
  17372. raycast: function (raycaster, intersects) {
  17373. _v1$4.setFromMatrixPosition(this.matrixWorld);
  17374. var distance = raycaster.ray.origin.distanceTo(_v1$4);
  17375. this.getObjectForDistance(distance).raycast(raycaster, intersects);
  17376. },
  17377. update: function (camera) {
  17378. var levels = this.levels;
  17379. if (levels.length > 1) {
  17380. _v1$4.setFromMatrixPosition(camera.matrixWorld);
  17381. _v2$2.setFromMatrixPosition(this.matrixWorld);
  17382. var distance = _v1$4.distanceTo(_v2$2);
  17383. levels[0].object.visible = true;
  17384. for (var i = 1, l = levels.length; i < l; i++) {
  17385. if (distance >= levels[i].distance) {
  17386. levels[i - 1].object.visible = false;
  17387. levels[i].object.visible = true;
  17388. } else {
  17389. break;
  17390. }
  17391. }
  17392. for (; i < l; i++) {
  17393. levels[i].object.visible = false;
  17394. }
  17395. }
  17396. },
  17397. toJSON: function (meta) {
  17398. var data = Object3D.prototype.toJSON.call(this, meta);
  17399. data.object.levels = [];
  17400. var levels = this.levels;
  17401. for (var i = 0, l = levels.length; i < l; i++) {
  17402. var level = levels[i];
  17403. data.object.levels.push({
  17404. object: level.object.uuid,
  17405. distance: level.distance
  17406. });
  17407. }
  17408. return data;
  17409. }
  17410. });
  17411. /**
  17412. * @author mikael emtinger / http://gomo.se/
  17413. * @author alteredq / http://alteredqualia.com/
  17414. * @author ikerr / http://verold.com
  17415. */
  17416. function SkinnedMesh(geometry, material) {
  17417. if (geometry && geometry.isGeometry) {
  17418. console.error('THREE.SkinnedMesh no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');
  17419. }
  17420. Mesh.call(this, geometry, material);
  17421. this.type = 'SkinnedMesh';
  17422. this.bindMode = 'attached';
  17423. this.bindMatrix = new Matrix4();
  17424. this.bindMatrixInverse = new Matrix4();
  17425. }
  17426. SkinnedMesh.prototype = Object.assign(Object.create(Mesh.prototype), {
  17427. constructor: SkinnedMesh,
  17428. isSkinnedMesh: true,
  17429. bind: function (skeleton, bindMatrix) {
  17430. this.skeleton = skeleton;
  17431. if (bindMatrix === undefined) {
  17432. this.updateMatrixWorld(true);
  17433. this.skeleton.calculateInverses();
  17434. bindMatrix = this.matrixWorld;
  17435. }
  17436. this.bindMatrix.copy(bindMatrix);
  17437. this.bindMatrixInverse.getInverse(bindMatrix);
  17438. },
  17439. pose: function () {
  17440. this.skeleton.pose();
  17441. },
  17442. normalizeSkinWeights: function () {
  17443. var vector = new Vector4();
  17444. var skinWeight = this.geometry.attributes.skinWeight;
  17445. for (var i = 0, l = skinWeight.count; i < l; i++) {
  17446. vector.x = skinWeight.getX(i);
  17447. vector.y = skinWeight.getY(i);
  17448. vector.z = skinWeight.getZ(i);
  17449. vector.w = skinWeight.getW(i);
  17450. var scale = 1.0 / vector.manhattanLength();
  17451. if (scale !== Infinity) {
  17452. vector.multiplyScalar(scale);
  17453. } else {
  17454. vector.set(1, 0, 0, 0); // do something reasonable
  17455. }
  17456. skinWeight.setXYZW(i, vector.x, vector.y, vector.z, vector.w);
  17457. }
  17458. },
  17459. updateMatrixWorld: function (force) {
  17460. Mesh.prototype.updateMatrixWorld.call(this, force);
  17461. if (this.bindMode === 'attached') {
  17462. this.bindMatrixInverse.getInverse(this.matrixWorld);
  17463. } else if (this.bindMode === 'detached') {
  17464. this.bindMatrixInverse.getInverse(this.bindMatrix);
  17465. } else {
  17466. console.warn('THREE.SkinnedMesh: Unrecognized bindMode: ' + this.bindMode);
  17467. }
  17468. },
  17469. clone: function () {
  17470. return new this.constructor(this.geometry, this.material).copy(this);
  17471. }
  17472. });
  17473. /**
  17474. * @author mikael emtinger / http://gomo.se/
  17475. * @author alteredq / http://alteredqualia.com/
  17476. * @author michael guerrero / http://realitymeltdown.com
  17477. * @author ikerr / http://verold.com
  17478. */
  17479. var _offsetMatrix = new Matrix4();
  17480. var _identityMatrix = new Matrix4();
  17481. function Skeleton(bones, boneInverses) {
  17482. // copy the bone array
  17483. bones = bones || [];
  17484. this.bones = bones.slice(0);
  17485. this.boneMatrices = new Float32Array(this.bones.length * 16);
  17486. this.frame = -1; // use the supplied bone inverses or calculate the inverses
  17487. if (boneInverses === undefined) {
  17488. this.calculateInverses();
  17489. } else {
  17490. if (this.bones.length === boneInverses.length) {
  17491. this.boneInverses = boneInverses.slice(0);
  17492. } else {
  17493. console.warn('THREE.Skeleton boneInverses is the wrong length.');
  17494. this.boneInverses = [];
  17495. for (var i = 0, il = this.bones.length; i < il; i++) {
  17496. this.boneInverses.push(new Matrix4());
  17497. }
  17498. }
  17499. }
  17500. }
  17501. Object.assign(Skeleton.prototype, {
  17502. calculateInverses: function () {
  17503. this.boneInverses = [];
  17504. for (var i = 0, il = this.bones.length; i < il; i++) {
  17505. var inverse = new Matrix4();
  17506. if (this.bones[i]) {
  17507. inverse.getInverse(this.bones[i].matrixWorld);
  17508. }
  17509. this.boneInverses.push(inverse);
  17510. }
  17511. },
  17512. pose: function () {
  17513. var bone, i, il; // recover the bind-time world matrices
  17514. for (i = 0, il = this.bones.length; i < il; i++) {
  17515. bone = this.bones[i];
  17516. if (bone) {
  17517. bone.matrixWorld.getInverse(this.boneInverses[i]);
  17518. }
  17519. } // compute the local matrices, positions, rotations and scales
  17520. for (i = 0, il = this.bones.length; i < il; i++) {
  17521. bone = this.bones[i];
  17522. if (bone) {
  17523. if (bone.parent && bone.parent.isBone) {
  17524. bone.matrix.getInverse(bone.parent.matrixWorld);
  17525. bone.matrix.multiply(bone.matrixWorld);
  17526. } else {
  17527. bone.matrix.copy(bone.matrixWorld);
  17528. }
  17529. bone.matrix.decompose(bone.position, bone.quaternion, bone.scale);
  17530. }
  17531. }
  17532. },
  17533. update: function () {
  17534. var bones = this.bones;
  17535. var boneInverses = this.boneInverses;
  17536. var boneMatrices = this.boneMatrices;
  17537. var boneTexture = this.boneTexture; // flatten bone matrices to array
  17538. for (var i = 0, il = bones.length; i < il; i++) {
  17539. // compute the offset between the current and the original transform
  17540. var matrix = bones[i] ? bones[i].matrixWorld : _identityMatrix;
  17541. _offsetMatrix.multiplyMatrices(matrix, boneInverses[i]);
  17542. _offsetMatrix.toArray(boneMatrices, i * 16);
  17543. }
  17544. if (boneTexture !== undefined) {
  17545. boneTexture.needsUpdate = true;
  17546. }
  17547. },
  17548. clone: function () {
  17549. return new Skeleton(this.bones, this.boneInverses);
  17550. },
  17551. getBoneByName: function (name) {
  17552. for (var i = 0, il = this.bones.length; i < il; i++) {
  17553. var bone = this.bones[i];
  17554. if (bone.name === name) {
  17555. return bone;
  17556. }
  17557. }
  17558. return undefined;
  17559. }
  17560. });
  17561. /**
  17562. * @author mikael emtinger / http://gomo.se/
  17563. * @author alteredq / http://alteredqualia.com/
  17564. * @author ikerr / http://verold.com
  17565. */
  17566. function Bone() {
  17567. Object3D.call(this);
  17568. this.type = 'Bone';
  17569. }
  17570. Bone.prototype = Object.assign(Object.create(Object3D.prototype), {
  17571. constructor: Bone,
  17572. isBone: true
  17573. });
  17574. /**
  17575. * @author mrdoob / http://mrdoob.com/
  17576. */
  17577. function InstancedMesh(geometry, material, count) {
  17578. Mesh.call(this, geometry, material);
  17579. this.instanceMatrix = new BufferAttribute(new Float32Array(count * 16), 16);
  17580. this.count = count;
  17581. }
  17582. InstancedMesh.prototype = Object.assign(Object.create(Mesh.prototype), {
  17583. constructor: InstancedMesh,
  17584. isInstancedMesh: true,
  17585. raycast: function () {},
  17586. setMatrixAt: function (index, matrix) {
  17587. matrix.toArray(this.instanceMatrix.array, index * 16);
  17588. },
  17589. updateMorphTargets: function () {}
  17590. });
  17591. /**
  17592. * @author mrdoob / http://mrdoob.com/
  17593. * @author alteredq / http://alteredqualia.com/
  17594. *
  17595. * parameters = {
  17596. * color: <hex>,
  17597. * opacity: <float>,
  17598. *
  17599. * linewidth: <float>,
  17600. * linecap: "round",
  17601. * linejoin: "round"
  17602. * }
  17603. */
  17604. function LineBasicMaterial(parameters) {
  17605. Material.call(this);
  17606. this.type = 'LineBasicMaterial';
  17607. this.color = new Color(0xffffff);
  17608. this.linewidth = 1;
  17609. this.linecap = 'round';
  17610. this.linejoin = 'round';
  17611. this.setValues(parameters);
  17612. }
  17613. LineBasicMaterial.prototype = Object.create(Material.prototype);
  17614. LineBasicMaterial.prototype.constructor = LineBasicMaterial;
  17615. LineBasicMaterial.prototype.isLineBasicMaterial = true;
  17616. LineBasicMaterial.prototype.copy = function (source) {
  17617. Material.prototype.copy.call(this, source);
  17618. this.color.copy(source.color);
  17619. this.linewidth = source.linewidth;
  17620. this.linecap = source.linecap;
  17621. this.linejoin = source.linejoin;
  17622. return this;
  17623. };
  17624. /**
  17625. * @author mrdoob / http://mrdoob.com/
  17626. */
  17627. var _start = new Vector3();
  17628. var _end = new Vector3();
  17629. var _inverseMatrix$1 = new Matrix4();
  17630. var _ray$1 = new Ray();
  17631. var _sphere$2 = new Sphere();
  17632. function Line(geometry, material, mode) {
  17633. if (mode === 1) {
  17634. console.error('THREE.Line: parameter THREE.LinePieces no longer supported. Use THREE.LineSegments instead.');
  17635. }
  17636. Object3D.call(this);
  17637. this.type = 'Line';
  17638. this.geometry = geometry !== undefined ? geometry : new BufferGeometry();
  17639. this.material = material !== undefined ? material : new LineBasicMaterial({
  17640. color: Math.random() * 0xffffff
  17641. });
  17642. }
  17643. Line.prototype = Object.assign(Object.create(Object3D.prototype), {
  17644. constructor: Line,
  17645. isLine: true,
  17646. computeLineDistances: function () {
  17647. var geometry = this.geometry;
  17648. if (geometry.isBufferGeometry) {
  17649. // we assume non-indexed geometry
  17650. if (geometry.index === null) {
  17651. var positionAttribute = geometry.attributes.position;
  17652. var lineDistances = [0];
  17653. for (var i = 1, l = positionAttribute.count; i < l; i++) {
  17654. _start.fromBufferAttribute(positionAttribute, i - 1);
  17655. _end.fromBufferAttribute(positionAttribute, i);
  17656. lineDistances[i] = lineDistances[i - 1];
  17657. lineDistances[i] += _start.distanceTo(_end);
  17658. }
  17659. geometry.addAttribute('lineDistance', new Float32BufferAttribute(lineDistances, 1));
  17660. } else {
  17661. console.warn('THREE.Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.');
  17662. }
  17663. } else if (geometry.isGeometry) {
  17664. var vertices = geometry.vertices;
  17665. var lineDistances = geometry.lineDistances;
  17666. lineDistances[0] = 0;
  17667. for (var i = 1, l = vertices.length; i < l; i++) {
  17668. lineDistances[i] = lineDistances[i - 1];
  17669. lineDistances[i] += vertices[i - 1].distanceTo(vertices[i]);
  17670. }
  17671. }
  17672. return this;
  17673. },
  17674. raycast: function (raycaster, intersects) {
  17675. var precision = raycaster.linePrecision;
  17676. var geometry = this.geometry;
  17677. var matrixWorld = this.matrixWorld; // Checking boundingSphere distance to ray
  17678. if (geometry.boundingSphere === null) geometry.computeBoundingSphere();
  17679. _sphere$2.copy(geometry.boundingSphere);
  17680. _sphere$2.applyMatrix4(matrixWorld);
  17681. _sphere$2.radius += precision;
  17682. if (raycaster.ray.intersectsSphere(_sphere$2) === false) return; //
  17683. _inverseMatrix$1.getInverse(matrixWorld);
  17684. _ray$1.copy(raycaster.ray).applyMatrix4(_inverseMatrix$1);
  17685. var localPrecision = precision / ((this.scale.x + this.scale.y + this.scale.z) / 3);
  17686. var localPrecisionSq = localPrecision * localPrecision;
  17687. var vStart = new Vector3();
  17688. var vEnd = new Vector3();
  17689. var interSegment = new Vector3();
  17690. var interRay = new Vector3();
  17691. var step = this && this.isLineSegments ? 2 : 1;
  17692. if (geometry.isBufferGeometry) {
  17693. var index = geometry.index;
  17694. var attributes = geometry.attributes;
  17695. var positions = attributes.position.array;
  17696. if (index !== null) {
  17697. var indices = index.array;
  17698. for (var i = 0, l = indices.length - 1; i < l; i += step) {
  17699. var a = indices[i];
  17700. var b = indices[i + 1];
  17701. vStart.fromArray(positions, a * 3);
  17702. vEnd.fromArray(positions, b * 3);
  17703. var distSq = _ray$1.distanceSqToSegment(vStart, vEnd, interRay, interSegment);
  17704. if (distSq > localPrecisionSq) continue;
  17705. interRay.applyMatrix4(this.matrixWorld); //Move back to world space for distance calculation
  17706. var distance = raycaster.ray.origin.distanceTo(interRay);
  17707. if (distance < raycaster.near || distance > raycaster.far) continue;
  17708. intersects.push({
  17709. distance: distance,
  17710. // What do we want? intersection point on the ray or on the segment??
  17711. // point: raycaster.ray.at( distance ),
  17712. point: interSegment.clone().applyMatrix4(this.matrixWorld),
  17713. index: i,
  17714. face: null,
  17715. faceIndex: null,
  17716. object: this
  17717. });
  17718. }
  17719. } else {
  17720. for (var i = 0, l = positions.length / 3 - 1; i < l; i += step) {
  17721. vStart.fromArray(positions, 3 * i);
  17722. vEnd.fromArray(positions, 3 * i + 3);
  17723. var distSq = _ray$1.distanceSqToSegment(vStart, vEnd, interRay, interSegment);
  17724. if (distSq > localPrecisionSq) continue;
  17725. interRay.applyMatrix4(this.matrixWorld); //Move back to world space for distance calculation
  17726. var distance = raycaster.ray.origin.distanceTo(interRay);
  17727. if (distance < raycaster.near || distance > raycaster.far) continue;
  17728. intersects.push({
  17729. distance: distance,
  17730. // What do we want? intersection point on the ray or on the segment??
  17731. // point: raycaster.ray.at( distance ),
  17732. point: interSegment.clone().applyMatrix4(this.matrixWorld),
  17733. index: i,
  17734. face: null,
  17735. faceIndex: null,
  17736. object: this
  17737. });
  17738. }
  17739. }
  17740. } else if (geometry.isGeometry) {
  17741. var vertices = geometry.vertices;
  17742. var nbVertices = vertices.length;
  17743. for (var i = 0; i < nbVertices - 1; i += step) {
  17744. var distSq = _ray$1.distanceSqToSegment(vertices[i], vertices[i + 1], interRay, interSegment);
  17745. if (distSq > localPrecisionSq) continue;
  17746. interRay.applyMatrix4(this.matrixWorld); //Move back to world space for distance calculation
  17747. var distance = raycaster.ray.origin.distanceTo(interRay);
  17748. if (distance < raycaster.near || distance > raycaster.far) continue;
  17749. intersects.push({
  17750. distance: distance,
  17751. // What do we want? intersection point on the ray or on the segment??
  17752. // point: raycaster.ray.at( distance ),
  17753. point: interSegment.clone().applyMatrix4(this.matrixWorld),
  17754. index: i,
  17755. face: null,
  17756. faceIndex: null,
  17757. object: this
  17758. });
  17759. }
  17760. }
  17761. },
  17762. clone: function () {
  17763. return new this.constructor(this.geometry, this.material).copy(this);
  17764. }
  17765. });
  17766. /**
  17767. * @author mrdoob / http://mrdoob.com/
  17768. */
  17769. var _start$1 = new Vector3();
  17770. var _end$1 = new Vector3();
  17771. function LineSegments(geometry, material) {
  17772. Line.call(this, geometry, material);
  17773. this.type = 'LineSegments';
  17774. }
  17775. LineSegments.prototype = Object.assign(Object.create(Line.prototype), {
  17776. constructor: LineSegments,
  17777. isLineSegments: true,
  17778. computeLineDistances: function () {
  17779. var geometry = this.geometry;
  17780. if (geometry.isBufferGeometry) {
  17781. // we assume non-indexed geometry
  17782. if (geometry.index === null) {
  17783. var positionAttribute = geometry.attributes.position;
  17784. var lineDistances = [];
  17785. for (var i = 0, l = positionAttribute.count; i < l; i += 2) {
  17786. _start$1.fromBufferAttribute(positionAttribute, i);
  17787. _end$1.fromBufferAttribute(positionAttribute, i + 1);
  17788. lineDistances[i] = i === 0 ? 0 : lineDistances[i - 1];
  17789. lineDistances[i + 1] = lineDistances[i] + _start$1.distanceTo(_end$1);
  17790. }
  17791. geometry.addAttribute('lineDistance', new Float32BufferAttribute(lineDistances, 1));
  17792. } else {
  17793. console.warn('THREE.LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.');
  17794. }
  17795. } else if (geometry.isGeometry) {
  17796. var vertices = geometry.vertices;
  17797. var lineDistances = geometry.lineDistances;
  17798. for (var i = 0, l = vertices.length; i < l; i += 2) {
  17799. _start$1.copy(vertices[i]);
  17800. _end$1.copy(vertices[i + 1]);
  17801. lineDistances[i] = i === 0 ? 0 : lineDistances[i - 1];
  17802. lineDistances[i + 1] = lineDistances[i] + _start$1.distanceTo(_end$1);
  17803. }
  17804. }
  17805. return this;
  17806. }
  17807. });
  17808. /**
  17809. * @author mgreter / http://github.com/mgreter
  17810. */
  17811. function LineLoop(geometry, material) {
  17812. Line.call(this, geometry, material);
  17813. this.type = 'LineLoop';
  17814. }
  17815. LineLoop.prototype = Object.assign(Object.create(Line.prototype), {
  17816. constructor: LineLoop,
  17817. isLineLoop: true
  17818. });
  17819. /**
  17820. * @author mrdoob / http://mrdoob.com/
  17821. * @author alteredq / http://alteredqualia.com/
  17822. *
  17823. * parameters = {
  17824. * color: <hex>,
  17825. * opacity: <float>,
  17826. * map: new THREE.Texture( <Image> ),
  17827. *
  17828. * size: <float>,
  17829. * sizeAttenuation: <bool>
  17830. *
  17831. * morphTargets: <bool>
  17832. * }
  17833. */
  17834. function PointsMaterial(parameters) {
  17835. Material.call(this);
  17836. this.type = 'PointsMaterial';
  17837. this.color = new Color(0xffffff);
  17838. this.map = null;
  17839. this.size = 1;
  17840. this.sizeAttenuation = true;
  17841. this.morphTargets = false;
  17842. this.setValues(parameters);
  17843. }
  17844. PointsMaterial.prototype = Object.create(Material.prototype);
  17845. PointsMaterial.prototype.constructor = PointsMaterial;
  17846. PointsMaterial.prototype.isPointsMaterial = true;
  17847. PointsMaterial.prototype.copy = function (source) {
  17848. Material.prototype.copy.call(this, source);
  17849. this.color.copy(source.color);
  17850. this.map = source.map;
  17851. this.size = source.size;
  17852. this.sizeAttenuation = source.sizeAttenuation;
  17853. this.morphTargets = source.morphTargets;
  17854. return this;
  17855. };
  17856. /**
  17857. * @author alteredq / http://alteredqualia.com/
  17858. */
  17859. var _inverseMatrix$2 = new Matrix4();
  17860. var _ray$2 = new Ray();
  17861. var _sphere$3 = new Sphere();
  17862. var _position$1 = new Vector3();
  17863. function Points(geometry, material) {
  17864. Object3D.call(this);
  17865. this.type = 'Points';
  17866. this.geometry = geometry !== undefined ? geometry : new BufferGeometry();
  17867. this.material = material !== undefined ? material : new PointsMaterial({
  17868. color: Math.random() * 0xffffff
  17869. });
  17870. this.updateMorphTargets();
  17871. }
  17872. Points.prototype = Object.assign(Object.create(Object3D.prototype), {
  17873. constructor: Points,
  17874. isPoints: true,
  17875. raycast: function (raycaster, intersects) {
  17876. var geometry = this.geometry;
  17877. var matrixWorld = this.matrixWorld;
  17878. var threshold = raycaster.params.Points.threshold; // Checking boundingSphere distance to ray
  17879. if (geometry.boundingSphere === null) geometry.computeBoundingSphere();
  17880. _sphere$3.copy(geometry.boundingSphere);
  17881. _sphere$3.applyMatrix4(matrixWorld);
  17882. _sphere$3.radius += threshold;
  17883. if (raycaster.ray.intersectsSphere(_sphere$3) === false) return; //
  17884. _inverseMatrix$2.getInverse(matrixWorld);
  17885. _ray$2.copy(raycaster.ray).applyMatrix4(_inverseMatrix$2);
  17886. var localThreshold = threshold / ((this.scale.x + this.scale.y + this.scale.z) / 3);
  17887. var localThresholdSq = localThreshold * localThreshold;
  17888. if (geometry.isBufferGeometry) {
  17889. var index = geometry.index;
  17890. var attributes = geometry.attributes;
  17891. var positions = attributes.position.array;
  17892. if (index !== null) {
  17893. var indices = index.array;
  17894. for (var i = 0, il = indices.length; i < il; i++) {
  17895. var a = indices[i];
  17896. _position$1.fromArray(positions, a * 3);
  17897. testPoint(_position$1, a, localThresholdSq, matrixWorld, raycaster, intersects, this);
  17898. }
  17899. } else {
  17900. for (var i = 0, l = positions.length / 3; i < l; i++) {
  17901. _position$1.fromArray(positions, i * 3);
  17902. testPoint(_position$1, i, localThresholdSq, matrixWorld, raycaster, intersects, this);
  17903. }
  17904. }
  17905. } else {
  17906. var vertices = geometry.vertices;
  17907. for (var i = 0, l = vertices.length; i < l; i++) {
  17908. testPoint(vertices[i], i, localThresholdSq, matrixWorld, raycaster, intersects, this);
  17909. }
  17910. }
  17911. },
  17912. updateMorphTargets: function () {
  17913. var geometry = this.geometry;
  17914. var m, ml, name;
  17915. if (geometry.isBufferGeometry) {
  17916. var morphAttributes = geometry.morphAttributes;
  17917. var keys = Object.keys(morphAttributes);
  17918. if (keys.length > 0) {
  17919. var morphAttribute = morphAttributes[keys[0]];
  17920. if (morphAttribute !== undefined) {
  17921. this.morphTargetInfluences = [];
  17922. this.morphTargetDictionary = {};
  17923. for (m = 0, ml = morphAttribute.length; m < ml; m++) {
  17924. name = morphAttribute[m].name || String(m);
  17925. this.morphTargetInfluences.push(0);
  17926. this.morphTargetDictionary[name] = m;
  17927. }
  17928. }
  17929. }
  17930. } else {
  17931. var morphTargets = geometry.morphTargets;
  17932. if (morphTargets !== undefined && morphTargets.length > 0) {
  17933. console.error('THREE.Points.updateMorphTargets() does not support THREE.Geometry. Use THREE.BufferGeometry instead.');
  17934. }
  17935. }
  17936. },
  17937. clone: function () {
  17938. return new this.constructor(this.geometry, this.material).copy(this);
  17939. }
  17940. });
  17941. function testPoint(point, index, localThresholdSq, matrixWorld, raycaster, intersects, object) {
  17942. var rayPointDistanceSq = _ray$2.distanceSqToPoint(point);
  17943. if (rayPointDistanceSq < localThresholdSq) {
  17944. var intersectPoint = new Vector3();
  17945. _ray$2.closestPointToPoint(point, intersectPoint);
  17946. intersectPoint.applyMatrix4(matrixWorld);
  17947. var distance = raycaster.ray.origin.distanceTo(intersectPoint);
  17948. if (distance < raycaster.near || distance > raycaster.far) return;
  17949. intersects.push({
  17950. distance: distance,
  17951. distanceToRay: Math.sqrt(rayPointDistanceSq),
  17952. point: intersectPoint,
  17953. index: index,
  17954. face: null,
  17955. object: object
  17956. });
  17957. }
  17958. }
  17959. /**
  17960. * @author mrdoob / http://mrdoob.com/
  17961. */
  17962. function VideoTexture(video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy) {
  17963. Texture.call(this, video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy);
  17964. this.format = format !== undefined ? format : RGBFormat;
  17965. this.minFilter = minFilter !== undefined ? minFilter : LinearFilter;
  17966. this.magFilter = magFilter !== undefined ? magFilter : LinearFilter;
  17967. this.generateMipmaps = false;
  17968. }
  17969. VideoTexture.prototype = Object.assign(Object.create(Texture.prototype), {
  17970. constructor: VideoTexture,
  17971. isVideoTexture: true,
  17972. update: function () {
  17973. var video = this.image;
  17974. if (video.readyState >= video.HAVE_CURRENT_DATA) {
  17975. this.needsUpdate = true;
  17976. }
  17977. }
  17978. });
  17979. /**
  17980. * @author alteredq / http://alteredqualia.com/
  17981. */
  17982. function CompressedTexture(mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding) {
  17983. Texture.call(this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding);
  17984. this.image = {
  17985. width: width,
  17986. height: height
  17987. };
  17988. this.mipmaps = mipmaps; // no flipping for cube textures
  17989. // (also flipping doesn't work for compressed textures )
  17990. this.flipY = false; // can't generate mipmaps for compressed textures
  17991. // mips must be embedded in DDS files
  17992. this.generateMipmaps = false;
  17993. }
  17994. CompressedTexture.prototype = Object.create(Texture.prototype);
  17995. CompressedTexture.prototype.constructor = CompressedTexture;
  17996. CompressedTexture.prototype.isCompressedTexture = true;
  17997. /**
  17998. * @author mrdoob / http://mrdoob.com/
  17999. */
  18000. function CanvasTexture(canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy) {
  18001. Texture.call(this, canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy);
  18002. this.needsUpdate = true;
  18003. }
  18004. CanvasTexture.prototype = Object.create(Texture.prototype);
  18005. CanvasTexture.prototype.constructor = CanvasTexture;
  18006. CanvasTexture.prototype.isCanvasTexture = true;
  18007. /**
  18008. * @author Matt DesLauriers / @mattdesl
  18009. * @author atix / arthursilber.de
  18010. */
  18011. function DepthTexture(width, height, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, format) {
  18012. format = format !== undefined ? format : DepthFormat;
  18013. if (format !== DepthFormat && format !== DepthStencilFormat) {
  18014. throw new Error('DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat');
  18015. }
  18016. if (type === undefined && format === DepthFormat) type = UnsignedShortType;
  18017. if (type === undefined && format === DepthStencilFormat) type = UnsignedInt248Type;
  18018. Texture.call(this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy);
  18019. this.image = {
  18020. width: width,
  18021. height: height
  18022. };
  18023. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  18024. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  18025. this.flipY = false;
  18026. this.generateMipmaps = false;
  18027. }
  18028. DepthTexture.prototype = Object.create(Texture.prototype);
  18029. DepthTexture.prototype.constructor = DepthTexture;
  18030. DepthTexture.prototype.isDepthTexture = true;
  18031. /**
  18032. * @author mrdoob / http://mrdoob.com/
  18033. * @author Mugen87 / https://github.com/Mugen87
  18034. */
  18035. function WireframeGeometry(geometry) {
  18036. BufferGeometry.call(this);
  18037. this.type = 'WireframeGeometry'; // buffer
  18038. var vertices = []; // helper variables
  18039. var i, j, l, o, ol;
  18040. var edge = [0, 0],
  18041. edges = {},
  18042. e,
  18043. edge1,
  18044. edge2;
  18045. var key,
  18046. keys = ['a', 'b', 'c'];
  18047. var vertex; // different logic for Geometry and BufferGeometry
  18048. if (geometry && geometry.isGeometry) {
  18049. // create a data structure that contains all edges without duplicates
  18050. var faces = geometry.faces;
  18051. for (i = 0, l = faces.length; i < l; i++) {
  18052. var face = faces[i];
  18053. for (j = 0; j < 3; j++) {
  18054. edge1 = face[keys[j]];
  18055. edge2 = face[keys[(j + 1) % 3]];
  18056. edge[0] = Math.min(edge1, edge2); // sorting prevents duplicates
  18057. edge[1] = Math.max(edge1, edge2);
  18058. key = edge[0] + ',' + edge[1];
  18059. if (edges[key] === undefined) {
  18060. edges[key] = {
  18061. index1: edge[0],
  18062. index2: edge[1]
  18063. };
  18064. }
  18065. }
  18066. } // generate vertices
  18067. for (key in edges) {
  18068. e = edges[key];
  18069. vertex = geometry.vertices[e.index1];
  18070. vertices.push(vertex.x, vertex.y, vertex.z);
  18071. vertex = geometry.vertices[e.index2];
  18072. vertices.push(vertex.x, vertex.y, vertex.z);
  18073. }
  18074. } else if (geometry && geometry.isBufferGeometry) {
  18075. var position, indices, groups;
  18076. var group, start, count;
  18077. var index1, index2;
  18078. vertex = new Vector3();
  18079. if (geometry.index !== null) {
  18080. // indexed BufferGeometry
  18081. position = geometry.attributes.position;
  18082. indices = geometry.index;
  18083. groups = geometry.groups;
  18084. if (groups.length === 0) {
  18085. groups = [{
  18086. start: 0,
  18087. count: indices.count,
  18088. materialIndex: 0
  18089. }];
  18090. } // create a data structure that contains all eges without duplicates
  18091. for (o = 0, ol = groups.length; o < ol; ++o) {
  18092. group = groups[o];
  18093. start = group.start;
  18094. count = group.count;
  18095. for (i = start, l = start + count; i < l; i += 3) {
  18096. for (j = 0; j < 3; j++) {
  18097. edge1 = indices.getX(i + j);
  18098. edge2 = indices.getX(i + (j + 1) % 3);
  18099. edge[0] = Math.min(edge1, edge2); // sorting prevents duplicates
  18100. edge[1] = Math.max(edge1, edge2);
  18101. key = edge[0] + ',' + edge[1];
  18102. if (edges[key] === undefined) {
  18103. edges[key] = {
  18104. index1: edge[0],
  18105. index2: edge[1]
  18106. };
  18107. }
  18108. }
  18109. }
  18110. } // generate vertices
  18111. for (key in edges) {
  18112. e = edges[key];
  18113. vertex.fromBufferAttribute(position, e.index1);
  18114. vertices.push(vertex.x, vertex.y, vertex.z);
  18115. vertex.fromBufferAttribute(position, e.index2);
  18116. vertices.push(vertex.x, vertex.y, vertex.z);
  18117. }
  18118. } else {
  18119. // non-indexed BufferGeometry
  18120. position = geometry.attributes.position;
  18121. for (i = 0, l = position.count / 3; i < l; i++) {
  18122. for (j = 0; j < 3; j++) {
  18123. // three edges per triangle, an edge is represented as (index1, index2)
  18124. // e.g. the first triangle has the following edges: (0,1),(1,2),(2,0)
  18125. index1 = 3 * i + j;
  18126. vertex.fromBufferAttribute(position, index1);
  18127. vertices.push(vertex.x, vertex.y, vertex.z);
  18128. index2 = 3 * i + (j + 1) % 3;
  18129. vertex.fromBufferAttribute(position, index2);
  18130. vertices.push(vertex.x, vertex.y, vertex.z);
  18131. }
  18132. }
  18133. }
  18134. } // build geometry
  18135. this.addAttribute('position', new Float32BufferAttribute(vertices, 3));
  18136. }
  18137. WireframeGeometry.prototype = Object.create(BufferGeometry.prototype);
  18138. WireframeGeometry.prototype.constructor = WireframeGeometry;
  18139. /**
  18140. * @author zz85 / https://github.com/zz85
  18141. * @author Mugen87 / https://github.com/Mugen87
  18142. *
  18143. * Parametric Surfaces Geometry
  18144. * based on the brilliant article by @prideout http://prideout.net/blog/?p=44
  18145. */
  18146. // ParametricGeometry
  18147. function ParametricGeometry(func, slices, stacks) {
  18148. Geometry.call(this);
  18149. this.type = 'ParametricGeometry';
  18150. this.parameters = {
  18151. func: func,
  18152. slices: slices,
  18153. stacks: stacks
  18154. };
  18155. this.fromBufferGeometry(new ParametricBufferGeometry(func, slices, stacks));
  18156. this.mergeVertices();
  18157. }
  18158. ParametricGeometry.prototype = Object.create(Geometry.prototype);
  18159. ParametricGeometry.prototype.constructor = ParametricGeometry; // ParametricBufferGeometry
  18160. function ParametricBufferGeometry(func, slices, stacks) {
  18161. BufferGeometry.call(this);
  18162. this.type = 'ParametricBufferGeometry';
  18163. this.parameters = {
  18164. func: func,
  18165. slices: slices,
  18166. stacks: stacks
  18167. }; // buffers
  18168. var indices = [];
  18169. var vertices = [];
  18170. var normals = [];
  18171. var uvs = [];
  18172. var EPS = 0.00001;
  18173. var normal = new Vector3();
  18174. var p0 = new Vector3(),
  18175. p1 = new Vector3();
  18176. var pu = new Vector3(),
  18177. pv = new Vector3();
  18178. var i, j;
  18179. if (func.length < 3) {
  18180. console.error('THREE.ParametricGeometry: Function must now modify a Vector3 as third parameter.');
  18181. } // generate vertices, normals and uvs
  18182. var sliceCount = slices + 1;
  18183. for (i = 0; i <= stacks; i++) {
  18184. var v = i / stacks;
  18185. for (j = 0; j <= slices; j++) {
  18186. var u = j / slices; // vertex
  18187. func(u, v, p0);
  18188. vertices.push(p0.x, p0.y, p0.z); // normal
  18189. // approximate tangent vectors via finite differences
  18190. if (u - EPS >= 0) {
  18191. func(u - EPS, v, p1);
  18192. pu.subVectors(p0, p1);
  18193. } else {
  18194. func(u + EPS, v, p1);
  18195. pu.subVectors(p1, p0);
  18196. }
  18197. if (v - EPS >= 0) {
  18198. func(u, v - EPS, p1);
  18199. pv.subVectors(p0, p1);
  18200. } else {
  18201. func(u, v + EPS, p1);
  18202. pv.subVectors(p1, p0);
  18203. } // cross product of tangent vectors returns surface normal
  18204. normal.crossVectors(pu, pv).normalize();
  18205. normals.push(normal.x, normal.y, normal.z); // uv
  18206. uvs.push(u, v);
  18207. }
  18208. } // generate indices
  18209. for (i = 0; i < stacks; i++) {
  18210. for (j = 0; j < slices; j++) {
  18211. var a = i * sliceCount + j;
  18212. var b = i * sliceCount + j + 1;
  18213. var c = (i + 1) * sliceCount + j + 1;
  18214. var d = (i + 1) * sliceCount + j; // faces one and two
  18215. indices.push(a, b, d);
  18216. indices.push(b, c, d);
  18217. }
  18218. } // build geometry
  18219. this.setIndex(indices);
  18220. this.addAttribute('position', new Float32BufferAttribute(vertices, 3));
  18221. this.addAttribute('normal', new Float32BufferAttribute(normals, 3));
  18222. this.addAttribute('uv', new Float32BufferAttribute(uvs, 2));
  18223. }
  18224. ParametricBufferGeometry.prototype = Object.create(BufferGeometry.prototype);
  18225. ParametricBufferGeometry.prototype.constructor = ParametricBufferGeometry;
  18226. /**
  18227. * @author clockworkgeek / https://github.com/clockworkgeek
  18228. * @author timothypratley / https://github.com/timothypratley
  18229. * @author WestLangley / http://github.com/WestLangley
  18230. * @author Mugen87 / https://github.com/Mugen87
  18231. */
  18232. // PolyhedronGeometry
  18233. function PolyhedronGeometry(vertices, indices, radius, detail) {
  18234. Geometry.call(this);
  18235. this.type = 'PolyhedronGeometry';
  18236. this.parameters = {
  18237. vertices: vertices,
  18238. indices: indices,
  18239. radius: radius,
  18240. detail: detail
  18241. };
  18242. this.fromBufferGeometry(new PolyhedronBufferGeometry(vertices, indices, radius, detail));
  18243. this.mergeVertices();
  18244. }
  18245. PolyhedronGeometry.prototype = Object.create(Geometry.prototype);
  18246. PolyhedronGeometry.prototype.constructor = PolyhedronGeometry; // PolyhedronBufferGeometry
  18247. function PolyhedronBufferGeometry(vertices, indices, radius, detail) {
  18248. BufferGeometry.call(this);
  18249. this.type = 'PolyhedronBufferGeometry';
  18250. this.parameters = {
  18251. vertices: vertices,
  18252. indices: indices,
  18253. radius: radius,
  18254. detail: detail
  18255. };
  18256. radius = radius || 1;
  18257. detail = detail || 0; // default buffer data
  18258. var vertexBuffer = [];
  18259. var uvBuffer = []; // the subdivision creates the vertex buffer data
  18260. subdivide(detail); // all vertices should lie on a conceptual sphere with a given radius
  18261. applyRadius(radius); // finally, create the uv data
  18262. generateUVs(); // build non-indexed geometry
  18263. this.addAttribute('position', new Float32BufferAttribute(vertexBuffer, 3));
  18264. this.addAttribute('normal', new Float32BufferAttribute(vertexBuffer.slice(), 3));
  18265. this.addAttribute('uv', new Float32BufferAttribute(uvBuffer, 2));
  18266. if (detail === 0) {
  18267. this.computeVertexNormals(); // flat normals
  18268. } else {
  18269. this.normalizeNormals(); // smooth normals
  18270. } // helper functions
  18271. function subdivide(detail) {
  18272. var a = new Vector3();
  18273. var b = new Vector3();
  18274. var c = new Vector3(); // iterate over all faces and apply a subdivison with the given detail value
  18275. for (var i = 0; i < indices.length; i += 3) {
  18276. // get the vertices of the face
  18277. getVertexByIndex(indices[i + 0], a);
  18278. getVertexByIndex(indices[i + 1], b);
  18279. getVertexByIndex(indices[i + 2], c); // perform subdivision
  18280. subdivideFace(a, b, c, detail);
  18281. }
  18282. }
  18283. function subdivideFace(a, b, c, detail) {
  18284. var cols = Math.pow(2, detail); // we use this multidimensional array as a data structure for creating the subdivision
  18285. var v = [];
  18286. var i, j; // construct all of the vertices for this subdivision
  18287. for (i = 0; i <= cols; i++) {
  18288. v[i] = [];
  18289. var aj = a.clone().lerp(c, i / cols);
  18290. var bj = b.clone().lerp(c, i / cols);
  18291. var rows = cols - i;
  18292. for (j = 0; j <= rows; j++) {
  18293. if (j === 0 && i === cols) {
  18294. v[i][j] = aj;
  18295. } else {
  18296. v[i][j] = aj.clone().lerp(bj, j / rows);
  18297. }
  18298. }
  18299. } // construct all of the faces
  18300. for (i = 0; i < cols; i++) {
  18301. for (j = 0; j < 2 * (cols - i) - 1; j++) {
  18302. var k = Math.floor(j / 2);
  18303. if (j % 2 === 0) {
  18304. pushVertex(v[i][k + 1]);
  18305. pushVertex(v[i + 1][k]);
  18306. pushVertex(v[i][k]);
  18307. } else {
  18308. pushVertex(v[i][k + 1]);
  18309. pushVertex(v[i + 1][k + 1]);
  18310. pushVertex(v[i + 1][k]);
  18311. }
  18312. }
  18313. }
  18314. }
  18315. function applyRadius(radius) {
  18316. var vertex = new Vector3(); // iterate over the entire buffer and apply the radius to each vertex
  18317. for (var i = 0; i < vertexBuffer.length; i += 3) {
  18318. vertex.x = vertexBuffer[i + 0];
  18319. vertex.y = vertexBuffer[i + 1];
  18320. vertex.z = vertexBuffer[i + 2];
  18321. vertex.normalize().multiplyScalar(radius);
  18322. vertexBuffer[i + 0] = vertex.x;
  18323. vertexBuffer[i + 1] = vertex.y;
  18324. vertexBuffer[i + 2] = vertex.z;
  18325. }
  18326. }
  18327. function generateUVs() {
  18328. var vertex = new Vector3();
  18329. for (var i = 0; i < vertexBuffer.length; i += 3) {
  18330. vertex.x = vertexBuffer[i + 0];
  18331. vertex.y = vertexBuffer[i + 1];
  18332. vertex.z = vertexBuffer[i + 2];
  18333. var u = azimuth(vertex) / 2 / Math.PI + 0.5;
  18334. var v = inclination(vertex) / Math.PI + 0.5;
  18335. uvBuffer.push(u, 1 - v);
  18336. }
  18337. correctUVs();
  18338. correctSeam();
  18339. }
  18340. function correctSeam() {
  18341. // handle case when face straddles the seam, see #3269
  18342. for (var i = 0; i < uvBuffer.length; i += 6) {
  18343. // uv data of a single face
  18344. var x0 = uvBuffer[i + 0];
  18345. var x1 = uvBuffer[i + 2];
  18346. var x2 = uvBuffer[i + 4];
  18347. var max = Math.max(x0, x1, x2);
  18348. var min = Math.min(x0, x1, x2); // 0.9 is somewhat arbitrary
  18349. if (max > 0.9 && min < 0.1) {
  18350. if (x0 < 0.2) uvBuffer[i + 0] += 1;
  18351. if (x1 < 0.2) uvBuffer[i + 2] += 1;
  18352. if (x2 < 0.2) uvBuffer[i + 4] += 1;
  18353. }
  18354. }
  18355. }
  18356. function pushVertex(vertex) {
  18357. vertexBuffer.push(vertex.x, vertex.y, vertex.z);
  18358. }
  18359. function getVertexByIndex(index, vertex) {
  18360. var stride = index * 3;
  18361. vertex.x = vertices[stride + 0];
  18362. vertex.y = vertices[stride + 1];
  18363. vertex.z = vertices[stride + 2];
  18364. }
  18365. function correctUVs() {
  18366. var a = new Vector3();
  18367. var b = new Vector3();
  18368. var c = new Vector3();
  18369. var centroid = new Vector3();
  18370. var uvA = new Vector2();
  18371. var uvB = new Vector2();
  18372. var uvC = new Vector2();
  18373. for (var i = 0, j = 0; i < vertexBuffer.length; i += 9, j += 6) {
  18374. a.set(vertexBuffer[i + 0], vertexBuffer[i + 1], vertexBuffer[i + 2]);
  18375. b.set(vertexBuffer[i + 3], vertexBuffer[i + 4], vertexBuffer[i + 5]);
  18376. c.set(vertexBuffer[i + 6], vertexBuffer[i + 7], vertexBuffer[i + 8]);
  18377. uvA.set(uvBuffer[j + 0], uvBuffer[j + 1]);
  18378. uvB.set(uvBuffer[j + 2], uvBuffer[j + 3]);
  18379. uvC.set(uvBuffer[j + 4], uvBuffer[j + 5]);
  18380. centroid.copy(a).add(b).add(c).divideScalar(3);
  18381. var azi = azimuth(centroid);
  18382. correctUV(uvA, j + 0, a, azi);
  18383. correctUV(uvB, j + 2, b, azi);
  18384. correctUV(uvC, j + 4, c, azi);
  18385. }
  18386. }
  18387. function correctUV(uv, stride, vector, azimuth) {
  18388. if (azimuth < 0 && uv.x === 1) {
  18389. uvBuffer[stride] = uv.x - 1;
  18390. }
  18391. if (vector.x === 0 && vector.z === 0) {
  18392. uvBuffer[stride] = azimuth / 2 / Math.PI + 0.5;
  18393. }
  18394. } // Angle around the Y axis, counter-clockwise when looking from above.
  18395. function azimuth(vector) {
  18396. return Math.atan2(vector.z, -vector.x);
  18397. } // Angle above the XZ plane.
  18398. function inclination(vector) {
  18399. return Math.atan2(-vector.y, Math.sqrt(vector.x * vector.x + vector.z * vector.z));
  18400. }
  18401. }
  18402. PolyhedronBufferGeometry.prototype = Object.create(BufferGeometry.prototype);
  18403. PolyhedronBufferGeometry.prototype.constructor = PolyhedronBufferGeometry;
  18404. /**
  18405. * @author timothypratley / https://github.com/timothypratley
  18406. * @author Mugen87 / https://github.com/Mugen87
  18407. */
  18408. // TetrahedronGeometry
  18409. function TetrahedronGeometry(radius, detail) {
  18410. Geometry.call(this);
  18411. this.type = 'TetrahedronGeometry';
  18412. this.parameters = {
  18413. radius: radius,
  18414. detail: detail
  18415. };
  18416. this.fromBufferGeometry(new TetrahedronBufferGeometry(radius, detail));
  18417. this.mergeVertices();
  18418. }
  18419. TetrahedronGeometry.prototype = Object.create(Geometry.prototype);
  18420. TetrahedronGeometry.prototype.constructor = TetrahedronGeometry; // TetrahedronBufferGeometry
  18421. function TetrahedronBufferGeometry(radius, detail) {
  18422. var vertices = [1, 1, 1, -1, -1, 1, -1, 1, -1, 1, -1, -1];
  18423. var indices = [2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1];
  18424. PolyhedronBufferGeometry.call(this, vertices, indices, radius, detail);
  18425. this.type = 'TetrahedronBufferGeometry';
  18426. this.parameters = {
  18427. radius: radius,
  18428. detail: detail
  18429. };
  18430. }
  18431. TetrahedronBufferGeometry.prototype = Object.create(PolyhedronBufferGeometry.prototype);
  18432. TetrahedronBufferGeometry.prototype.constructor = TetrahedronBufferGeometry;
  18433. /**
  18434. * @author timothypratley / https://github.com/timothypratley
  18435. * @author Mugen87 / https://github.com/Mugen87
  18436. */
  18437. // OctahedronGeometry
  18438. function OctahedronGeometry(radius, detail) {
  18439. Geometry.call(this);
  18440. this.type = 'OctahedronGeometry';
  18441. this.parameters = {
  18442. radius: radius,
  18443. detail: detail
  18444. };
  18445. this.fromBufferGeometry(new OctahedronBufferGeometry(radius, detail));
  18446. this.mergeVertices();
  18447. }
  18448. OctahedronGeometry.prototype = Object.create(Geometry.prototype);
  18449. OctahedronGeometry.prototype.constructor = OctahedronGeometry; // OctahedronBufferGeometry
  18450. function OctahedronBufferGeometry(radius, detail) {
  18451. var vertices = [1, 0, 0, -1, 0, 0, 0, 1, 0, 0, -1, 0, 0, 0, 1, 0, 0, -1];
  18452. 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];
  18453. PolyhedronBufferGeometry.call(this, vertices, indices, radius, detail);
  18454. this.type = 'OctahedronBufferGeometry';
  18455. this.parameters = {
  18456. radius: radius,
  18457. detail: detail
  18458. };
  18459. }
  18460. OctahedronBufferGeometry.prototype = Object.create(PolyhedronBufferGeometry.prototype);
  18461. OctahedronBufferGeometry.prototype.constructor = OctahedronBufferGeometry;
  18462. /**
  18463. * @author timothypratley / https://github.com/timothypratley
  18464. * @author Mugen87 / https://github.com/Mugen87
  18465. */
  18466. // IcosahedronGeometry
  18467. function IcosahedronGeometry(radius, detail) {
  18468. Geometry.call(this);
  18469. this.type = 'IcosahedronGeometry';
  18470. this.parameters = {
  18471. radius: radius,
  18472. detail: detail
  18473. };
  18474. this.fromBufferGeometry(new IcosahedronBufferGeometry(radius, detail));
  18475. this.mergeVertices();
  18476. }
  18477. IcosahedronGeometry.prototype = Object.create(Geometry.prototype);
  18478. IcosahedronGeometry.prototype.constructor = IcosahedronGeometry; // IcosahedronBufferGeometry
  18479. function IcosahedronBufferGeometry(radius, detail) {
  18480. var t = (1 + Math.sqrt(5)) / 2;
  18481. 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];
  18482. 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];
  18483. PolyhedronBufferGeometry.call(this, vertices, indices, radius, detail);
  18484. this.type = 'IcosahedronBufferGeometry';
  18485. this.parameters = {
  18486. radius: radius,
  18487. detail: detail
  18488. };
  18489. }
  18490. IcosahedronBufferGeometry.prototype = Object.create(PolyhedronBufferGeometry.prototype);
  18491. IcosahedronBufferGeometry.prototype.constructor = IcosahedronBufferGeometry;
  18492. /**
  18493. * @author Abe Pazos / https://hamoid.com
  18494. * @author Mugen87 / https://github.com/Mugen87
  18495. */
  18496. // DodecahedronGeometry
  18497. function DodecahedronGeometry(radius, detail) {
  18498. Geometry.call(this);
  18499. this.type = 'DodecahedronGeometry';
  18500. this.parameters = {
  18501. radius: radius,
  18502. detail: detail
  18503. };
  18504. this.fromBufferGeometry(new DodecahedronBufferGeometry(radius, detail));
  18505. this.mergeVertices();
  18506. }
  18507. DodecahedronGeometry.prototype = Object.create(Geometry.prototype);
  18508. DodecahedronGeometry.prototype.constructor = DodecahedronGeometry; // DodecahedronBufferGeometry
  18509. function DodecahedronBufferGeometry(radius, detail) {
  18510. var t = (1 + Math.sqrt(5)) / 2;
  18511. var r = 1 / t;
  18512. var vertices = [// (±1, ±1, ±1)
  18513. -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/φ, ±φ)
  18514. 0, -r, -t, 0, -r, t, 0, r, -t, 0, r, t, // (±1/φ, ±φ, 0)
  18515. -r, -t, 0, -r, t, 0, r, -t, 0, r, t, 0, // (±φ, 0, ±1/φ)
  18516. -t, 0, -r, t, 0, -r, -t, 0, r, t, 0, r];
  18517. 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];
  18518. PolyhedronBufferGeometry.call(this, vertices, indices, radius, detail);
  18519. this.type = 'DodecahedronBufferGeometry';
  18520. this.parameters = {
  18521. radius: radius,
  18522. detail: detail
  18523. };
  18524. }
  18525. DodecahedronBufferGeometry.prototype = Object.create(PolyhedronBufferGeometry.prototype);
  18526. DodecahedronBufferGeometry.prototype.constructor = DodecahedronBufferGeometry;
  18527. /**
  18528. * @author oosmoxiecode / https://github.com/oosmoxiecode
  18529. * @author WestLangley / https://github.com/WestLangley
  18530. * @author zz85 / https://github.com/zz85
  18531. * @author miningold / https://github.com/miningold
  18532. * @author jonobr1 / https://github.com/jonobr1
  18533. * @author Mugen87 / https://github.com/Mugen87
  18534. *
  18535. */
  18536. // TubeGeometry
  18537. function TubeGeometry(path, tubularSegments, radius, radialSegments, closed, taper) {
  18538. Geometry.call(this);
  18539. this.type = 'TubeGeometry';
  18540. this.parameters = {
  18541. path: path,
  18542. tubularSegments: tubularSegments,
  18543. radius: radius,
  18544. radialSegments: radialSegments,
  18545. closed: closed
  18546. };
  18547. if (taper !== undefined) console.warn('THREE.TubeGeometry: taper has been removed.');
  18548. var bufferGeometry = new TubeBufferGeometry(path, tubularSegments, radius, radialSegments, closed); // expose internals
  18549. this.tangents = bufferGeometry.tangents;
  18550. this.normals = bufferGeometry.normals;
  18551. this.binormals = bufferGeometry.binormals; // create geometry
  18552. this.fromBufferGeometry(bufferGeometry);
  18553. this.mergeVertices();
  18554. }
  18555. TubeGeometry.prototype = Object.create(Geometry.prototype);
  18556. TubeGeometry.prototype.constructor = TubeGeometry; // TubeBufferGeometry
  18557. function TubeBufferGeometry(path, tubularSegments, radius, radialSegments, closed) {
  18558. BufferGeometry.call(this);
  18559. this.type = 'TubeBufferGeometry';
  18560. this.parameters = {
  18561. path: path,
  18562. tubularSegments: tubularSegments,
  18563. radius: radius,
  18564. radialSegments: radialSegments,
  18565. closed: closed
  18566. };
  18567. tubularSegments = tubularSegments || 64;
  18568. radius = radius || 1;
  18569. radialSegments = radialSegments || 8;
  18570. closed = closed || false;
  18571. var frames = path.computeFrenetFrames(tubularSegments, closed); // expose internals
  18572. this.tangents = frames.tangents;
  18573. this.normals = frames.normals;
  18574. this.binormals = frames.binormals; // helper variables
  18575. var vertex = new Vector3();
  18576. var normal = new Vector3();
  18577. var uv = new Vector2();
  18578. var P = new Vector3();
  18579. var i, j; // buffer
  18580. var vertices = [];
  18581. var normals = [];
  18582. var uvs = [];
  18583. var indices = []; // create buffer data
  18584. generateBufferData(); // build geometry
  18585. this.setIndex(indices);
  18586. this.addAttribute('position', new Float32BufferAttribute(vertices, 3));
  18587. this.addAttribute('normal', new Float32BufferAttribute(normals, 3));
  18588. this.addAttribute('uv', new Float32BufferAttribute(uvs, 2)); // functions
  18589. function generateBufferData() {
  18590. for (i = 0; i < tubularSegments; i++) {
  18591. generateSegment(i);
  18592. } // if the geometry is not closed, generate the last row of vertices and normals
  18593. // at the regular position on the given path
  18594. //
  18595. // if the geometry is closed, duplicate the first row of vertices and normals (uvs will differ)
  18596. generateSegment(closed === false ? tubularSegments : 0); // uvs are generated in a separate function.
  18597. // this makes it easy compute correct values for closed geometries
  18598. generateUVs(); // finally create faces
  18599. generateIndices();
  18600. }
  18601. function generateSegment(i) {
  18602. // we use getPointAt to sample evenly distributed points from the given path
  18603. P = path.getPointAt(i / tubularSegments, P); // retrieve corresponding normal and binormal
  18604. var N = frames.normals[i];
  18605. var B = frames.binormals[i]; // generate normals and vertices for the current segment
  18606. for (j = 0; j <= radialSegments; j++) {
  18607. var v = j / radialSegments * Math.PI * 2;
  18608. var sin = Math.sin(v);
  18609. var cos = -Math.cos(v); // normal
  18610. normal.x = cos * N.x + sin * B.x;
  18611. normal.y = cos * N.y + sin * B.y;
  18612. normal.z = cos * N.z + sin * B.z;
  18613. normal.normalize();
  18614. normals.push(normal.x, normal.y, normal.z); // vertex
  18615. vertex.x = P.x + radius * normal.x;
  18616. vertex.y = P.y + radius * normal.y;
  18617. vertex.z = P.z + radius * normal.z;
  18618. vertices.push(vertex.x, vertex.y, vertex.z);
  18619. }
  18620. }
  18621. function generateIndices() {
  18622. for (j = 1; j <= tubularSegments; j++) {
  18623. for (i = 1; i <= radialSegments; i++) {
  18624. var a = (radialSegments + 1) * (j - 1) + (i - 1);
  18625. var b = (radialSegments + 1) * j + (i - 1);
  18626. var c = (radialSegments + 1) * j + i;
  18627. var d = (radialSegments + 1) * (j - 1) + i; // faces
  18628. indices.push(a, b, d);
  18629. indices.push(b, c, d);
  18630. }
  18631. }
  18632. }
  18633. function generateUVs() {
  18634. for (i = 0; i <= tubularSegments; i++) {
  18635. for (j = 0; j <= radialSegments; j++) {
  18636. uv.x = i / tubularSegments;
  18637. uv.y = j / radialSegments;
  18638. uvs.push(uv.x, uv.y);
  18639. }
  18640. }
  18641. }
  18642. }
  18643. TubeBufferGeometry.prototype = Object.create(BufferGeometry.prototype);
  18644. TubeBufferGeometry.prototype.constructor = TubeBufferGeometry;
  18645. TubeBufferGeometry.prototype.toJSON = function () {
  18646. var data = BufferGeometry.prototype.toJSON.call(this);
  18647. data.path = this.parameters.path.toJSON();
  18648. return data;
  18649. };
  18650. /**
  18651. * @author oosmoxiecode
  18652. * @author Mugen87 / https://github.com/Mugen87
  18653. *
  18654. * based on http://www.blackpawn.com/texts/pqtorus/
  18655. */
  18656. // TorusKnotGeometry
  18657. function TorusKnotGeometry(radius, tube, tubularSegments, radialSegments, p, q, heightScale) {
  18658. Geometry.call(this);
  18659. this.type = 'TorusKnotGeometry';
  18660. this.parameters = {
  18661. radius: radius,
  18662. tube: tube,
  18663. tubularSegments: tubularSegments,
  18664. radialSegments: radialSegments,
  18665. p: p,
  18666. q: q
  18667. };
  18668. if (heightScale !== undefined) console.warn('THREE.TorusKnotGeometry: heightScale has been deprecated. Use .scale( x, y, z ) instead.');
  18669. this.fromBufferGeometry(new TorusKnotBufferGeometry(radius, tube, tubularSegments, radialSegments, p, q));
  18670. this.mergeVertices();
  18671. }
  18672. TorusKnotGeometry.prototype = Object.create(Geometry.prototype);
  18673. TorusKnotGeometry.prototype.constructor = TorusKnotGeometry; // TorusKnotBufferGeometry
  18674. function TorusKnotBufferGeometry(radius, tube, tubularSegments, radialSegments, p, q) {
  18675. BufferGeometry.call(this);
  18676. this.type = 'TorusKnotBufferGeometry';
  18677. this.parameters = {
  18678. radius: radius,
  18679. tube: tube,
  18680. tubularSegments: tubularSegments,
  18681. radialSegments: radialSegments,
  18682. p: p,
  18683. q: q
  18684. };
  18685. radius = radius || 1;
  18686. tube = tube || 0.4;
  18687. tubularSegments = Math.floor(tubularSegments) || 64;
  18688. radialSegments = Math.floor(radialSegments) || 8;
  18689. p = p || 2;
  18690. q = q || 3; // buffers
  18691. var indices = [];
  18692. var vertices = [];
  18693. var normals = [];
  18694. var uvs = []; // helper variables
  18695. var i, j;
  18696. var vertex = new Vector3();
  18697. var normal = new Vector3();
  18698. var P1 = new Vector3();
  18699. var P2 = new Vector3();
  18700. var B = new Vector3();
  18701. var T = new Vector3();
  18702. var N = new Vector3(); // generate vertices, normals and uvs
  18703. for (i = 0; i <= tubularSegments; ++i) {
  18704. // the radian "u" is used to calculate the position on the torus curve of the current tubular segement
  18705. 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.
  18706. // these points are used to create a special "coordinate space", which is necessary to calculate the correct vertex positions
  18707. calculatePositionOnCurve(u, p, q, radius, P1);
  18708. calculatePositionOnCurve(u + 0.01, p, q, radius, P2); // calculate orthonormal basis
  18709. T.subVectors(P2, P1);
  18710. N.addVectors(P2, P1);
  18711. B.crossVectors(T, N);
  18712. N.crossVectors(B, T); // normalize B, N. T can be ignored, we don't use it
  18713. B.normalize();
  18714. N.normalize();
  18715. for (j = 0; j <= radialSegments; ++j) {
  18716. // now calculate the vertices. they are nothing more than an extrusion of the torus curve.
  18717. // because we extrude a shape in the xy-plane, there is no need to calculate a z-value.
  18718. var v = j / radialSegments * Math.PI * 2;
  18719. var cx = -tube * Math.cos(v);
  18720. var cy = tube * Math.sin(v); // now calculate the final vertex position.
  18721. // first we orient the extrusion with our basis vectos, then we add it to the current position on the curve
  18722. vertex.x = P1.x + (cx * N.x + cy * B.x);
  18723. vertex.y = P1.y + (cx * N.y + cy * B.y);
  18724. vertex.z = P1.z + (cx * N.z + cy * B.z);
  18725. 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)
  18726. normal.subVectors(vertex, P1).normalize();
  18727. normals.push(normal.x, normal.y, normal.z); // uv
  18728. uvs.push(i / tubularSegments);
  18729. uvs.push(j / radialSegments);
  18730. }
  18731. } // generate indices
  18732. for (j = 1; j <= tubularSegments; j++) {
  18733. for (i = 1; i <= radialSegments; i++) {
  18734. // indices
  18735. var a = (radialSegments + 1) * (j - 1) + (i - 1);
  18736. var b = (radialSegments + 1) * j + (i - 1);
  18737. var c = (radialSegments + 1) * j + i;
  18738. var d = (radialSegments + 1) * (j - 1) + i; // faces
  18739. indices.push(a, b, d);
  18740. indices.push(b, c, d);
  18741. }
  18742. } // build geometry
  18743. this.setIndex(indices);
  18744. this.addAttribute('position', new Float32BufferAttribute(vertices, 3));
  18745. this.addAttribute('normal', new Float32BufferAttribute(normals, 3));
  18746. this.addAttribute('uv', new Float32BufferAttribute(uvs, 2)); // this function calculates the current position on the torus curve
  18747. function calculatePositionOnCurve(u, p, q, radius, position) {
  18748. var cu = Math.cos(u);
  18749. var su = Math.sin(u);
  18750. var quOverP = q / p * u;
  18751. var cs = Math.cos(quOverP);
  18752. position.x = radius * (2 + cs) * 0.5 * cu;
  18753. position.y = radius * (2 + cs) * su * 0.5;
  18754. position.z = radius * Math.sin(quOverP) * 0.5;
  18755. }
  18756. }
  18757. TorusKnotBufferGeometry.prototype = Object.create(BufferGeometry.prototype);
  18758. TorusKnotBufferGeometry.prototype.constructor = TorusKnotBufferGeometry;
  18759. /**
  18760. * @author oosmoxiecode
  18761. * @author mrdoob / http://mrdoob.com/
  18762. * @author Mugen87 / https://github.com/Mugen87
  18763. */
  18764. // TorusGeometry
  18765. function TorusGeometry(radius, tube, radialSegments, tubularSegments, arc) {
  18766. Geometry.call(this);
  18767. this.type = 'TorusGeometry';
  18768. this.parameters = {
  18769. radius: radius,
  18770. tube: tube,
  18771. radialSegments: radialSegments,
  18772. tubularSegments: tubularSegments,
  18773. arc: arc
  18774. };
  18775. this.fromBufferGeometry(new TorusBufferGeometry(radius, tube, radialSegments, tubularSegments, arc));
  18776. this.mergeVertices();
  18777. }
  18778. TorusGeometry.prototype = Object.create(Geometry.prototype);
  18779. TorusGeometry.prototype.constructor = TorusGeometry; // TorusBufferGeometry
  18780. function TorusBufferGeometry(radius, tube, radialSegments, tubularSegments, arc) {
  18781. BufferGeometry.call(this);
  18782. this.type = 'TorusBufferGeometry';
  18783. this.parameters = {
  18784. radius: radius,
  18785. tube: tube,
  18786. radialSegments: radialSegments,
  18787. tubularSegments: tubularSegments,
  18788. arc: arc
  18789. };
  18790. radius = radius || 1;
  18791. tube = tube || 0.4;
  18792. radialSegments = Math.floor(radialSegments) || 8;
  18793. tubularSegments = Math.floor(tubularSegments) || 6;
  18794. arc = arc || Math.PI * 2; // buffers
  18795. var indices = [];
  18796. var vertices = [];
  18797. var normals = [];
  18798. var uvs = []; // helper variables
  18799. var center = new Vector3();
  18800. var vertex = new Vector3();
  18801. var normal = new Vector3();
  18802. var j, i; // generate vertices, normals and uvs
  18803. for (j = 0; j <= radialSegments; j++) {
  18804. for (i = 0; i <= tubularSegments; i++) {
  18805. var u = i / tubularSegments * arc;
  18806. var v = j / radialSegments * Math.PI * 2; // vertex
  18807. vertex.x = (radius + tube * Math.cos(v)) * Math.cos(u);
  18808. vertex.y = (radius + tube * Math.cos(v)) * Math.sin(u);
  18809. vertex.z = tube * Math.sin(v);
  18810. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  18811. center.x = radius * Math.cos(u);
  18812. center.y = radius * Math.sin(u);
  18813. normal.subVectors(vertex, center).normalize();
  18814. normals.push(normal.x, normal.y, normal.z); // uv
  18815. uvs.push(i / tubularSegments);
  18816. uvs.push(j / radialSegments);
  18817. }
  18818. } // generate indices
  18819. for (j = 1; j <= radialSegments; j++) {
  18820. for (i = 1; i <= tubularSegments; i++) {
  18821. // indices
  18822. var a = (tubularSegments + 1) * j + i - 1;
  18823. var b = (tubularSegments + 1) * (j - 1) + i - 1;
  18824. var c = (tubularSegments + 1) * (j - 1) + i;
  18825. var d = (tubularSegments + 1) * j + i; // faces
  18826. indices.push(a, b, d);
  18827. indices.push(b, c, d);
  18828. }
  18829. } // build geometry
  18830. this.setIndex(indices);
  18831. this.addAttribute('position', new Float32BufferAttribute(vertices, 3));
  18832. this.addAttribute('normal', new Float32BufferAttribute(normals, 3));
  18833. this.addAttribute('uv', new Float32BufferAttribute(uvs, 2));
  18834. }
  18835. TorusBufferGeometry.prototype = Object.create(BufferGeometry.prototype);
  18836. TorusBufferGeometry.prototype.constructor = TorusBufferGeometry;
  18837. /**
  18838. * @author Mugen87 / https://github.com/Mugen87
  18839. * Port from https://github.com/mapbox/earcut (v2.1.5)
  18840. */
  18841. var Earcut = {
  18842. triangulate: function (data, holeIndices, dim) {
  18843. dim = dim || 2;
  18844. var hasHoles = holeIndices && holeIndices.length,
  18845. outerLen = hasHoles ? holeIndices[0] * dim : data.length,
  18846. outerNode = linkedList(data, 0, outerLen, dim, true),
  18847. triangles = [];
  18848. if (!outerNode || outerNode.next === outerNode.prev) return triangles;
  18849. var minX, minY, maxX, maxY, x, y, invSize;
  18850. 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
  18851. if (data.length > 80 * dim) {
  18852. minX = maxX = data[0];
  18853. minY = maxY = data[1];
  18854. for (var i = dim; i < outerLen; i += dim) {
  18855. x = data[i];
  18856. y = data[i + 1];
  18857. if (x < minX) minX = x;
  18858. if (y < minY) minY = y;
  18859. if (x > maxX) maxX = x;
  18860. if (y > maxY) maxY = y;
  18861. } // minX, minY and invSize are later used to transform coords into integers for z-order calculation
  18862. invSize = Math.max(maxX - minX, maxY - minY);
  18863. invSize = invSize !== 0 ? 1 / invSize : 0;
  18864. }
  18865. earcutLinked(outerNode, triangles, dim, minX, minY, invSize);
  18866. return triangles;
  18867. }
  18868. }; // create a circular doubly linked list from polygon points in the specified winding order
  18869. function linkedList(data, start, end, dim, clockwise) {
  18870. var i, last;
  18871. if (clockwise === signedArea(data, start, end, dim) > 0) {
  18872. for (i = start; i < end; i += dim) last = insertNode(i, data[i], data[i + 1], last);
  18873. } else {
  18874. for (i = end - dim; i >= start; i -= dim) last = insertNode(i, data[i], data[i + 1], last);
  18875. }
  18876. if (last && equals(last, last.next)) {
  18877. removeNode(last);
  18878. last = last.next;
  18879. }
  18880. return last;
  18881. } // eliminate colinear or duplicate points
  18882. function filterPoints(start, end) {
  18883. if (!start) return start;
  18884. if (!end) end = start;
  18885. var p = start,
  18886. again;
  18887. do {
  18888. again = false;
  18889. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  18890. removeNode(p);
  18891. p = end = p.prev;
  18892. if (p === p.next) break;
  18893. again = true;
  18894. } else {
  18895. p = p.next;
  18896. }
  18897. } while (again || p !== end);
  18898. return end;
  18899. } // main ear slicing loop which triangulates a polygon (given as a linked list)
  18900. function earcutLinked(ear, triangles, dim, minX, minY, invSize, pass) {
  18901. if (!ear) return; // interlink polygon nodes in z-order
  18902. if (!pass && invSize) indexCurve(ear, minX, minY, invSize);
  18903. var stop = ear,
  18904. prev,
  18905. next; // iterate through ears, slicing them one by one
  18906. while (ear.prev !== ear.next) {
  18907. prev = ear.prev;
  18908. next = ear.next;
  18909. if (invSize ? isEarHashed(ear, minX, minY, invSize) : isEar(ear)) {
  18910. // cut off the triangle
  18911. triangles.push(prev.i / dim);
  18912. triangles.push(ear.i / dim);
  18913. triangles.push(next.i / dim);
  18914. removeNode(ear); // skipping the next vertex leads to less sliver triangles
  18915. ear = next.next;
  18916. stop = next.next;
  18917. continue;
  18918. }
  18919. ear = next; // if we looped through the whole remaining polygon and can't find any more ears
  18920. if (ear === stop) {
  18921. // try filtering points and slicing again
  18922. if (!pass) {
  18923. earcutLinked(filterPoints(ear), triangles, dim, minX, minY, invSize, 1); // if this didn't work, try curing all small self-intersections locally
  18924. } else if (pass === 1) {
  18925. ear = cureLocalIntersections(ear, triangles, dim);
  18926. earcutLinked(ear, triangles, dim, minX, minY, invSize, 2); // as a last resort, try splitting the remaining polygon into two
  18927. } else if (pass === 2) {
  18928. splitEarcut(ear, triangles, dim, minX, minY, invSize);
  18929. }
  18930. break;
  18931. }
  18932. }
  18933. } // check whether a polygon node forms a valid ear with adjacent nodes
  18934. function isEar(ear) {
  18935. var a = ear.prev,
  18936. b = ear,
  18937. c = ear.next;
  18938. if (area(a, b, c) >= 0) return false; // reflex, can't be an ear
  18939. // now make sure we don't have other points inside the potential ear
  18940. var p = ear.next.next;
  18941. while (p !== ear.prev) {
  18942. 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;
  18943. p = p.next;
  18944. }
  18945. return true;
  18946. }
  18947. function isEarHashed(ear, minX, minY, invSize) {
  18948. var a = ear.prev,
  18949. b = ear,
  18950. c = ear.next;
  18951. if (area(a, b, c) >= 0) return false; // reflex, can't be an ear
  18952. // triangle bbox; min & max are calculated like this for speed
  18953. var minTX = a.x < b.x ? a.x < c.x ? a.x : c.x : b.x < c.x ? b.x : c.x,
  18954. minTY = a.y < b.y ? a.y < c.y ? a.y : c.y : b.y < c.y ? b.y : c.y,
  18955. maxTX = a.x > b.x ? a.x > c.x ? a.x : c.x : b.x > c.x ? b.x : c.x,
  18956. 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;
  18957. var minZ = zOrder(minTX, minTY, minX, minY, invSize),
  18958. maxZ = zOrder(maxTX, maxTY, minX, minY, invSize);
  18959. var p = ear.prevZ,
  18960. n = ear.nextZ; // look for points inside the triangle in both directions
  18961. while (p && p.z >= minZ && n && n.z <= maxZ) {
  18962. 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;
  18963. p = p.prevZ;
  18964. 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;
  18965. n = n.nextZ;
  18966. } // look for remaining points in decreasing z-order
  18967. while (p && p.z >= minZ) {
  18968. 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;
  18969. p = p.prevZ;
  18970. } // look for remaining points in increasing z-order
  18971. while (n && n.z <= maxZ) {
  18972. 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;
  18973. n = n.nextZ;
  18974. }
  18975. return true;
  18976. } // go through all polygon nodes and cure small local self-intersections
  18977. function cureLocalIntersections(start, triangles, dim) {
  18978. var p = start;
  18979. do {
  18980. var a = p.prev,
  18981. b = p.next.next;
  18982. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  18983. triangles.push(a.i / dim);
  18984. triangles.push(p.i / dim);
  18985. triangles.push(b.i / dim); // remove two nodes involved
  18986. removeNode(p);
  18987. removeNode(p.next);
  18988. p = start = b;
  18989. }
  18990. p = p.next;
  18991. } while (p !== start);
  18992. return p;
  18993. } // try splitting polygon into two and triangulate them independently
  18994. function splitEarcut(start, triangles, dim, minX, minY, invSize) {
  18995. // look for a valid diagonal that divides the polygon into two
  18996. var a = start;
  18997. do {
  18998. var b = a.next.next;
  18999. while (b !== a.prev) {
  19000. if (a.i !== b.i && isValidDiagonal(a, b)) {
  19001. // split the polygon in two by the diagonal
  19002. var c = splitPolygon(a, b); // filter colinear points around the cuts
  19003. a = filterPoints(a, a.next);
  19004. c = filterPoints(c, c.next); // run earcut on each half
  19005. earcutLinked(a, triangles, dim, minX, minY, invSize);
  19006. earcutLinked(c, triangles, dim, minX, minY, invSize);
  19007. return;
  19008. }
  19009. b = b.next;
  19010. }
  19011. a = a.next;
  19012. } while (a !== start);
  19013. } // link every hole into the outer loop, producing a single-ring polygon without holes
  19014. function eliminateHoles(data, holeIndices, outerNode, dim) {
  19015. var queue = [],
  19016. i,
  19017. len,
  19018. start,
  19019. end,
  19020. list;
  19021. for (i = 0, len = holeIndices.length; i < len; i++) {
  19022. start = holeIndices[i] * dim;
  19023. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  19024. list = linkedList(data, start, end, dim, false);
  19025. if (list === list.next) list.steiner = true;
  19026. queue.push(getLeftmost(list));
  19027. }
  19028. queue.sort(compareX); // process holes from left to right
  19029. for (i = 0; i < queue.length; i++) {
  19030. eliminateHole(queue[i], outerNode);
  19031. outerNode = filterPoints(outerNode, outerNode.next);
  19032. }
  19033. return outerNode;
  19034. }
  19035. function compareX(a, b) {
  19036. return a.x - b.x;
  19037. } // find a bridge between vertices that connects hole with an outer ring and and link it
  19038. function eliminateHole(hole, outerNode) {
  19039. outerNode = findHoleBridge(hole, outerNode);
  19040. if (outerNode) {
  19041. var b = splitPolygon(outerNode, hole);
  19042. filterPoints(b, b.next);
  19043. }
  19044. } // David Eberly's algorithm for finding a bridge between hole and outer polygon
  19045. function findHoleBridge(hole, outerNode) {
  19046. var p = outerNode,
  19047. hx = hole.x,
  19048. hy = hole.y,
  19049. qx = -Infinity,
  19050. m; // find a segment intersected by a ray from the hole's leftmost point to the left;
  19051. // segment's endpoint with lesser x will be potential connection point
  19052. do {
  19053. if (hy <= p.y && hy >= p.next.y && p.next.y !== p.y) {
  19054. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  19055. if (x <= hx && x > qx) {
  19056. qx = x;
  19057. if (x === hx) {
  19058. if (hy === p.y) return p;
  19059. if (hy === p.next.y) return p.next;
  19060. }
  19061. m = p.x < p.next.x ? p : p.next;
  19062. }
  19063. }
  19064. p = p.next;
  19065. } while (p !== outerNode);
  19066. if (!m) return null;
  19067. if (hx === qx) return m.prev; // hole touches outer segment; pick lower endpoint
  19068. // look for points inside the triangle of hole point, segment intersection and endpoint;
  19069. // if there are no points found, we have a valid connection;
  19070. // otherwise choose the point of the minimum angle with the ray as connection point
  19071. var stop = m,
  19072. mx = m.x,
  19073. my = m.y,
  19074. tanMin = Infinity,
  19075. tan;
  19076. p = m.next;
  19077. while (p !== stop) {
  19078. 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)) {
  19079. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  19080. if ((tan < tanMin || tan === tanMin && p.x > m.x) && locallyInside(p, hole)) {
  19081. m = p;
  19082. tanMin = tan;
  19083. }
  19084. }
  19085. p = p.next;
  19086. }
  19087. return m;
  19088. } // interlink polygon nodes in z-order
  19089. function indexCurve(start, minX, minY, invSize) {
  19090. var p = start;
  19091. do {
  19092. if (p.z === null) p.z = zOrder(p.x, p.y, minX, minY, invSize);
  19093. p.prevZ = p.prev;
  19094. p.nextZ = p.next;
  19095. p = p.next;
  19096. } while (p !== start);
  19097. p.prevZ.nextZ = null;
  19098. p.prevZ = null;
  19099. sortLinked(p);
  19100. } // Simon Tatham's linked list merge sort algorithm
  19101. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  19102. function sortLinked(list) {
  19103. var i,
  19104. p,
  19105. q,
  19106. e,
  19107. tail,
  19108. numMerges,
  19109. pSize,
  19110. qSize,
  19111. inSize = 1;
  19112. do {
  19113. p = list;
  19114. list = null;
  19115. tail = null;
  19116. numMerges = 0;
  19117. while (p) {
  19118. numMerges++;
  19119. q = p;
  19120. pSize = 0;
  19121. for (i = 0; i < inSize; i++) {
  19122. pSize++;
  19123. q = q.nextZ;
  19124. if (!q) break;
  19125. }
  19126. qSize = inSize;
  19127. while (pSize > 0 || qSize > 0 && q) {
  19128. if (pSize !== 0 && (qSize === 0 || !q || p.z <= q.z)) {
  19129. e = p;
  19130. p = p.nextZ;
  19131. pSize--;
  19132. } else {
  19133. e = q;
  19134. q = q.nextZ;
  19135. qSize--;
  19136. }
  19137. if (tail) tail.nextZ = e;else list = e;
  19138. e.prevZ = tail;
  19139. tail = e;
  19140. }
  19141. p = q;
  19142. }
  19143. tail.nextZ = null;
  19144. inSize *= 2;
  19145. } while (numMerges > 1);
  19146. return list;
  19147. } // z-order of a point given coords and inverse of the longer side of data bbox
  19148. function zOrder(x, y, minX, minY, invSize) {
  19149. // coords are transformed into non-negative 15-bit integer range
  19150. x = 32767 * (x - minX) * invSize;
  19151. y = 32767 * (y - minY) * invSize;
  19152. x = (x | x << 8) & 0x00FF00FF;
  19153. x = (x | x << 4) & 0x0F0F0F0F;
  19154. x = (x | x << 2) & 0x33333333;
  19155. x = (x | x << 1) & 0x55555555;
  19156. y = (y | y << 8) & 0x00FF00FF;
  19157. y = (y | y << 4) & 0x0F0F0F0F;
  19158. y = (y | y << 2) & 0x33333333;
  19159. y = (y | y << 1) & 0x55555555;
  19160. return x | y << 1;
  19161. } // find the leftmost node of a polygon ring
  19162. function getLeftmost(start) {
  19163. var p = start,
  19164. leftmost = start;
  19165. do {
  19166. if (p.x < leftmost.x || p.x === leftmost.x && p.y < leftmost.y) leftmost = p;
  19167. p = p.next;
  19168. } while (p !== start);
  19169. return leftmost;
  19170. } // check if a point lies within a convex triangle
  19171. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  19172. 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;
  19173. } // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  19174. function isValidDiagonal(a, b) {
  19175. return a.next.i !== b.i && a.prev.i !== b.i && !intersectsPolygon(a, b) && locallyInside(a, b) && locallyInside(b, a) && middleInside(a, b);
  19176. } // signed area of a triangle
  19177. function area(p, q, r) {
  19178. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  19179. } // check if two points are equal
  19180. function equals(p1, p2) {
  19181. return p1.x === p2.x && p1.y === p2.y;
  19182. } // check if two segments intersect
  19183. function intersects(p1, q1, p2, q2) {
  19184. if (equals(p1, p2) && equals(q1, q2) || equals(p1, q2) && equals(p2, q1)) return true;
  19185. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 && area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  19186. } // check if a polygon diagonal intersects any polygon segments
  19187. function intersectsPolygon(a, b) {
  19188. var p = a;
  19189. do {
  19190. 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;
  19191. p = p.next;
  19192. } while (p !== a);
  19193. return false;
  19194. } // check if a polygon diagonal is locally inside the polygon
  19195. function locallyInside(a, b) {
  19196. 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;
  19197. } // check if the middle point of a polygon diagonal is inside the polygon
  19198. function middleInside(a, b) {
  19199. var p = a,
  19200. inside = false,
  19201. px = (a.x + b.x) / 2,
  19202. py = (a.y + b.y) / 2;
  19203. do {
  19204. 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;
  19205. p = p.next;
  19206. } while (p !== a);
  19207. return inside;
  19208. } // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  19209. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  19210. function splitPolygon(a, b) {
  19211. var a2 = new Node(a.i, a.x, a.y),
  19212. b2 = new Node(b.i, b.x, b.y),
  19213. an = a.next,
  19214. bp = b.prev;
  19215. a.next = b;
  19216. b.prev = a;
  19217. a2.next = an;
  19218. an.prev = a2;
  19219. b2.next = a2;
  19220. a2.prev = b2;
  19221. bp.next = b2;
  19222. b2.prev = bp;
  19223. return b2;
  19224. } // create a node and optionally link it with previous one (in a circular doubly linked list)
  19225. function insertNode(i, x, y, last) {
  19226. var p = new Node(i, x, y);
  19227. if (!last) {
  19228. p.prev = p;
  19229. p.next = p;
  19230. } else {
  19231. p.next = last.next;
  19232. p.prev = last;
  19233. last.next.prev = p;
  19234. last.next = p;
  19235. }
  19236. return p;
  19237. }
  19238. function removeNode(p) {
  19239. p.next.prev = p.prev;
  19240. p.prev.next = p.next;
  19241. if (p.prevZ) p.prevZ.nextZ = p.nextZ;
  19242. if (p.nextZ) p.nextZ.prevZ = p.prevZ;
  19243. }
  19244. function Node(i, x, y) {
  19245. // vertex index in coordinates array
  19246. this.i = i; // vertex coordinates
  19247. this.x = x;
  19248. this.y = y; // previous and next vertex nodes in a polygon ring
  19249. this.prev = null;
  19250. this.next = null; // z-order curve value
  19251. this.z = null; // previous and next nodes in z-order
  19252. this.prevZ = null;
  19253. this.nextZ = null; // indicates whether this is a steiner point
  19254. this.steiner = false;
  19255. }
  19256. function signedArea(data, start, end, dim) {
  19257. var sum = 0;
  19258. for (var i = start, j = end - dim; i < end; i += dim) {
  19259. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  19260. j = i;
  19261. }
  19262. return sum;
  19263. }
  19264. /**
  19265. * @author zz85 / http://www.lab4games.net/zz85/blog
  19266. */
  19267. var ShapeUtils = {
  19268. // calculate area of the contour polygon
  19269. area: function (contour) {
  19270. var n = contour.length;
  19271. var a = 0.0;
  19272. for (var p = n - 1, q = 0; q < n; p = q++) {
  19273. a += contour[p].x * contour[q].y - contour[q].x * contour[p].y;
  19274. }
  19275. return a * 0.5;
  19276. },
  19277. isClockWise: function (pts) {
  19278. return ShapeUtils.area(pts) < 0;
  19279. },
  19280. triangulateShape: function (contour, holes) {
  19281. var vertices = []; // flat array of vertices like [ x0,y0, x1,y1, x2,y2, ... ]
  19282. var holeIndices = []; // array of hole indices
  19283. var faces = []; // final array of vertex indices like [ [ a,b,d ], [ b,c,d ] ]
  19284. removeDupEndPts(contour);
  19285. addContour(vertices, contour); //
  19286. var holeIndex = contour.length;
  19287. holes.forEach(removeDupEndPts);
  19288. for (var i = 0; i < holes.length; i++) {
  19289. holeIndices.push(holeIndex);
  19290. holeIndex += holes[i].length;
  19291. addContour(vertices, holes[i]);
  19292. } //
  19293. var triangles = Earcut.triangulate(vertices, holeIndices); //
  19294. for (var i = 0; i < triangles.length; i += 3) {
  19295. faces.push(triangles.slice(i, i + 3));
  19296. }
  19297. return faces;
  19298. }
  19299. };
  19300. exports.ShapeUtils = ShapeUtils;
  19301. function removeDupEndPts(points) {
  19302. var l = points.length;
  19303. if (l > 2 && points[l - 1].equals(points[0])) {
  19304. points.pop();
  19305. }
  19306. }
  19307. function addContour(vertices, contour) {
  19308. for (var i = 0; i < contour.length; i++) {
  19309. vertices.push(contour[i].x);
  19310. vertices.push(contour[i].y);
  19311. }
  19312. }
  19313. /**
  19314. * @author zz85 / http://www.lab4games.net/zz85/blog
  19315. *
  19316. * Creates extruded geometry from a path shape.
  19317. *
  19318. * parameters = {
  19319. *
  19320. * curveSegments: <int>, // number of points on the curves
  19321. * steps: <int>, // number of points for z-side extrusions / used for subdividing segments of extrude spline too
  19322. * depth: <float>, // Depth to extrude the shape
  19323. *
  19324. * bevelEnabled: <bool>, // turn on bevel
  19325. * bevelThickness: <float>, // how deep into the original shape bevel goes
  19326. * bevelSize: <float>, // how far from shape outline (including bevelOffset) is bevel
  19327. * bevelOffset: <float>, // how far from shape outline does bevel start
  19328. * bevelSegments: <int>, // number of bevel layers
  19329. *
  19330. * extrudePath: <THREE.Curve> // curve to extrude shape along
  19331. *
  19332. * UVGenerator: <Object> // object that provides UV generator functions
  19333. *
  19334. * }
  19335. */
  19336. // ExtrudeGeometry
  19337. function ExtrudeGeometry(shapes, options) {
  19338. Geometry.call(this);
  19339. this.type = 'ExtrudeGeometry';
  19340. this.parameters = {
  19341. shapes: shapes,
  19342. options: options
  19343. };
  19344. this.fromBufferGeometry(new ExtrudeBufferGeometry(shapes, options));
  19345. this.mergeVertices();
  19346. }
  19347. ExtrudeGeometry.prototype = Object.create(Geometry.prototype);
  19348. ExtrudeGeometry.prototype.constructor = ExtrudeGeometry;
  19349. ExtrudeGeometry.prototype.toJSON = function () {
  19350. var data = Geometry.prototype.toJSON.call(this);
  19351. var shapes = this.parameters.shapes;
  19352. var options = this.parameters.options;
  19353. return toJSON(shapes, options, data);
  19354. }; // ExtrudeBufferGeometry
  19355. function ExtrudeBufferGeometry(shapes, options) {
  19356. BufferGeometry.call(this);
  19357. this.type = 'ExtrudeBufferGeometry';
  19358. this.parameters = {
  19359. shapes: shapes,
  19360. options: options
  19361. };
  19362. shapes = Array.isArray(shapes) ? shapes : [shapes];
  19363. var scope = this;
  19364. var verticesArray = [];
  19365. var uvArray = [];
  19366. for (var i = 0, l = shapes.length; i < l; i++) {
  19367. var shape = shapes[i];
  19368. addShape(shape);
  19369. } // build geometry
  19370. this.addAttribute('position', new Float32BufferAttribute(verticesArray, 3));
  19371. this.addAttribute('uv', new Float32BufferAttribute(uvArray, 2));
  19372. this.computeVertexNormals(); // functions
  19373. function addShape(shape) {
  19374. var placeholder = []; // options
  19375. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  19376. var steps = options.steps !== undefined ? options.steps : 1;
  19377. var depth = options.depth !== undefined ? options.depth : 100;
  19378. var bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true;
  19379. var bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 6;
  19380. var bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 2;
  19381. var bevelOffset = options.bevelOffset !== undefined ? options.bevelOffset : 0;
  19382. var bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  19383. var extrudePath = options.extrudePath;
  19384. var uvgen = options.UVGenerator !== undefined ? options.UVGenerator : WorldUVGenerator; // deprecated options
  19385. if (options.amount !== undefined) {
  19386. console.warn('THREE.ExtrudeBufferGeometry: amount has been renamed to depth.');
  19387. depth = options.amount;
  19388. } //
  19389. var extrudePts,
  19390. extrudeByPath = false;
  19391. var splineTube, binormal, normal, position2;
  19392. if (extrudePath) {
  19393. extrudePts = extrudePath.getSpacedPoints(steps);
  19394. extrudeByPath = true;
  19395. bevelEnabled = false; // bevels not supported for path extrusion
  19396. // SETUP TNB variables
  19397. // TODO1 - have a .isClosed in spline?
  19398. splineTube = extrudePath.computeFrenetFrames(steps, false); // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  19399. binormal = new Vector3();
  19400. normal = new Vector3();
  19401. position2 = new Vector3();
  19402. } // Safeguards if bevels are not enabled
  19403. if (!bevelEnabled) {
  19404. bevelSegments = 0;
  19405. bevelThickness = 0;
  19406. bevelSize = 0;
  19407. bevelOffset = 0;
  19408. } // Variables initialization
  19409. var ahole, h, hl; // looping of holes
  19410. var shapePoints = shape.extractPoints(curveSegments);
  19411. var vertices = shapePoints.shape;
  19412. var holes = shapePoints.holes;
  19413. var reverse = !ShapeUtils.isClockWise(vertices);
  19414. if (reverse) {
  19415. vertices = vertices.reverse(); // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  19416. for (h = 0, hl = holes.length; h < hl; h++) {
  19417. ahole = holes[h];
  19418. if (ShapeUtils.isClockWise(ahole)) {
  19419. holes[h] = ahole.reverse();
  19420. }
  19421. }
  19422. }
  19423. var faces = ShapeUtils.triangulateShape(vertices, holes);
  19424. /* Vertices */
  19425. var contour = vertices; // vertices has all points but contour has only points of circumference
  19426. for (h = 0, hl = holes.length; h < hl; h++) {
  19427. ahole = holes[h];
  19428. vertices = vertices.concat(ahole);
  19429. }
  19430. function scalePt2(pt, vec, size) {
  19431. if (!vec) console.error("THREE.ExtrudeGeometry: vec does not exist");
  19432. return vec.clone().multiplyScalar(size).add(pt);
  19433. }
  19434. var b,
  19435. bs,
  19436. t,
  19437. z,
  19438. vert,
  19439. vlen = vertices.length,
  19440. face,
  19441. flen = faces.length; // Find directions for point movement
  19442. function getBevelVec(inPt, inPrev, inNext) {
  19443. // computes for inPt the corresponding point inPt' on a new contour
  19444. // shifted by 1 unit (length of normalized vector) to the left
  19445. // if we walk along contour clockwise, this new contour is outside the old one
  19446. //
  19447. // inPt' is the intersection of the two lines parallel to the two
  19448. // adjacent edges of inPt at a distance of 1 unit on the left side.
  19449. var v_trans_x, v_trans_y, shrink_by; // resulting translation vector for inPt
  19450. // good reading for geometry algorithms (here: line-line intersection)
  19451. // http://geomalgorithms.com/a05-_intersect-1.html
  19452. var v_prev_x = inPt.x - inPrev.x,
  19453. v_prev_y = inPt.y - inPrev.y;
  19454. var v_next_x = inNext.x - inPt.x,
  19455. v_next_y = inNext.y - inPt.y;
  19456. var v_prev_lensq = v_prev_x * v_prev_x + v_prev_y * v_prev_y; // check for collinear edges
  19457. var collinear0 = v_prev_x * v_next_y - v_prev_y * v_next_x;
  19458. if (Math.abs(collinear0) > Number.EPSILON) {
  19459. // not collinear
  19460. // length of vectors for normalizing
  19461. var v_prev_len = Math.sqrt(v_prev_lensq);
  19462. 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
  19463. var ptPrevShift_x = inPrev.x - v_prev_y / v_prev_len;
  19464. var ptPrevShift_y = inPrev.y + v_prev_x / v_prev_len;
  19465. var ptNextShift_x = inNext.x - v_next_y / v_next_len;
  19466. var ptNextShift_y = inNext.y + v_next_x / v_next_len; // scaling factor for v_prev to intersection point
  19467. 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
  19468. v_trans_x = ptPrevShift_x + v_prev_x * sf - inPt.x;
  19469. v_trans_y = ptPrevShift_y + v_prev_y * sf - inPt.y; // Don't normalize!, otherwise sharp corners become ugly
  19470. // but prevent crazy spikes
  19471. var v_trans_lensq = v_trans_x * v_trans_x + v_trans_y * v_trans_y;
  19472. if (v_trans_lensq <= 2) {
  19473. return new Vector2(v_trans_x, v_trans_y);
  19474. } else {
  19475. shrink_by = Math.sqrt(v_trans_lensq / 2);
  19476. }
  19477. } else {
  19478. // handle special case of collinear edges
  19479. var direction_eq = false; // assumes: opposite
  19480. if (v_prev_x > Number.EPSILON) {
  19481. if (v_next_x > Number.EPSILON) {
  19482. direction_eq = true;
  19483. }
  19484. } else {
  19485. if (v_prev_x < -Number.EPSILON) {
  19486. if (v_next_x < -Number.EPSILON) {
  19487. direction_eq = true;
  19488. }
  19489. } else {
  19490. if (Math.sign(v_prev_y) === Math.sign(v_next_y)) {
  19491. direction_eq = true;
  19492. }
  19493. }
  19494. }
  19495. if (direction_eq) {
  19496. // console.log("Warning: lines are a straight sequence");
  19497. v_trans_x = -v_prev_y;
  19498. v_trans_y = v_prev_x;
  19499. shrink_by = Math.sqrt(v_prev_lensq);
  19500. } else {
  19501. // console.log("Warning: lines are a straight spike");
  19502. v_trans_x = v_prev_x;
  19503. v_trans_y = v_prev_y;
  19504. shrink_by = Math.sqrt(v_prev_lensq / 2);
  19505. }
  19506. }
  19507. return new Vector2(v_trans_x / shrink_by, v_trans_y / shrink_by);
  19508. }
  19509. var contourMovements = [];
  19510. for (var i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i++, j++, k++) {
  19511. if (j === il) j = 0;
  19512. if (k === il) k = 0; // (j)---(i)---(k)
  19513. // console.log('i,j,k', i, j , k)
  19514. contourMovements[i] = getBevelVec(contour[i], contour[j], contour[k]);
  19515. }
  19516. var holesMovements = [],
  19517. oneHoleMovements,
  19518. verticesMovements = contourMovements.concat();
  19519. for (h = 0, hl = holes.length; h < hl; h++) {
  19520. ahole = holes[h];
  19521. oneHoleMovements = [];
  19522. for (i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i++, j++, k++) {
  19523. if (j === il) j = 0;
  19524. if (k === il) k = 0; // (j)---(i)---(k)
  19525. oneHoleMovements[i] = getBevelVec(ahole[i], ahole[j], ahole[k]);
  19526. }
  19527. holesMovements.push(oneHoleMovements);
  19528. verticesMovements = verticesMovements.concat(oneHoleMovements);
  19529. } // Loop bevelSegments, 1 for the front, 1 for the back
  19530. for (b = 0; b < bevelSegments; b++) {
  19531. //for ( b = bevelSegments; b > 0; b -- ) {
  19532. t = b / bevelSegments;
  19533. z = bevelThickness * Math.cos(t * Math.PI / 2);
  19534. bs = bevelSize * Math.sin(t * Math.PI / 2) + bevelOffset; // contract shape
  19535. for (i = 0, il = contour.length; i < il; i++) {
  19536. vert = scalePt2(contour[i], contourMovements[i], bs);
  19537. v(vert.x, vert.y, -z);
  19538. } // expand holes
  19539. for (h = 0, hl = holes.length; h < hl; h++) {
  19540. ahole = holes[h];
  19541. oneHoleMovements = holesMovements[h];
  19542. for (i = 0, il = ahole.length; i < il; i++) {
  19543. vert = scalePt2(ahole[i], oneHoleMovements[i], bs);
  19544. v(vert.x, vert.y, -z);
  19545. }
  19546. }
  19547. }
  19548. bs = bevelSize + bevelOffset; // Back facing vertices
  19549. for (i = 0; i < vlen; i++) {
  19550. vert = bevelEnabled ? scalePt2(vertices[i], verticesMovements[i], bs) : vertices[i];
  19551. if (!extrudeByPath) {
  19552. v(vert.x, vert.y, 0);
  19553. } else {
  19554. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  19555. normal.copy(splineTube.normals[0]).multiplyScalar(vert.x);
  19556. binormal.copy(splineTube.binormals[0]).multiplyScalar(vert.y);
  19557. position2.copy(extrudePts[0]).add(normal).add(binormal);
  19558. v(position2.x, position2.y, position2.z);
  19559. }
  19560. } // Add stepped vertices...
  19561. // Including front facing vertices
  19562. var s;
  19563. for (s = 1; s <= steps; s++) {
  19564. for (i = 0; i < vlen; i++) {
  19565. vert = bevelEnabled ? scalePt2(vertices[i], verticesMovements[i], bs) : vertices[i];
  19566. if (!extrudeByPath) {
  19567. v(vert.x, vert.y, depth / steps * s);
  19568. } else {
  19569. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  19570. normal.copy(splineTube.normals[s]).multiplyScalar(vert.x);
  19571. binormal.copy(splineTube.binormals[s]).multiplyScalar(vert.y);
  19572. position2.copy(extrudePts[s]).add(normal).add(binormal);
  19573. v(position2.x, position2.y, position2.z);
  19574. }
  19575. }
  19576. } // Add bevel segments planes
  19577. //for ( b = 1; b <= bevelSegments; b ++ ) {
  19578. for (b = bevelSegments - 1; b >= 0; b--) {
  19579. t = b / bevelSegments;
  19580. z = bevelThickness * Math.cos(t * Math.PI / 2);
  19581. bs = bevelSize * Math.sin(t * Math.PI / 2) + bevelOffset; // contract shape
  19582. for (i = 0, il = contour.length; i < il; i++) {
  19583. vert = scalePt2(contour[i], contourMovements[i], bs);
  19584. v(vert.x, vert.y, depth + z);
  19585. } // expand holes
  19586. for (h = 0, hl = holes.length; h < hl; h++) {
  19587. ahole = holes[h];
  19588. oneHoleMovements = holesMovements[h];
  19589. for (i = 0, il = ahole.length; i < il; i++) {
  19590. vert = scalePt2(ahole[i], oneHoleMovements[i], bs);
  19591. if (!extrudeByPath) {
  19592. v(vert.x, vert.y, depth + z);
  19593. } else {
  19594. v(vert.x, vert.y + extrudePts[steps - 1].y, extrudePts[steps - 1].x + z);
  19595. }
  19596. }
  19597. }
  19598. }
  19599. /* Faces */
  19600. // Top and bottom faces
  19601. buildLidFaces(); // Sides faces
  19602. buildSideFaces(); ///// Internal functions
  19603. function buildLidFaces() {
  19604. var start = verticesArray.length / 3;
  19605. if (bevelEnabled) {
  19606. var layer = 0; // steps + 1
  19607. var offset = vlen * layer; // Bottom faces
  19608. for (i = 0; i < flen; i++) {
  19609. face = faces[i];
  19610. f3(face[2] + offset, face[1] + offset, face[0] + offset);
  19611. }
  19612. layer = steps + bevelSegments * 2;
  19613. offset = vlen * layer; // Top faces
  19614. for (i = 0; i < flen; i++) {
  19615. face = faces[i];
  19616. f3(face[0] + offset, face[1] + offset, face[2] + offset);
  19617. }
  19618. } else {
  19619. // Bottom faces
  19620. for (i = 0; i < flen; i++) {
  19621. face = faces[i];
  19622. f3(face[2], face[1], face[0]);
  19623. } // Top faces
  19624. for (i = 0; i < flen; i++) {
  19625. face = faces[i];
  19626. f3(face[0] + vlen * steps, face[1] + vlen * steps, face[2] + vlen * steps);
  19627. }
  19628. }
  19629. scope.addGroup(start, verticesArray.length / 3 - start, 0);
  19630. } // Create faces for the z-sides of the shape
  19631. function buildSideFaces() {
  19632. var start = verticesArray.length / 3;
  19633. var layeroffset = 0;
  19634. sidewalls(contour, layeroffset);
  19635. layeroffset += contour.length;
  19636. for (h = 0, hl = holes.length; h < hl; h++) {
  19637. ahole = holes[h];
  19638. sidewalls(ahole, layeroffset); //, true
  19639. layeroffset += ahole.length;
  19640. }
  19641. scope.addGroup(start, verticesArray.length / 3 - start, 1);
  19642. }
  19643. function sidewalls(contour, layeroffset) {
  19644. var j, k;
  19645. i = contour.length;
  19646. while (--i >= 0) {
  19647. j = i;
  19648. k = i - 1;
  19649. if (k < 0) k = contour.length - 1; //console.log('b', i,j, i-1, k,vertices.length);
  19650. var s = 0,
  19651. sl = steps + bevelSegments * 2;
  19652. for (s = 0; s < sl; s++) {
  19653. var slen1 = vlen * s;
  19654. var slen2 = vlen * (s + 1);
  19655. var a = layeroffset + j + slen1,
  19656. b = layeroffset + k + slen1,
  19657. c = layeroffset + k + slen2,
  19658. d = layeroffset + j + slen2;
  19659. f4(a, b, c, d);
  19660. }
  19661. }
  19662. }
  19663. function v(x, y, z) {
  19664. placeholder.push(x);
  19665. placeholder.push(y);
  19666. placeholder.push(z);
  19667. }
  19668. function f3(a, b, c) {
  19669. addVertex(a);
  19670. addVertex(b);
  19671. addVertex(c);
  19672. var nextIndex = verticesArray.length / 3;
  19673. var uvs = uvgen.generateTopUV(scope, verticesArray, nextIndex - 3, nextIndex - 2, nextIndex - 1);
  19674. addUV(uvs[0]);
  19675. addUV(uvs[1]);
  19676. addUV(uvs[2]);
  19677. }
  19678. function f4(a, b, c, d) {
  19679. addVertex(a);
  19680. addVertex(b);
  19681. addVertex(d);
  19682. addVertex(b);
  19683. addVertex(c);
  19684. addVertex(d);
  19685. var nextIndex = verticesArray.length / 3;
  19686. var uvs = uvgen.generateSideWallUV(scope, verticesArray, nextIndex - 6, nextIndex - 3, nextIndex - 2, nextIndex - 1);
  19687. addUV(uvs[0]);
  19688. addUV(uvs[1]);
  19689. addUV(uvs[3]);
  19690. addUV(uvs[1]);
  19691. addUV(uvs[2]);
  19692. addUV(uvs[3]);
  19693. }
  19694. function addVertex(index) {
  19695. verticesArray.push(placeholder[index * 3 + 0]);
  19696. verticesArray.push(placeholder[index * 3 + 1]);
  19697. verticesArray.push(placeholder[index * 3 + 2]);
  19698. }
  19699. function addUV(vector2) {
  19700. uvArray.push(vector2.x);
  19701. uvArray.push(vector2.y);
  19702. }
  19703. }
  19704. }
  19705. ExtrudeBufferGeometry.prototype = Object.create(BufferGeometry.prototype);
  19706. ExtrudeBufferGeometry.prototype.constructor = ExtrudeBufferGeometry;
  19707. ExtrudeBufferGeometry.prototype.toJSON = function () {
  19708. var data = BufferGeometry.prototype.toJSON.call(this);
  19709. var shapes = this.parameters.shapes;
  19710. var options = this.parameters.options;
  19711. return toJSON(shapes, options, data);
  19712. }; //
  19713. var WorldUVGenerator = {
  19714. generateTopUV: function (geometry, vertices, indexA, indexB, indexC) {
  19715. var a_x = vertices[indexA * 3];
  19716. var a_y = vertices[indexA * 3 + 1];
  19717. var b_x = vertices[indexB * 3];
  19718. var b_y = vertices[indexB * 3 + 1];
  19719. var c_x = vertices[indexC * 3];
  19720. var c_y = vertices[indexC * 3 + 1];
  19721. return [new Vector2(a_x, a_y), new Vector2(b_x, b_y), new Vector2(c_x, c_y)];
  19722. },
  19723. generateSideWallUV: function (geometry, vertices, indexA, indexB, indexC, indexD) {
  19724. var a_x = vertices[indexA * 3];
  19725. var a_y = vertices[indexA * 3 + 1];
  19726. var a_z = vertices[indexA * 3 + 2];
  19727. var b_x = vertices[indexB * 3];
  19728. var b_y = vertices[indexB * 3 + 1];
  19729. var b_z = vertices[indexB * 3 + 2];
  19730. var c_x = vertices[indexC * 3];
  19731. var c_y = vertices[indexC * 3 + 1];
  19732. var c_z = vertices[indexC * 3 + 2];
  19733. var d_x = vertices[indexD * 3];
  19734. var d_y = vertices[indexD * 3 + 1];
  19735. var d_z = vertices[indexD * 3 + 2];
  19736. if (Math.abs(a_y - b_y) < 0.01) {
  19737. 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)];
  19738. } else {
  19739. 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)];
  19740. }
  19741. }
  19742. };
  19743. function toJSON(shapes, options, data) {
  19744. //
  19745. data.shapes = [];
  19746. if (Array.isArray(shapes)) {
  19747. for (var i = 0, l = shapes.length; i < l; i++) {
  19748. var shape = shapes[i];
  19749. data.shapes.push(shape.uuid);
  19750. }
  19751. } else {
  19752. data.shapes.push(shapes.uuid);
  19753. } //
  19754. if (options.extrudePath !== undefined) data.options.extrudePath = options.extrudePath.toJSON();
  19755. return data;
  19756. }
  19757. /**
  19758. * @author zz85 / http://www.lab4games.net/zz85/blog
  19759. * @author alteredq / http://alteredqualia.com/
  19760. *
  19761. * Text = 3D Text
  19762. *
  19763. * parameters = {
  19764. * font: <THREE.Font>, // font
  19765. *
  19766. * size: <float>, // size of the text
  19767. * height: <float>, // thickness to extrude text
  19768. * curveSegments: <int>, // number of points on the curves
  19769. *
  19770. * bevelEnabled: <bool>, // turn on bevel
  19771. * bevelThickness: <float>, // how deep into text bevel goes
  19772. * bevelSize: <float>, // how far from text outline (including bevelOffset) is bevel
  19773. * bevelOffset: <float> // how far from text outline does bevel start
  19774. * }
  19775. */
  19776. // TextGeometry
  19777. function TextGeometry(text, parameters) {
  19778. Geometry.call(this);
  19779. this.type = 'TextGeometry';
  19780. this.parameters = {
  19781. text: text,
  19782. parameters: parameters
  19783. };
  19784. this.fromBufferGeometry(new TextBufferGeometry(text, parameters));
  19785. this.mergeVertices();
  19786. }
  19787. TextGeometry.prototype = Object.create(Geometry.prototype);
  19788. TextGeometry.prototype.constructor = TextGeometry; // TextBufferGeometry
  19789. function TextBufferGeometry(text, parameters) {
  19790. parameters = parameters || {};
  19791. var font = parameters.font;
  19792. if (!(font && font.isFont)) {
  19793. console.error('THREE.TextGeometry: font parameter is not an instance of THREE.Font.');
  19794. return new Geometry();
  19795. }
  19796. var shapes = font.generateShapes(text, parameters.size); // translate parameters to ExtrudeGeometry API
  19797. parameters.depth = parameters.height !== undefined ? parameters.height : 50; // defaults
  19798. if (parameters.bevelThickness === undefined) parameters.bevelThickness = 10;
  19799. if (parameters.bevelSize === undefined) parameters.bevelSize = 8;
  19800. if (parameters.bevelEnabled === undefined) parameters.bevelEnabled = false;
  19801. ExtrudeBufferGeometry.call(this, shapes, parameters);
  19802. this.type = 'TextBufferGeometry';
  19803. }
  19804. TextBufferGeometry.prototype = Object.create(ExtrudeBufferGeometry.prototype);
  19805. TextBufferGeometry.prototype.constructor = TextBufferGeometry;
  19806. /**
  19807. * @author mrdoob / http://mrdoob.com/
  19808. * @author benaadams / https://twitter.com/ben_a_adams
  19809. * @author Mugen87 / https://github.com/Mugen87
  19810. */
  19811. // SphereGeometry
  19812. function SphereGeometry(radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength) {
  19813. Geometry.call(this);
  19814. this.type = 'SphereGeometry';
  19815. this.parameters = {
  19816. radius: radius,
  19817. widthSegments: widthSegments,
  19818. heightSegments: heightSegments,
  19819. phiStart: phiStart,
  19820. phiLength: phiLength,
  19821. thetaStart: thetaStart,
  19822. thetaLength: thetaLength
  19823. };
  19824. this.fromBufferGeometry(new SphereBufferGeometry(radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength));
  19825. this.mergeVertices();
  19826. }
  19827. SphereGeometry.prototype = Object.create(Geometry.prototype);
  19828. SphereGeometry.prototype.constructor = SphereGeometry; // SphereBufferGeometry
  19829. function SphereBufferGeometry(radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength) {
  19830. BufferGeometry.call(this);
  19831. this.type = 'SphereBufferGeometry';
  19832. this.parameters = {
  19833. radius: radius,
  19834. widthSegments: widthSegments,
  19835. heightSegments: heightSegments,
  19836. phiStart: phiStart,
  19837. phiLength: phiLength,
  19838. thetaStart: thetaStart,
  19839. thetaLength: thetaLength
  19840. };
  19841. radius = radius || 1;
  19842. widthSegments = Math.max(3, Math.floor(widthSegments) || 8);
  19843. heightSegments = Math.max(2, Math.floor(heightSegments) || 6);
  19844. phiStart = phiStart !== undefined ? phiStart : 0;
  19845. phiLength = phiLength !== undefined ? phiLength : Math.PI * 2;
  19846. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  19847. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI;
  19848. var thetaEnd = Math.min(thetaStart + thetaLength, Math.PI);
  19849. var ix, iy;
  19850. var index = 0;
  19851. var grid = [];
  19852. var vertex = new Vector3();
  19853. var normal = new Vector3(); // buffers
  19854. var indices = [];
  19855. var vertices = [];
  19856. var normals = [];
  19857. var uvs = []; // generate vertices, normals and uvs
  19858. for (iy = 0; iy <= heightSegments; iy++) {
  19859. var verticesRow = [];
  19860. var v = iy / heightSegments; // special case for the poles
  19861. var uOffset = 0;
  19862. if (iy == 0 && thetaStart == 0) {
  19863. uOffset = 0.5 / widthSegments;
  19864. } else if (iy == heightSegments && thetaEnd == Math.PI) {
  19865. uOffset = -0.5 / widthSegments;
  19866. }
  19867. for (ix = 0; ix <= widthSegments; ix++) {
  19868. var u = ix / widthSegments; // vertex
  19869. vertex.x = -radius * Math.cos(phiStart + u * phiLength) * Math.sin(thetaStart + v * thetaLength);
  19870. vertex.y = radius * Math.cos(thetaStart + v * thetaLength);
  19871. vertex.z = radius * Math.sin(phiStart + u * phiLength) * Math.sin(thetaStart + v * thetaLength);
  19872. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  19873. normal.copy(vertex).normalize();
  19874. normals.push(normal.x, normal.y, normal.z); // uv
  19875. uvs.push(u + uOffset, 1 - v);
  19876. verticesRow.push(index++);
  19877. }
  19878. grid.push(verticesRow);
  19879. } // indices
  19880. for (iy = 0; iy < heightSegments; iy++) {
  19881. for (ix = 0; ix < widthSegments; ix++) {
  19882. var a = grid[iy][ix + 1];
  19883. var b = grid[iy][ix];
  19884. var c = grid[iy + 1][ix];
  19885. var d = grid[iy + 1][ix + 1];
  19886. if (iy !== 0 || thetaStart > 0) indices.push(a, b, d);
  19887. if (iy !== heightSegments - 1 || thetaEnd < Math.PI) indices.push(b, c, d);
  19888. }
  19889. } // build geometry
  19890. this.setIndex(indices);
  19891. this.addAttribute('position', new Float32BufferAttribute(vertices, 3));
  19892. this.addAttribute('normal', new Float32BufferAttribute(normals, 3));
  19893. this.addAttribute('uv', new Float32BufferAttribute(uvs, 2));
  19894. }
  19895. SphereBufferGeometry.prototype = Object.create(BufferGeometry.prototype);
  19896. SphereBufferGeometry.prototype.constructor = SphereBufferGeometry;
  19897. /**
  19898. * @author Kaleb Murphy
  19899. * @author Mugen87 / https://github.com/Mugen87
  19900. */
  19901. // RingGeometry
  19902. function RingGeometry(innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength) {
  19903. Geometry.call(this);
  19904. this.type = 'RingGeometry';
  19905. this.parameters = {
  19906. innerRadius: innerRadius,
  19907. outerRadius: outerRadius,
  19908. thetaSegments: thetaSegments,
  19909. phiSegments: phiSegments,
  19910. thetaStart: thetaStart,
  19911. thetaLength: thetaLength
  19912. };
  19913. this.fromBufferGeometry(new RingBufferGeometry(innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength));
  19914. this.mergeVertices();
  19915. }
  19916. RingGeometry.prototype = Object.create(Geometry.prototype);
  19917. RingGeometry.prototype.constructor = RingGeometry; // RingBufferGeometry
  19918. function RingBufferGeometry(innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength) {
  19919. BufferGeometry.call(this);
  19920. this.type = 'RingBufferGeometry';
  19921. this.parameters = {
  19922. innerRadius: innerRadius,
  19923. outerRadius: outerRadius,
  19924. thetaSegments: thetaSegments,
  19925. phiSegments: phiSegments,
  19926. thetaStart: thetaStart,
  19927. thetaLength: thetaLength
  19928. };
  19929. innerRadius = innerRadius || 0.5;
  19930. outerRadius = outerRadius || 1;
  19931. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  19932. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  19933. thetaSegments = thetaSegments !== undefined ? Math.max(3, thetaSegments) : 8;
  19934. phiSegments = phiSegments !== undefined ? Math.max(1, phiSegments) : 1; // buffers
  19935. var indices = [];
  19936. var vertices = [];
  19937. var normals = [];
  19938. var uvs = []; // some helper variables
  19939. var segment;
  19940. var radius = innerRadius;
  19941. var radiusStep = (outerRadius - innerRadius) / phiSegments;
  19942. var vertex = new Vector3();
  19943. var uv = new Vector2();
  19944. var j, i; // generate vertices, normals and uvs
  19945. for (j = 0; j <= phiSegments; j++) {
  19946. for (i = 0; i <= thetaSegments; i++) {
  19947. // values are generate from the inside of the ring to the outside
  19948. segment = thetaStart + i / thetaSegments * thetaLength; // vertex
  19949. vertex.x = radius * Math.cos(segment);
  19950. vertex.y = radius * Math.sin(segment);
  19951. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  19952. normals.push(0, 0, 1); // uv
  19953. uv.x = (vertex.x / outerRadius + 1) / 2;
  19954. uv.y = (vertex.y / outerRadius + 1) / 2;
  19955. uvs.push(uv.x, uv.y);
  19956. } // increase the radius for next row of vertices
  19957. radius += radiusStep;
  19958. } // indices
  19959. for (j = 0; j < phiSegments; j++) {
  19960. var thetaSegmentLevel = j * (thetaSegments + 1);
  19961. for (i = 0; i < thetaSegments; i++) {
  19962. segment = i + thetaSegmentLevel;
  19963. var a = segment;
  19964. var b = segment + thetaSegments + 1;
  19965. var c = segment + thetaSegments + 2;
  19966. var d = segment + 1; // faces
  19967. indices.push(a, b, d);
  19968. indices.push(b, c, d);
  19969. }
  19970. } // build geometry
  19971. this.setIndex(indices);
  19972. this.addAttribute('position', new Float32BufferAttribute(vertices, 3));
  19973. this.addAttribute('normal', new Float32BufferAttribute(normals, 3));
  19974. this.addAttribute('uv', new Float32BufferAttribute(uvs, 2));
  19975. }
  19976. RingBufferGeometry.prototype = Object.create(BufferGeometry.prototype);
  19977. RingBufferGeometry.prototype.constructor = RingBufferGeometry;
  19978. /**
  19979. * @author zz85 / https://github.com/zz85
  19980. * @author bhouston / http://clara.io
  19981. * @author Mugen87 / https://github.com/Mugen87
  19982. */
  19983. // LatheGeometry
  19984. function LatheGeometry(points, segments, phiStart, phiLength) {
  19985. Geometry.call(this);
  19986. this.type = 'LatheGeometry';
  19987. this.parameters = {
  19988. points: points,
  19989. segments: segments,
  19990. phiStart: phiStart,
  19991. phiLength: phiLength
  19992. };
  19993. this.fromBufferGeometry(new LatheBufferGeometry(points, segments, phiStart, phiLength));
  19994. this.mergeVertices();
  19995. }
  19996. LatheGeometry.prototype = Object.create(Geometry.prototype);
  19997. LatheGeometry.prototype.constructor = LatheGeometry; // LatheBufferGeometry
  19998. function LatheBufferGeometry(points, segments, phiStart, phiLength) {
  19999. BufferGeometry.call(this);
  20000. this.type = 'LatheBufferGeometry';
  20001. this.parameters = {
  20002. points: points,
  20003. segments: segments,
  20004. phiStart: phiStart,
  20005. phiLength: phiLength
  20006. };
  20007. segments = Math.floor(segments) || 12;
  20008. phiStart = phiStart || 0;
  20009. phiLength = phiLength || Math.PI * 2; // clamp phiLength so it's in range of [ 0, 2PI ]
  20010. phiLength = _Math.clamp(phiLength, 0, Math.PI * 2); // buffers
  20011. var indices = [];
  20012. var vertices = [];
  20013. var uvs = []; // helper variables
  20014. var base;
  20015. var inverseSegments = 1.0 / segments;
  20016. var vertex = new Vector3();
  20017. var uv = new Vector2();
  20018. var i, j; // generate vertices and uvs
  20019. for (i = 0; i <= segments; i++) {
  20020. var phi = phiStart + i * inverseSegments * phiLength;
  20021. var sin = Math.sin(phi);
  20022. var cos = Math.cos(phi);
  20023. for (j = 0; j <= points.length - 1; j++) {
  20024. // vertex
  20025. vertex.x = points[j].x * sin;
  20026. vertex.y = points[j].y;
  20027. vertex.z = points[j].x * cos;
  20028. vertices.push(vertex.x, vertex.y, vertex.z); // uv
  20029. uv.x = i / segments;
  20030. uv.y = j / (points.length - 1);
  20031. uvs.push(uv.x, uv.y);
  20032. }
  20033. } // indices
  20034. for (i = 0; i < segments; i++) {
  20035. for (j = 0; j < points.length - 1; j++) {
  20036. base = j + i * points.length;
  20037. var a = base;
  20038. var b = base + points.length;
  20039. var c = base + points.length + 1;
  20040. var d = base + 1; // faces
  20041. indices.push(a, b, d);
  20042. indices.push(b, c, d);
  20043. }
  20044. } // build geometry
  20045. this.setIndex(indices);
  20046. this.addAttribute('position', new Float32BufferAttribute(vertices, 3));
  20047. this.addAttribute('uv', new Float32BufferAttribute(uvs, 2)); // generate normals
  20048. this.computeVertexNormals(); // if the geometry is closed, we need to average the normals along the seam.
  20049. // because the corresponding vertices are identical (but still have different UVs).
  20050. if (phiLength === Math.PI * 2) {
  20051. var normals = this.attributes.normal.array;
  20052. var n1 = new Vector3();
  20053. var n2 = new Vector3();
  20054. var n = new Vector3(); // this is the buffer offset for the last line of vertices
  20055. base = segments * points.length * 3;
  20056. for (i = 0, j = 0; i < points.length; i++, j += 3) {
  20057. // select the normal of the vertex in the first line
  20058. n1.x = normals[j + 0];
  20059. n1.y = normals[j + 1];
  20060. n1.z = normals[j + 2]; // select the normal of the vertex in the last line
  20061. n2.x = normals[base + j + 0];
  20062. n2.y = normals[base + j + 1];
  20063. n2.z = normals[base + j + 2]; // average normals
  20064. n.addVectors(n1, n2).normalize(); // assign the new values to both normals
  20065. normals[j + 0] = normals[base + j + 0] = n.x;
  20066. normals[j + 1] = normals[base + j + 1] = n.y;
  20067. normals[j + 2] = normals[base + j + 2] = n.z;
  20068. }
  20069. }
  20070. }
  20071. LatheBufferGeometry.prototype = Object.create(BufferGeometry.prototype);
  20072. LatheBufferGeometry.prototype.constructor = LatheBufferGeometry;
  20073. /**
  20074. * @author jonobr1 / http://jonobr1.com
  20075. * @author Mugen87 / https://github.com/Mugen87
  20076. */
  20077. // ShapeGeometry
  20078. function ShapeGeometry(shapes, curveSegments) {
  20079. Geometry.call(this);
  20080. this.type = 'ShapeGeometry';
  20081. if (typeof curveSegments === 'object') {
  20082. console.warn('THREE.ShapeGeometry: Options parameter has been removed.');
  20083. curveSegments = curveSegments.curveSegments;
  20084. }
  20085. this.parameters = {
  20086. shapes: shapes,
  20087. curveSegments: curveSegments
  20088. };
  20089. this.fromBufferGeometry(new ShapeBufferGeometry(shapes, curveSegments));
  20090. this.mergeVertices();
  20091. }
  20092. ShapeGeometry.prototype = Object.create(Geometry.prototype);
  20093. ShapeGeometry.prototype.constructor = ShapeGeometry;
  20094. ShapeGeometry.prototype.toJSON = function () {
  20095. var data = Geometry.prototype.toJSON.call(this);
  20096. var shapes = this.parameters.shapes;
  20097. return toJSON$1(shapes, data);
  20098. }; // ShapeBufferGeometry
  20099. function ShapeBufferGeometry(shapes, curveSegments) {
  20100. BufferGeometry.call(this);
  20101. this.type = 'ShapeBufferGeometry';
  20102. this.parameters = {
  20103. shapes: shapes,
  20104. curveSegments: curveSegments
  20105. };
  20106. curveSegments = curveSegments || 12; // buffers
  20107. var indices = [];
  20108. var vertices = [];
  20109. var normals = [];
  20110. var uvs = []; // helper variables
  20111. var groupStart = 0;
  20112. var groupCount = 0; // allow single and array values for "shapes" parameter
  20113. if (Array.isArray(shapes) === false) {
  20114. addShape(shapes);
  20115. } else {
  20116. for (var i = 0; i < shapes.length; i++) {
  20117. addShape(shapes[i]);
  20118. this.addGroup(groupStart, groupCount, i); // enables MultiMaterial support
  20119. groupStart += groupCount;
  20120. groupCount = 0;
  20121. }
  20122. } // build geometry
  20123. this.setIndex(indices);
  20124. this.addAttribute('position', new Float32BufferAttribute(vertices, 3));
  20125. this.addAttribute('normal', new Float32BufferAttribute(normals, 3));
  20126. this.addAttribute('uv', new Float32BufferAttribute(uvs, 2)); // helper functions
  20127. function addShape(shape) {
  20128. var i, l, shapeHole;
  20129. var indexOffset = vertices.length / 3;
  20130. var points = shape.extractPoints(curveSegments);
  20131. var shapeVertices = points.shape;
  20132. var shapeHoles = points.holes; // check direction of vertices
  20133. if (ShapeUtils.isClockWise(shapeVertices) === false) {
  20134. shapeVertices = shapeVertices.reverse();
  20135. }
  20136. for (i = 0, l = shapeHoles.length; i < l; i++) {
  20137. shapeHole = shapeHoles[i];
  20138. if (ShapeUtils.isClockWise(shapeHole) === true) {
  20139. shapeHoles[i] = shapeHole.reverse();
  20140. }
  20141. }
  20142. var faces = ShapeUtils.triangulateShape(shapeVertices, shapeHoles); // join vertices of inner and outer paths to a single array
  20143. for (i = 0, l = shapeHoles.length; i < l; i++) {
  20144. shapeHole = shapeHoles[i];
  20145. shapeVertices = shapeVertices.concat(shapeHole);
  20146. } // vertices, normals, uvs
  20147. for (i = 0, l = shapeVertices.length; i < l; i++) {
  20148. var vertex = shapeVertices[i];
  20149. vertices.push(vertex.x, vertex.y, 0);
  20150. normals.push(0, 0, 1);
  20151. uvs.push(vertex.x, vertex.y); // world uvs
  20152. } // incides
  20153. for (i = 0, l = faces.length; i < l; i++) {
  20154. var face = faces[i];
  20155. var a = face[0] + indexOffset;
  20156. var b = face[1] + indexOffset;
  20157. var c = face[2] + indexOffset;
  20158. indices.push(a, b, c);
  20159. groupCount += 3;
  20160. }
  20161. }
  20162. }
  20163. ShapeBufferGeometry.prototype = Object.create(BufferGeometry.prototype);
  20164. ShapeBufferGeometry.prototype.constructor = ShapeBufferGeometry;
  20165. ShapeBufferGeometry.prototype.toJSON = function () {
  20166. var data = BufferGeometry.prototype.toJSON.call(this);
  20167. var shapes = this.parameters.shapes;
  20168. return toJSON$1(shapes, data);
  20169. }; //
  20170. function toJSON$1(shapes, data) {
  20171. data.shapes = [];
  20172. if (Array.isArray(shapes)) {
  20173. for (var i = 0, l = shapes.length; i < l; i++) {
  20174. var shape = shapes[i];
  20175. data.shapes.push(shape.uuid);
  20176. }
  20177. } else {
  20178. data.shapes.push(shapes.uuid);
  20179. }
  20180. return data;
  20181. }
  20182. /**
  20183. * @author WestLangley / http://github.com/WestLangley
  20184. * @author Mugen87 / https://github.com/Mugen87
  20185. */
  20186. function EdgesGeometry(geometry, thresholdAngle) {
  20187. BufferGeometry.call(this);
  20188. this.type = 'EdgesGeometry';
  20189. this.parameters = {
  20190. thresholdAngle: thresholdAngle
  20191. };
  20192. thresholdAngle = thresholdAngle !== undefined ? thresholdAngle : 1; // buffer
  20193. var vertices = []; // helper variables
  20194. var thresholdDot = Math.cos(_Math.DEG2RAD * thresholdAngle);
  20195. var edge = [0, 0],
  20196. edges = {},
  20197. edge1,
  20198. edge2;
  20199. var key,
  20200. keys = ['a', 'b', 'c']; // prepare source geometry
  20201. var geometry2;
  20202. if (geometry.isBufferGeometry) {
  20203. geometry2 = new Geometry();
  20204. geometry2.fromBufferGeometry(geometry);
  20205. } else {
  20206. geometry2 = geometry.clone();
  20207. }
  20208. geometry2.mergeVertices();
  20209. geometry2.computeFaceNormals();
  20210. var sourceVertices = geometry2.vertices;
  20211. var faces = geometry2.faces; // now create a data structure where each entry represents an edge with its adjoining faces
  20212. for (var i = 0, l = faces.length; i < l; i++) {
  20213. var face = faces[i];
  20214. for (var j = 0; j < 3; j++) {
  20215. edge1 = face[keys[j]];
  20216. edge2 = face[keys[(j + 1) % 3]];
  20217. edge[0] = Math.min(edge1, edge2);
  20218. edge[1] = Math.max(edge1, edge2);
  20219. key = edge[0] + ',' + edge[1];
  20220. if (edges[key] === undefined) {
  20221. edges[key] = {
  20222. index1: edge[0],
  20223. index2: edge[1],
  20224. face1: i,
  20225. face2: undefined
  20226. };
  20227. } else {
  20228. edges[key].face2 = i;
  20229. }
  20230. }
  20231. } // generate vertices
  20232. for (key in edges) {
  20233. 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.
  20234. if (e.face2 === undefined || faces[e.face1].normal.dot(faces[e.face2].normal) <= thresholdDot) {
  20235. var vertex = sourceVertices[e.index1];
  20236. vertices.push(vertex.x, vertex.y, vertex.z);
  20237. vertex = sourceVertices[e.index2];
  20238. vertices.push(vertex.x, vertex.y, vertex.z);
  20239. }
  20240. } // build geometry
  20241. this.addAttribute('position', new Float32BufferAttribute(vertices, 3));
  20242. }
  20243. EdgesGeometry.prototype = Object.create(BufferGeometry.prototype);
  20244. EdgesGeometry.prototype.constructor = EdgesGeometry;
  20245. /**
  20246. * @author mrdoob / http://mrdoob.com/
  20247. * @author Mugen87 / https://github.com/Mugen87
  20248. */
  20249. // CylinderGeometry
  20250. function CylinderGeometry(radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength) {
  20251. Geometry.call(this);
  20252. this.type = 'CylinderGeometry';
  20253. this.parameters = {
  20254. radiusTop: radiusTop,
  20255. radiusBottom: radiusBottom,
  20256. height: height,
  20257. radialSegments: radialSegments,
  20258. heightSegments: heightSegments,
  20259. openEnded: openEnded,
  20260. thetaStart: thetaStart,
  20261. thetaLength: thetaLength
  20262. };
  20263. this.fromBufferGeometry(new CylinderBufferGeometry(radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength));
  20264. this.mergeVertices();
  20265. }
  20266. CylinderGeometry.prototype = Object.create(Geometry.prototype);
  20267. CylinderGeometry.prototype.constructor = CylinderGeometry; // CylinderBufferGeometry
  20268. function CylinderBufferGeometry(radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength) {
  20269. BufferGeometry.call(this);
  20270. this.type = 'CylinderBufferGeometry';
  20271. this.parameters = {
  20272. radiusTop: radiusTop,
  20273. radiusBottom: radiusBottom,
  20274. height: height,
  20275. radialSegments: radialSegments,
  20276. heightSegments: heightSegments,
  20277. openEnded: openEnded,
  20278. thetaStart: thetaStart,
  20279. thetaLength: thetaLength
  20280. };
  20281. var scope = this;
  20282. radiusTop = radiusTop !== undefined ? radiusTop : 1;
  20283. radiusBottom = radiusBottom !== undefined ? radiusBottom : 1;
  20284. height = height || 1;
  20285. radialSegments = Math.floor(radialSegments) || 8;
  20286. heightSegments = Math.floor(heightSegments) || 1;
  20287. openEnded = openEnded !== undefined ? openEnded : false;
  20288. thetaStart = thetaStart !== undefined ? thetaStart : 0.0;
  20289. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2; // buffers
  20290. var indices = [];
  20291. var vertices = [];
  20292. var normals = [];
  20293. var uvs = []; // helper variables
  20294. var index = 0;
  20295. var indexArray = [];
  20296. var halfHeight = height / 2;
  20297. var groupStart = 0; // generate geometry
  20298. generateTorso();
  20299. if (openEnded === false) {
  20300. if (radiusTop > 0) generateCap(true);
  20301. if (radiusBottom > 0) generateCap(false);
  20302. } // build geometry
  20303. this.setIndex(indices);
  20304. this.addAttribute('position', new Float32BufferAttribute(vertices, 3));
  20305. this.addAttribute('normal', new Float32BufferAttribute(normals, 3));
  20306. this.addAttribute('uv', new Float32BufferAttribute(uvs, 2));
  20307. function generateTorso() {
  20308. var x, y;
  20309. var normal = new Vector3();
  20310. var vertex = new Vector3();
  20311. var groupCount = 0; // this will be used to calculate the normal
  20312. var slope = (radiusBottom - radiusTop) / height; // generate vertices, normals and uvs
  20313. for (y = 0; y <= heightSegments; y++) {
  20314. var indexRow = [];
  20315. var v = y / heightSegments; // calculate the radius of the current row
  20316. var radius = v * (radiusBottom - radiusTop) + radiusTop;
  20317. for (x = 0; x <= radialSegments; x++) {
  20318. var u = x / radialSegments;
  20319. var theta = u * thetaLength + thetaStart;
  20320. var sinTheta = Math.sin(theta);
  20321. var cosTheta = Math.cos(theta); // vertex
  20322. vertex.x = radius * sinTheta;
  20323. vertex.y = -v * height + halfHeight;
  20324. vertex.z = radius * cosTheta;
  20325. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  20326. normal.set(sinTheta, slope, cosTheta).normalize();
  20327. normals.push(normal.x, normal.y, normal.z); // uv
  20328. uvs.push(u, 1 - v); // save index of vertex in respective row
  20329. indexRow.push(index++);
  20330. } // now save vertices of the row in our index array
  20331. indexArray.push(indexRow);
  20332. } // generate indices
  20333. for (x = 0; x < radialSegments; x++) {
  20334. for (y = 0; y < heightSegments; y++) {
  20335. // we use the index array to access the correct indices
  20336. var a = indexArray[y][x];
  20337. var b = indexArray[y + 1][x];
  20338. var c = indexArray[y + 1][x + 1];
  20339. var d = indexArray[y][x + 1]; // faces
  20340. indices.push(a, b, d);
  20341. indices.push(b, c, d); // update group counter
  20342. groupCount += 6;
  20343. }
  20344. } // add a group to the geometry. this will ensure multi material support
  20345. scope.addGroup(groupStart, groupCount, 0); // calculate new start value for groups
  20346. groupStart += groupCount;
  20347. }
  20348. function generateCap(top) {
  20349. var x, centerIndexStart, centerIndexEnd;
  20350. var uv = new Vector2();
  20351. var vertex = new Vector3();
  20352. var groupCount = 0;
  20353. var radius = top === true ? radiusTop : radiusBottom;
  20354. var sign = top === true ? 1 : -1; // save the index of the first center vertex
  20355. centerIndexStart = index; // first we generate the center vertex data of the cap.
  20356. // because the geometry needs one set of uvs per face,
  20357. // we must generate a center vertex per face/segment
  20358. for (x = 1; x <= radialSegments; x++) {
  20359. // vertex
  20360. vertices.push(0, halfHeight * sign, 0); // normal
  20361. normals.push(0, sign, 0); // uv
  20362. uvs.push(0.5, 0.5); // increase index
  20363. index++;
  20364. } // save the index of the last center vertex
  20365. centerIndexEnd = index; // now we generate the surrounding vertices, normals and uvs
  20366. for (x = 0; x <= radialSegments; x++) {
  20367. var u = x / radialSegments;
  20368. var theta = u * thetaLength + thetaStart;
  20369. var cosTheta = Math.cos(theta);
  20370. var sinTheta = Math.sin(theta); // vertex
  20371. vertex.x = radius * sinTheta;
  20372. vertex.y = halfHeight * sign;
  20373. vertex.z = radius * cosTheta;
  20374. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  20375. normals.push(0, sign, 0); // uv
  20376. uv.x = cosTheta * 0.5 + 0.5;
  20377. uv.y = sinTheta * 0.5 * sign + 0.5;
  20378. uvs.push(uv.x, uv.y); // increase index
  20379. index++;
  20380. } // generate indices
  20381. for (x = 0; x < radialSegments; x++) {
  20382. var c = centerIndexStart + x;
  20383. var i = centerIndexEnd + x;
  20384. if (top === true) {
  20385. // face top
  20386. indices.push(i, i + 1, c);
  20387. } else {
  20388. // face bottom
  20389. indices.push(i + 1, i, c);
  20390. }
  20391. groupCount += 3;
  20392. } // add a group to the geometry. this will ensure multi material support
  20393. scope.addGroup(groupStart, groupCount, top === true ? 1 : 2); // calculate new start value for groups
  20394. groupStart += groupCount;
  20395. }
  20396. }
  20397. CylinderBufferGeometry.prototype = Object.create(BufferGeometry.prototype);
  20398. CylinderBufferGeometry.prototype.constructor = CylinderBufferGeometry;
  20399. /**
  20400. * @author abelnation / http://github.com/abelnation
  20401. */
  20402. // ConeGeometry
  20403. function ConeGeometry(radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength) {
  20404. CylinderGeometry.call(this, 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength);
  20405. this.type = 'ConeGeometry';
  20406. this.parameters = {
  20407. radius: radius,
  20408. height: height,
  20409. radialSegments: radialSegments,
  20410. heightSegments: heightSegments,
  20411. openEnded: openEnded,
  20412. thetaStart: thetaStart,
  20413. thetaLength: thetaLength
  20414. };
  20415. }
  20416. ConeGeometry.prototype = Object.create(CylinderGeometry.prototype);
  20417. ConeGeometry.prototype.constructor = ConeGeometry; // ConeBufferGeometry
  20418. function ConeBufferGeometry(radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength) {
  20419. CylinderBufferGeometry.call(this, 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength);
  20420. this.type = 'ConeBufferGeometry';
  20421. this.parameters = {
  20422. radius: radius,
  20423. height: height,
  20424. radialSegments: radialSegments,
  20425. heightSegments: heightSegments,
  20426. openEnded: openEnded,
  20427. thetaStart: thetaStart,
  20428. thetaLength: thetaLength
  20429. };
  20430. }
  20431. ConeBufferGeometry.prototype = Object.create(CylinderBufferGeometry.prototype);
  20432. ConeBufferGeometry.prototype.constructor = ConeBufferGeometry;
  20433. /**
  20434. * @author benaadams / https://twitter.com/ben_a_adams
  20435. * @author Mugen87 / https://github.com/Mugen87
  20436. * @author hughes
  20437. */
  20438. // CircleGeometry
  20439. function CircleGeometry(radius, segments, thetaStart, thetaLength) {
  20440. Geometry.call(this);
  20441. this.type = 'CircleGeometry';
  20442. this.parameters = {
  20443. radius: radius,
  20444. segments: segments,
  20445. thetaStart: thetaStart,
  20446. thetaLength: thetaLength
  20447. };
  20448. this.fromBufferGeometry(new CircleBufferGeometry(radius, segments, thetaStart, thetaLength));
  20449. this.mergeVertices();
  20450. }
  20451. CircleGeometry.prototype = Object.create(Geometry.prototype);
  20452. CircleGeometry.prototype.constructor = CircleGeometry; // CircleBufferGeometry
  20453. function CircleBufferGeometry(radius, segments, thetaStart, thetaLength) {
  20454. BufferGeometry.call(this);
  20455. this.type = 'CircleBufferGeometry';
  20456. this.parameters = {
  20457. radius: radius,
  20458. segments: segments,
  20459. thetaStart: thetaStart,
  20460. thetaLength: thetaLength
  20461. };
  20462. radius = radius || 1;
  20463. segments = segments !== undefined ? Math.max(3, segments) : 8;
  20464. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  20465. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2; // buffers
  20466. var indices = [];
  20467. var vertices = [];
  20468. var normals = [];
  20469. var uvs = []; // helper variables
  20470. var i, s;
  20471. var vertex = new Vector3();
  20472. var uv = new Vector2(); // center point
  20473. vertices.push(0, 0, 0);
  20474. normals.push(0, 0, 1);
  20475. uvs.push(0.5, 0.5);
  20476. for (s = 0, i = 3; s <= segments; s++, i += 3) {
  20477. var segment = thetaStart + s / segments * thetaLength; // vertex
  20478. vertex.x = radius * Math.cos(segment);
  20479. vertex.y = radius * Math.sin(segment);
  20480. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  20481. normals.push(0, 0, 1); // uvs
  20482. uv.x = (vertices[i] / radius + 1) / 2;
  20483. uv.y = (vertices[i + 1] / radius + 1) / 2;
  20484. uvs.push(uv.x, uv.y);
  20485. } // indices
  20486. for (i = 1; i <= segments; i++) {
  20487. indices.push(i, i + 1, 0);
  20488. } // build geometry
  20489. this.setIndex(indices);
  20490. this.addAttribute('position', new Float32BufferAttribute(vertices, 3));
  20491. this.addAttribute('normal', new Float32BufferAttribute(normals, 3));
  20492. this.addAttribute('uv', new Float32BufferAttribute(uvs, 2));
  20493. }
  20494. CircleBufferGeometry.prototype = Object.create(BufferGeometry.prototype);
  20495. CircleBufferGeometry.prototype.constructor = CircleBufferGeometry;
  20496. var Geometries =
  20497. /*#__PURE__*/
  20498. Object.freeze({
  20499. WireframeGeometry: WireframeGeometry,
  20500. ParametricGeometry: ParametricGeometry,
  20501. ParametricBufferGeometry: ParametricBufferGeometry,
  20502. TetrahedronGeometry: TetrahedronGeometry,
  20503. TetrahedronBufferGeometry: TetrahedronBufferGeometry,
  20504. OctahedronGeometry: OctahedronGeometry,
  20505. OctahedronBufferGeometry: OctahedronBufferGeometry,
  20506. IcosahedronGeometry: IcosahedronGeometry,
  20507. IcosahedronBufferGeometry: IcosahedronBufferGeometry,
  20508. DodecahedronGeometry: DodecahedronGeometry,
  20509. DodecahedronBufferGeometry: DodecahedronBufferGeometry,
  20510. PolyhedronGeometry: PolyhedronGeometry,
  20511. PolyhedronBufferGeometry: PolyhedronBufferGeometry,
  20512. TubeGeometry: TubeGeometry,
  20513. TubeBufferGeometry: TubeBufferGeometry,
  20514. TorusKnotGeometry: TorusKnotGeometry,
  20515. TorusKnotBufferGeometry: TorusKnotBufferGeometry,
  20516. TorusGeometry: TorusGeometry,
  20517. TorusBufferGeometry: TorusBufferGeometry,
  20518. TextGeometry: TextGeometry,
  20519. TextBufferGeometry: TextBufferGeometry,
  20520. SphereGeometry: SphereGeometry,
  20521. SphereBufferGeometry: SphereBufferGeometry,
  20522. RingGeometry: RingGeometry,
  20523. RingBufferGeometry: RingBufferGeometry,
  20524. PlaneGeometry: PlaneGeometry,
  20525. PlaneBufferGeometry: PlaneBufferGeometry,
  20526. LatheGeometry: LatheGeometry,
  20527. LatheBufferGeometry: LatheBufferGeometry,
  20528. ShapeGeometry: ShapeGeometry,
  20529. ShapeBufferGeometry: ShapeBufferGeometry,
  20530. ExtrudeGeometry: ExtrudeGeometry,
  20531. ExtrudeBufferGeometry: ExtrudeBufferGeometry,
  20532. EdgesGeometry: EdgesGeometry,
  20533. ConeGeometry: ConeGeometry,
  20534. ConeBufferGeometry: ConeBufferGeometry,
  20535. CylinderGeometry: CylinderGeometry,
  20536. CylinderBufferGeometry: CylinderBufferGeometry,
  20537. CircleGeometry: CircleGeometry,
  20538. CircleBufferGeometry: CircleBufferGeometry,
  20539. BoxGeometry: BoxGeometry,
  20540. BoxBufferGeometry: BoxBufferGeometry
  20541. });
  20542. /**
  20543. * @author mrdoob / http://mrdoob.com/
  20544. *
  20545. * parameters = {
  20546. * color: <THREE.Color>
  20547. * }
  20548. */
  20549. function ShadowMaterial(parameters) {
  20550. Material.call(this);
  20551. this.type = 'ShadowMaterial';
  20552. this.color = new Color(0x000000);
  20553. this.transparent = true;
  20554. this.setValues(parameters);
  20555. }
  20556. ShadowMaterial.prototype = Object.create(Material.prototype);
  20557. ShadowMaterial.prototype.constructor = ShadowMaterial;
  20558. ShadowMaterial.prototype.isShadowMaterial = true;
  20559. ShadowMaterial.prototype.copy = function (source) {
  20560. Material.prototype.copy.call(this, source);
  20561. this.color.copy(source.color);
  20562. return this;
  20563. };
  20564. /**
  20565. * @author mrdoob / http://mrdoob.com/
  20566. */
  20567. function RawShaderMaterial(parameters) {
  20568. ShaderMaterial.call(this, parameters);
  20569. this.type = 'RawShaderMaterial';
  20570. }
  20571. RawShaderMaterial.prototype = Object.create(ShaderMaterial.prototype);
  20572. RawShaderMaterial.prototype.constructor = RawShaderMaterial;
  20573. RawShaderMaterial.prototype.isRawShaderMaterial = true;
  20574. /**
  20575. * @author WestLangley / http://github.com/WestLangley
  20576. *
  20577. * parameters = {
  20578. * color: <hex>,
  20579. * roughness: <float>,
  20580. * metalness: <float>,
  20581. * opacity: <float>,
  20582. *
  20583. * map: new THREE.Texture( <Image> ),
  20584. *
  20585. * lightMap: new THREE.Texture( <Image> ),
  20586. * lightMapIntensity: <float>
  20587. *
  20588. * aoMap: new THREE.Texture( <Image> ),
  20589. * aoMapIntensity: <float>
  20590. *
  20591. * emissive: <hex>,
  20592. * emissiveIntensity: <float>
  20593. * emissiveMap: new THREE.Texture( <Image> ),
  20594. *
  20595. * bumpMap: new THREE.Texture( <Image> ),
  20596. * bumpScale: <float>,
  20597. *
  20598. * normalMap: new THREE.Texture( <Image> ),
  20599. * normalMapType: THREE.TangentSpaceNormalMap,
  20600. * normalScale: <Vector2>,
  20601. *
  20602. * displacementMap: new THREE.Texture( <Image> ),
  20603. * displacementScale: <float>,
  20604. * displacementBias: <float>,
  20605. *
  20606. * roughnessMap: new THREE.Texture( <Image> ),
  20607. *
  20608. * metalnessMap: new THREE.Texture( <Image> ),
  20609. *
  20610. * alphaMap: new THREE.Texture( <Image> ),
  20611. *
  20612. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  20613. * envMapIntensity: <float>
  20614. *
  20615. * refractionRatio: <float>,
  20616. *
  20617. * wireframe: <boolean>,
  20618. * wireframeLinewidth: <float>,
  20619. *
  20620. * skinning: <bool>,
  20621. * morphTargets: <bool>,
  20622. * morphNormals: <bool>
  20623. * }
  20624. */
  20625. function MeshStandardMaterial(parameters) {
  20626. Material.call(this);
  20627. this.defines = {
  20628. 'STANDARD': ''
  20629. };
  20630. this.type = 'MeshStandardMaterial';
  20631. this.color = new Color(0xffffff); // diffuse
  20632. this.roughness = 0.5;
  20633. this.metalness = 0.5;
  20634. this.map = null;
  20635. this.lightMap = null;
  20636. this.lightMapIntensity = 1.0;
  20637. this.aoMap = null;
  20638. this.aoMapIntensity = 1.0;
  20639. this.emissive = new Color(0x000000);
  20640. this.emissiveIntensity = 1.0;
  20641. this.emissiveMap = null;
  20642. this.bumpMap = null;
  20643. this.bumpScale = 1;
  20644. this.normalMap = null;
  20645. this.normalMapType = TangentSpaceNormalMap;
  20646. this.normalScale = new Vector2(1, 1);
  20647. this.displacementMap = null;
  20648. this.displacementScale = 1;
  20649. this.displacementBias = 0;
  20650. this.roughnessMap = null;
  20651. this.metalnessMap = null;
  20652. this.alphaMap = null;
  20653. this.envMap = null;
  20654. this.envMapIntensity = 1.0;
  20655. this.refractionRatio = 0.98;
  20656. this.wireframe = false;
  20657. this.wireframeLinewidth = 1;
  20658. this.wireframeLinecap = 'round';
  20659. this.wireframeLinejoin = 'round';
  20660. this.skinning = false;
  20661. this.morphTargets = false;
  20662. this.morphNormals = false;
  20663. this.setValues(parameters);
  20664. }
  20665. MeshStandardMaterial.prototype = Object.create(Material.prototype);
  20666. MeshStandardMaterial.prototype.constructor = MeshStandardMaterial;
  20667. MeshStandardMaterial.prototype.isMeshStandardMaterial = true;
  20668. MeshStandardMaterial.prototype.copy = function (source) {
  20669. Material.prototype.copy.call(this, source);
  20670. this.defines = {
  20671. 'STANDARD': ''
  20672. };
  20673. this.color.copy(source.color);
  20674. this.roughness = source.roughness;
  20675. this.metalness = source.metalness;
  20676. this.map = source.map;
  20677. this.lightMap = source.lightMap;
  20678. this.lightMapIntensity = source.lightMapIntensity;
  20679. this.aoMap = source.aoMap;
  20680. this.aoMapIntensity = source.aoMapIntensity;
  20681. this.emissive.copy(source.emissive);
  20682. this.emissiveMap = source.emissiveMap;
  20683. this.emissiveIntensity = source.emissiveIntensity;
  20684. this.bumpMap = source.bumpMap;
  20685. this.bumpScale = source.bumpScale;
  20686. this.normalMap = source.normalMap;
  20687. this.normalMapType = source.normalMapType;
  20688. this.normalScale.copy(source.normalScale);
  20689. this.displacementMap = source.displacementMap;
  20690. this.displacementScale = source.displacementScale;
  20691. this.displacementBias = source.displacementBias;
  20692. this.roughnessMap = source.roughnessMap;
  20693. this.metalnessMap = source.metalnessMap;
  20694. this.alphaMap = source.alphaMap;
  20695. this.envMap = source.envMap;
  20696. this.envMapIntensity = source.envMapIntensity;
  20697. this.refractionRatio = source.refractionRatio;
  20698. this.wireframe = source.wireframe;
  20699. this.wireframeLinewidth = source.wireframeLinewidth;
  20700. this.wireframeLinecap = source.wireframeLinecap;
  20701. this.wireframeLinejoin = source.wireframeLinejoin;
  20702. this.skinning = source.skinning;
  20703. this.morphTargets = source.morphTargets;
  20704. this.morphNormals = source.morphNormals;
  20705. return this;
  20706. };
  20707. /**
  20708. * @author WestLangley / http://github.com/WestLangley
  20709. *
  20710. * parameters = {
  20711. * reflectivity: <float>
  20712. * clearcoat: <float>
  20713. * clearcoatRoughness: <float>
  20714. *
  20715. * sheen: <Color>
  20716. *
  20717. * clearcoatNormalScale: <Vector2>,
  20718. * clearcoatNormalMap: new THREE.Texture( <Image> ),
  20719. * }
  20720. */
  20721. function MeshPhysicalMaterial(parameters) {
  20722. MeshStandardMaterial.call(this);
  20723. this.defines = {
  20724. 'STANDARD': '',
  20725. 'PHYSICAL': ''
  20726. };
  20727. this.type = 'MeshPhysicalMaterial';
  20728. this.reflectivity = 0.5; // maps to F0 = 0.04
  20729. this.clearcoat = 0.0;
  20730. this.clearcoatRoughness = 0.0;
  20731. this.sheen = null; // null will disable sheen bsdf
  20732. this.clearcoatNormalScale = new Vector2(1, 1);
  20733. this.clearcoatNormalMap = null;
  20734. this.transparency = 0.0;
  20735. this.setValues(parameters);
  20736. }
  20737. MeshPhysicalMaterial.prototype = Object.create(MeshStandardMaterial.prototype);
  20738. MeshPhysicalMaterial.prototype.constructor = MeshPhysicalMaterial;
  20739. MeshPhysicalMaterial.prototype.isMeshPhysicalMaterial = true;
  20740. MeshPhysicalMaterial.prototype.copy = function (source) {
  20741. MeshStandardMaterial.prototype.copy.call(this, source);
  20742. this.defines = {
  20743. 'STANDARD': '',
  20744. 'PHYSICAL': ''
  20745. };
  20746. this.reflectivity = source.reflectivity;
  20747. this.clearcoat = source.clearcoat;
  20748. this.clearcoatRoughness = source.clearcoatRoughness;
  20749. if (source.sheen) this.sheen = (this.sheen || new Color()).copy(source.sheen);else this.sheen = null;
  20750. this.clearcoatNormalMap = source.clearcoatNormalMap;
  20751. this.clearcoatNormalScale.copy(source.clearcoatNormalScale);
  20752. this.transparency = source.transparency;
  20753. return this;
  20754. };
  20755. /**
  20756. * @author mrdoob / http://mrdoob.com/
  20757. * @author alteredq / http://alteredqualia.com/
  20758. *
  20759. * parameters = {
  20760. * color: <hex>,
  20761. * specular: <hex>,
  20762. * shininess: <float>,
  20763. * opacity: <float>,
  20764. *
  20765. * map: new THREE.Texture( <Image> ),
  20766. *
  20767. * lightMap: new THREE.Texture( <Image> ),
  20768. * lightMapIntensity: <float>
  20769. *
  20770. * aoMap: new THREE.Texture( <Image> ),
  20771. * aoMapIntensity: <float>
  20772. *
  20773. * emissive: <hex>,
  20774. * emissiveIntensity: <float>
  20775. * emissiveMap: new THREE.Texture( <Image> ),
  20776. *
  20777. * bumpMap: new THREE.Texture( <Image> ),
  20778. * bumpScale: <float>,
  20779. *
  20780. * normalMap: new THREE.Texture( <Image> ),
  20781. * normalMapType: THREE.TangentSpaceNormalMap,
  20782. * normalScale: <Vector2>,
  20783. *
  20784. * displacementMap: new THREE.Texture( <Image> ),
  20785. * displacementScale: <float>,
  20786. * displacementBias: <float>,
  20787. *
  20788. * specularMap: new THREE.Texture( <Image> ),
  20789. *
  20790. * alphaMap: new THREE.Texture( <Image> ),
  20791. *
  20792. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  20793. * combine: THREE.Multiply,
  20794. * reflectivity: <float>,
  20795. * refractionRatio: <float>,
  20796. *
  20797. * wireframe: <boolean>,
  20798. * wireframeLinewidth: <float>,
  20799. *
  20800. * skinning: <bool>,
  20801. * morphTargets: <bool>,
  20802. * morphNormals: <bool>
  20803. * }
  20804. */
  20805. function MeshPhongMaterial(parameters) {
  20806. Material.call(this);
  20807. this.type = 'MeshPhongMaterial';
  20808. this.color = new Color(0xffffff); // diffuse
  20809. this.specular = new Color(0x111111);
  20810. this.shininess = 30;
  20811. this.map = null;
  20812. this.lightMap = null;
  20813. this.lightMapIntensity = 1.0;
  20814. this.aoMap = null;
  20815. this.aoMapIntensity = 1.0;
  20816. this.emissive = new Color(0x000000);
  20817. this.emissiveIntensity = 1.0;
  20818. this.emissiveMap = null;
  20819. this.bumpMap = null;
  20820. this.bumpScale = 1;
  20821. this.normalMap = null;
  20822. this.normalMapType = TangentSpaceNormalMap;
  20823. this.normalScale = new Vector2(1, 1);
  20824. this.displacementMap = null;
  20825. this.displacementScale = 1;
  20826. this.displacementBias = 0;
  20827. this.specularMap = null;
  20828. this.alphaMap = null;
  20829. this.envMap = null;
  20830. this.combine = MultiplyOperation;
  20831. this.reflectivity = 1;
  20832. this.refractionRatio = 0.98;
  20833. this.wireframe = false;
  20834. this.wireframeLinewidth = 1;
  20835. this.wireframeLinecap = 'round';
  20836. this.wireframeLinejoin = 'round';
  20837. this.skinning = false;
  20838. this.morphTargets = false;
  20839. this.morphNormals = false;
  20840. this.setValues(parameters);
  20841. }
  20842. MeshPhongMaterial.prototype = Object.create(Material.prototype);
  20843. MeshPhongMaterial.prototype.constructor = MeshPhongMaterial;
  20844. MeshPhongMaterial.prototype.isMeshPhongMaterial = true;
  20845. MeshPhongMaterial.prototype.copy = function (source) {
  20846. Material.prototype.copy.call(this, source);
  20847. this.color.copy(source.color);
  20848. this.specular.copy(source.specular);
  20849. this.shininess = source.shininess;
  20850. this.map = source.map;
  20851. this.lightMap = source.lightMap;
  20852. this.lightMapIntensity = source.lightMapIntensity;
  20853. this.aoMap = source.aoMap;
  20854. this.aoMapIntensity = source.aoMapIntensity;
  20855. this.emissive.copy(source.emissive);
  20856. this.emissiveMap = source.emissiveMap;
  20857. this.emissiveIntensity = source.emissiveIntensity;
  20858. this.bumpMap = source.bumpMap;
  20859. this.bumpScale = source.bumpScale;
  20860. this.normalMap = source.normalMap;
  20861. this.normalMapType = source.normalMapType;
  20862. this.normalScale.copy(source.normalScale);
  20863. this.displacementMap = source.displacementMap;
  20864. this.displacementScale = source.displacementScale;
  20865. this.displacementBias = source.displacementBias;
  20866. this.specularMap = source.specularMap;
  20867. this.alphaMap = source.alphaMap;
  20868. this.envMap = source.envMap;
  20869. this.combine = source.combine;
  20870. this.reflectivity = source.reflectivity;
  20871. this.refractionRatio = source.refractionRatio;
  20872. this.wireframe = source.wireframe;
  20873. this.wireframeLinewidth = source.wireframeLinewidth;
  20874. this.wireframeLinecap = source.wireframeLinecap;
  20875. this.wireframeLinejoin = source.wireframeLinejoin;
  20876. this.skinning = source.skinning;
  20877. this.morphTargets = source.morphTargets;
  20878. this.morphNormals = source.morphNormals;
  20879. return this;
  20880. };
  20881. /**
  20882. * @author takahirox / http://github.com/takahirox
  20883. *
  20884. * parameters = {
  20885. * gradientMap: new THREE.Texture( <Image> )
  20886. * }
  20887. */
  20888. function MeshToonMaterial(parameters) {
  20889. MeshPhongMaterial.call(this);
  20890. this.defines = {
  20891. 'TOON': ''
  20892. };
  20893. this.type = 'MeshToonMaterial';
  20894. this.gradientMap = null;
  20895. this.setValues(parameters);
  20896. }
  20897. MeshToonMaterial.prototype = Object.create(MeshPhongMaterial.prototype);
  20898. MeshToonMaterial.prototype.constructor = MeshToonMaterial;
  20899. MeshToonMaterial.prototype.isMeshToonMaterial = true;
  20900. MeshToonMaterial.prototype.copy = function (source) {
  20901. MeshPhongMaterial.prototype.copy.call(this, source);
  20902. this.gradientMap = source.gradientMap;
  20903. return this;
  20904. };
  20905. /**
  20906. * @author mrdoob / http://mrdoob.com/
  20907. * @author WestLangley / http://github.com/WestLangley
  20908. *
  20909. * parameters = {
  20910. * opacity: <float>,
  20911. *
  20912. * bumpMap: new THREE.Texture( <Image> ),
  20913. * bumpScale: <float>,
  20914. *
  20915. * normalMap: new THREE.Texture( <Image> ),
  20916. * normalMapType: THREE.TangentSpaceNormalMap,
  20917. * normalScale: <Vector2>,
  20918. *
  20919. * displacementMap: new THREE.Texture( <Image> ),
  20920. * displacementScale: <float>,
  20921. * displacementBias: <float>,
  20922. *
  20923. * wireframe: <boolean>,
  20924. * wireframeLinewidth: <float>
  20925. *
  20926. * skinning: <bool>,
  20927. * morphTargets: <bool>,
  20928. * morphNormals: <bool>
  20929. * }
  20930. */
  20931. function MeshNormalMaterial(parameters) {
  20932. Material.call(this);
  20933. this.type = 'MeshNormalMaterial';
  20934. this.bumpMap = null;
  20935. this.bumpScale = 1;
  20936. this.normalMap = null;
  20937. this.normalMapType = TangentSpaceNormalMap;
  20938. this.normalScale = new Vector2(1, 1);
  20939. this.displacementMap = null;
  20940. this.displacementScale = 1;
  20941. this.displacementBias = 0;
  20942. this.wireframe = false;
  20943. this.wireframeLinewidth = 1;
  20944. this.fog = false;
  20945. this.skinning = false;
  20946. this.morphTargets = false;
  20947. this.morphNormals = false;
  20948. this.setValues(parameters);
  20949. }
  20950. MeshNormalMaterial.prototype = Object.create(Material.prototype);
  20951. MeshNormalMaterial.prototype.constructor = MeshNormalMaterial;
  20952. MeshNormalMaterial.prototype.isMeshNormalMaterial = true;
  20953. MeshNormalMaterial.prototype.copy = function (source) {
  20954. Material.prototype.copy.call(this, source);
  20955. this.bumpMap = source.bumpMap;
  20956. this.bumpScale = source.bumpScale;
  20957. this.normalMap = source.normalMap;
  20958. this.normalMapType = source.normalMapType;
  20959. this.normalScale.copy(source.normalScale);
  20960. this.displacementMap = source.displacementMap;
  20961. this.displacementScale = source.displacementScale;
  20962. this.displacementBias = source.displacementBias;
  20963. this.wireframe = source.wireframe;
  20964. this.wireframeLinewidth = source.wireframeLinewidth;
  20965. this.skinning = source.skinning;
  20966. this.morphTargets = source.morphTargets;
  20967. this.morphNormals = source.morphNormals;
  20968. return this;
  20969. };
  20970. /**
  20971. * @author mrdoob / http://mrdoob.com/
  20972. * @author alteredq / http://alteredqualia.com/
  20973. *
  20974. * parameters = {
  20975. * color: <hex>,
  20976. * opacity: <float>,
  20977. *
  20978. * map: new THREE.Texture( <Image> ),
  20979. *
  20980. * lightMap: new THREE.Texture( <Image> ),
  20981. * lightMapIntensity: <float>
  20982. *
  20983. * aoMap: new THREE.Texture( <Image> ),
  20984. * aoMapIntensity: <float>
  20985. *
  20986. * emissive: <hex>,
  20987. * emissiveIntensity: <float>
  20988. * emissiveMap: new THREE.Texture( <Image> ),
  20989. *
  20990. * specularMap: new THREE.Texture( <Image> ),
  20991. *
  20992. * alphaMap: new THREE.Texture( <Image> ),
  20993. *
  20994. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  20995. * combine: THREE.Multiply,
  20996. * reflectivity: <float>,
  20997. * refractionRatio: <float>,
  20998. *
  20999. * wireframe: <boolean>,
  21000. * wireframeLinewidth: <float>,
  21001. *
  21002. * skinning: <bool>,
  21003. * morphTargets: <bool>,
  21004. * morphNormals: <bool>
  21005. * }
  21006. */
  21007. function MeshLambertMaterial(parameters) {
  21008. Material.call(this);
  21009. this.type = 'MeshLambertMaterial';
  21010. this.color = new Color(0xffffff); // diffuse
  21011. this.map = null;
  21012. this.lightMap = null;
  21013. this.lightMapIntensity = 1.0;
  21014. this.aoMap = null;
  21015. this.aoMapIntensity = 1.0;
  21016. this.emissive = new Color(0x000000);
  21017. this.emissiveIntensity = 1.0;
  21018. this.emissiveMap = null;
  21019. this.specularMap = null;
  21020. this.alphaMap = null;
  21021. this.envMap = null;
  21022. this.combine = MultiplyOperation;
  21023. this.reflectivity = 1;
  21024. this.refractionRatio = 0.98;
  21025. this.wireframe = false;
  21026. this.wireframeLinewidth = 1;
  21027. this.wireframeLinecap = 'round';
  21028. this.wireframeLinejoin = 'round';
  21029. this.skinning = false;
  21030. this.morphTargets = false;
  21031. this.morphNormals = false;
  21032. this.setValues(parameters);
  21033. }
  21034. MeshLambertMaterial.prototype = Object.create(Material.prototype);
  21035. MeshLambertMaterial.prototype.constructor = MeshLambertMaterial;
  21036. MeshLambertMaterial.prototype.isMeshLambertMaterial = true;
  21037. MeshLambertMaterial.prototype.copy = function (source) {
  21038. Material.prototype.copy.call(this, source);
  21039. this.color.copy(source.color);
  21040. this.map = source.map;
  21041. this.lightMap = source.lightMap;
  21042. this.lightMapIntensity = source.lightMapIntensity;
  21043. this.aoMap = source.aoMap;
  21044. this.aoMapIntensity = source.aoMapIntensity;
  21045. this.emissive.copy(source.emissive);
  21046. this.emissiveMap = source.emissiveMap;
  21047. this.emissiveIntensity = source.emissiveIntensity;
  21048. this.specularMap = source.specularMap;
  21049. this.alphaMap = source.alphaMap;
  21050. this.envMap = source.envMap;
  21051. this.combine = source.combine;
  21052. this.reflectivity = source.reflectivity;
  21053. this.refractionRatio = source.refractionRatio;
  21054. this.wireframe = source.wireframe;
  21055. this.wireframeLinewidth = source.wireframeLinewidth;
  21056. this.wireframeLinecap = source.wireframeLinecap;
  21057. this.wireframeLinejoin = source.wireframeLinejoin;
  21058. this.skinning = source.skinning;
  21059. this.morphTargets = source.morphTargets;
  21060. this.morphNormals = source.morphNormals;
  21061. return this;
  21062. };
  21063. /**
  21064. * @author WestLangley / http://github.com/WestLangley
  21065. *
  21066. * parameters = {
  21067. * color: <hex>,
  21068. * opacity: <float>,
  21069. *
  21070. * matcap: new THREE.Texture( <Image> ),
  21071. *
  21072. * map: new THREE.Texture( <Image> ),
  21073. *
  21074. * bumpMap: new THREE.Texture( <Image> ),
  21075. * bumpScale: <float>,
  21076. *
  21077. * normalMap: new THREE.Texture( <Image> ),
  21078. * normalMapType: THREE.TangentSpaceNormalMap,
  21079. * normalScale: <Vector2>,
  21080. *
  21081. * displacementMap: new THREE.Texture( <Image> ),
  21082. * displacementScale: <float>,
  21083. * displacementBias: <float>,
  21084. *
  21085. * alphaMap: new THREE.Texture( <Image> ),
  21086. *
  21087. * skinning: <bool>,
  21088. * morphTargets: <bool>,
  21089. * morphNormals: <bool>
  21090. * }
  21091. */
  21092. function MeshMatcapMaterial(parameters) {
  21093. Material.call(this);
  21094. this.defines = {
  21095. 'MATCAP': ''
  21096. };
  21097. this.type = 'MeshMatcapMaterial';
  21098. this.color = new Color(0xffffff); // diffuse
  21099. this.matcap = null;
  21100. this.map = null;
  21101. this.bumpMap = null;
  21102. this.bumpScale = 1;
  21103. this.normalMap = null;
  21104. this.normalMapType = TangentSpaceNormalMap;
  21105. this.normalScale = new Vector2(1, 1);
  21106. this.displacementMap = null;
  21107. this.displacementScale = 1;
  21108. this.displacementBias = 0;
  21109. this.alphaMap = null;
  21110. this.skinning = false;
  21111. this.morphTargets = false;
  21112. this.morphNormals = false;
  21113. this.setValues(parameters);
  21114. }
  21115. MeshMatcapMaterial.prototype = Object.create(Material.prototype);
  21116. MeshMatcapMaterial.prototype.constructor = MeshMatcapMaterial;
  21117. MeshMatcapMaterial.prototype.isMeshMatcapMaterial = true;
  21118. MeshMatcapMaterial.prototype.copy = function (source) {
  21119. Material.prototype.copy.call(this, source);
  21120. this.defines = {
  21121. 'MATCAP': ''
  21122. };
  21123. this.color.copy(source.color);
  21124. this.matcap = source.matcap;
  21125. this.map = source.map;
  21126. this.bumpMap = source.bumpMap;
  21127. this.bumpScale = source.bumpScale;
  21128. this.normalMap = source.normalMap;
  21129. this.normalMapType = source.normalMapType;
  21130. this.normalScale.copy(source.normalScale);
  21131. this.displacementMap = source.displacementMap;
  21132. this.displacementScale = source.displacementScale;
  21133. this.displacementBias = source.displacementBias;
  21134. this.alphaMap = source.alphaMap;
  21135. this.skinning = source.skinning;
  21136. this.morphTargets = source.morphTargets;
  21137. this.morphNormals = source.morphNormals;
  21138. return this;
  21139. };
  21140. /**
  21141. * @author alteredq / http://alteredqualia.com/
  21142. *
  21143. * parameters = {
  21144. * color: <hex>,
  21145. * opacity: <float>,
  21146. *
  21147. * linewidth: <float>,
  21148. *
  21149. * scale: <float>,
  21150. * dashSize: <float>,
  21151. * gapSize: <float>
  21152. * }
  21153. */
  21154. function LineDashedMaterial(parameters) {
  21155. LineBasicMaterial.call(this);
  21156. this.type = 'LineDashedMaterial';
  21157. this.scale = 1;
  21158. this.dashSize = 3;
  21159. this.gapSize = 1;
  21160. this.setValues(parameters);
  21161. }
  21162. LineDashedMaterial.prototype = Object.create(LineBasicMaterial.prototype);
  21163. LineDashedMaterial.prototype.constructor = LineDashedMaterial;
  21164. LineDashedMaterial.prototype.isLineDashedMaterial = true;
  21165. LineDashedMaterial.prototype.copy = function (source) {
  21166. LineBasicMaterial.prototype.copy.call(this, source);
  21167. this.scale = source.scale;
  21168. this.dashSize = source.dashSize;
  21169. this.gapSize = source.gapSize;
  21170. return this;
  21171. };
  21172. var Materials =
  21173. /*#__PURE__*/
  21174. Object.freeze({
  21175. ShadowMaterial: ShadowMaterial,
  21176. SpriteMaterial: SpriteMaterial,
  21177. RawShaderMaterial: RawShaderMaterial,
  21178. ShaderMaterial: ShaderMaterial,
  21179. PointsMaterial: PointsMaterial,
  21180. MeshPhysicalMaterial: MeshPhysicalMaterial,
  21181. MeshStandardMaterial: MeshStandardMaterial,
  21182. MeshPhongMaterial: MeshPhongMaterial,
  21183. MeshToonMaterial: MeshToonMaterial,
  21184. MeshNormalMaterial: MeshNormalMaterial,
  21185. MeshLambertMaterial: MeshLambertMaterial,
  21186. MeshDepthMaterial: MeshDepthMaterial,
  21187. MeshDistanceMaterial: MeshDistanceMaterial,
  21188. MeshBasicMaterial: MeshBasicMaterial,
  21189. MeshMatcapMaterial: MeshMatcapMaterial,
  21190. LineDashedMaterial: LineDashedMaterial,
  21191. LineBasicMaterial: LineBasicMaterial,
  21192. Material: Material
  21193. });
  21194. /**
  21195. * @author tschw
  21196. * @author Ben Houston / http://clara.io/
  21197. * @author David Sarno / http://lighthaus.us/
  21198. */
  21199. var AnimationUtils = {
  21200. // same as Array.prototype.slice, but also works on typed arrays
  21201. arraySlice: function (array, from, to) {
  21202. if (AnimationUtils.isTypedArray(array)) {
  21203. // in ios9 array.subarray(from, undefined) will return empty array
  21204. // but array.subarray(from) or array.subarray(from, len) is correct
  21205. return new array.constructor(array.subarray(from, to !== undefined ? to : array.length));
  21206. }
  21207. return array.slice(from, to);
  21208. },
  21209. // converts an array to a specific type
  21210. convertArray: function (array, type, forceClone) {
  21211. if (!array || // let 'undefined' and 'null' pass
  21212. !forceClone && array.constructor === type) return array;
  21213. if (typeof type.BYTES_PER_ELEMENT === 'number') {
  21214. return new type(array); // create typed array
  21215. }
  21216. return Array.prototype.slice.call(array); // create Array
  21217. },
  21218. isTypedArray: function (object) {
  21219. return ArrayBuffer.isView(object) && !(object instanceof DataView);
  21220. },
  21221. // returns an array by which times and values can be sorted
  21222. getKeyframeOrder: function (times) {
  21223. function compareTime(i, j) {
  21224. return times[i] - times[j];
  21225. }
  21226. var n = times.length;
  21227. var result = new Array(n);
  21228. for (var i = 0; i !== n; ++i) result[i] = i;
  21229. result.sort(compareTime);
  21230. return result;
  21231. },
  21232. // uses the array previously returned by 'getKeyframeOrder' to sort data
  21233. sortedArray: function (values, stride, order) {
  21234. var nValues = values.length;
  21235. var result = new values.constructor(nValues);
  21236. for (var i = 0, dstOffset = 0; dstOffset !== nValues; ++i) {
  21237. var srcOffset = order[i] * stride;
  21238. for (var j = 0; j !== stride; ++j) {
  21239. result[dstOffset++] = values[srcOffset + j];
  21240. }
  21241. }
  21242. return result;
  21243. },
  21244. // function for parsing AOS keyframe formats
  21245. flattenJSON: function (jsonKeys, times, values, valuePropertyName) {
  21246. var i = 1,
  21247. key = jsonKeys[0];
  21248. while (key !== undefined && key[valuePropertyName] === undefined) {
  21249. key = jsonKeys[i++];
  21250. }
  21251. if (key === undefined) return; // no data
  21252. var value = key[valuePropertyName];
  21253. if (value === undefined) return; // no data
  21254. if (Array.isArray(value)) {
  21255. do {
  21256. value = key[valuePropertyName];
  21257. if (value !== undefined) {
  21258. times.push(key.time);
  21259. values.push.apply(values, value); // push all elements
  21260. }
  21261. key = jsonKeys[i++];
  21262. } while (key !== undefined);
  21263. } else if (value.toArray !== undefined) {
  21264. // ...assume THREE.Math-ish
  21265. do {
  21266. value = key[valuePropertyName];
  21267. if (value !== undefined) {
  21268. times.push(key.time);
  21269. value.toArray(values, values.length);
  21270. }
  21271. key = jsonKeys[i++];
  21272. } while (key !== undefined);
  21273. } else {
  21274. // otherwise push as-is
  21275. do {
  21276. value = key[valuePropertyName];
  21277. if (value !== undefined) {
  21278. times.push(key.time);
  21279. values.push(value);
  21280. }
  21281. key = jsonKeys[i++];
  21282. } while (key !== undefined);
  21283. }
  21284. }
  21285. };
  21286. /**
  21287. * Abstract base class of interpolants over parametric samples.
  21288. *
  21289. * The parameter domain is one dimensional, typically the time or a path
  21290. * along a curve defined by the data.
  21291. *
  21292. * The sample values can have any dimensionality and derived classes may
  21293. * apply special interpretations to the data.
  21294. *
  21295. * This class provides the interval seek in a Template Method, deferring
  21296. * the actual interpolation to derived classes.
  21297. *
  21298. * Time complexity is O(1) for linear access crossing at most two points
  21299. * and O(log N) for random access, where N is the number of positions.
  21300. *
  21301. * References:
  21302. *
  21303. * http://www.oodesign.com/template-method-pattern.html
  21304. *
  21305. * @author tschw
  21306. */
  21307. exports.AnimationUtils = AnimationUtils;
  21308. function Interpolant(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  21309. this.parameterPositions = parameterPositions;
  21310. this._cachedIndex = 0;
  21311. this.resultBuffer = resultBuffer !== undefined ? resultBuffer : new sampleValues.constructor(sampleSize);
  21312. this.sampleValues = sampleValues;
  21313. this.valueSize = sampleSize;
  21314. }
  21315. Object.assign(Interpolant.prototype, {
  21316. evaluate: function (t) {
  21317. var pp = this.parameterPositions,
  21318. i1 = this._cachedIndex,
  21319. t1 = pp[i1],
  21320. t0 = pp[i1 - 1];
  21321. validate_interval: {
  21322. seek: {
  21323. var right;
  21324. linear_scan: {
  21325. //- See http://jsperf.com/comparison-to-undefined/3
  21326. //- slower code:
  21327. //-
  21328. //- if ( t >= t1 || t1 === undefined ) {
  21329. forward_scan: if (!(t < t1)) {
  21330. for (var giveUpAt = i1 + 2;;) {
  21331. if (t1 === undefined) {
  21332. if (t < t0) break forward_scan; // after end
  21333. i1 = pp.length;
  21334. this._cachedIndex = i1;
  21335. return this.afterEnd_(i1 - 1, t, t0);
  21336. }
  21337. if (i1 === giveUpAt) break; // this loop
  21338. t0 = t1;
  21339. t1 = pp[++i1];
  21340. if (t < t1) {
  21341. // we have arrived at the sought interval
  21342. break seek;
  21343. }
  21344. } // prepare binary search on the right side of the index
  21345. right = pp.length;
  21346. break linear_scan;
  21347. } //- slower code:
  21348. //- if ( t < t0 || t0 === undefined ) {
  21349. if (!(t >= t0)) {
  21350. // looping?
  21351. var t1global = pp[1];
  21352. if (t < t1global) {
  21353. i1 = 2; // + 1, using the scan for the details
  21354. t0 = t1global;
  21355. } // linear reverse scan
  21356. for (var giveUpAt = i1 - 2;;) {
  21357. if (t0 === undefined) {
  21358. // before start
  21359. this._cachedIndex = 0;
  21360. return this.beforeStart_(0, t, t1);
  21361. }
  21362. if (i1 === giveUpAt) break; // this loop
  21363. t1 = t0;
  21364. t0 = pp[--i1 - 1];
  21365. if (t >= t0) {
  21366. // we have arrived at the sought interval
  21367. break seek;
  21368. }
  21369. } // prepare binary search on the left side of the index
  21370. right = i1;
  21371. i1 = 0;
  21372. break linear_scan;
  21373. } // the interval is valid
  21374. break validate_interval;
  21375. } // linear scan
  21376. // binary search
  21377. while (i1 < right) {
  21378. var mid = i1 + right >>> 1;
  21379. if (t < pp[mid]) {
  21380. right = mid;
  21381. } else {
  21382. i1 = mid + 1;
  21383. }
  21384. }
  21385. t1 = pp[i1];
  21386. t0 = pp[i1 - 1]; // check boundary cases, again
  21387. if (t0 === undefined) {
  21388. this._cachedIndex = 0;
  21389. return this.beforeStart_(0, t, t1);
  21390. }
  21391. if (t1 === undefined) {
  21392. i1 = pp.length;
  21393. this._cachedIndex = i1;
  21394. return this.afterEnd_(i1 - 1, t0, t);
  21395. }
  21396. } // seek
  21397. this._cachedIndex = i1;
  21398. this.intervalChanged_(i1, t0, t1);
  21399. } // validate_interval
  21400. return this.interpolate_(i1, t0, t, t1);
  21401. },
  21402. settings: null,
  21403. // optional, subclass-specific settings structure
  21404. // Note: The indirection allows central control of many interpolants.
  21405. // --- Protected interface
  21406. DefaultSettings_: {},
  21407. getSettings_: function () {
  21408. return this.settings || this.DefaultSettings_;
  21409. },
  21410. copySampleValue_: function (index) {
  21411. // copies a sample value to the result buffer
  21412. var result = this.resultBuffer,
  21413. values = this.sampleValues,
  21414. stride = this.valueSize,
  21415. offset = index * stride;
  21416. for (var i = 0; i !== stride; ++i) {
  21417. result[i] = values[offset + i];
  21418. }
  21419. return result;
  21420. },
  21421. // Template methods for derived classes:
  21422. interpolate_: function ()
  21423. /* i1, t0, t, t1 */
  21424. {
  21425. throw new Error('call to abstract method'); // implementations shall return this.resultBuffer
  21426. },
  21427. intervalChanged_: function ()
  21428. /* i1, t0, t1 */
  21429. {// empty
  21430. }
  21431. }); //!\ DECLARE ALIAS AFTER assign prototype !
  21432. Object.assign(Interpolant.prototype, {
  21433. //( 0, t, t0 ), returns this.resultBuffer
  21434. beforeStart_: Interpolant.prototype.copySampleValue_,
  21435. //( N-1, tN-1, t ), returns this.resultBuffer
  21436. afterEnd_: Interpolant.prototype.copySampleValue_
  21437. });
  21438. /**
  21439. * Fast and simple cubic spline interpolant.
  21440. *
  21441. * It was derived from a Hermitian construction setting the first derivative
  21442. * at each sample position to the linear slope between neighboring positions
  21443. * over their parameter interval.
  21444. *
  21445. * @author tschw
  21446. */
  21447. function CubicInterpolant(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  21448. Interpolant.call(this, parameterPositions, sampleValues, sampleSize, resultBuffer);
  21449. this._weightPrev = -0;
  21450. this._offsetPrev = -0;
  21451. this._weightNext = -0;
  21452. this._offsetNext = -0;
  21453. }
  21454. CubicInterpolant.prototype = Object.assign(Object.create(Interpolant.prototype), {
  21455. constructor: CubicInterpolant,
  21456. DefaultSettings_: {
  21457. endingStart: ZeroCurvatureEnding,
  21458. endingEnd: ZeroCurvatureEnding
  21459. },
  21460. intervalChanged_: function (i1, t0, t1) {
  21461. var pp = this.parameterPositions,
  21462. iPrev = i1 - 2,
  21463. iNext = i1 + 1,
  21464. tPrev = pp[iPrev],
  21465. tNext = pp[iNext];
  21466. if (tPrev === undefined) {
  21467. switch (this.getSettings_().endingStart) {
  21468. case ZeroSlopeEnding:
  21469. // f'(t0) = 0
  21470. iPrev = i1;
  21471. tPrev = 2 * t0 - t1;
  21472. break;
  21473. case WrapAroundEnding:
  21474. // use the other end of the curve
  21475. iPrev = pp.length - 2;
  21476. tPrev = t0 + pp[iPrev] - pp[iPrev + 1];
  21477. break;
  21478. default:
  21479. // ZeroCurvatureEnding
  21480. // f''(t0) = 0 a.k.a. Natural Spline
  21481. iPrev = i1;
  21482. tPrev = t1;
  21483. }
  21484. }
  21485. if (tNext === undefined) {
  21486. switch (this.getSettings_().endingEnd) {
  21487. case ZeroSlopeEnding:
  21488. // f'(tN) = 0
  21489. iNext = i1;
  21490. tNext = 2 * t1 - t0;
  21491. break;
  21492. case WrapAroundEnding:
  21493. // use the other end of the curve
  21494. iNext = 1;
  21495. tNext = t1 + pp[1] - pp[0];
  21496. break;
  21497. default:
  21498. // ZeroCurvatureEnding
  21499. // f''(tN) = 0, a.k.a. Natural Spline
  21500. iNext = i1 - 1;
  21501. tNext = t0;
  21502. }
  21503. }
  21504. var halfDt = (t1 - t0) * 0.5,
  21505. stride = this.valueSize;
  21506. this._weightPrev = halfDt / (t0 - tPrev);
  21507. this._weightNext = halfDt / (tNext - t1);
  21508. this._offsetPrev = iPrev * stride;
  21509. this._offsetNext = iNext * stride;
  21510. },
  21511. interpolate_: function (i1, t0, t, t1) {
  21512. var result = this.resultBuffer,
  21513. values = this.sampleValues,
  21514. stride = this.valueSize,
  21515. o1 = i1 * stride,
  21516. o0 = o1 - stride,
  21517. oP = this._offsetPrev,
  21518. oN = this._offsetNext,
  21519. wP = this._weightPrev,
  21520. wN = this._weightNext,
  21521. p = (t - t0) / (t1 - t0),
  21522. pp = p * p,
  21523. ppp = pp * p; // evaluate polynomials
  21524. var sP = -wP * ppp + 2 * wP * pp - wP * p;
  21525. var s0 = (1 + wP) * ppp + (-1.5 - 2 * wP) * pp + (-0.5 + wP) * p + 1;
  21526. var s1 = (-1 - wN) * ppp + (1.5 + wN) * pp + 0.5 * p;
  21527. var sN = wN * ppp - wN * pp; // combine data linearly
  21528. for (var i = 0; i !== stride; ++i) {
  21529. result[i] = sP * values[oP + i] + s0 * values[o0 + i] + s1 * values[o1 + i] + sN * values[oN + i];
  21530. }
  21531. return result;
  21532. }
  21533. });
  21534. /**
  21535. * @author tschw
  21536. */
  21537. function LinearInterpolant(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  21538. Interpolant.call(this, parameterPositions, sampleValues, sampleSize, resultBuffer);
  21539. }
  21540. LinearInterpolant.prototype = Object.assign(Object.create(Interpolant.prototype), {
  21541. constructor: LinearInterpolant,
  21542. interpolate_: function (i1, t0, t, t1) {
  21543. var result = this.resultBuffer,
  21544. values = this.sampleValues,
  21545. stride = this.valueSize,
  21546. offset1 = i1 * stride,
  21547. offset0 = offset1 - stride,
  21548. weight1 = (t - t0) / (t1 - t0),
  21549. weight0 = 1 - weight1;
  21550. for (var i = 0; i !== stride; ++i) {
  21551. result[i] = values[offset0 + i] * weight0 + values[offset1 + i] * weight1;
  21552. }
  21553. return result;
  21554. }
  21555. });
  21556. /**
  21557. *
  21558. * Interpolant that evaluates to the sample value at the position preceeding
  21559. * the parameter.
  21560. *
  21561. * @author tschw
  21562. */
  21563. function DiscreteInterpolant(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  21564. Interpolant.call(this, parameterPositions, sampleValues, sampleSize, resultBuffer);
  21565. }
  21566. DiscreteInterpolant.prototype = Object.assign(Object.create(Interpolant.prototype), {
  21567. constructor: DiscreteInterpolant,
  21568. interpolate_: function (i1
  21569. /*, t0, t, t1 */
  21570. ) {
  21571. return this.copySampleValue_(i1 - 1);
  21572. }
  21573. });
  21574. /**
  21575. *
  21576. * A timed sequence of keyframes for a specific property.
  21577. *
  21578. *
  21579. * @author Ben Houston / http://clara.io/
  21580. * @author David Sarno / http://lighthaus.us/
  21581. * @author tschw
  21582. */
  21583. function KeyframeTrack(name, times, values, interpolation) {
  21584. if (name === undefined) throw new Error('THREE.KeyframeTrack: track name is undefined');
  21585. if (times === undefined || times.length === 0) throw new Error('THREE.KeyframeTrack: no keyframes in track named ' + name);
  21586. this.name = name;
  21587. this.times = AnimationUtils.convertArray(times, this.TimeBufferType);
  21588. this.values = AnimationUtils.convertArray(values, this.ValueBufferType);
  21589. this.setInterpolation(interpolation || this.DefaultInterpolation);
  21590. } // Static methods
  21591. Object.assign(KeyframeTrack, {
  21592. // Serialization (in static context, because of constructor invocation
  21593. // and automatic invocation of .toJSON):
  21594. toJSON: function (track) {
  21595. var trackType = track.constructor;
  21596. var json; // derived classes can define a static toJSON method
  21597. if (trackType.toJSON !== undefined) {
  21598. json = trackType.toJSON(track);
  21599. } else {
  21600. // by default, we assume the data can be serialized as-is
  21601. json = {
  21602. 'name': track.name,
  21603. 'times': AnimationUtils.convertArray(track.times, Array),
  21604. 'values': AnimationUtils.convertArray(track.values, Array)
  21605. };
  21606. var interpolation = track.getInterpolation();
  21607. if (interpolation !== track.DefaultInterpolation) {
  21608. json.interpolation = interpolation;
  21609. }
  21610. }
  21611. json.type = track.ValueTypeName; // mandatory
  21612. return json;
  21613. }
  21614. });
  21615. Object.assign(KeyframeTrack.prototype, {
  21616. constructor: KeyframeTrack,
  21617. TimeBufferType: Float32Array,
  21618. ValueBufferType: Float32Array,
  21619. DefaultInterpolation: InterpolateLinear,
  21620. InterpolantFactoryMethodDiscrete: function (result) {
  21621. return new DiscreteInterpolant(this.times, this.values, this.getValueSize(), result);
  21622. },
  21623. InterpolantFactoryMethodLinear: function (result) {
  21624. return new LinearInterpolant(this.times, this.values, this.getValueSize(), result);
  21625. },
  21626. InterpolantFactoryMethodSmooth: function (result) {
  21627. return new CubicInterpolant(this.times, this.values, this.getValueSize(), result);
  21628. },
  21629. setInterpolation: function (interpolation) {
  21630. var factoryMethod;
  21631. switch (interpolation) {
  21632. case InterpolateDiscrete:
  21633. factoryMethod = this.InterpolantFactoryMethodDiscrete;
  21634. break;
  21635. case InterpolateLinear:
  21636. factoryMethod = this.InterpolantFactoryMethodLinear;
  21637. break;
  21638. case InterpolateSmooth:
  21639. factoryMethod = this.InterpolantFactoryMethodSmooth;
  21640. break;
  21641. }
  21642. if (factoryMethod === undefined) {
  21643. var message = "unsupported interpolation for " + this.ValueTypeName + " keyframe track named " + this.name;
  21644. if (this.createInterpolant === undefined) {
  21645. // fall back to default, unless the default itself is messed up
  21646. if (interpolation !== this.DefaultInterpolation) {
  21647. this.setInterpolation(this.DefaultInterpolation);
  21648. } else {
  21649. throw new Error(message); // fatal, in this case
  21650. }
  21651. }
  21652. console.warn('THREE.KeyframeTrack:', message);
  21653. return this;
  21654. }
  21655. this.createInterpolant = factoryMethod;
  21656. return this;
  21657. },
  21658. getInterpolation: function () {
  21659. switch (this.createInterpolant) {
  21660. case this.InterpolantFactoryMethodDiscrete:
  21661. return InterpolateDiscrete;
  21662. case this.InterpolantFactoryMethodLinear:
  21663. return InterpolateLinear;
  21664. case this.InterpolantFactoryMethodSmooth:
  21665. return InterpolateSmooth;
  21666. }
  21667. },
  21668. getValueSize: function () {
  21669. return this.values.length / this.times.length;
  21670. },
  21671. // move all keyframes either forwards or backwards in time
  21672. shift: function (timeOffset) {
  21673. if (timeOffset !== 0.0) {
  21674. var times = this.times;
  21675. for (var i = 0, n = times.length; i !== n; ++i) {
  21676. times[i] += timeOffset;
  21677. }
  21678. }
  21679. return this;
  21680. },
  21681. // scale all keyframe times by a factor (useful for frame <-> seconds conversions)
  21682. scale: function (timeScale) {
  21683. if (timeScale !== 1.0) {
  21684. var times = this.times;
  21685. for (var i = 0, n = times.length; i !== n; ++i) {
  21686. times[i] *= timeScale;
  21687. }
  21688. }
  21689. return this;
  21690. },
  21691. // removes keyframes before and after animation without changing any values within the range [startTime, endTime].
  21692. // IMPORTANT: We do not shift around keys to the start of the track time, because for interpolated keys this will change their values
  21693. trim: function (startTime, endTime) {
  21694. var times = this.times,
  21695. nKeys = times.length,
  21696. from = 0,
  21697. to = nKeys - 1;
  21698. while (from !== nKeys && times[from] < startTime) {
  21699. ++from;
  21700. }
  21701. while (to !== -1 && times[to] > endTime) {
  21702. --to;
  21703. }
  21704. ++to; // inclusive -> exclusive bound
  21705. if (from !== 0 || to !== nKeys) {
  21706. // empty tracks are forbidden, so keep at least one keyframe
  21707. if (from >= to) to = Math.max(to, 1), from = to - 1;
  21708. var stride = this.getValueSize();
  21709. this.times = AnimationUtils.arraySlice(times, from, to);
  21710. this.values = AnimationUtils.arraySlice(this.values, from * stride, to * stride);
  21711. }
  21712. return this;
  21713. },
  21714. // ensure we do not get a GarbageInGarbageOut situation, make sure tracks are at least minimally viable
  21715. validate: function () {
  21716. var valid = true;
  21717. var valueSize = this.getValueSize();
  21718. if (valueSize - Math.floor(valueSize) !== 0) {
  21719. console.error('THREE.KeyframeTrack: Invalid value size in track.', this);
  21720. valid = false;
  21721. }
  21722. var times = this.times,
  21723. values = this.values,
  21724. nKeys = times.length;
  21725. if (nKeys === 0) {
  21726. console.error('THREE.KeyframeTrack: Track is empty.', this);
  21727. valid = false;
  21728. }
  21729. var prevTime = null;
  21730. for (var i = 0; i !== nKeys; i++) {
  21731. var currTime = times[i];
  21732. if (typeof currTime === 'number' && isNaN(currTime)) {
  21733. console.error('THREE.KeyframeTrack: Time is not a valid number.', this, i, currTime);
  21734. valid = false;
  21735. break;
  21736. }
  21737. if (prevTime !== null && prevTime > currTime) {
  21738. console.error('THREE.KeyframeTrack: Out of order keys.', this, i, currTime, prevTime);
  21739. valid = false;
  21740. break;
  21741. }
  21742. prevTime = currTime;
  21743. }
  21744. if (values !== undefined) {
  21745. if (AnimationUtils.isTypedArray(values)) {
  21746. for (var i = 0, n = values.length; i !== n; ++i) {
  21747. var value = values[i];
  21748. if (isNaN(value)) {
  21749. console.error('THREE.KeyframeTrack: Value is not a valid number.', this, i, value);
  21750. valid = false;
  21751. break;
  21752. }
  21753. }
  21754. }
  21755. }
  21756. return valid;
  21757. },
  21758. // removes equivalent sequential keys as common in morph target sequences
  21759. // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0)
  21760. optimize: function () {
  21761. var times = this.times,
  21762. values = this.values,
  21763. stride = this.getValueSize(),
  21764. smoothInterpolation = this.getInterpolation() === InterpolateSmooth,
  21765. writeIndex = 1,
  21766. lastIndex = times.length - 1;
  21767. for (var i = 1; i < lastIndex; ++i) {
  21768. var keep = false;
  21769. var time = times[i];
  21770. var timeNext = times[i + 1]; // remove adjacent keyframes scheduled at the same time
  21771. if (time !== timeNext && (i !== 1 || time !== time[0])) {
  21772. if (!smoothInterpolation) {
  21773. // remove unnecessary keyframes same as their neighbors
  21774. var offset = i * stride,
  21775. offsetP = offset - stride,
  21776. offsetN = offset + stride;
  21777. for (var j = 0; j !== stride; ++j) {
  21778. var value = values[offset + j];
  21779. if (value !== values[offsetP + j] || value !== values[offsetN + j]) {
  21780. keep = true;
  21781. break;
  21782. }
  21783. }
  21784. } else {
  21785. keep = true;
  21786. }
  21787. } // in-place compaction
  21788. if (keep) {
  21789. if (i !== writeIndex) {
  21790. times[writeIndex] = times[i];
  21791. var readOffset = i * stride,
  21792. writeOffset = writeIndex * stride;
  21793. for (var j = 0; j !== stride; ++j) {
  21794. values[writeOffset + j] = values[readOffset + j];
  21795. }
  21796. }
  21797. ++writeIndex;
  21798. }
  21799. } // flush last keyframe (compaction looks ahead)
  21800. if (lastIndex > 0) {
  21801. times[writeIndex] = times[lastIndex];
  21802. for (var readOffset = lastIndex * stride, writeOffset = writeIndex * stride, j = 0; j !== stride; ++j) {
  21803. values[writeOffset + j] = values[readOffset + j];
  21804. }
  21805. ++writeIndex;
  21806. }
  21807. if (writeIndex !== times.length) {
  21808. this.times = AnimationUtils.arraySlice(times, 0, writeIndex);
  21809. this.values = AnimationUtils.arraySlice(values, 0, writeIndex * stride);
  21810. }
  21811. return this;
  21812. },
  21813. clone: function () {
  21814. var times = AnimationUtils.arraySlice(this.times, 0);
  21815. var values = AnimationUtils.arraySlice(this.values, 0);
  21816. var TypedKeyframeTrack = this.constructor;
  21817. var track = new TypedKeyframeTrack(this.name, times, values); // Interpolant argument to constructor is not saved, so copy the factory method directly.
  21818. track.createInterpolant = this.createInterpolant;
  21819. return track;
  21820. }
  21821. });
  21822. /**
  21823. *
  21824. * A Track of Boolean keyframe values.
  21825. *
  21826. *
  21827. * @author Ben Houston / http://clara.io/
  21828. * @author David Sarno / http://lighthaus.us/
  21829. * @author tschw
  21830. */
  21831. function BooleanKeyframeTrack(name, times, values) {
  21832. KeyframeTrack.call(this, name, times, values);
  21833. }
  21834. BooleanKeyframeTrack.prototype = Object.assign(Object.create(KeyframeTrack.prototype), {
  21835. constructor: BooleanKeyframeTrack,
  21836. ValueTypeName: 'bool',
  21837. ValueBufferType: Array,
  21838. DefaultInterpolation: InterpolateDiscrete,
  21839. InterpolantFactoryMethodLinear: undefined,
  21840. InterpolantFactoryMethodSmooth: undefined // Note: Actually this track could have a optimized / compressed
  21841. // representation of a single value and a custom interpolant that
  21842. // computes "firstValue ^ isOdd( index )".
  21843. });
  21844. /**
  21845. *
  21846. * A Track of keyframe values that represent color.
  21847. *
  21848. *
  21849. * @author Ben Houston / http://clara.io/
  21850. * @author David Sarno / http://lighthaus.us/
  21851. * @author tschw
  21852. */
  21853. function ColorKeyframeTrack(name, times, values, interpolation) {
  21854. KeyframeTrack.call(this, name, times, values, interpolation);
  21855. }
  21856. ColorKeyframeTrack.prototype = Object.assign(Object.create(KeyframeTrack.prototype), {
  21857. constructor: ColorKeyframeTrack,
  21858. ValueTypeName: 'color' // ValueBufferType is inherited
  21859. // DefaultInterpolation is inherited
  21860. // Note: Very basic implementation and nothing special yet.
  21861. // However, this is the place for color space parameterization.
  21862. });
  21863. /**
  21864. *
  21865. * A Track of numeric keyframe values.
  21866. *
  21867. * @author Ben Houston / http://clara.io/
  21868. * @author David Sarno / http://lighthaus.us/
  21869. * @author tschw
  21870. */
  21871. function NumberKeyframeTrack(name, times, values, interpolation) {
  21872. KeyframeTrack.call(this, name, times, values, interpolation);
  21873. }
  21874. NumberKeyframeTrack.prototype = Object.assign(Object.create(KeyframeTrack.prototype), {
  21875. constructor: NumberKeyframeTrack,
  21876. ValueTypeName: 'number' // ValueBufferType is inherited
  21877. // DefaultInterpolation is inherited
  21878. });
  21879. /**
  21880. * Spherical linear unit quaternion interpolant.
  21881. *
  21882. * @author tschw
  21883. */
  21884. function QuaternionLinearInterpolant(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  21885. Interpolant.call(this, parameterPositions, sampleValues, sampleSize, resultBuffer);
  21886. }
  21887. QuaternionLinearInterpolant.prototype = Object.assign(Object.create(Interpolant.prototype), {
  21888. constructor: QuaternionLinearInterpolant,
  21889. interpolate_: function (i1, t0, t, t1) {
  21890. var result = this.resultBuffer,
  21891. values = this.sampleValues,
  21892. stride = this.valueSize,
  21893. offset = i1 * stride,
  21894. alpha = (t - t0) / (t1 - t0);
  21895. for (var end = offset + stride; offset !== end; offset += 4) {
  21896. Quaternion.slerpFlat(result, 0, values, offset - stride, values, offset, alpha);
  21897. }
  21898. return result;
  21899. }
  21900. });
  21901. /**
  21902. *
  21903. * A Track of quaternion keyframe values.
  21904. *
  21905. * @author Ben Houston / http://clara.io/
  21906. * @author David Sarno / http://lighthaus.us/
  21907. * @author tschw
  21908. */
  21909. function QuaternionKeyframeTrack(name, times, values, interpolation) {
  21910. KeyframeTrack.call(this, name, times, values, interpolation);
  21911. }
  21912. QuaternionKeyframeTrack.prototype = Object.assign(Object.create(KeyframeTrack.prototype), {
  21913. constructor: QuaternionKeyframeTrack,
  21914. ValueTypeName: 'quaternion',
  21915. // ValueBufferType is inherited
  21916. DefaultInterpolation: InterpolateLinear,
  21917. InterpolantFactoryMethodLinear: function (result) {
  21918. return new QuaternionLinearInterpolant(this.times, this.values, this.getValueSize(), result);
  21919. },
  21920. InterpolantFactoryMethodSmooth: undefined // not yet implemented
  21921. });
  21922. /**
  21923. *
  21924. * A Track that interpolates Strings
  21925. *
  21926. *
  21927. * @author Ben Houston / http://clara.io/
  21928. * @author David Sarno / http://lighthaus.us/
  21929. * @author tschw
  21930. */
  21931. function StringKeyframeTrack(name, times, values, interpolation) {
  21932. KeyframeTrack.call(this, name, times, values, interpolation);
  21933. }
  21934. StringKeyframeTrack.prototype = Object.assign(Object.create(KeyframeTrack.prototype), {
  21935. constructor: StringKeyframeTrack,
  21936. ValueTypeName: 'string',
  21937. ValueBufferType: Array,
  21938. DefaultInterpolation: InterpolateDiscrete,
  21939. InterpolantFactoryMethodLinear: undefined,
  21940. InterpolantFactoryMethodSmooth: undefined
  21941. });
  21942. /**
  21943. *
  21944. * A Track of vectored keyframe values.
  21945. *
  21946. *
  21947. * @author Ben Houston / http://clara.io/
  21948. * @author David Sarno / http://lighthaus.us/
  21949. * @author tschw
  21950. */
  21951. function VectorKeyframeTrack(name, times, values, interpolation) {
  21952. KeyframeTrack.call(this, name, times, values, interpolation);
  21953. }
  21954. VectorKeyframeTrack.prototype = Object.assign(Object.create(KeyframeTrack.prototype), {
  21955. constructor: VectorKeyframeTrack,
  21956. ValueTypeName: 'vector' // ValueBufferType is inherited
  21957. // DefaultInterpolation is inherited
  21958. });
  21959. /**
  21960. *
  21961. * Reusable set of Tracks that represent an animation.
  21962. *
  21963. * @author Ben Houston / http://clara.io/
  21964. * @author David Sarno / http://lighthaus.us/
  21965. */
  21966. function AnimationClip(name, duration, tracks) {
  21967. this.name = name;
  21968. this.tracks = tracks;
  21969. this.duration = duration !== undefined ? duration : -1;
  21970. this.uuid = _Math.generateUUID(); // this means it should figure out its duration by scanning the tracks
  21971. if (this.duration < 0) {
  21972. this.resetDuration();
  21973. }
  21974. }
  21975. function getTrackTypeForValueTypeName(typeName) {
  21976. switch (typeName.toLowerCase()) {
  21977. case 'scalar':
  21978. case 'double':
  21979. case 'float':
  21980. case 'number':
  21981. case 'integer':
  21982. return NumberKeyframeTrack;
  21983. case 'vector':
  21984. case 'vector2':
  21985. case 'vector3':
  21986. case 'vector4':
  21987. return VectorKeyframeTrack;
  21988. case 'color':
  21989. return ColorKeyframeTrack;
  21990. case 'quaternion':
  21991. return QuaternionKeyframeTrack;
  21992. case 'bool':
  21993. case 'boolean':
  21994. return BooleanKeyframeTrack;
  21995. case 'string':
  21996. return StringKeyframeTrack;
  21997. }
  21998. throw new Error('THREE.KeyframeTrack: Unsupported typeName: ' + typeName);
  21999. }
  22000. function parseKeyframeTrack(json) {
  22001. if (json.type === undefined) {
  22002. throw new Error('THREE.KeyframeTrack: track type undefined, can not parse');
  22003. }
  22004. var trackType = getTrackTypeForValueTypeName(json.type);
  22005. if (json.times === undefined) {
  22006. var times = [],
  22007. values = [];
  22008. AnimationUtils.flattenJSON(json.keys, times, values, 'value');
  22009. json.times = times;
  22010. json.values = values;
  22011. } // derived classes can define a static parse method
  22012. if (trackType.parse !== undefined) {
  22013. return trackType.parse(json);
  22014. } else {
  22015. // by default, we assume a constructor compatible with the base
  22016. return new trackType(json.name, json.times, json.values, json.interpolation);
  22017. }
  22018. }
  22019. Object.assign(AnimationClip, {
  22020. parse: function (json) {
  22021. var tracks = [],
  22022. jsonTracks = json.tracks,
  22023. frameTime = 1.0 / (json.fps || 1.0);
  22024. for (var i = 0, n = jsonTracks.length; i !== n; ++i) {
  22025. tracks.push(parseKeyframeTrack(jsonTracks[i]).scale(frameTime));
  22026. }
  22027. return new AnimationClip(json.name, json.duration, tracks);
  22028. },
  22029. toJSON: function (clip) {
  22030. var tracks = [],
  22031. clipTracks = clip.tracks;
  22032. var json = {
  22033. 'name': clip.name,
  22034. 'duration': clip.duration,
  22035. 'tracks': tracks,
  22036. 'uuid': clip.uuid
  22037. };
  22038. for (var i = 0, n = clipTracks.length; i !== n; ++i) {
  22039. tracks.push(KeyframeTrack.toJSON(clipTracks[i]));
  22040. }
  22041. return json;
  22042. },
  22043. CreateFromMorphTargetSequence: function (name, morphTargetSequence, fps, noLoop) {
  22044. var numMorphTargets = morphTargetSequence.length;
  22045. var tracks = [];
  22046. for (var i = 0; i < numMorphTargets; i++) {
  22047. var times = [];
  22048. var values = [];
  22049. times.push((i + numMorphTargets - 1) % numMorphTargets, i, (i + 1) % numMorphTargets);
  22050. values.push(0, 1, 0);
  22051. var order = AnimationUtils.getKeyframeOrder(times);
  22052. times = AnimationUtils.sortedArray(times, 1, order);
  22053. values = AnimationUtils.sortedArray(values, 1, order); // if there is a key at the first frame, duplicate it as the
  22054. // last frame as well for perfect loop.
  22055. if (!noLoop && times[0] === 0) {
  22056. times.push(numMorphTargets);
  22057. values.push(values[0]);
  22058. }
  22059. tracks.push(new NumberKeyframeTrack('.morphTargetInfluences[' + morphTargetSequence[i].name + ']', times, values).scale(1.0 / fps));
  22060. }
  22061. return new AnimationClip(name, -1, tracks);
  22062. },
  22063. findByName: function (objectOrClipArray, name) {
  22064. var clipArray = objectOrClipArray;
  22065. if (!Array.isArray(objectOrClipArray)) {
  22066. var o = objectOrClipArray;
  22067. clipArray = o.geometry && o.geometry.animations || o.animations;
  22068. }
  22069. for (var i = 0; i < clipArray.length; i++) {
  22070. if (clipArray[i].name === name) {
  22071. return clipArray[i];
  22072. }
  22073. }
  22074. return null;
  22075. },
  22076. CreateClipsFromMorphTargetSequences: function (morphTargets, fps, noLoop) {
  22077. var animationToMorphTargets = {}; // tested with https://regex101.com/ on trick sequences
  22078. // such flamingo_flyA_003, flamingo_run1_003, crdeath0059
  22079. var pattern = /^([\w-]*?)([\d]+)$/; // sort morph target names into animation groups based
  22080. // patterns like Walk_001, Walk_002, Run_001, Run_002
  22081. for (var i = 0, il = morphTargets.length; i < il; i++) {
  22082. var morphTarget = morphTargets[i];
  22083. var parts = morphTarget.name.match(pattern);
  22084. if (parts && parts.length > 1) {
  22085. var name = parts[1];
  22086. var animationMorphTargets = animationToMorphTargets[name];
  22087. if (!animationMorphTargets) {
  22088. animationToMorphTargets[name] = animationMorphTargets = [];
  22089. }
  22090. animationMorphTargets.push(morphTarget);
  22091. }
  22092. }
  22093. var clips = [];
  22094. for (var name in animationToMorphTargets) {
  22095. clips.push(AnimationClip.CreateFromMorphTargetSequence(name, animationToMorphTargets[name], fps, noLoop));
  22096. }
  22097. return clips;
  22098. },
  22099. // parse the animation.hierarchy format
  22100. parseAnimation: function (animation, bones) {
  22101. if (!animation) {
  22102. console.error('THREE.AnimationClip: No animation in JSONLoader data.');
  22103. return null;
  22104. }
  22105. var addNonemptyTrack = function (trackType, trackName, animationKeys, propertyName, destTracks) {
  22106. // only return track if there are actually keys.
  22107. if (animationKeys.length !== 0) {
  22108. var times = [];
  22109. var values = [];
  22110. AnimationUtils.flattenJSON(animationKeys, times, values, propertyName); // empty keys are filtered out, so check again
  22111. if (times.length !== 0) {
  22112. destTracks.push(new trackType(trackName, times, values));
  22113. }
  22114. }
  22115. };
  22116. var tracks = [];
  22117. var clipName = animation.name || 'default'; // automatic length determination in AnimationClip.
  22118. var duration = animation.length || -1;
  22119. var fps = animation.fps || 30;
  22120. var hierarchyTracks = animation.hierarchy || [];
  22121. for (var h = 0; h < hierarchyTracks.length; h++) {
  22122. var animationKeys = hierarchyTracks[h].keys; // skip empty tracks
  22123. if (!animationKeys || animationKeys.length === 0) continue; // process morph targets
  22124. if (animationKeys[0].morphTargets) {
  22125. // figure out all morph targets used in this track
  22126. var morphTargetNames = {};
  22127. for (var k = 0; k < animationKeys.length; k++) {
  22128. if (animationKeys[k].morphTargets) {
  22129. for (var m = 0; m < animationKeys[k].morphTargets.length; m++) {
  22130. morphTargetNames[animationKeys[k].morphTargets[m]] = -1;
  22131. }
  22132. }
  22133. } // create a track for each morph target with all zero
  22134. // morphTargetInfluences except for the keys in which
  22135. // the morphTarget is named.
  22136. for (var morphTargetName in morphTargetNames) {
  22137. var times = [];
  22138. var values = [];
  22139. for (var m = 0; m !== animationKeys[k].morphTargets.length; ++m) {
  22140. var animationKey = animationKeys[k];
  22141. times.push(animationKey.time);
  22142. values.push(animationKey.morphTarget === morphTargetName ? 1 : 0);
  22143. }
  22144. tracks.push(new NumberKeyframeTrack('.morphTargetInfluence[' + morphTargetName + ']', times, values));
  22145. }
  22146. duration = morphTargetNames.length * (fps || 1.0);
  22147. } else {
  22148. // ...assume skeletal animation
  22149. var boneName = '.bones[' + bones[h].name + ']';
  22150. addNonemptyTrack(VectorKeyframeTrack, boneName + '.position', animationKeys, 'pos', tracks);
  22151. addNonemptyTrack(QuaternionKeyframeTrack, boneName + '.quaternion', animationKeys, 'rot', tracks);
  22152. addNonemptyTrack(VectorKeyframeTrack, boneName + '.scale', animationKeys, 'scl', tracks);
  22153. }
  22154. }
  22155. if (tracks.length === 0) {
  22156. return null;
  22157. }
  22158. var clip = new AnimationClip(clipName, duration, tracks);
  22159. return clip;
  22160. }
  22161. });
  22162. Object.assign(AnimationClip.prototype, {
  22163. resetDuration: function () {
  22164. var tracks = this.tracks,
  22165. duration = 0;
  22166. for (var i = 0, n = tracks.length; i !== n; ++i) {
  22167. var track = this.tracks[i];
  22168. duration = Math.max(duration, track.times[track.times.length - 1]);
  22169. }
  22170. this.duration = duration;
  22171. return this;
  22172. },
  22173. trim: function () {
  22174. for (var i = 0; i < this.tracks.length; i++) {
  22175. this.tracks[i].trim(0, this.duration);
  22176. }
  22177. return this;
  22178. },
  22179. validate: function () {
  22180. var valid = true;
  22181. for (var i = 0; i < this.tracks.length; i++) {
  22182. valid = valid && this.tracks[i].validate();
  22183. }
  22184. return valid;
  22185. },
  22186. optimize: function () {
  22187. for (var i = 0; i < this.tracks.length; i++) {
  22188. this.tracks[i].optimize();
  22189. }
  22190. return this;
  22191. },
  22192. clone: function () {
  22193. var tracks = [];
  22194. for (var i = 0; i < this.tracks.length; i++) {
  22195. tracks.push(this.tracks[i].clone());
  22196. }
  22197. return new AnimationClip(this.name, this.duration, tracks);
  22198. }
  22199. });
  22200. /**
  22201. * @author mrdoob / http://mrdoob.com/
  22202. */
  22203. var Cache = {
  22204. enabled: false,
  22205. files: {},
  22206. add: function (key, file) {
  22207. if (this.enabled === false) return; // console.log( 'THREE.Cache', 'Adding key:', key );
  22208. this.files[key] = file;
  22209. },
  22210. get: function (key) {
  22211. if (this.enabled === false) return; // console.log( 'THREE.Cache', 'Checking key:', key );
  22212. return this.files[key];
  22213. },
  22214. remove: function (key) {
  22215. delete this.files[key];
  22216. },
  22217. clear: function () {
  22218. this.files = {};
  22219. }
  22220. };
  22221. /**
  22222. * @author mrdoob / http://mrdoob.com/
  22223. */
  22224. exports.Cache = Cache;
  22225. function LoadingManager(onLoad, onProgress, onError) {
  22226. var scope = this;
  22227. var isLoading = false;
  22228. var itemsLoaded = 0;
  22229. var itemsTotal = 0;
  22230. var urlModifier = undefined;
  22231. var handlers = []; // Refer to #5689 for the reason why we don't set .onStart
  22232. // in the constructor
  22233. this.onStart = undefined;
  22234. this.onLoad = onLoad;
  22235. this.onProgress = onProgress;
  22236. this.onError = onError;
  22237. this.itemStart = function (url) {
  22238. itemsTotal++;
  22239. if (isLoading === false) {
  22240. if (scope.onStart !== undefined) {
  22241. scope.onStart(url, itemsLoaded, itemsTotal);
  22242. }
  22243. }
  22244. isLoading = true;
  22245. };
  22246. this.itemEnd = function (url) {
  22247. itemsLoaded++;
  22248. if (scope.onProgress !== undefined) {
  22249. scope.onProgress(url, itemsLoaded, itemsTotal);
  22250. }
  22251. if (itemsLoaded === itemsTotal) {
  22252. isLoading = false;
  22253. if (scope.onLoad !== undefined) {
  22254. scope.onLoad();
  22255. }
  22256. }
  22257. };
  22258. this.itemError = function (url) {
  22259. if (scope.onError !== undefined) {
  22260. scope.onError(url);
  22261. }
  22262. };
  22263. this.resolveURL = function (url) {
  22264. if (urlModifier) {
  22265. return urlModifier(url);
  22266. }
  22267. return url;
  22268. };
  22269. this.setURLModifier = function (transform) {
  22270. urlModifier = transform;
  22271. return this;
  22272. };
  22273. this.addHandler = function (regex, loader) {
  22274. handlers.push(regex, loader);
  22275. return this;
  22276. };
  22277. this.removeHandler = function (regex) {
  22278. var index = handlers.indexOf(regex);
  22279. if (index !== -1) {
  22280. handlers.splice(index, 2);
  22281. }
  22282. return this;
  22283. };
  22284. this.getHandler = function (file) {
  22285. for (var i = 0, l = handlers.length; i < l; i += 2) {
  22286. var regex = handlers[i];
  22287. var loader = handlers[i + 1];
  22288. if (regex.test(file)) {
  22289. return loader;
  22290. }
  22291. }
  22292. return null;
  22293. };
  22294. }
  22295. var DefaultLoadingManager = new LoadingManager();
  22296. /**
  22297. * @author alteredq / http://alteredqualia.com/
  22298. */
  22299. exports.DefaultLoadingManager = DefaultLoadingManager;
  22300. function Loader(manager) {
  22301. this.manager = manager !== undefined ? manager : DefaultLoadingManager;
  22302. this.crossOrigin = 'anonymous';
  22303. this.path = '';
  22304. this.resourcePath = '';
  22305. }
  22306. Object.assign(Loader.prototype, {
  22307. load: function ()
  22308. /* url, onLoad, onProgress, onError */
  22309. {},
  22310. parse: function ()
  22311. /* data */
  22312. {},
  22313. setCrossOrigin: function (crossOrigin) {
  22314. this.crossOrigin = crossOrigin;
  22315. return this;
  22316. },
  22317. setPath: function (path) {
  22318. this.path = path;
  22319. return this;
  22320. },
  22321. setResourcePath: function (resourcePath) {
  22322. this.resourcePath = resourcePath;
  22323. return this;
  22324. }
  22325. });
  22326. /**
  22327. * @author mrdoob / http://mrdoob.com/
  22328. */
  22329. var loading = {};
  22330. function FileLoader(manager) {
  22331. Loader.call(this, manager);
  22332. }
  22333. FileLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  22334. constructor: FileLoader,
  22335. load: function (url, onLoad, onProgress, onError) {
  22336. if (url === undefined) url = '';
  22337. if (this.path !== undefined) url = this.path + url;
  22338. url = this.manager.resolveURL(url);
  22339. var scope = this;
  22340. var cached = Cache.get(url);
  22341. if (cached !== undefined) {
  22342. scope.manager.itemStart(url);
  22343. setTimeout(function () {
  22344. if (onLoad) onLoad(cached);
  22345. scope.manager.itemEnd(url);
  22346. }, 0);
  22347. return cached;
  22348. } // Check if request is duplicate
  22349. if (loading[url] !== undefined) {
  22350. loading[url].push({
  22351. onLoad: onLoad,
  22352. onProgress: onProgress,
  22353. onError: onError
  22354. });
  22355. return;
  22356. } // Check for data: URI
  22357. var dataUriRegex = /^data:(.*?)(;base64)?,(.*)$/;
  22358. var dataUriRegexResult = url.match(dataUriRegex); // Safari can not handle Data URIs through XMLHttpRequest so process manually
  22359. if (dataUriRegexResult) {
  22360. var mimeType = dataUriRegexResult[1];
  22361. var isBase64 = !!dataUriRegexResult[2];
  22362. var data = dataUriRegexResult[3];
  22363. data = decodeURIComponent(data);
  22364. if (isBase64) data = atob(data);
  22365. try {
  22366. var response;
  22367. var responseType = (this.responseType || '').toLowerCase();
  22368. switch (responseType) {
  22369. case 'arraybuffer':
  22370. case 'blob':
  22371. var view = new Uint8Array(data.length);
  22372. for (var i = 0; i < data.length; i++) {
  22373. view[i] = data.charCodeAt(i);
  22374. }
  22375. if (responseType === 'blob') {
  22376. response = new Blob([view.buffer], {
  22377. type: mimeType
  22378. });
  22379. } else {
  22380. response = view.buffer;
  22381. }
  22382. break;
  22383. case 'document':
  22384. var parser = new DOMParser();
  22385. response = parser.parseFromString(data, mimeType);
  22386. break;
  22387. case 'json':
  22388. response = JSON.parse(data);
  22389. break;
  22390. default:
  22391. // 'text' or other
  22392. response = data;
  22393. break;
  22394. } // Wait for next browser tick like standard XMLHttpRequest event dispatching does
  22395. setTimeout(function () {
  22396. if (onLoad) onLoad(response);
  22397. scope.manager.itemEnd(url);
  22398. }, 0);
  22399. } catch (error) {
  22400. // Wait for next browser tick like standard XMLHttpRequest event dispatching does
  22401. setTimeout(function () {
  22402. if (onError) onError(error);
  22403. scope.manager.itemError(url);
  22404. scope.manager.itemEnd(url);
  22405. }, 0);
  22406. }
  22407. } else {
  22408. // Initialise array for duplicate requests
  22409. loading[url] = [];
  22410. loading[url].push({
  22411. onLoad: onLoad,
  22412. onProgress: onProgress,
  22413. onError: onError
  22414. });
  22415. var request = new XMLHttpRequest();
  22416. request.open('GET', url, true);
  22417. request.addEventListener('load', function (event) {
  22418. var response = this.response;
  22419. Cache.add(url, response);
  22420. var callbacks = loading[url];
  22421. delete loading[url];
  22422. if (this.status === 200 || this.status === 0) {
  22423. // Some browsers return HTTP Status 0 when using non-http protocol
  22424. // e.g. 'file://' or 'data://'. Handle as success.
  22425. if (this.status === 0) console.warn('THREE.FileLoader: HTTP Status 0 received.');
  22426. for (var i = 0, il = callbacks.length; i < il; i++) {
  22427. var callback = callbacks[i];
  22428. if (callback.onLoad) callback.onLoad(response);
  22429. }
  22430. scope.manager.itemEnd(url);
  22431. } else {
  22432. for (var i = 0, il = callbacks.length; i < il; i++) {
  22433. var callback = callbacks[i];
  22434. if (callback.onError) callback.onError(event);
  22435. }
  22436. scope.manager.itemError(url);
  22437. scope.manager.itemEnd(url);
  22438. }
  22439. }, false);
  22440. request.addEventListener('progress', function (event) {
  22441. var callbacks = loading[url];
  22442. for (var i = 0, il = callbacks.length; i < il; i++) {
  22443. var callback = callbacks[i];
  22444. if (callback.onProgress) callback.onProgress(event);
  22445. }
  22446. }, false);
  22447. request.addEventListener('error', function (event) {
  22448. var callbacks = loading[url];
  22449. delete loading[url];
  22450. for (var i = 0, il = callbacks.length; i < il; i++) {
  22451. var callback = callbacks[i];
  22452. if (callback.onError) callback.onError(event);
  22453. }
  22454. scope.manager.itemError(url);
  22455. scope.manager.itemEnd(url);
  22456. }, false);
  22457. request.addEventListener('abort', function (event) {
  22458. var callbacks = loading[url];
  22459. delete loading[url];
  22460. for (var i = 0, il = callbacks.length; i < il; i++) {
  22461. var callback = callbacks[i];
  22462. if (callback.onError) callback.onError(event);
  22463. }
  22464. scope.manager.itemError(url);
  22465. scope.manager.itemEnd(url);
  22466. }, false);
  22467. if (this.responseType !== undefined) request.responseType = this.responseType;
  22468. if (this.withCredentials !== undefined) request.withCredentials = this.withCredentials;
  22469. if (request.overrideMimeType) request.overrideMimeType(this.mimeType !== undefined ? this.mimeType : 'text/plain');
  22470. for (var header in this.requestHeader) {
  22471. request.setRequestHeader(header, this.requestHeader[header]);
  22472. }
  22473. request.send(null);
  22474. }
  22475. scope.manager.itemStart(url);
  22476. return request;
  22477. },
  22478. setResponseType: function (value) {
  22479. this.responseType = value;
  22480. return this;
  22481. },
  22482. setWithCredentials: function (value) {
  22483. this.withCredentials = value;
  22484. return this;
  22485. },
  22486. setMimeType: function (value) {
  22487. this.mimeType = value;
  22488. return this;
  22489. },
  22490. setRequestHeader: function (value) {
  22491. this.requestHeader = value;
  22492. return this;
  22493. }
  22494. });
  22495. /**
  22496. * @author bhouston / http://clara.io/
  22497. */
  22498. function AnimationLoader(manager) {
  22499. Loader.call(this, manager);
  22500. }
  22501. AnimationLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  22502. constructor: AnimationLoader,
  22503. load: function (url, onLoad, onProgress, onError) {
  22504. var scope = this;
  22505. var loader = new FileLoader(scope.manager);
  22506. loader.setPath(scope.path);
  22507. loader.load(url, function (text) {
  22508. onLoad(scope.parse(JSON.parse(text)));
  22509. }, onProgress, onError);
  22510. },
  22511. parse: function (json) {
  22512. var animations = [];
  22513. for (var i = 0; i < json.length; i++) {
  22514. var clip = AnimationClip.parse(json[i]);
  22515. animations.push(clip);
  22516. }
  22517. return animations;
  22518. }
  22519. });
  22520. /**
  22521. * @author mrdoob / http://mrdoob.com/
  22522. *
  22523. * Abstract Base class to block based textures loader (dds, pvr, ...)
  22524. *
  22525. * Sub classes have to implement the parse() method which will be used in load().
  22526. */
  22527. function CompressedTextureLoader(manager) {
  22528. Loader.call(this, manager);
  22529. }
  22530. CompressedTextureLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  22531. constructor: CompressedTextureLoader,
  22532. load: function (url, onLoad, onProgress, onError) {
  22533. var scope = this;
  22534. var images = [];
  22535. var texture = new CompressedTexture();
  22536. texture.image = images;
  22537. var loader = new FileLoader(this.manager);
  22538. loader.setPath(this.path);
  22539. loader.setResponseType('arraybuffer');
  22540. function loadTexture(i) {
  22541. loader.load(url[i], function (buffer) {
  22542. var texDatas = scope.parse(buffer, true);
  22543. images[i] = {
  22544. width: texDatas.width,
  22545. height: texDatas.height,
  22546. format: texDatas.format,
  22547. mipmaps: texDatas.mipmaps
  22548. };
  22549. loaded += 1;
  22550. if (loaded === 6) {
  22551. if (texDatas.mipmapCount === 1) texture.minFilter = LinearFilter;
  22552. texture.format = texDatas.format;
  22553. texture.needsUpdate = true;
  22554. if (onLoad) onLoad(texture);
  22555. }
  22556. }, onProgress, onError);
  22557. }
  22558. if (Array.isArray(url)) {
  22559. var loaded = 0;
  22560. for (var i = 0, il = url.length; i < il; ++i) {
  22561. loadTexture(i);
  22562. }
  22563. } else {
  22564. // compressed cubemap texture stored in a single DDS file
  22565. loader.load(url, function (buffer) {
  22566. var texDatas = scope.parse(buffer, true);
  22567. if (texDatas.isCubemap) {
  22568. var faces = texDatas.mipmaps.length / texDatas.mipmapCount;
  22569. for (var f = 0; f < faces; f++) {
  22570. images[f] = {
  22571. mipmaps: []
  22572. };
  22573. for (var i = 0; i < texDatas.mipmapCount; i++) {
  22574. images[f].mipmaps.push(texDatas.mipmaps[f * texDatas.mipmapCount + i]);
  22575. images[f].format = texDatas.format;
  22576. images[f].width = texDatas.width;
  22577. images[f].height = texDatas.height;
  22578. }
  22579. }
  22580. } else {
  22581. texture.image.width = texDatas.width;
  22582. texture.image.height = texDatas.height;
  22583. texture.mipmaps = texDatas.mipmaps;
  22584. }
  22585. if (texDatas.mipmapCount === 1) {
  22586. texture.minFilter = LinearFilter;
  22587. }
  22588. texture.format = texDatas.format;
  22589. texture.needsUpdate = true;
  22590. if (onLoad) onLoad(texture);
  22591. }, onProgress, onError);
  22592. }
  22593. return texture;
  22594. }
  22595. });
  22596. /**
  22597. * @author Nikos M. / https://github.com/foo123/
  22598. *
  22599. * Abstract Base class to load generic binary textures formats (rgbe, hdr, ...)
  22600. *
  22601. * Sub classes have to implement the parse() method which will be used in load().
  22602. */
  22603. function DataTextureLoader(manager) {
  22604. Loader.call(this, manager);
  22605. }
  22606. DataTextureLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  22607. constructor: DataTextureLoader,
  22608. load: function (url, onLoad, onProgress, onError) {
  22609. var scope = this;
  22610. var texture = new DataTexture();
  22611. var loader = new FileLoader(this.manager);
  22612. loader.setResponseType('arraybuffer');
  22613. loader.setPath(this.path);
  22614. loader.load(url, function (buffer) {
  22615. var texData = scope.parse(buffer);
  22616. if (!texData) return;
  22617. if (texData.image !== undefined) {
  22618. texture.image = texData.image;
  22619. } else if (texData.data !== undefined) {
  22620. texture.image.width = texData.width;
  22621. texture.image.height = texData.height;
  22622. texture.image.data = texData.data;
  22623. }
  22624. texture.wrapS = texData.wrapS !== undefined ? texData.wrapS : ClampToEdgeWrapping;
  22625. texture.wrapT = texData.wrapT !== undefined ? texData.wrapT : ClampToEdgeWrapping;
  22626. texture.magFilter = texData.magFilter !== undefined ? texData.magFilter : LinearFilter;
  22627. texture.minFilter = texData.minFilter !== undefined ? texData.minFilter : LinearMipmapLinearFilter;
  22628. texture.anisotropy = texData.anisotropy !== undefined ? texData.anisotropy : 1;
  22629. if (texData.format !== undefined) {
  22630. texture.format = texData.format;
  22631. }
  22632. if (texData.type !== undefined) {
  22633. texture.type = texData.type;
  22634. }
  22635. if (texData.mipmaps !== undefined) {
  22636. texture.mipmaps = texData.mipmaps;
  22637. }
  22638. if (texData.mipmapCount === 1) {
  22639. texture.minFilter = LinearFilter;
  22640. }
  22641. texture.needsUpdate = true;
  22642. if (onLoad) onLoad(texture, texData);
  22643. }, onProgress, onError);
  22644. return texture;
  22645. }
  22646. });
  22647. /**
  22648. * @author mrdoob / http://mrdoob.com/
  22649. */
  22650. function ImageLoader(manager) {
  22651. Loader.call(this, manager);
  22652. }
  22653. ImageLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  22654. constructor: ImageLoader,
  22655. load: function (url, onLoad, onProgress, onError) {
  22656. if (this.path !== undefined) url = this.path + url;
  22657. url = this.manager.resolveURL(url);
  22658. var scope = this;
  22659. var cached = Cache.get(url);
  22660. if (cached !== undefined) {
  22661. scope.manager.itemStart(url);
  22662. setTimeout(function () {
  22663. if (onLoad) onLoad(cached);
  22664. scope.manager.itemEnd(url);
  22665. }, 0);
  22666. return cached;
  22667. }
  22668. var image = document.createElementNS('http://www.w3.org/1999/xhtml', 'img');
  22669. function onImageLoad() {
  22670. image.removeEventListener('load', onImageLoad, false);
  22671. image.removeEventListener('error', onImageError, false);
  22672. Cache.add(url, this);
  22673. if (onLoad) onLoad(this);
  22674. scope.manager.itemEnd(url);
  22675. }
  22676. function onImageError(event) {
  22677. image.removeEventListener('load', onImageLoad, false);
  22678. image.removeEventListener('error', onImageError, false);
  22679. if (onError) onError(event);
  22680. scope.manager.itemError(url);
  22681. scope.manager.itemEnd(url);
  22682. }
  22683. image.addEventListener('load', onImageLoad, false);
  22684. image.addEventListener('error', onImageError, false);
  22685. if (url.substr(0, 5) !== 'data:') {
  22686. if (this.crossOrigin !== undefined) image.crossOrigin = this.crossOrigin;
  22687. }
  22688. scope.manager.itemStart(url);
  22689. image.src = url;
  22690. return image;
  22691. }
  22692. });
  22693. /**
  22694. * @author mrdoob / http://mrdoob.com/
  22695. */
  22696. function CubeTextureLoader(manager) {
  22697. Loader.call(this, manager);
  22698. }
  22699. CubeTextureLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  22700. constructor: CubeTextureLoader,
  22701. load: function (urls, onLoad, onProgress, onError) {
  22702. var texture = new CubeTexture();
  22703. var loader = new ImageLoader(this.manager);
  22704. loader.setCrossOrigin(this.crossOrigin);
  22705. loader.setPath(this.path);
  22706. var loaded = 0;
  22707. function loadTexture(i) {
  22708. loader.load(urls[i], function (image) {
  22709. texture.images[i] = image;
  22710. loaded++;
  22711. if (loaded === 6) {
  22712. texture.needsUpdate = true;
  22713. if (onLoad) onLoad(texture);
  22714. }
  22715. }, undefined, onError);
  22716. }
  22717. for (var i = 0; i < urls.length; ++i) {
  22718. loadTexture(i);
  22719. }
  22720. return texture;
  22721. }
  22722. });
  22723. /**
  22724. * @author mrdoob / http://mrdoob.com/
  22725. */
  22726. function TextureLoader(manager) {
  22727. Loader.call(this, manager);
  22728. }
  22729. TextureLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  22730. constructor: TextureLoader,
  22731. load: function (url, onLoad, onProgress, onError) {
  22732. var texture = new Texture();
  22733. var loader = new ImageLoader(this.manager);
  22734. loader.setCrossOrigin(this.crossOrigin);
  22735. loader.setPath(this.path);
  22736. loader.load(url, function (image) {
  22737. texture.image = image; // JPEGs can't have an alpha channel, so memory can be saved by storing them as RGB.
  22738. var isJPEG = url.search(/\.jpe?g($|\?)/i) > 0 || url.search(/^data\:image\/jpeg/) === 0;
  22739. texture.format = isJPEG ? RGBFormat : RGBAFormat;
  22740. texture.needsUpdate = true;
  22741. if (onLoad !== undefined) {
  22742. onLoad(texture);
  22743. }
  22744. }, onProgress, onError);
  22745. return texture;
  22746. }
  22747. });
  22748. /**
  22749. * @author zz85 / http://www.lab4games.net/zz85/blog
  22750. * Extensible curve object
  22751. *
  22752. * Some common of curve methods:
  22753. * .getPoint( t, optionalTarget ), .getTangent( t )
  22754. * .getPointAt( u, optionalTarget ), .getTangentAt( u )
  22755. * .getPoints(), .getSpacedPoints()
  22756. * .getLength()
  22757. * .updateArcLengths()
  22758. *
  22759. * This following curves inherit from THREE.Curve:
  22760. *
  22761. * -- 2D curves --
  22762. * THREE.ArcCurve
  22763. * THREE.CubicBezierCurve
  22764. * THREE.EllipseCurve
  22765. * THREE.LineCurve
  22766. * THREE.QuadraticBezierCurve
  22767. * THREE.SplineCurve
  22768. *
  22769. * -- 3D curves --
  22770. * THREE.CatmullRomCurve3
  22771. * THREE.CubicBezierCurve3
  22772. * THREE.LineCurve3
  22773. * THREE.QuadraticBezierCurve3
  22774. *
  22775. * A series of curves can be represented as a THREE.CurvePath.
  22776. *
  22777. **/
  22778. /**************************************************************
  22779. * Abstract Curve base class
  22780. **************************************************************/
  22781. function Curve() {
  22782. this.type = 'Curve';
  22783. this.arcLengthDivisions = 200;
  22784. }
  22785. Object.assign(Curve.prototype, {
  22786. // Virtual base class method to overwrite and implement in subclasses
  22787. // - t [0 .. 1]
  22788. getPoint: function ()
  22789. /* t, optionalTarget */
  22790. {
  22791. console.warn('THREE.Curve: .getPoint() not implemented.');
  22792. return null;
  22793. },
  22794. // Get point at relative position in curve according to arc length
  22795. // - u [0 .. 1]
  22796. getPointAt: function (u, optionalTarget) {
  22797. var t = this.getUtoTmapping(u);
  22798. return this.getPoint(t, optionalTarget);
  22799. },
  22800. // Get sequence of points using getPoint( t )
  22801. getPoints: function (divisions) {
  22802. if (divisions === undefined) divisions = 5;
  22803. var points = [];
  22804. for (var d = 0; d <= divisions; d++) {
  22805. points.push(this.getPoint(d / divisions));
  22806. }
  22807. return points;
  22808. },
  22809. // Get sequence of points using getPointAt( u )
  22810. getSpacedPoints: function (divisions) {
  22811. if (divisions === undefined) divisions = 5;
  22812. var points = [];
  22813. for (var d = 0; d <= divisions; d++) {
  22814. points.push(this.getPointAt(d / divisions));
  22815. }
  22816. return points;
  22817. },
  22818. // Get total curve arc length
  22819. getLength: function () {
  22820. var lengths = this.getLengths();
  22821. return lengths[lengths.length - 1];
  22822. },
  22823. // Get list of cumulative segment lengths
  22824. getLengths: function (divisions) {
  22825. if (divisions === undefined) divisions = this.arcLengthDivisions;
  22826. if (this.cacheArcLengths && this.cacheArcLengths.length === divisions + 1 && !this.needsUpdate) {
  22827. return this.cacheArcLengths;
  22828. }
  22829. this.needsUpdate = false;
  22830. var cache = [];
  22831. var current,
  22832. last = this.getPoint(0);
  22833. var p,
  22834. sum = 0;
  22835. cache.push(0);
  22836. for (p = 1; p <= divisions; p++) {
  22837. current = this.getPoint(p / divisions);
  22838. sum += current.distanceTo(last);
  22839. cache.push(sum);
  22840. last = current;
  22841. }
  22842. this.cacheArcLengths = cache;
  22843. return cache; // { sums: cache, sum: sum }; Sum is in the last element.
  22844. },
  22845. updateArcLengths: function () {
  22846. this.needsUpdate = true;
  22847. this.getLengths();
  22848. },
  22849. // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equidistant
  22850. getUtoTmapping: function (u, distance) {
  22851. var arcLengths = this.getLengths();
  22852. var i = 0,
  22853. il = arcLengths.length;
  22854. var targetArcLength; // The targeted u distance value to get
  22855. if (distance) {
  22856. targetArcLength = distance;
  22857. } else {
  22858. targetArcLength = u * arcLengths[il - 1];
  22859. } // binary search for the index with largest value smaller than target u distance
  22860. var low = 0,
  22861. high = il - 1,
  22862. comparison;
  22863. while (low <= high) {
  22864. 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
  22865. comparison = arcLengths[i] - targetArcLength;
  22866. if (comparison < 0) {
  22867. low = i + 1;
  22868. } else if (comparison > 0) {
  22869. high = i - 1;
  22870. } else {
  22871. high = i;
  22872. break; // DONE
  22873. }
  22874. }
  22875. i = high;
  22876. if (arcLengths[i] === targetArcLength) {
  22877. return i / (il - 1);
  22878. } // we could get finer grain at lengths, or use simple interpolation between two points
  22879. var lengthBefore = arcLengths[i];
  22880. var lengthAfter = arcLengths[i + 1];
  22881. var segmentLength = lengthAfter - lengthBefore; // determine where we are between the 'before' and 'after' points
  22882. var segmentFraction = (targetArcLength - lengthBefore) / segmentLength; // add that fractional amount to t
  22883. var t = (i + segmentFraction) / (il - 1);
  22884. return t;
  22885. },
  22886. // Returns a unit vector tangent at t
  22887. // In case any sub curve does not implement its tangent derivation,
  22888. // 2 points a small delta apart will be used to find its gradient
  22889. // which seems to give a reasonable approximation
  22890. getTangent: function (t) {
  22891. var delta = 0.0001;
  22892. var t1 = t - delta;
  22893. var t2 = t + delta; // Capping in case of danger
  22894. if (t1 < 0) t1 = 0;
  22895. if (t2 > 1) t2 = 1;
  22896. var pt1 = this.getPoint(t1);
  22897. var pt2 = this.getPoint(t2);
  22898. var vec = pt2.clone().sub(pt1);
  22899. return vec.normalize();
  22900. },
  22901. getTangentAt: function (u) {
  22902. var t = this.getUtoTmapping(u);
  22903. return this.getTangent(t);
  22904. },
  22905. computeFrenetFrames: function (segments, closed) {
  22906. // see http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  22907. var normal = new Vector3();
  22908. var tangents = [];
  22909. var normals = [];
  22910. var binormals = [];
  22911. var vec = new Vector3();
  22912. var mat = new Matrix4();
  22913. var i, u, theta; // compute the tangent vectors for each segment on the curve
  22914. for (i = 0; i <= segments; i++) {
  22915. u = i / segments;
  22916. tangents[i] = this.getTangentAt(u);
  22917. tangents[i].normalize();
  22918. } // select an initial normal vector perpendicular to the first tangent vector,
  22919. // and in the direction of the minimum tangent xyz component
  22920. normals[0] = new Vector3();
  22921. binormals[0] = new Vector3();
  22922. var min = Number.MAX_VALUE;
  22923. var tx = Math.abs(tangents[0].x);
  22924. var ty = Math.abs(tangents[0].y);
  22925. var tz = Math.abs(tangents[0].z);
  22926. if (tx <= min) {
  22927. min = tx;
  22928. normal.set(1, 0, 0);
  22929. }
  22930. if (ty <= min) {
  22931. min = ty;
  22932. normal.set(0, 1, 0);
  22933. }
  22934. if (tz <= min) {
  22935. normal.set(0, 0, 1);
  22936. }
  22937. vec.crossVectors(tangents[0], normal).normalize();
  22938. normals[0].crossVectors(tangents[0], vec);
  22939. binormals[0].crossVectors(tangents[0], normals[0]); // compute the slowly-varying normal and binormal vectors for each segment on the curve
  22940. for (i = 1; i <= segments; i++) {
  22941. normals[i] = normals[i - 1].clone();
  22942. binormals[i] = binormals[i - 1].clone();
  22943. vec.crossVectors(tangents[i - 1], tangents[i]);
  22944. if (vec.length() > Number.EPSILON) {
  22945. vec.normalize();
  22946. theta = Math.acos(_Math.clamp(tangents[i - 1].dot(tangents[i]), -1, 1)); // clamp for floating pt errors
  22947. normals[i].applyMatrix4(mat.makeRotationAxis(vec, theta));
  22948. }
  22949. binormals[i].crossVectors(tangents[i], normals[i]);
  22950. } // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  22951. if (closed === true) {
  22952. theta = Math.acos(_Math.clamp(normals[0].dot(normals[segments]), -1, 1));
  22953. theta /= segments;
  22954. if (tangents[0].dot(vec.crossVectors(normals[0], normals[segments])) > 0) {
  22955. theta = -theta;
  22956. }
  22957. for (i = 1; i <= segments; i++) {
  22958. // twist a little...
  22959. normals[i].applyMatrix4(mat.makeRotationAxis(tangents[i], theta * i));
  22960. binormals[i].crossVectors(tangents[i], normals[i]);
  22961. }
  22962. }
  22963. return {
  22964. tangents: tangents,
  22965. normals: normals,
  22966. binormals: binormals
  22967. };
  22968. },
  22969. clone: function () {
  22970. return new this.constructor().copy(this);
  22971. },
  22972. copy: function (source) {
  22973. this.arcLengthDivisions = source.arcLengthDivisions;
  22974. return this;
  22975. },
  22976. toJSON: function () {
  22977. var data = {
  22978. metadata: {
  22979. version: 4.5,
  22980. type: 'Curve',
  22981. generator: 'Curve.toJSON'
  22982. }
  22983. };
  22984. data.arcLengthDivisions = this.arcLengthDivisions;
  22985. data.type = this.type;
  22986. return data;
  22987. },
  22988. fromJSON: function (json) {
  22989. this.arcLengthDivisions = json.arcLengthDivisions;
  22990. return this;
  22991. }
  22992. });
  22993. function EllipseCurve(aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation) {
  22994. Curve.call(this);
  22995. this.type = 'EllipseCurve';
  22996. this.aX = aX || 0;
  22997. this.aY = aY || 0;
  22998. this.xRadius = xRadius || 1;
  22999. this.yRadius = yRadius || 1;
  23000. this.aStartAngle = aStartAngle || 0;
  23001. this.aEndAngle = aEndAngle || 2 * Math.PI;
  23002. this.aClockwise = aClockwise || false;
  23003. this.aRotation = aRotation || 0;
  23004. }
  23005. EllipseCurve.prototype = Object.create(Curve.prototype);
  23006. EllipseCurve.prototype.constructor = EllipseCurve;
  23007. EllipseCurve.prototype.isEllipseCurve = true;
  23008. EllipseCurve.prototype.getPoint = function (t, optionalTarget) {
  23009. var point = optionalTarget || new Vector2();
  23010. var twoPi = Math.PI * 2;
  23011. var deltaAngle = this.aEndAngle - this.aStartAngle;
  23012. var samePoints = Math.abs(deltaAngle) < Number.EPSILON; // ensures that deltaAngle is 0 .. 2 PI
  23013. while (deltaAngle < 0) deltaAngle += twoPi;
  23014. while (deltaAngle > twoPi) deltaAngle -= twoPi;
  23015. if (deltaAngle < Number.EPSILON) {
  23016. if (samePoints) {
  23017. deltaAngle = 0;
  23018. } else {
  23019. deltaAngle = twoPi;
  23020. }
  23021. }
  23022. if (this.aClockwise === true && !samePoints) {
  23023. if (deltaAngle === twoPi) {
  23024. deltaAngle = -twoPi;
  23025. } else {
  23026. deltaAngle = deltaAngle - twoPi;
  23027. }
  23028. }
  23029. var angle = this.aStartAngle + t * deltaAngle;
  23030. var x = this.aX + this.xRadius * Math.cos(angle);
  23031. var y = this.aY + this.yRadius * Math.sin(angle);
  23032. if (this.aRotation !== 0) {
  23033. var cos = Math.cos(this.aRotation);
  23034. var sin = Math.sin(this.aRotation);
  23035. var tx = x - this.aX;
  23036. var ty = y - this.aY; // Rotate the point about the center of the ellipse.
  23037. x = tx * cos - ty * sin + this.aX;
  23038. y = tx * sin + ty * cos + this.aY;
  23039. }
  23040. return point.set(x, y);
  23041. };
  23042. EllipseCurve.prototype.copy = function (source) {
  23043. Curve.prototype.copy.call(this, source);
  23044. this.aX = source.aX;
  23045. this.aY = source.aY;
  23046. this.xRadius = source.xRadius;
  23047. this.yRadius = source.yRadius;
  23048. this.aStartAngle = source.aStartAngle;
  23049. this.aEndAngle = source.aEndAngle;
  23050. this.aClockwise = source.aClockwise;
  23051. this.aRotation = source.aRotation;
  23052. return this;
  23053. };
  23054. EllipseCurve.prototype.toJSON = function () {
  23055. var data = Curve.prototype.toJSON.call(this);
  23056. data.aX = this.aX;
  23057. data.aY = this.aY;
  23058. data.xRadius = this.xRadius;
  23059. data.yRadius = this.yRadius;
  23060. data.aStartAngle = this.aStartAngle;
  23061. data.aEndAngle = this.aEndAngle;
  23062. data.aClockwise = this.aClockwise;
  23063. data.aRotation = this.aRotation;
  23064. return data;
  23065. };
  23066. EllipseCurve.prototype.fromJSON = function (json) {
  23067. Curve.prototype.fromJSON.call(this, json);
  23068. this.aX = json.aX;
  23069. this.aY = json.aY;
  23070. this.xRadius = json.xRadius;
  23071. this.yRadius = json.yRadius;
  23072. this.aStartAngle = json.aStartAngle;
  23073. this.aEndAngle = json.aEndAngle;
  23074. this.aClockwise = json.aClockwise;
  23075. this.aRotation = json.aRotation;
  23076. return this;
  23077. };
  23078. function ArcCurve(aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise) {
  23079. EllipseCurve.call(this, aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise);
  23080. this.type = 'ArcCurve';
  23081. }
  23082. ArcCurve.prototype = Object.create(EllipseCurve.prototype);
  23083. ArcCurve.prototype.constructor = ArcCurve;
  23084. ArcCurve.prototype.isArcCurve = true;
  23085. /**
  23086. * @author zz85 https://github.com/zz85
  23087. *
  23088. * Centripetal CatmullRom Curve - which is useful for avoiding
  23089. * cusps and self-intersections in non-uniform catmull rom curves.
  23090. * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf
  23091. *
  23092. * curve.type accepts centripetal(default), chordal and catmullrom
  23093. * curve.tension is used for catmullrom which defaults to 0.5
  23094. */
  23095. /*
  23096. Based on an optimized c++ solution in
  23097. - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/
  23098. - http://ideone.com/NoEbVM
  23099. This CubicPoly class could be used for reusing some variables and calculations,
  23100. but for three.js curve use, it could be possible inlined and flatten into a single function call
  23101. which can be placed in CurveUtils.
  23102. */
  23103. function CubicPoly() {
  23104. var c0 = 0,
  23105. c1 = 0,
  23106. c2 = 0,
  23107. c3 = 0;
  23108. /*
  23109. * Compute coefficients for a cubic polynomial
  23110. * p(s) = c0 + c1*s + c2*s^2 + c3*s^3
  23111. * such that
  23112. * p(0) = x0, p(1) = x1
  23113. * and
  23114. * p'(0) = t0, p'(1) = t1.
  23115. */
  23116. function init(x0, x1, t0, t1) {
  23117. c0 = x0;
  23118. c1 = t0;
  23119. c2 = -3 * x0 + 3 * x1 - 2 * t0 - t1;
  23120. c3 = 2 * x0 - 2 * x1 + t0 + t1;
  23121. }
  23122. return {
  23123. initCatmullRom: function (x0, x1, x2, x3, tension) {
  23124. init(x1, x2, tension * (x2 - x0), tension * (x3 - x1));
  23125. },
  23126. initNonuniformCatmullRom: function (x0, x1, x2, x3, dt0, dt1, dt2) {
  23127. // compute tangents when parameterized in [t1,t2]
  23128. var t1 = (x1 - x0) / dt0 - (x2 - x0) / (dt0 + dt1) + (x2 - x1) / dt1;
  23129. var t2 = (x2 - x1) / dt1 - (x3 - x1) / (dt1 + dt2) + (x3 - x2) / dt2; // rescale tangents for parametrization in [0,1]
  23130. t1 *= dt1;
  23131. t2 *= dt1;
  23132. init(x1, x2, t1, t2);
  23133. },
  23134. calc: function (t) {
  23135. var t2 = t * t;
  23136. var t3 = t2 * t;
  23137. return c0 + c1 * t + c2 * t2 + c3 * t3;
  23138. }
  23139. };
  23140. } //
  23141. var tmp = new Vector3();
  23142. var px = new CubicPoly(),
  23143. py = new CubicPoly(),
  23144. pz = new CubicPoly();
  23145. function CatmullRomCurve3(points, closed, curveType, tension) {
  23146. Curve.call(this);
  23147. this.type = 'CatmullRomCurve3';
  23148. this.points = points || [];
  23149. this.closed = closed || false;
  23150. this.curveType = curveType || 'centripetal';
  23151. this.tension = tension || 0.5;
  23152. }
  23153. CatmullRomCurve3.prototype = Object.create(Curve.prototype);
  23154. CatmullRomCurve3.prototype.constructor = CatmullRomCurve3;
  23155. CatmullRomCurve3.prototype.isCatmullRomCurve3 = true;
  23156. CatmullRomCurve3.prototype.getPoint = function (t, optionalTarget) {
  23157. var point = optionalTarget || new Vector3();
  23158. var points = this.points;
  23159. var l = points.length;
  23160. var p = (l - (this.closed ? 0 : 1)) * t;
  23161. var intPoint = Math.floor(p);
  23162. var weight = p - intPoint;
  23163. if (this.closed) {
  23164. intPoint += intPoint > 0 ? 0 : (Math.floor(Math.abs(intPoint) / l) + 1) * l;
  23165. } else if (weight === 0 && intPoint === l - 1) {
  23166. intPoint = l - 2;
  23167. weight = 1;
  23168. }
  23169. var p0, p1, p2, p3; // 4 points
  23170. if (this.closed || intPoint > 0) {
  23171. p0 = points[(intPoint - 1) % l];
  23172. } else {
  23173. // extrapolate first point
  23174. tmp.subVectors(points[0], points[1]).add(points[0]);
  23175. p0 = tmp;
  23176. }
  23177. p1 = points[intPoint % l];
  23178. p2 = points[(intPoint + 1) % l];
  23179. if (this.closed || intPoint + 2 < l) {
  23180. p3 = points[(intPoint + 2) % l];
  23181. } else {
  23182. // extrapolate last point
  23183. tmp.subVectors(points[l - 1], points[l - 2]).add(points[l - 1]);
  23184. p3 = tmp;
  23185. }
  23186. if (this.curveType === 'centripetal' || this.curveType === 'chordal') {
  23187. // init Centripetal / Chordal Catmull-Rom
  23188. var pow = this.curveType === 'chordal' ? 0.5 : 0.25;
  23189. var dt0 = Math.pow(p0.distanceToSquared(p1), pow);
  23190. var dt1 = Math.pow(p1.distanceToSquared(p2), pow);
  23191. var dt2 = Math.pow(p2.distanceToSquared(p3), pow); // safety check for repeated points
  23192. if (dt1 < 1e-4) dt1 = 1.0;
  23193. if (dt0 < 1e-4) dt0 = dt1;
  23194. if (dt2 < 1e-4) dt2 = dt1;
  23195. px.initNonuniformCatmullRom(p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2);
  23196. py.initNonuniformCatmullRom(p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2);
  23197. pz.initNonuniformCatmullRom(p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2);
  23198. } else if (this.curveType === 'catmullrom') {
  23199. px.initCatmullRom(p0.x, p1.x, p2.x, p3.x, this.tension);
  23200. py.initCatmullRom(p0.y, p1.y, p2.y, p3.y, this.tension);
  23201. pz.initCatmullRom(p0.z, p1.z, p2.z, p3.z, this.tension);
  23202. }
  23203. point.set(px.calc(weight), py.calc(weight), pz.calc(weight));
  23204. return point;
  23205. };
  23206. CatmullRomCurve3.prototype.copy = function (source) {
  23207. Curve.prototype.copy.call(this, source);
  23208. this.points = [];
  23209. for (var i = 0, l = source.points.length; i < l; i++) {
  23210. var point = source.points[i];
  23211. this.points.push(point.clone());
  23212. }
  23213. this.closed = source.closed;
  23214. this.curveType = source.curveType;
  23215. this.tension = source.tension;
  23216. return this;
  23217. };
  23218. CatmullRomCurve3.prototype.toJSON = function () {
  23219. var data = Curve.prototype.toJSON.call(this);
  23220. data.points = [];
  23221. for (var i = 0, l = this.points.length; i < l; i++) {
  23222. var point = this.points[i];
  23223. data.points.push(point.toArray());
  23224. }
  23225. data.closed = this.closed;
  23226. data.curveType = this.curveType;
  23227. data.tension = this.tension;
  23228. return data;
  23229. };
  23230. CatmullRomCurve3.prototype.fromJSON = function (json) {
  23231. Curve.prototype.fromJSON.call(this, json);
  23232. this.points = [];
  23233. for (var i = 0, l = json.points.length; i < l; i++) {
  23234. var point = json.points[i];
  23235. this.points.push(new Vector3().fromArray(point));
  23236. }
  23237. this.closed = json.closed;
  23238. this.curveType = json.curveType;
  23239. this.tension = json.tension;
  23240. return this;
  23241. };
  23242. /**
  23243. * @author zz85 / http://www.lab4games.net/zz85/blog
  23244. *
  23245. * Bezier Curves formulas obtained from
  23246. * http://en.wikipedia.org/wiki/Bézier_curve
  23247. */
  23248. function CatmullRom(t, p0, p1, p2, p3) {
  23249. var v0 = (p2 - p0) * 0.5;
  23250. var v1 = (p3 - p1) * 0.5;
  23251. var t2 = t * t;
  23252. var t3 = t * t2;
  23253. return (2 * p1 - 2 * p2 + v0 + v1) * t3 + (-3 * p1 + 3 * p2 - 2 * v0 - v1) * t2 + v0 * t + p1;
  23254. } //
  23255. function QuadraticBezierP0(t, p) {
  23256. var k = 1 - t;
  23257. return k * k * p;
  23258. }
  23259. function QuadraticBezierP1(t, p) {
  23260. return 2 * (1 - t) * t * p;
  23261. }
  23262. function QuadraticBezierP2(t, p) {
  23263. return t * t * p;
  23264. }
  23265. function QuadraticBezier(t, p0, p1, p2) {
  23266. return QuadraticBezierP0(t, p0) + QuadraticBezierP1(t, p1) + QuadraticBezierP2(t, p2);
  23267. } //
  23268. function CubicBezierP0(t, p) {
  23269. var k = 1 - t;
  23270. return k * k * k * p;
  23271. }
  23272. function CubicBezierP1(t, p) {
  23273. var k = 1 - t;
  23274. return 3 * k * k * t * p;
  23275. }
  23276. function CubicBezierP2(t, p) {
  23277. return 3 * (1 - t) * t * t * p;
  23278. }
  23279. function CubicBezierP3(t, p) {
  23280. return t * t * t * p;
  23281. }
  23282. function CubicBezier(t, p0, p1, p2, p3) {
  23283. return CubicBezierP0(t, p0) + CubicBezierP1(t, p1) + CubicBezierP2(t, p2) + CubicBezierP3(t, p3);
  23284. }
  23285. function CubicBezierCurve(v0, v1, v2, v3) {
  23286. Curve.call(this);
  23287. this.type = 'CubicBezierCurve';
  23288. this.v0 = v0 || new Vector2();
  23289. this.v1 = v1 || new Vector2();
  23290. this.v2 = v2 || new Vector2();
  23291. this.v3 = v3 || new Vector2();
  23292. }
  23293. CubicBezierCurve.prototype = Object.create(Curve.prototype);
  23294. CubicBezierCurve.prototype.constructor = CubicBezierCurve;
  23295. CubicBezierCurve.prototype.isCubicBezierCurve = true;
  23296. CubicBezierCurve.prototype.getPoint = function (t, optionalTarget) {
  23297. var point = optionalTarget || new Vector2();
  23298. var v0 = this.v0,
  23299. v1 = this.v1,
  23300. v2 = this.v2,
  23301. v3 = this.v3;
  23302. point.set(CubicBezier(t, v0.x, v1.x, v2.x, v3.x), CubicBezier(t, v0.y, v1.y, v2.y, v3.y));
  23303. return point;
  23304. };
  23305. CubicBezierCurve.prototype.copy = function (source) {
  23306. Curve.prototype.copy.call(this, source);
  23307. this.v0.copy(source.v0);
  23308. this.v1.copy(source.v1);
  23309. this.v2.copy(source.v2);
  23310. this.v3.copy(source.v3);
  23311. return this;
  23312. };
  23313. CubicBezierCurve.prototype.toJSON = function () {
  23314. var data = Curve.prototype.toJSON.call(this);
  23315. data.v0 = this.v0.toArray();
  23316. data.v1 = this.v1.toArray();
  23317. data.v2 = this.v2.toArray();
  23318. data.v3 = this.v3.toArray();
  23319. return data;
  23320. };
  23321. CubicBezierCurve.prototype.fromJSON = function (json) {
  23322. Curve.prototype.fromJSON.call(this, json);
  23323. this.v0.fromArray(json.v0);
  23324. this.v1.fromArray(json.v1);
  23325. this.v2.fromArray(json.v2);
  23326. this.v3.fromArray(json.v3);
  23327. return this;
  23328. };
  23329. function CubicBezierCurve3(v0, v1, v2, v3) {
  23330. Curve.call(this);
  23331. this.type = 'CubicBezierCurve3';
  23332. this.v0 = v0 || new Vector3();
  23333. this.v1 = v1 || new Vector3();
  23334. this.v2 = v2 || new Vector3();
  23335. this.v3 = v3 || new Vector3();
  23336. }
  23337. CubicBezierCurve3.prototype = Object.create(Curve.prototype);
  23338. CubicBezierCurve3.prototype.constructor = CubicBezierCurve3;
  23339. CubicBezierCurve3.prototype.isCubicBezierCurve3 = true;
  23340. CubicBezierCurve3.prototype.getPoint = function (t, optionalTarget) {
  23341. var point = optionalTarget || new Vector3();
  23342. var v0 = this.v0,
  23343. v1 = this.v1,
  23344. v2 = this.v2,
  23345. v3 = this.v3;
  23346. 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));
  23347. return point;
  23348. };
  23349. CubicBezierCurve3.prototype.copy = function (source) {
  23350. Curve.prototype.copy.call(this, source);
  23351. this.v0.copy(source.v0);
  23352. this.v1.copy(source.v1);
  23353. this.v2.copy(source.v2);
  23354. this.v3.copy(source.v3);
  23355. return this;
  23356. };
  23357. CubicBezierCurve3.prototype.toJSON = function () {
  23358. var data = Curve.prototype.toJSON.call(this);
  23359. data.v0 = this.v0.toArray();
  23360. data.v1 = this.v1.toArray();
  23361. data.v2 = this.v2.toArray();
  23362. data.v3 = this.v3.toArray();
  23363. return data;
  23364. };
  23365. CubicBezierCurve3.prototype.fromJSON = function (json) {
  23366. Curve.prototype.fromJSON.call(this, json);
  23367. this.v0.fromArray(json.v0);
  23368. this.v1.fromArray(json.v1);
  23369. this.v2.fromArray(json.v2);
  23370. this.v3.fromArray(json.v3);
  23371. return this;
  23372. };
  23373. function LineCurve(v1, v2) {
  23374. Curve.call(this);
  23375. this.type = 'LineCurve';
  23376. this.v1 = v1 || new Vector2();
  23377. this.v2 = v2 || new Vector2();
  23378. }
  23379. LineCurve.prototype = Object.create(Curve.prototype);
  23380. LineCurve.prototype.constructor = LineCurve;
  23381. LineCurve.prototype.isLineCurve = true;
  23382. LineCurve.prototype.getPoint = function (t, optionalTarget) {
  23383. var point = optionalTarget || new Vector2();
  23384. if (t === 1) {
  23385. point.copy(this.v2);
  23386. } else {
  23387. point.copy(this.v2).sub(this.v1);
  23388. point.multiplyScalar(t).add(this.v1);
  23389. }
  23390. return point;
  23391. }; // Line curve is linear, so we can overwrite default getPointAt
  23392. LineCurve.prototype.getPointAt = function (u, optionalTarget) {
  23393. return this.getPoint(u, optionalTarget);
  23394. };
  23395. LineCurve.prototype.getTangent = function ()
  23396. /* t */
  23397. {
  23398. var tangent = this.v2.clone().sub(this.v1);
  23399. return tangent.normalize();
  23400. };
  23401. LineCurve.prototype.copy = function (source) {
  23402. Curve.prototype.copy.call(this, source);
  23403. this.v1.copy(source.v1);
  23404. this.v2.copy(source.v2);
  23405. return this;
  23406. };
  23407. LineCurve.prototype.toJSON = function () {
  23408. var data = Curve.prototype.toJSON.call(this);
  23409. data.v1 = this.v1.toArray();
  23410. data.v2 = this.v2.toArray();
  23411. return data;
  23412. };
  23413. LineCurve.prototype.fromJSON = function (json) {
  23414. Curve.prototype.fromJSON.call(this, json);
  23415. this.v1.fromArray(json.v1);
  23416. this.v2.fromArray(json.v2);
  23417. return this;
  23418. };
  23419. function LineCurve3(v1, v2) {
  23420. Curve.call(this);
  23421. this.type = 'LineCurve3';
  23422. this.v1 = v1 || new Vector3();
  23423. this.v2 = v2 || new Vector3();
  23424. }
  23425. LineCurve3.prototype = Object.create(Curve.prototype);
  23426. LineCurve3.prototype.constructor = LineCurve3;
  23427. LineCurve3.prototype.isLineCurve3 = true;
  23428. LineCurve3.prototype.getPoint = function (t, optionalTarget) {
  23429. var point = optionalTarget || new Vector3();
  23430. if (t === 1) {
  23431. point.copy(this.v2);
  23432. } else {
  23433. point.copy(this.v2).sub(this.v1);
  23434. point.multiplyScalar(t).add(this.v1);
  23435. }
  23436. return point;
  23437. }; // Line curve is linear, so we can overwrite default getPointAt
  23438. LineCurve3.prototype.getPointAt = function (u, optionalTarget) {
  23439. return this.getPoint(u, optionalTarget);
  23440. };
  23441. LineCurve3.prototype.copy = function (source) {
  23442. Curve.prototype.copy.call(this, source);
  23443. this.v1.copy(source.v1);
  23444. this.v2.copy(source.v2);
  23445. return this;
  23446. };
  23447. LineCurve3.prototype.toJSON = function () {
  23448. var data = Curve.prototype.toJSON.call(this);
  23449. data.v1 = this.v1.toArray();
  23450. data.v2 = this.v2.toArray();
  23451. return data;
  23452. };
  23453. LineCurve3.prototype.fromJSON = function (json) {
  23454. Curve.prototype.fromJSON.call(this, json);
  23455. this.v1.fromArray(json.v1);
  23456. this.v2.fromArray(json.v2);
  23457. return this;
  23458. };
  23459. function QuadraticBezierCurve(v0, v1, v2) {
  23460. Curve.call(this);
  23461. this.type = 'QuadraticBezierCurve';
  23462. this.v0 = v0 || new Vector2();
  23463. this.v1 = v1 || new Vector2();
  23464. this.v2 = v2 || new Vector2();
  23465. }
  23466. QuadraticBezierCurve.prototype = Object.create(Curve.prototype);
  23467. QuadraticBezierCurve.prototype.constructor = QuadraticBezierCurve;
  23468. QuadraticBezierCurve.prototype.isQuadraticBezierCurve = true;
  23469. QuadraticBezierCurve.prototype.getPoint = function (t, optionalTarget) {
  23470. var point = optionalTarget || new Vector2();
  23471. var v0 = this.v0,
  23472. v1 = this.v1,
  23473. v2 = this.v2;
  23474. point.set(QuadraticBezier(t, v0.x, v1.x, v2.x), QuadraticBezier(t, v0.y, v1.y, v2.y));
  23475. return point;
  23476. };
  23477. QuadraticBezierCurve.prototype.copy = function (source) {
  23478. Curve.prototype.copy.call(this, source);
  23479. this.v0.copy(source.v0);
  23480. this.v1.copy(source.v1);
  23481. this.v2.copy(source.v2);
  23482. return this;
  23483. };
  23484. QuadraticBezierCurve.prototype.toJSON = function () {
  23485. var data = Curve.prototype.toJSON.call(this);
  23486. data.v0 = this.v0.toArray();
  23487. data.v1 = this.v1.toArray();
  23488. data.v2 = this.v2.toArray();
  23489. return data;
  23490. };
  23491. QuadraticBezierCurve.prototype.fromJSON = function (json) {
  23492. Curve.prototype.fromJSON.call(this, json);
  23493. this.v0.fromArray(json.v0);
  23494. this.v1.fromArray(json.v1);
  23495. this.v2.fromArray(json.v2);
  23496. return this;
  23497. };
  23498. function QuadraticBezierCurve3(v0, v1, v2) {
  23499. Curve.call(this);
  23500. this.type = 'QuadraticBezierCurve3';
  23501. this.v0 = v0 || new Vector3();
  23502. this.v1 = v1 || new Vector3();
  23503. this.v2 = v2 || new Vector3();
  23504. }
  23505. QuadraticBezierCurve3.prototype = Object.create(Curve.prototype);
  23506. QuadraticBezierCurve3.prototype.constructor = QuadraticBezierCurve3;
  23507. QuadraticBezierCurve3.prototype.isQuadraticBezierCurve3 = true;
  23508. QuadraticBezierCurve3.prototype.getPoint = function (t, optionalTarget) {
  23509. var point = optionalTarget || new Vector3();
  23510. var v0 = this.v0,
  23511. v1 = this.v1,
  23512. v2 = this.v2;
  23513. 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));
  23514. return point;
  23515. };
  23516. QuadraticBezierCurve3.prototype.copy = function (source) {
  23517. Curve.prototype.copy.call(this, source);
  23518. this.v0.copy(source.v0);
  23519. this.v1.copy(source.v1);
  23520. this.v2.copy(source.v2);
  23521. return this;
  23522. };
  23523. QuadraticBezierCurve3.prototype.toJSON = function () {
  23524. var data = Curve.prototype.toJSON.call(this);
  23525. data.v0 = this.v0.toArray();
  23526. data.v1 = this.v1.toArray();
  23527. data.v2 = this.v2.toArray();
  23528. return data;
  23529. };
  23530. QuadraticBezierCurve3.prototype.fromJSON = function (json) {
  23531. Curve.prototype.fromJSON.call(this, json);
  23532. this.v0.fromArray(json.v0);
  23533. this.v1.fromArray(json.v1);
  23534. this.v2.fromArray(json.v2);
  23535. return this;
  23536. };
  23537. function SplineCurve(points
  23538. /* array of Vector2 */
  23539. ) {
  23540. Curve.call(this);
  23541. this.type = 'SplineCurve';
  23542. this.points = points || [];
  23543. }
  23544. SplineCurve.prototype = Object.create(Curve.prototype);
  23545. SplineCurve.prototype.constructor = SplineCurve;
  23546. SplineCurve.prototype.isSplineCurve = true;
  23547. SplineCurve.prototype.getPoint = function (t, optionalTarget) {
  23548. var point = optionalTarget || new Vector2();
  23549. var points = this.points;
  23550. var p = (points.length - 1) * t;
  23551. var intPoint = Math.floor(p);
  23552. var weight = p - intPoint;
  23553. var p0 = points[intPoint === 0 ? intPoint : intPoint - 1];
  23554. var p1 = points[intPoint];
  23555. var p2 = points[intPoint > points.length - 2 ? points.length - 1 : intPoint + 1];
  23556. var p3 = points[intPoint > points.length - 3 ? points.length - 1 : intPoint + 2];
  23557. point.set(CatmullRom(weight, p0.x, p1.x, p2.x, p3.x), CatmullRom(weight, p0.y, p1.y, p2.y, p3.y));
  23558. return point;
  23559. };
  23560. SplineCurve.prototype.copy = function (source) {
  23561. Curve.prototype.copy.call(this, source);
  23562. this.points = [];
  23563. for (var i = 0, l = source.points.length; i < l; i++) {
  23564. var point = source.points[i];
  23565. this.points.push(point.clone());
  23566. }
  23567. return this;
  23568. };
  23569. SplineCurve.prototype.toJSON = function () {
  23570. var data = Curve.prototype.toJSON.call(this);
  23571. data.points = [];
  23572. for (var i = 0, l = this.points.length; i < l; i++) {
  23573. var point = this.points[i];
  23574. data.points.push(point.toArray());
  23575. }
  23576. return data;
  23577. };
  23578. SplineCurve.prototype.fromJSON = function (json) {
  23579. Curve.prototype.fromJSON.call(this, json);
  23580. this.points = [];
  23581. for (var i = 0, l = json.points.length; i < l; i++) {
  23582. var point = json.points[i];
  23583. this.points.push(new Vector2().fromArray(point));
  23584. }
  23585. return this;
  23586. };
  23587. var Curves =
  23588. /*#__PURE__*/
  23589. Object.freeze({
  23590. ArcCurve: ArcCurve,
  23591. CatmullRomCurve3: CatmullRomCurve3,
  23592. CubicBezierCurve: CubicBezierCurve,
  23593. CubicBezierCurve3: CubicBezierCurve3,
  23594. EllipseCurve: EllipseCurve,
  23595. LineCurve: LineCurve,
  23596. LineCurve3: LineCurve3,
  23597. QuadraticBezierCurve: QuadraticBezierCurve,
  23598. QuadraticBezierCurve3: QuadraticBezierCurve3,
  23599. SplineCurve: SplineCurve
  23600. });
  23601. /**
  23602. * @author zz85 / http://www.lab4games.net/zz85/blog
  23603. *
  23604. **/
  23605. /**************************************************************
  23606. * Curved Path - a curve path is simply a array of connected
  23607. * curves, but retains the api of a curve
  23608. **************************************************************/
  23609. function CurvePath() {
  23610. Curve.call(this);
  23611. this.type = 'CurvePath';
  23612. this.curves = [];
  23613. this.autoClose = false; // Automatically closes the path
  23614. }
  23615. CurvePath.prototype = Object.assign(Object.create(Curve.prototype), {
  23616. constructor: CurvePath,
  23617. add: function (curve) {
  23618. this.curves.push(curve);
  23619. },
  23620. closePath: function () {
  23621. // Add a line curve if start and end of lines are not connected
  23622. var startPoint = this.curves[0].getPoint(0);
  23623. var endPoint = this.curves[this.curves.length - 1].getPoint(1);
  23624. if (!startPoint.equals(endPoint)) {
  23625. this.curves.push(new LineCurve(endPoint, startPoint));
  23626. }
  23627. },
  23628. // To get accurate point with reference to
  23629. // entire path distance at time t,
  23630. // following has to be done:
  23631. // 1. Length of each sub path have to be known
  23632. // 2. Locate and identify type of curve
  23633. // 3. Get t for the curve
  23634. // 4. Return curve.getPointAt(t')
  23635. getPoint: function (t) {
  23636. var d = t * this.getLength();
  23637. var curveLengths = this.getCurveLengths();
  23638. var i = 0; // To think about boundaries points.
  23639. while (i < curveLengths.length) {
  23640. if (curveLengths[i] >= d) {
  23641. var diff = curveLengths[i] - d;
  23642. var curve = this.curves[i];
  23643. var segmentLength = curve.getLength();
  23644. var u = segmentLength === 0 ? 0 : 1 - diff / segmentLength;
  23645. return curve.getPointAt(u);
  23646. }
  23647. i++;
  23648. }
  23649. return null; // loop where sum != 0, sum > d , sum+1 <d
  23650. },
  23651. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  23652. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  23653. // getPoint() depends on getLength
  23654. getLength: function () {
  23655. var lens = this.getCurveLengths();
  23656. return lens[lens.length - 1];
  23657. },
  23658. // cacheLengths must be recalculated.
  23659. updateArcLengths: function () {
  23660. this.needsUpdate = true;
  23661. this.cacheLengths = null;
  23662. this.getCurveLengths();
  23663. },
  23664. // Compute lengths and cache them
  23665. // We cannot overwrite getLengths() because UtoT mapping uses it.
  23666. getCurveLengths: function () {
  23667. // We use cache values if curves and cache array are same length
  23668. if (this.cacheLengths && this.cacheLengths.length === this.curves.length) {
  23669. return this.cacheLengths;
  23670. } // Get length of sub-curve
  23671. // Push sums into cached array
  23672. var lengths = [],
  23673. sums = 0;
  23674. for (var i = 0, l = this.curves.length; i < l; i++) {
  23675. sums += this.curves[i].getLength();
  23676. lengths.push(sums);
  23677. }
  23678. this.cacheLengths = lengths;
  23679. return lengths;
  23680. },
  23681. getSpacedPoints: function (divisions) {
  23682. if (divisions === undefined) divisions = 40;
  23683. var points = [];
  23684. for (var i = 0; i <= divisions; i++) {
  23685. points.push(this.getPoint(i / divisions));
  23686. }
  23687. if (this.autoClose) {
  23688. points.push(points[0]);
  23689. }
  23690. return points;
  23691. },
  23692. getPoints: function (divisions) {
  23693. divisions = divisions || 12;
  23694. var points = [],
  23695. last;
  23696. for (var i = 0, curves = this.curves; i < curves.length; i++) {
  23697. var curve = curves[i];
  23698. var resolution = curve && curve.isEllipseCurve ? divisions * 2 : curve && (curve.isLineCurve || curve.isLineCurve3) ? 1 : curve && curve.isSplineCurve ? divisions * curve.points.length : divisions;
  23699. var pts = curve.getPoints(resolution);
  23700. for (var j = 0; j < pts.length; j++) {
  23701. var point = pts[j];
  23702. if (last && last.equals(point)) continue; // ensures no consecutive points are duplicates
  23703. points.push(point);
  23704. last = point;
  23705. }
  23706. }
  23707. if (this.autoClose && points.length > 1 && !points[points.length - 1].equals(points[0])) {
  23708. points.push(points[0]);
  23709. }
  23710. return points;
  23711. },
  23712. copy: function (source) {
  23713. Curve.prototype.copy.call(this, source);
  23714. this.curves = [];
  23715. for (var i = 0, l = source.curves.length; i < l; i++) {
  23716. var curve = source.curves[i];
  23717. this.curves.push(curve.clone());
  23718. }
  23719. this.autoClose = source.autoClose;
  23720. return this;
  23721. },
  23722. toJSON: function () {
  23723. var data = Curve.prototype.toJSON.call(this);
  23724. data.autoClose = this.autoClose;
  23725. data.curves = [];
  23726. for (var i = 0, l = this.curves.length; i < l; i++) {
  23727. var curve = this.curves[i];
  23728. data.curves.push(curve.toJSON());
  23729. }
  23730. return data;
  23731. },
  23732. fromJSON: function (json) {
  23733. Curve.prototype.fromJSON.call(this, json);
  23734. this.autoClose = json.autoClose;
  23735. this.curves = [];
  23736. for (var i = 0, l = json.curves.length; i < l; i++) {
  23737. var curve = json.curves[i];
  23738. this.curves.push(new Curves[curve.type]().fromJSON(curve));
  23739. }
  23740. return this;
  23741. }
  23742. });
  23743. /**
  23744. * @author zz85 / http://www.lab4games.net/zz85/blog
  23745. * Creates free form 2d path using series of points, lines or curves.
  23746. **/
  23747. function Path(points) {
  23748. CurvePath.call(this);
  23749. this.type = 'Path';
  23750. this.currentPoint = new Vector2();
  23751. if (points) {
  23752. this.setFromPoints(points);
  23753. }
  23754. }
  23755. Path.prototype = Object.assign(Object.create(CurvePath.prototype), {
  23756. constructor: Path,
  23757. setFromPoints: function (points) {
  23758. this.moveTo(points[0].x, points[0].y);
  23759. for (var i = 1, l = points.length; i < l; i++) {
  23760. this.lineTo(points[i].x, points[i].y);
  23761. }
  23762. },
  23763. moveTo: function (x, y) {
  23764. this.currentPoint.set(x, y); // TODO consider referencing vectors instead of copying?
  23765. },
  23766. lineTo: function (x, y) {
  23767. var curve = new LineCurve(this.currentPoint.clone(), new Vector2(x, y));
  23768. this.curves.push(curve);
  23769. this.currentPoint.set(x, y);
  23770. },
  23771. quadraticCurveTo: function (aCPx, aCPy, aX, aY) {
  23772. var curve = new QuadraticBezierCurve(this.currentPoint.clone(), new Vector2(aCPx, aCPy), new Vector2(aX, aY));
  23773. this.curves.push(curve);
  23774. this.currentPoint.set(aX, aY);
  23775. },
  23776. bezierCurveTo: function (aCP1x, aCP1y, aCP2x, aCP2y, aX, aY) {
  23777. var curve = new CubicBezierCurve(this.currentPoint.clone(), new Vector2(aCP1x, aCP1y), new Vector2(aCP2x, aCP2y), new Vector2(aX, aY));
  23778. this.curves.push(curve);
  23779. this.currentPoint.set(aX, aY);
  23780. },
  23781. splineThru: function (pts
  23782. /*Array of Vector*/
  23783. ) {
  23784. var npts = [this.currentPoint.clone()].concat(pts);
  23785. var curve = new SplineCurve(npts);
  23786. this.curves.push(curve);
  23787. this.currentPoint.copy(pts[pts.length - 1]);
  23788. },
  23789. arc: function (aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise) {
  23790. var x0 = this.currentPoint.x;
  23791. var y0 = this.currentPoint.y;
  23792. this.absarc(aX + x0, aY + y0, aRadius, aStartAngle, aEndAngle, aClockwise);
  23793. },
  23794. absarc: function (aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise) {
  23795. this.absellipse(aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise);
  23796. },
  23797. ellipse: function (aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation) {
  23798. var x0 = this.currentPoint.x;
  23799. var y0 = this.currentPoint.y;
  23800. this.absellipse(aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation);
  23801. },
  23802. absellipse: function (aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation) {
  23803. var curve = new EllipseCurve(aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation);
  23804. if (this.curves.length > 0) {
  23805. // if a previous curve is present, attempt to join
  23806. var firstPoint = curve.getPoint(0);
  23807. if (!firstPoint.equals(this.currentPoint)) {
  23808. this.lineTo(firstPoint.x, firstPoint.y);
  23809. }
  23810. }
  23811. this.curves.push(curve);
  23812. var lastPoint = curve.getPoint(1);
  23813. this.currentPoint.copy(lastPoint);
  23814. },
  23815. copy: function (source) {
  23816. CurvePath.prototype.copy.call(this, source);
  23817. this.currentPoint.copy(source.currentPoint);
  23818. return this;
  23819. },
  23820. toJSON: function () {
  23821. var data = CurvePath.prototype.toJSON.call(this);
  23822. data.currentPoint = this.currentPoint.toArray();
  23823. return data;
  23824. },
  23825. fromJSON: function (json) {
  23826. CurvePath.prototype.fromJSON.call(this, json);
  23827. this.currentPoint.fromArray(json.currentPoint);
  23828. return this;
  23829. }
  23830. });
  23831. /**
  23832. * @author zz85 / http://www.lab4games.net/zz85/blog
  23833. * Defines a 2d shape plane using paths.
  23834. **/
  23835. // STEP 1 Create a path.
  23836. // STEP 2 Turn path into shape.
  23837. // STEP 3 ExtrudeGeometry takes in Shape/Shapes
  23838. // STEP 3a - Extract points from each shape, turn to vertices
  23839. // STEP 3b - Triangulate each shape, add faces.
  23840. function Shape(points) {
  23841. Path.call(this, points);
  23842. this.uuid = _Math.generateUUID();
  23843. this.type = 'Shape';
  23844. this.holes = [];
  23845. }
  23846. Shape.prototype = Object.assign(Object.create(Path.prototype), {
  23847. constructor: Shape,
  23848. getPointsHoles: function (divisions) {
  23849. var holesPts = [];
  23850. for (var i = 0, l = this.holes.length; i < l; i++) {
  23851. holesPts[i] = this.holes[i].getPoints(divisions);
  23852. }
  23853. return holesPts;
  23854. },
  23855. // get points of shape and holes (keypoints based on segments parameter)
  23856. extractPoints: function (divisions) {
  23857. return {
  23858. shape: this.getPoints(divisions),
  23859. holes: this.getPointsHoles(divisions)
  23860. };
  23861. },
  23862. copy: function (source) {
  23863. Path.prototype.copy.call(this, source);
  23864. this.holes = [];
  23865. for (var i = 0, l = source.holes.length; i < l; i++) {
  23866. var hole = source.holes[i];
  23867. this.holes.push(hole.clone());
  23868. }
  23869. return this;
  23870. },
  23871. toJSON: function () {
  23872. var data = Path.prototype.toJSON.call(this);
  23873. data.uuid = this.uuid;
  23874. data.holes = [];
  23875. for (var i = 0, l = this.holes.length; i < l; i++) {
  23876. var hole = this.holes[i];
  23877. data.holes.push(hole.toJSON());
  23878. }
  23879. return data;
  23880. },
  23881. fromJSON: function (json) {
  23882. Path.prototype.fromJSON.call(this, json);
  23883. this.uuid = json.uuid;
  23884. this.holes = [];
  23885. for (var i = 0, l = json.holes.length; i < l; i++) {
  23886. var hole = json.holes[i];
  23887. this.holes.push(new Path().fromJSON(hole));
  23888. }
  23889. return this;
  23890. }
  23891. });
  23892. /**
  23893. * @author mrdoob / http://mrdoob.com/
  23894. * @author alteredq / http://alteredqualia.com/
  23895. */
  23896. function Light(color, intensity) {
  23897. Object3D.call(this);
  23898. this.type = 'Light';
  23899. this.color = new Color(color);
  23900. this.intensity = intensity !== undefined ? intensity : 1;
  23901. this.receiveShadow = undefined;
  23902. }
  23903. Light.prototype = Object.assign(Object.create(Object3D.prototype), {
  23904. constructor: Light,
  23905. isLight: true,
  23906. copy: function (source) {
  23907. Object3D.prototype.copy.call(this, source);
  23908. this.color.copy(source.color);
  23909. this.intensity = source.intensity;
  23910. return this;
  23911. },
  23912. toJSON: function (meta) {
  23913. var data = Object3D.prototype.toJSON.call(this, meta);
  23914. data.object.color = this.color.getHex();
  23915. data.object.intensity = this.intensity;
  23916. if (this.groundColor !== undefined) data.object.groundColor = this.groundColor.getHex();
  23917. if (this.distance !== undefined) data.object.distance = this.distance;
  23918. if (this.angle !== undefined) data.object.angle = this.angle;
  23919. if (this.decay !== undefined) data.object.decay = this.decay;
  23920. if (this.penumbra !== undefined) data.object.penumbra = this.penumbra;
  23921. if (this.shadow !== undefined) data.object.shadow = this.shadow.toJSON();
  23922. return data;
  23923. }
  23924. });
  23925. /**
  23926. * @author alteredq / http://alteredqualia.com/
  23927. */
  23928. function HemisphereLight(skyColor, groundColor, intensity) {
  23929. Light.call(this, skyColor, intensity);
  23930. this.type = 'HemisphereLight';
  23931. this.castShadow = undefined;
  23932. this.position.copy(Object3D.DefaultUp);
  23933. this.updateMatrix();
  23934. this.groundColor = new Color(groundColor);
  23935. }
  23936. HemisphereLight.prototype = Object.assign(Object.create(Light.prototype), {
  23937. constructor: HemisphereLight,
  23938. isHemisphereLight: true,
  23939. copy: function (source) {
  23940. Light.prototype.copy.call(this, source);
  23941. this.groundColor.copy(source.groundColor);
  23942. return this;
  23943. }
  23944. });
  23945. /**
  23946. * @author mrdoob / http://mrdoob.com/
  23947. */
  23948. function LightShadow(camera) {
  23949. this.camera = camera;
  23950. this.bias = 0;
  23951. this.radius = 1;
  23952. this.mapSize = new Vector2(512, 512);
  23953. this.map = null;
  23954. this.mapPass = null;
  23955. this.matrix = new Matrix4();
  23956. this._frustum = new Frustum();
  23957. this._frameExtents = new Vector2(1, 1);
  23958. this._viewportCount = 1;
  23959. this._viewports = [new Vector4(0, 0, 1, 1)];
  23960. }
  23961. Object.assign(LightShadow.prototype, {
  23962. _projScreenMatrix: new Matrix4(),
  23963. _lightPositionWorld: new Vector3(),
  23964. _lookTarget: new Vector3(),
  23965. getViewportCount: function () {
  23966. return this._viewportCount;
  23967. },
  23968. getFrustum: function () {
  23969. return this._frustum;
  23970. },
  23971. updateMatrices: function (light) {
  23972. var shadowCamera = this.camera,
  23973. shadowMatrix = this.matrix,
  23974. projScreenMatrix = this._projScreenMatrix,
  23975. lookTarget = this._lookTarget,
  23976. lightPositionWorld = this._lightPositionWorld;
  23977. lightPositionWorld.setFromMatrixPosition(light.matrixWorld);
  23978. shadowCamera.position.copy(lightPositionWorld);
  23979. lookTarget.setFromMatrixPosition(light.target.matrixWorld);
  23980. shadowCamera.lookAt(lookTarget);
  23981. shadowCamera.updateMatrixWorld();
  23982. projScreenMatrix.multiplyMatrices(shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse);
  23983. this._frustum.setFromMatrix(projScreenMatrix);
  23984. 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);
  23985. shadowMatrix.multiply(shadowCamera.projectionMatrix);
  23986. shadowMatrix.multiply(shadowCamera.matrixWorldInverse);
  23987. },
  23988. getViewport: function (viewportIndex) {
  23989. return this._viewports[viewportIndex];
  23990. },
  23991. getFrameExtents: function () {
  23992. return this._frameExtents;
  23993. },
  23994. copy: function (source) {
  23995. this.camera = source.camera.clone();
  23996. this.bias = source.bias;
  23997. this.radius = source.radius;
  23998. this.mapSize.copy(source.mapSize);
  23999. return this;
  24000. },
  24001. clone: function () {
  24002. return new this.constructor().copy(this);
  24003. },
  24004. toJSON: function () {
  24005. var object = {};
  24006. if (this.bias !== 0) object.bias = this.bias;
  24007. if (this.radius !== 1) object.radius = this.radius;
  24008. if (this.mapSize.x !== 512 || this.mapSize.y !== 512) object.mapSize = this.mapSize.toArray();
  24009. object.camera = this.camera.toJSON(false).object;
  24010. delete object.camera.matrix;
  24011. return object;
  24012. }
  24013. });
  24014. /**
  24015. * @author mrdoob / http://mrdoob.com/
  24016. */
  24017. function SpotLightShadow() {
  24018. LightShadow.call(this, new PerspectiveCamera(50, 1, 0.5, 500));
  24019. }
  24020. SpotLightShadow.prototype = Object.assign(Object.create(LightShadow.prototype), {
  24021. constructor: SpotLightShadow,
  24022. isSpotLightShadow: true,
  24023. updateMatrices: function (light, viewCamera, viewportIndex) {
  24024. var camera = this.camera;
  24025. var fov = _Math.RAD2DEG * 2 * light.angle;
  24026. var aspect = this.mapSize.width / this.mapSize.height;
  24027. var far = light.distance || camera.far;
  24028. if (fov !== camera.fov || aspect !== camera.aspect || far !== camera.far) {
  24029. camera.fov = fov;
  24030. camera.aspect = aspect;
  24031. camera.far = far;
  24032. camera.updateProjectionMatrix();
  24033. }
  24034. LightShadow.prototype.updateMatrices.call(this, light, viewCamera, viewportIndex);
  24035. }
  24036. });
  24037. /**
  24038. * @author alteredq / http://alteredqualia.com/
  24039. */
  24040. function SpotLight(color, intensity, distance, angle, penumbra, decay) {
  24041. Light.call(this, color, intensity);
  24042. this.type = 'SpotLight';
  24043. this.position.copy(Object3D.DefaultUp);
  24044. this.updateMatrix();
  24045. this.target = new Object3D();
  24046. Object.defineProperty(this, 'power', {
  24047. get: function () {
  24048. // intensity = power per solid angle.
  24049. // ref: equation (17) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  24050. return this.intensity * Math.PI;
  24051. },
  24052. set: function (power) {
  24053. // intensity = power per solid angle.
  24054. // ref: equation (17) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  24055. this.intensity = power / Math.PI;
  24056. }
  24057. });
  24058. this.distance = distance !== undefined ? distance : 0;
  24059. this.angle = angle !== undefined ? angle : Math.PI / 3;
  24060. this.penumbra = penumbra !== undefined ? penumbra : 0;
  24061. this.decay = decay !== undefined ? decay : 1; // for physically correct lights, should be 2.
  24062. this.shadow = new SpotLightShadow();
  24063. }
  24064. SpotLight.prototype = Object.assign(Object.create(Light.prototype), {
  24065. constructor: SpotLight,
  24066. isSpotLight: true,
  24067. copy: function (source) {
  24068. Light.prototype.copy.call(this, source);
  24069. this.distance = source.distance;
  24070. this.angle = source.angle;
  24071. this.penumbra = source.penumbra;
  24072. this.decay = source.decay;
  24073. this.target = source.target.clone();
  24074. this.shadow = source.shadow.clone();
  24075. return this;
  24076. }
  24077. });
  24078. function PointLightShadow() {
  24079. LightShadow.call(this, new PerspectiveCamera(90, 1, 0.5, 500));
  24080. this._frameExtents = new Vector2(4, 2);
  24081. this._viewportCount = 6;
  24082. this._viewports = [// These viewports map a cube-map onto a 2D texture with the
  24083. // following orientation:
  24084. //
  24085. // xzXZ
  24086. // y Y
  24087. //
  24088. // X - Positive x direction
  24089. // x - Negative x direction
  24090. // Y - Positive y direction
  24091. // y - Negative y direction
  24092. // Z - Positive z direction
  24093. // z - Negative z direction
  24094. // positive X
  24095. new Vector4(2, 1, 1, 1), // negative X
  24096. new Vector4(0, 1, 1, 1), // positive Z
  24097. new Vector4(3, 1, 1, 1), // negative Z
  24098. new Vector4(1, 1, 1, 1), // positive Y
  24099. new Vector4(3, 0, 1, 1), // negative Y
  24100. new Vector4(1, 0, 1, 1)];
  24101. 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)];
  24102. 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)];
  24103. }
  24104. PointLightShadow.prototype = Object.assign(Object.create(LightShadow.prototype), {
  24105. constructor: PointLightShadow,
  24106. isPointLightShadow: true,
  24107. updateMatrices: function (light, viewCamera, viewportIndex) {
  24108. var camera = this.camera,
  24109. shadowMatrix = this.matrix,
  24110. lightPositionWorld = this._lightPositionWorld,
  24111. lookTarget = this._lookTarget,
  24112. projScreenMatrix = this._projScreenMatrix;
  24113. lightPositionWorld.setFromMatrixPosition(light.matrixWorld);
  24114. camera.position.copy(lightPositionWorld);
  24115. lookTarget.copy(camera.position);
  24116. lookTarget.add(this._cubeDirections[viewportIndex]);
  24117. camera.up.copy(this._cubeUps[viewportIndex]);
  24118. camera.lookAt(lookTarget);
  24119. camera.updateMatrixWorld();
  24120. shadowMatrix.makeTranslation(-lightPositionWorld.x, -lightPositionWorld.y, -lightPositionWorld.z);
  24121. projScreenMatrix.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse);
  24122. this._frustum.setFromMatrix(projScreenMatrix);
  24123. }
  24124. });
  24125. /**
  24126. * @author mrdoob / http://mrdoob.com/
  24127. */
  24128. function PointLight(color, intensity, distance, decay) {
  24129. Light.call(this, color, intensity);
  24130. this.type = 'PointLight';
  24131. Object.defineProperty(this, 'power', {
  24132. get: function () {
  24133. // intensity = power per solid angle.
  24134. // ref: equation (15) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  24135. return this.intensity * 4 * Math.PI;
  24136. },
  24137. set: function (power) {
  24138. // intensity = power per solid angle.
  24139. // ref: equation (15) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  24140. this.intensity = power / (4 * Math.PI);
  24141. }
  24142. });
  24143. this.distance = distance !== undefined ? distance : 0;
  24144. this.decay = decay !== undefined ? decay : 1; // for physically correct lights, should be 2.
  24145. this.shadow = new PointLightShadow();
  24146. }
  24147. PointLight.prototype = Object.assign(Object.create(Light.prototype), {
  24148. constructor: PointLight,
  24149. isPointLight: true,
  24150. copy: function (source) {
  24151. Light.prototype.copy.call(this, source);
  24152. this.distance = source.distance;
  24153. this.decay = source.decay;
  24154. this.shadow = source.shadow.clone();
  24155. return this;
  24156. }
  24157. });
  24158. /**
  24159. * @author alteredq / http://alteredqualia.com/
  24160. * @author arose / http://github.com/arose
  24161. */
  24162. function OrthographicCamera(left, right, top, bottom, near, far) {
  24163. Camera.call(this);
  24164. this.type = 'OrthographicCamera';
  24165. this.zoom = 1;
  24166. this.view = null;
  24167. this.left = left !== undefined ? left : -1;
  24168. this.right = right !== undefined ? right : 1;
  24169. this.top = top !== undefined ? top : 1;
  24170. this.bottom = bottom !== undefined ? bottom : -1;
  24171. this.near = near !== undefined ? near : 0.1;
  24172. this.far = far !== undefined ? far : 2000;
  24173. this.updateProjectionMatrix();
  24174. }
  24175. OrthographicCamera.prototype = Object.assign(Object.create(Camera.prototype), {
  24176. constructor: OrthographicCamera,
  24177. isOrthographicCamera: true,
  24178. copy: function (source, recursive) {
  24179. Camera.prototype.copy.call(this, source, recursive);
  24180. this.left = source.left;
  24181. this.right = source.right;
  24182. this.top = source.top;
  24183. this.bottom = source.bottom;
  24184. this.near = source.near;
  24185. this.far = source.far;
  24186. this.zoom = source.zoom;
  24187. this.view = source.view === null ? null : Object.assign({}, source.view);
  24188. return this;
  24189. },
  24190. setViewOffset: function (fullWidth, fullHeight, x, y, width, height) {
  24191. if (this.view === null) {
  24192. this.view = {
  24193. enabled: true,
  24194. fullWidth: 1,
  24195. fullHeight: 1,
  24196. offsetX: 0,
  24197. offsetY: 0,
  24198. width: 1,
  24199. height: 1
  24200. };
  24201. }
  24202. this.view.enabled = true;
  24203. this.view.fullWidth = fullWidth;
  24204. this.view.fullHeight = fullHeight;
  24205. this.view.offsetX = x;
  24206. this.view.offsetY = y;
  24207. this.view.width = width;
  24208. this.view.height = height;
  24209. this.updateProjectionMatrix();
  24210. },
  24211. clearViewOffset: function () {
  24212. if (this.view !== null) {
  24213. this.view.enabled = false;
  24214. }
  24215. this.updateProjectionMatrix();
  24216. },
  24217. updateProjectionMatrix: function () {
  24218. var dx = (this.right - this.left) / (2 * this.zoom);
  24219. var dy = (this.top - this.bottom) / (2 * this.zoom);
  24220. var cx = (this.right + this.left) / 2;
  24221. var cy = (this.top + this.bottom) / 2;
  24222. var left = cx - dx;
  24223. var right = cx + dx;
  24224. var top = cy + dy;
  24225. var bottom = cy - dy;
  24226. if (this.view !== null && this.view.enabled) {
  24227. var zoomW = this.zoom / (this.view.width / this.view.fullWidth);
  24228. var zoomH = this.zoom / (this.view.height / this.view.fullHeight);
  24229. var scaleW = (this.right - this.left) / this.view.width;
  24230. var scaleH = (this.top - this.bottom) / this.view.height;
  24231. left += scaleW * (this.view.offsetX / zoomW);
  24232. right = left + scaleW * (this.view.width / zoomW);
  24233. top -= scaleH * (this.view.offsetY / zoomH);
  24234. bottom = top - scaleH * (this.view.height / zoomH);
  24235. }
  24236. this.projectionMatrix.makeOrthographic(left, right, top, bottom, this.near, this.far);
  24237. this.projectionMatrixInverse.getInverse(this.projectionMatrix);
  24238. },
  24239. toJSON: function (meta) {
  24240. var data = Object3D.prototype.toJSON.call(this, meta);
  24241. data.object.zoom = this.zoom;
  24242. data.object.left = this.left;
  24243. data.object.right = this.right;
  24244. data.object.top = this.top;
  24245. data.object.bottom = this.bottom;
  24246. data.object.near = this.near;
  24247. data.object.far = this.far;
  24248. if (this.view !== null) data.object.view = Object.assign({}, this.view);
  24249. return data;
  24250. }
  24251. });
  24252. /**
  24253. * @author mrdoob / http://mrdoob.com/
  24254. */
  24255. function DirectionalLightShadow() {
  24256. LightShadow.call(this, new OrthographicCamera(-5, 5, 5, -5, 0.5, 500));
  24257. }
  24258. DirectionalLightShadow.prototype = Object.assign(Object.create(LightShadow.prototype), {
  24259. constructor: DirectionalLightShadow,
  24260. isDirectionalLightShadow: true,
  24261. updateMatrices: function (light, viewCamera, viewportIndex) {
  24262. LightShadow.prototype.updateMatrices.call(this, light, viewCamera, viewportIndex);
  24263. }
  24264. });
  24265. /**
  24266. * @author mrdoob / http://mrdoob.com/
  24267. * @author alteredq / http://alteredqualia.com/
  24268. */
  24269. function DirectionalLight(color, intensity) {
  24270. Light.call(this, color, intensity);
  24271. this.type = 'DirectionalLight';
  24272. this.position.copy(Object3D.DefaultUp);
  24273. this.updateMatrix();
  24274. this.target = new Object3D();
  24275. this.shadow = new DirectionalLightShadow();
  24276. }
  24277. DirectionalLight.prototype = Object.assign(Object.create(Light.prototype), {
  24278. constructor: DirectionalLight,
  24279. isDirectionalLight: true,
  24280. copy: function (source) {
  24281. Light.prototype.copy.call(this, source);
  24282. this.target = source.target.clone();
  24283. this.shadow = source.shadow.clone();
  24284. return this;
  24285. }
  24286. });
  24287. /**
  24288. * @author mrdoob / http://mrdoob.com/
  24289. */
  24290. function AmbientLight(color, intensity) {
  24291. Light.call(this, color, intensity);
  24292. this.type = 'AmbientLight';
  24293. this.castShadow = undefined;
  24294. }
  24295. AmbientLight.prototype = Object.assign(Object.create(Light.prototype), {
  24296. constructor: AmbientLight,
  24297. isAmbientLight: true
  24298. });
  24299. /**
  24300. * @author abelnation / http://github.com/abelnation
  24301. */
  24302. function RectAreaLight(color, intensity, width, height) {
  24303. Light.call(this, color, intensity);
  24304. this.type = 'RectAreaLight';
  24305. this.width = width !== undefined ? width : 10;
  24306. this.height = height !== undefined ? height : 10;
  24307. }
  24308. RectAreaLight.prototype = Object.assign(Object.create(Light.prototype), {
  24309. constructor: RectAreaLight,
  24310. isRectAreaLight: true,
  24311. copy: function (source) {
  24312. Light.prototype.copy.call(this, source);
  24313. this.width = source.width;
  24314. this.height = source.height;
  24315. return this;
  24316. },
  24317. toJSON: function (meta) {
  24318. var data = Light.prototype.toJSON.call(this, meta);
  24319. data.object.width = this.width;
  24320. data.object.height = this.height;
  24321. return data;
  24322. }
  24323. });
  24324. /**
  24325. * @author mrdoob / http://mrdoob.com/
  24326. */
  24327. function MaterialLoader(manager) {
  24328. Loader.call(this, manager);
  24329. this.textures = {};
  24330. }
  24331. MaterialLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  24332. constructor: MaterialLoader,
  24333. load: function (url, onLoad, onProgress, onError) {
  24334. var scope = this;
  24335. var loader = new FileLoader(scope.manager);
  24336. loader.setPath(scope.path);
  24337. loader.load(url, function (text) {
  24338. onLoad(scope.parse(JSON.parse(text)));
  24339. }, onProgress, onError);
  24340. },
  24341. parse: function (json) {
  24342. var textures = this.textures;
  24343. function getTexture(name) {
  24344. if (textures[name] === undefined) {
  24345. console.warn('THREE.MaterialLoader: Undefined texture', name);
  24346. }
  24347. return textures[name];
  24348. }
  24349. var material = new Materials[json.type]();
  24350. if (json.uuid !== undefined) material.uuid = json.uuid;
  24351. if (json.name !== undefined) material.name = json.name;
  24352. if (json.color !== undefined) material.color.setHex(json.color);
  24353. if (json.roughness !== undefined) material.roughness = json.roughness;
  24354. if (json.metalness !== undefined) material.metalness = json.metalness;
  24355. if (json.sheen !== undefined) material.sheen = new Color().setHex(json.sheen);
  24356. if (json.emissive !== undefined) material.emissive.setHex(json.emissive);
  24357. if (json.specular !== undefined) material.specular.setHex(json.specular);
  24358. if (json.shininess !== undefined) material.shininess = json.shininess;
  24359. if (json.clearcoat !== undefined) material.clearcoat = json.clearcoat;
  24360. if (json.clearcoatRoughness !== undefined) material.clearcoatRoughness = json.clearcoatRoughness;
  24361. if (json.vertexColors !== undefined) material.vertexColors = json.vertexColors;
  24362. if (json.fog !== undefined) material.fog = json.fog;
  24363. if (json.flatShading !== undefined) material.flatShading = json.flatShading;
  24364. if (json.blending !== undefined) material.blending = json.blending;
  24365. if (json.combine !== undefined) material.combine = json.combine;
  24366. if (json.side !== undefined) material.side = json.side;
  24367. if (json.opacity !== undefined) material.opacity = json.opacity;
  24368. if (json.transparent !== undefined) material.transparent = json.transparent;
  24369. if (json.alphaTest !== undefined) material.alphaTest = json.alphaTest;
  24370. if (json.depthTest !== undefined) material.depthTest = json.depthTest;
  24371. if (json.depthWrite !== undefined) material.depthWrite = json.depthWrite;
  24372. if (json.colorWrite !== undefined) material.colorWrite = json.colorWrite;
  24373. if (json.stencilWrite !== undefined) material.stencilWrite = json.stencilWrite;
  24374. if (json.stencilWriteMask !== undefined) material.stencilWriteMask = json.stencilWriteMask;
  24375. if (json.stencilFunc !== undefined) material.stencilFunc = json.stencilFunc;
  24376. if (json.stencilRef !== undefined) material.stencilRef = json.stencilRef;
  24377. if (json.stencilFuncMask !== undefined) material.stencilFuncMask = json.stencilFuncMask;
  24378. if (json.stencilFail !== undefined) material.stencilFail = json.stencilFail;
  24379. if (json.stencilZFail !== undefined) material.stencilZFail = json.stencilZFail;
  24380. if (json.stencilZPass !== undefined) material.stencilZPass = json.stencilZPass;
  24381. if (json.wireframe !== undefined) material.wireframe = json.wireframe;
  24382. if (json.wireframeLinewidth !== undefined) material.wireframeLinewidth = json.wireframeLinewidth;
  24383. if (json.wireframeLinecap !== undefined) material.wireframeLinecap = json.wireframeLinecap;
  24384. if (json.wireframeLinejoin !== undefined) material.wireframeLinejoin = json.wireframeLinejoin;
  24385. if (json.rotation !== undefined) material.rotation = json.rotation;
  24386. if (json.linewidth !== 1) material.linewidth = json.linewidth;
  24387. if (json.dashSize !== undefined) material.dashSize = json.dashSize;
  24388. if (json.gapSize !== undefined) material.gapSize = json.gapSize;
  24389. if (json.scale !== undefined) material.scale = json.scale;
  24390. if (json.polygonOffset !== undefined) material.polygonOffset = json.polygonOffset;
  24391. if (json.polygonOffsetFactor !== undefined) material.polygonOffsetFactor = json.polygonOffsetFactor;
  24392. if (json.polygonOffsetUnits !== undefined) material.polygonOffsetUnits = json.polygonOffsetUnits;
  24393. if (json.skinning !== undefined) material.skinning = json.skinning;
  24394. if (json.morphTargets !== undefined) material.morphTargets = json.morphTargets;
  24395. if (json.morphNormals !== undefined) material.morphNormals = json.morphNormals;
  24396. if (json.dithering !== undefined) material.dithering = json.dithering;
  24397. if (json.visible !== undefined) material.visible = json.visible;
  24398. if (json.toneMapped !== undefined) material.toneMapped = json.toneMapped;
  24399. if (json.userData !== undefined) material.userData = json.userData; // Shader Material
  24400. if (json.uniforms !== undefined) {
  24401. for (var name in json.uniforms) {
  24402. var uniform = json.uniforms[name];
  24403. material.uniforms[name] = {};
  24404. switch (uniform.type) {
  24405. case 't':
  24406. material.uniforms[name].value = getTexture(uniform.value);
  24407. break;
  24408. case 'c':
  24409. material.uniforms[name].value = new Color().setHex(uniform.value);
  24410. break;
  24411. case 'v2':
  24412. material.uniforms[name].value = new Vector2().fromArray(uniform.value);
  24413. break;
  24414. case 'v3':
  24415. material.uniforms[name].value = new Vector3().fromArray(uniform.value);
  24416. break;
  24417. case 'v4':
  24418. material.uniforms[name].value = new Vector4().fromArray(uniform.value);
  24419. break;
  24420. case 'm3':
  24421. material.uniforms[name].value = new Matrix3().fromArray(uniform.value);
  24422. case 'm4':
  24423. material.uniforms[name].value = new Matrix4().fromArray(uniform.value);
  24424. break;
  24425. default:
  24426. material.uniforms[name].value = uniform.value;
  24427. }
  24428. }
  24429. }
  24430. if (json.defines !== undefined) material.defines = json.defines;
  24431. if (json.vertexShader !== undefined) material.vertexShader = json.vertexShader;
  24432. if (json.fragmentShader !== undefined) material.fragmentShader = json.fragmentShader;
  24433. if (json.extensions !== undefined) {
  24434. for (var key in json.extensions) {
  24435. material.extensions[key] = json.extensions[key];
  24436. }
  24437. } // Deprecated
  24438. if (json.shading !== undefined) material.flatShading = json.shading === 1; // THREE.FlatShading
  24439. // for PointsMaterial
  24440. if (json.size !== undefined) material.size = json.size;
  24441. if (json.sizeAttenuation !== undefined) material.sizeAttenuation = json.sizeAttenuation; // maps
  24442. if (json.map !== undefined) material.map = getTexture(json.map);
  24443. if (json.matcap !== undefined) material.matcap = getTexture(json.matcap);
  24444. if (json.alphaMap !== undefined) {
  24445. material.alphaMap = getTexture(json.alphaMap);
  24446. material.transparent = true;
  24447. }
  24448. if (json.bumpMap !== undefined) material.bumpMap = getTexture(json.bumpMap);
  24449. if (json.bumpScale !== undefined) material.bumpScale = json.bumpScale;
  24450. if (json.normalMap !== undefined) material.normalMap = getTexture(json.normalMap);
  24451. if (json.normalMapType !== undefined) material.normalMapType = json.normalMapType;
  24452. if (json.normalScale !== undefined) {
  24453. var normalScale = json.normalScale;
  24454. if (Array.isArray(normalScale) === false) {
  24455. // Blender exporter used to export a scalar. See #7459
  24456. normalScale = [normalScale, normalScale];
  24457. }
  24458. material.normalScale = new Vector2().fromArray(normalScale);
  24459. }
  24460. if (json.displacementMap !== undefined) material.displacementMap = getTexture(json.displacementMap);
  24461. if (json.displacementScale !== undefined) material.displacementScale = json.displacementScale;
  24462. if (json.displacementBias !== undefined) material.displacementBias = json.displacementBias;
  24463. if (json.roughnessMap !== undefined) material.roughnessMap = getTexture(json.roughnessMap);
  24464. if (json.metalnessMap !== undefined) material.metalnessMap = getTexture(json.metalnessMap);
  24465. if (json.emissiveMap !== undefined) material.emissiveMap = getTexture(json.emissiveMap);
  24466. if (json.emissiveIntensity !== undefined) material.emissiveIntensity = json.emissiveIntensity;
  24467. if (json.specularMap !== undefined) material.specularMap = getTexture(json.specularMap);
  24468. if (json.envMap !== undefined) material.envMap = getTexture(json.envMap);
  24469. if (json.envMapIntensity !== undefined) material.envMapIntensity = json.envMapIntensity;
  24470. if (json.reflectivity !== undefined) material.reflectivity = json.reflectivity;
  24471. if (json.refractionRatio !== undefined) material.refractionRatio = json.refractionRatio;
  24472. if (json.lightMap !== undefined) material.lightMap = getTexture(json.lightMap);
  24473. if (json.lightMapIntensity !== undefined) material.lightMapIntensity = json.lightMapIntensity;
  24474. if (json.aoMap !== undefined) material.aoMap = getTexture(json.aoMap);
  24475. if (json.aoMapIntensity !== undefined) material.aoMapIntensity = json.aoMapIntensity;
  24476. if (json.gradientMap !== undefined) material.gradientMap = getTexture(json.gradientMap);
  24477. if (json.clearcoatNormalMap !== undefined) material.clearcoatNormalMap = getTexture(json.clearcoatNormalMap);
  24478. if (json.clearcoatNormalScale !== undefined) material.clearcoatNormalScale = new Vector2().fromArray(json.clearcoatNormalScale);
  24479. return material;
  24480. },
  24481. setTextures: function (value) {
  24482. this.textures = value;
  24483. return this;
  24484. }
  24485. });
  24486. /**
  24487. * @author Don McCurdy / https://www.donmccurdy.com
  24488. */
  24489. var LoaderUtils = {
  24490. decodeText: function (array) {
  24491. if (typeof TextDecoder !== 'undefined') {
  24492. return new TextDecoder().decode(array);
  24493. } // Avoid the String.fromCharCode.apply(null, array) shortcut, which
  24494. // throws a "maximum call stack size exceeded" error for large arrays.
  24495. var s = '';
  24496. for (var i = 0, il = array.length; i < il; i++) {
  24497. // Implicitly assumes little-endian.
  24498. s += String.fromCharCode(array[i]);
  24499. }
  24500. try {
  24501. // merges multi-byte utf-8 characters.
  24502. return decodeURIComponent(escape(s));
  24503. } catch (e) {
  24504. // see #16358
  24505. return s;
  24506. }
  24507. },
  24508. extractUrlBase: function (url) {
  24509. var index = url.lastIndexOf('/');
  24510. if (index === -1) return './';
  24511. return url.substr(0, index + 1);
  24512. }
  24513. };
  24514. /**
  24515. * @author benaadams / https://twitter.com/ben_a_adams
  24516. */
  24517. exports.LoaderUtils = LoaderUtils;
  24518. function InstancedBufferGeometry() {
  24519. BufferGeometry.call(this);
  24520. this.type = 'InstancedBufferGeometry';
  24521. this.maxInstancedCount = undefined;
  24522. }
  24523. InstancedBufferGeometry.prototype = Object.assign(Object.create(BufferGeometry.prototype), {
  24524. constructor: InstancedBufferGeometry,
  24525. isInstancedBufferGeometry: true,
  24526. copy: function (source) {
  24527. BufferGeometry.prototype.copy.call(this, source);
  24528. this.maxInstancedCount = source.maxInstancedCount;
  24529. return this;
  24530. },
  24531. clone: function () {
  24532. return new this.constructor().copy(this);
  24533. },
  24534. toJSON: function () {
  24535. var data = BufferGeometry.prototype.toJSON.call(this);
  24536. data.maxInstancedCount = this.maxInstancedCount;
  24537. data.isInstancedBufferGeometry = true;
  24538. return data;
  24539. }
  24540. });
  24541. /**
  24542. * @author benaadams / https://twitter.com/ben_a_adams
  24543. */
  24544. function InstancedBufferAttribute(array, itemSize, normalized, meshPerAttribute) {
  24545. if (typeof normalized === 'number') {
  24546. meshPerAttribute = normalized;
  24547. normalized = false;
  24548. console.error('THREE.InstancedBufferAttribute: The constructor now expects normalized as the third argument.');
  24549. }
  24550. BufferAttribute.call(this, array, itemSize, normalized);
  24551. this.meshPerAttribute = meshPerAttribute || 1;
  24552. }
  24553. InstancedBufferAttribute.prototype = Object.assign(Object.create(BufferAttribute.prototype), {
  24554. constructor: InstancedBufferAttribute,
  24555. isInstancedBufferAttribute: true,
  24556. copy: function (source) {
  24557. BufferAttribute.prototype.copy.call(this, source);
  24558. this.meshPerAttribute = source.meshPerAttribute;
  24559. return this;
  24560. },
  24561. toJSON: function () {
  24562. var data = BufferAttribute.prototype.toJSON.call(this);
  24563. data.meshPerAttribute = this.meshPerAttribute;
  24564. data.isInstancedBufferAttribute = true;
  24565. return data;
  24566. }
  24567. });
  24568. /**
  24569. * @author mrdoob / http://mrdoob.com/
  24570. */
  24571. function BufferGeometryLoader(manager) {
  24572. Loader.call(this, manager);
  24573. }
  24574. BufferGeometryLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  24575. constructor: BufferGeometryLoader,
  24576. load: function (url, onLoad, onProgress, onError) {
  24577. var scope = this;
  24578. var loader = new FileLoader(scope.manager);
  24579. loader.setPath(scope.path);
  24580. loader.load(url, function (text) {
  24581. onLoad(scope.parse(JSON.parse(text)));
  24582. }, onProgress, onError);
  24583. },
  24584. parse: function (json) {
  24585. var geometry = json.isInstancedBufferGeometry ? new InstancedBufferGeometry() : new BufferGeometry();
  24586. var index = json.data.index;
  24587. if (index !== undefined) {
  24588. var typedArray = new TYPED_ARRAYS[index.type](index.array);
  24589. geometry.setIndex(new BufferAttribute(typedArray, 1));
  24590. }
  24591. var attributes = json.data.attributes;
  24592. for (var key in attributes) {
  24593. var attribute = attributes[key];
  24594. var typedArray = new TYPED_ARRAYS[attribute.type](attribute.array);
  24595. var bufferAttributeConstr = attribute.isInstancedBufferAttribute ? InstancedBufferAttribute : BufferAttribute;
  24596. var bufferAttribute = new bufferAttributeConstr(typedArray, attribute.itemSize, attribute.normalized);
  24597. if (attribute.name !== undefined) bufferAttribute.name = attribute.name;
  24598. geometry.addAttribute(key, bufferAttribute);
  24599. }
  24600. var morphAttributes = json.data.morphAttributes;
  24601. if (morphAttributes) {
  24602. for (var key in morphAttributes) {
  24603. var attributeArray = morphAttributes[key];
  24604. var array = [];
  24605. for (var i = 0, il = attributeArray.length; i < il; i++) {
  24606. var attribute = attributeArray[i];
  24607. var typedArray = new TYPED_ARRAYS[attribute.type](attribute.array);
  24608. var bufferAttribute = new BufferAttribute(typedArray, attribute.itemSize, attribute.normalized);
  24609. if (attribute.name !== undefined) bufferAttribute.name = attribute.name;
  24610. array.push(bufferAttribute);
  24611. }
  24612. geometry.morphAttributes[key] = array;
  24613. }
  24614. }
  24615. var groups = json.data.groups || json.data.drawcalls || json.data.offsets;
  24616. if (groups !== undefined) {
  24617. for (var i = 0, n = groups.length; i !== n; ++i) {
  24618. var group = groups[i];
  24619. geometry.addGroup(group.start, group.count, group.materialIndex);
  24620. }
  24621. }
  24622. var boundingSphere = json.data.boundingSphere;
  24623. if (boundingSphere !== undefined) {
  24624. var center = new Vector3();
  24625. if (boundingSphere.center !== undefined) {
  24626. center.fromArray(boundingSphere.center);
  24627. }
  24628. geometry.boundingSphere = new Sphere(center, boundingSphere.radius);
  24629. }
  24630. if (json.name) geometry.name = json.name;
  24631. if (json.userData) geometry.userData = json.userData;
  24632. return geometry;
  24633. }
  24634. });
  24635. var TYPED_ARRAYS = {
  24636. Int8Array: Int8Array,
  24637. Uint8Array: Uint8Array,
  24638. // Workaround for IE11 pre KB2929437. See #11440
  24639. Uint8ClampedArray: typeof Uint8ClampedArray !== 'undefined' ? Uint8ClampedArray : Uint8Array,
  24640. Int16Array: Int16Array,
  24641. Uint16Array: Uint16Array,
  24642. Int32Array: Int32Array,
  24643. Uint32Array: Uint32Array,
  24644. Float32Array: Float32Array,
  24645. Float64Array: Float64Array
  24646. };
  24647. /**
  24648. * @author mrdoob / http://mrdoob.com/
  24649. */
  24650. function ObjectLoader(manager) {
  24651. Loader.call(this, manager);
  24652. }
  24653. ObjectLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  24654. constructor: ObjectLoader,
  24655. load: function (url, onLoad, onProgress, onError) {
  24656. var scope = this;
  24657. var path = this.path === '' ? LoaderUtils.extractUrlBase(url) : this.path;
  24658. this.resourcePath = this.resourcePath || path;
  24659. var loader = new FileLoader(scope.manager);
  24660. loader.setPath(this.path);
  24661. loader.load(url, function (text) {
  24662. var json = null;
  24663. try {
  24664. json = JSON.parse(text);
  24665. } catch (error) {
  24666. if (onError !== undefined) onError(error);
  24667. console.error('THREE:ObjectLoader: Can\'t parse ' + url + '.', error.message);
  24668. return;
  24669. }
  24670. var metadata = json.metadata;
  24671. if (metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry') {
  24672. console.error('THREE.ObjectLoader: Can\'t load ' + url);
  24673. return;
  24674. }
  24675. scope.parse(json, onLoad);
  24676. }, onProgress, onError);
  24677. },
  24678. parse: function (json, onLoad) {
  24679. var shapes = this.parseShape(json.shapes);
  24680. var geometries = this.parseGeometries(json.geometries, shapes);
  24681. var images = this.parseImages(json.images, function () {
  24682. if (onLoad !== undefined) onLoad(object);
  24683. });
  24684. var textures = this.parseTextures(json.textures, images);
  24685. var materials = this.parseMaterials(json.materials, textures);
  24686. var object = this.parseObject(json.object, geometries, materials);
  24687. if (json.animations) {
  24688. object.animations = this.parseAnimations(json.animations);
  24689. }
  24690. if (json.images === undefined || json.images.length === 0) {
  24691. if (onLoad !== undefined) onLoad(object);
  24692. }
  24693. return object;
  24694. },
  24695. parseShape: function (json) {
  24696. var shapes = {};
  24697. if (json !== undefined) {
  24698. for (var i = 0, l = json.length; i < l; i++) {
  24699. var shape = new Shape().fromJSON(json[i]);
  24700. shapes[shape.uuid] = shape;
  24701. }
  24702. }
  24703. return shapes;
  24704. },
  24705. parseGeometries: function (json, shapes) {
  24706. var geometries = {};
  24707. if (json !== undefined) {
  24708. var bufferGeometryLoader = new BufferGeometryLoader();
  24709. for (var i = 0, l = json.length; i < l; i++) {
  24710. var geometry;
  24711. var data = json[i];
  24712. switch (data.type) {
  24713. case 'PlaneGeometry':
  24714. case 'PlaneBufferGeometry':
  24715. geometry = new Geometries[data.type](data.width, data.height, data.widthSegments, data.heightSegments);
  24716. break;
  24717. case 'BoxGeometry':
  24718. case 'BoxBufferGeometry':
  24719. case 'CubeGeometry':
  24720. // backwards compatible
  24721. geometry = new Geometries[data.type](data.width, data.height, data.depth, data.widthSegments, data.heightSegments, data.depthSegments);
  24722. break;
  24723. case 'CircleGeometry':
  24724. case 'CircleBufferGeometry':
  24725. geometry = new Geometries[data.type](data.radius, data.segments, data.thetaStart, data.thetaLength);
  24726. break;
  24727. case 'CylinderGeometry':
  24728. case 'CylinderBufferGeometry':
  24729. geometry = new Geometries[data.type](data.radiusTop, data.radiusBottom, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength);
  24730. break;
  24731. case 'ConeGeometry':
  24732. case 'ConeBufferGeometry':
  24733. geometry = new Geometries[data.type](data.radius, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength);
  24734. break;
  24735. case 'SphereGeometry':
  24736. case 'SphereBufferGeometry':
  24737. geometry = new Geometries[data.type](data.radius, data.widthSegments, data.heightSegments, data.phiStart, data.phiLength, data.thetaStart, data.thetaLength);
  24738. break;
  24739. case 'DodecahedronGeometry':
  24740. case 'DodecahedronBufferGeometry':
  24741. case 'IcosahedronGeometry':
  24742. case 'IcosahedronBufferGeometry':
  24743. case 'OctahedronGeometry':
  24744. case 'OctahedronBufferGeometry':
  24745. case 'TetrahedronGeometry':
  24746. case 'TetrahedronBufferGeometry':
  24747. geometry = new Geometries[data.type](data.radius, data.detail);
  24748. break;
  24749. case 'RingGeometry':
  24750. case 'RingBufferGeometry':
  24751. geometry = new Geometries[data.type](data.innerRadius, data.outerRadius, data.thetaSegments, data.phiSegments, data.thetaStart, data.thetaLength);
  24752. break;
  24753. case 'TorusGeometry':
  24754. case 'TorusBufferGeometry':
  24755. geometry = new Geometries[data.type](data.radius, data.tube, data.radialSegments, data.tubularSegments, data.arc);
  24756. break;
  24757. case 'TorusKnotGeometry':
  24758. case 'TorusKnotBufferGeometry':
  24759. geometry = new Geometries[data.type](data.radius, data.tube, data.tubularSegments, data.radialSegments, data.p, data.q);
  24760. break;
  24761. case 'TubeGeometry':
  24762. case 'TubeBufferGeometry':
  24763. // This only works for built-in curves (e.g. CatmullRomCurve3).
  24764. // User defined curves or instances of CurvePath will not be deserialized.
  24765. geometry = new Geometries[data.type](new Curves[data.path.type]().fromJSON(data.path), data.tubularSegments, data.radius, data.radialSegments, data.closed);
  24766. break;
  24767. case 'LatheGeometry':
  24768. case 'LatheBufferGeometry':
  24769. geometry = new Geometries[data.type](data.points, data.segments, data.phiStart, data.phiLength);
  24770. break;
  24771. case 'PolyhedronGeometry':
  24772. case 'PolyhedronBufferGeometry':
  24773. geometry = new Geometries[data.type](data.vertices, data.indices, data.radius, data.details);
  24774. break;
  24775. case 'ShapeGeometry':
  24776. case 'ShapeBufferGeometry':
  24777. var geometryShapes = [];
  24778. for (var j = 0, jl = data.shapes.length; j < jl; j++) {
  24779. var shape = shapes[data.shapes[j]];
  24780. geometryShapes.push(shape);
  24781. }
  24782. geometry = new Geometries[data.type](geometryShapes, data.curveSegments);
  24783. break;
  24784. case 'ExtrudeGeometry':
  24785. case 'ExtrudeBufferGeometry':
  24786. var geometryShapes = [];
  24787. for (var j = 0, jl = data.shapes.length; j < jl; j++) {
  24788. var shape = shapes[data.shapes[j]];
  24789. geometryShapes.push(shape);
  24790. }
  24791. var extrudePath = data.options.extrudePath;
  24792. if (extrudePath !== undefined) {
  24793. data.options.extrudePath = new Curves[extrudePath.type]().fromJSON(extrudePath);
  24794. }
  24795. geometry = new Geometries[data.type](geometryShapes, data.options);
  24796. break;
  24797. case 'BufferGeometry':
  24798. case 'InstancedBufferGeometry':
  24799. geometry = bufferGeometryLoader.parse(data);
  24800. break;
  24801. case 'Geometry':
  24802. if ('THREE' in window && 'LegacyJSONLoader' in THREE) {
  24803. var geometryLoader = new THREE.LegacyJSONLoader();
  24804. geometry = geometryLoader.parse(data, this.resourcePath).geometry;
  24805. } else {
  24806. console.error('THREE.ObjectLoader: You have to import LegacyJSONLoader in order load geometry data of type "Geometry".');
  24807. }
  24808. break;
  24809. default:
  24810. console.warn('THREE.ObjectLoader: Unsupported geometry type "' + data.type + '"');
  24811. continue;
  24812. }
  24813. geometry.uuid = data.uuid;
  24814. if (data.name !== undefined) geometry.name = data.name;
  24815. if (geometry.isBufferGeometry === true && data.userData !== undefined) geometry.userData = data.userData;
  24816. geometries[data.uuid] = geometry;
  24817. }
  24818. }
  24819. return geometries;
  24820. },
  24821. parseMaterials: function (json, textures) {
  24822. var cache = {}; // MultiMaterial
  24823. var materials = {};
  24824. if (json !== undefined) {
  24825. var loader = new MaterialLoader();
  24826. loader.setTextures(textures);
  24827. for (var i = 0, l = json.length; i < l; i++) {
  24828. var data = json[i];
  24829. if (data.type === 'MultiMaterial') {
  24830. // Deprecated
  24831. var array = [];
  24832. for (var j = 0; j < data.materials.length; j++) {
  24833. var material = data.materials[j];
  24834. if (cache[material.uuid] === undefined) {
  24835. cache[material.uuid] = loader.parse(material);
  24836. }
  24837. array.push(cache[material.uuid]);
  24838. }
  24839. materials[data.uuid] = array;
  24840. } else {
  24841. if (cache[data.uuid] === undefined) {
  24842. cache[data.uuid] = loader.parse(data);
  24843. }
  24844. materials[data.uuid] = cache[data.uuid];
  24845. }
  24846. }
  24847. }
  24848. return materials;
  24849. },
  24850. parseAnimations: function (json) {
  24851. var animations = [];
  24852. for (var i = 0; i < json.length; i++) {
  24853. var data = json[i];
  24854. var clip = AnimationClip.parse(data);
  24855. if (data.uuid !== undefined) clip.uuid = data.uuid;
  24856. animations.push(clip);
  24857. }
  24858. return animations;
  24859. },
  24860. parseImages: function (json, onLoad) {
  24861. var scope = this;
  24862. var images = {};
  24863. function loadImage(url) {
  24864. scope.manager.itemStart(url);
  24865. return loader.load(url, function () {
  24866. scope.manager.itemEnd(url);
  24867. }, undefined, function () {
  24868. scope.manager.itemError(url);
  24869. scope.manager.itemEnd(url);
  24870. });
  24871. }
  24872. if (json !== undefined && json.length > 0) {
  24873. var manager = new LoadingManager(onLoad);
  24874. var loader = new ImageLoader(manager);
  24875. loader.setCrossOrigin(this.crossOrigin);
  24876. for (var i = 0, il = json.length; i < il; i++) {
  24877. var image = json[i];
  24878. var url = image.url;
  24879. if (Array.isArray(url)) {
  24880. // load array of images e.g CubeTexture
  24881. images[image.uuid] = [];
  24882. for (var j = 0, jl = url.length; j < jl; j++) {
  24883. var currentUrl = url[j];
  24884. var path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test(currentUrl) ? currentUrl : scope.resourcePath + currentUrl;
  24885. images[image.uuid].push(loadImage(path));
  24886. }
  24887. } else {
  24888. // load single image
  24889. var path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test(image.url) ? image.url : scope.resourcePath + image.url;
  24890. images[image.uuid] = loadImage(path);
  24891. }
  24892. }
  24893. }
  24894. return images;
  24895. },
  24896. parseTextures: function (json, images) {
  24897. function parseConstant(value, type) {
  24898. if (typeof value === 'number') return value;
  24899. console.warn('THREE.ObjectLoader.parseTexture: Constant should be in numeric form.', value);
  24900. return type[value];
  24901. }
  24902. var textures = {};
  24903. if (json !== undefined) {
  24904. for (var i = 0, l = json.length; i < l; i++) {
  24905. var data = json[i];
  24906. if (data.image === undefined) {
  24907. console.warn('THREE.ObjectLoader: No "image" specified for', data.uuid);
  24908. }
  24909. if (images[data.image] === undefined) {
  24910. console.warn('THREE.ObjectLoader: Undefined image', data.image);
  24911. }
  24912. var texture;
  24913. if (Array.isArray(images[data.image])) {
  24914. texture = new CubeTexture(images[data.image]);
  24915. } else {
  24916. texture = new Texture(images[data.image]);
  24917. }
  24918. texture.needsUpdate = true;
  24919. texture.uuid = data.uuid;
  24920. if (data.name !== undefined) texture.name = data.name;
  24921. if (data.mapping !== undefined) texture.mapping = parseConstant(data.mapping, TEXTURE_MAPPING);
  24922. if (data.offset !== undefined) texture.offset.fromArray(data.offset);
  24923. if (data.repeat !== undefined) texture.repeat.fromArray(data.repeat);
  24924. if (data.center !== undefined) texture.center.fromArray(data.center);
  24925. if (data.rotation !== undefined) texture.rotation = data.rotation;
  24926. if (data.wrap !== undefined) {
  24927. texture.wrapS = parseConstant(data.wrap[0], TEXTURE_WRAPPING);
  24928. texture.wrapT = parseConstant(data.wrap[1], TEXTURE_WRAPPING);
  24929. }
  24930. if (data.format !== undefined) texture.format = data.format;
  24931. if (data.type !== undefined) texture.type = data.type;
  24932. if (data.encoding !== undefined) texture.encoding = data.encoding;
  24933. if (data.minFilter !== undefined) texture.minFilter = parseConstant(data.minFilter, TEXTURE_FILTER);
  24934. if (data.magFilter !== undefined) texture.magFilter = parseConstant(data.magFilter, TEXTURE_FILTER);
  24935. if (data.anisotropy !== undefined) texture.anisotropy = data.anisotropy;
  24936. if (data.flipY !== undefined) texture.flipY = data.flipY;
  24937. if (data.premultiplyAlpha !== undefined) texture.premultiplyAlpha = data.premultiplyAlpha;
  24938. if (data.unpackAlignment !== undefined) texture.unpackAlignment = data.unpackAlignment;
  24939. textures[data.uuid] = texture;
  24940. }
  24941. }
  24942. return textures;
  24943. },
  24944. parseObject: function (data, geometries, materials) {
  24945. var object;
  24946. function getGeometry(name) {
  24947. if (geometries[name] === undefined) {
  24948. console.warn('THREE.ObjectLoader: Undefined geometry', name);
  24949. }
  24950. return geometries[name];
  24951. }
  24952. function getMaterial(name) {
  24953. if (name === undefined) return undefined;
  24954. if (Array.isArray(name)) {
  24955. var array = [];
  24956. for (var i = 0, l = name.length; i < l; i++) {
  24957. var uuid = name[i];
  24958. if (materials[uuid] === undefined) {
  24959. console.warn('THREE.ObjectLoader: Undefined material', uuid);
  24960. }
  24961. array.push(materials[uuid]);
  24962. }
  24963. return array;
  24964. }
  24965. if (materials[name] === undefined) {
  24966. console.warn('THREE.ObjectLoader: Undefined material', name);
  24967. }
  24968. return materials[name];
  24969. }
  24970. switch (data.type) {
  24971. case 'Scene':
  24972. object = new Scene();
  24973. if (data.background !== undefined) {
  24974. if (Number.isInteger(data.background)) {
  24975. object.background = new Color(data.background);
  24976. }
  24977. }
  24978. if (data.fog !== undefined) {
  24979. if (data.fog.type === 'Fog') {
  24980. object.fog = new Fog(data.fog.color, data.fog.near, data.fog.far);
  24981. } else if (data.fog.type === 'FogExp2') {
  24982. object.fog = new FogExp2(data.fog.color, data.fog.density);
  24983. }
  24984. }
  24985. break;
  24986. case 'PerspectiveCamera':
  24987. object = new PerspectiveCamera(data.fov, data.aspect, data.near, data.far);
  24988. if (data.focus !== undefined) object.focus = data.focus;
  24989. if (data.zoom !== undefined) object.zoom = data.zoom;
  24990. if (data.filmGauge !== undefined) object.filmGauge = data.filmGauge;
  24991. if (data.filmOffset !== undefined) object.filmOffset = data.filmOffset;
  24992. if (data.view !== undefined) object.view = Object.assign({}, data.view);
  24993. break;
  24994. case 'OrthographicCamera':
  24995. object = new OrthographicCamera(data.left, data.right, data.top, data.bottom, data.near, data.far);
  24996. if (data.zoom !== undefined) object.zoom = data.zoom;
  24997. if (data.view !== undefined) object.view = Object.assign({}, data.view);
  24998. break;
  24999. case 'AmbientLight':
  25000. object = new AmbientLight(data.color, data.intensity);
  25001. break;
  25002. case 'DirectionalLight':
  25003. object = new DirectionalLight(data.color, data.intensity);
  25004. break;
  25005. case 'PointLight':
  25006. object = new PointLight(data.color, data.intensity, data.distance, data.decay);
  25007. break;
  25008. case 'RectAreaLight':
  25009. object = new RectAreaLight(data.color, data.intensity, data.width, data.height);
  25010. break;
  25011. case 'SpotLight':
  25012. object = new SpotLight(data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay);
  25013. break;
  25014. case 'HemisphereLight':
  25015. object = new HemisphereLight(data.color, data.groundColor, data.intensity);
  25016. break;
  25017. case 'SkinnedMesh':
  25018. console.warn('THREE.ObjectLoader.parseObject() does not support SkinnedMesh yet.');
  25019. case 'Mesh':
  25020. var geometry = getGeometry(data.geometry);
  25021. var material = getMaterial(data.material);
  25022. if (geometry.bones && geometry.bones.length > 0) {
  25023. object = new SkinnedMesh(geometry, material);
  25024. } else {
  25025. object = new Mesh(geometry, material);
  25026. }
  25027. if (data.drawMode !== undefined) object.setDrawMode(data.drawMode);
  25028. break;
  25029. case 'LOD':
  25030. object = new LOD();
  25031. break;
  25032. case 'Line':
  25033. object = new Line(getGeometry(data.geometry), getMaterial(data.material), data.mode);
  25034. break;
  25035. case 'LineLoop':
  25036. object = new LineLoop(getGeometry(data.geometry), getMaterial(data.material));
  25037. break;
  25038. case 'LineSegments':
  25039. object = new LineSegments(getGeometry(data.geometry), getMaterial(data.material));
  25040. break;
  25041. case 'PointCloud':
  25042. case 'Points':
  25043. object = new Points(getGeometry(data.geometry), getMaterial(data.material));
  25044. break;
  25045. case 'Sprite':
  25046. object = new Sprite(getMaterial(data.material));
  25047. break;
  25048. case 'Group':
  25049. object = new Group();
  25050. break;
  25051. default:
  25052. object = new Object3D();
  25053. }
  25054. object.uuid = data.uuid;
  25055. if (data.name !== undefined) object.name = data.name;
  25056. if (data.matrix !== undefined) {
  25057. object.matrix.fromArray(data.matrix);
  25058. if (data.matrixAutoUpdate !== undefined) object.matrixAutoUpdate = data.matrixAutoUpdate;
  25059. if (object.matrixAutoUpdate) object.matrix.decompose(object.position, object.quaternion, object.scale);
  25060. } else {
  25061. if (data.position !== undefined) object.position.fromArray(data.position);
  25062. if (data.rotation !== undefined) object.rotation.fromArray(data.rotation);
  25063. if (data.quaternion !== undefined) object.quaternion.fromArray(data.quaternion);
  25064. if (data.scale !== undefined) object.scale.fromArray(data.scale);
  25065. }
  25066. if (data.castShadow !== undefined) object.castShadow = data.castShadow;
  25067. if (data.receiveShadow !== undefined) object.receiveShadow = data.receiveShadow;
  25068. if (data.shadow) {
  25069. if (data.shadow.bias !== undefined) object.shadow.bias = data.shadow.bias;
  25070. if (data.shadow.radius !== undefined) object.shadow.radius = data.shadow.radius;
  25071. if (data.shadow.mapSize !== undefined) object.shadow.mapSize.fromArray(data.shadow.mapSize);
  25072. if (data.shadow.camera !== undefined) object.shadow.camera = this.parseObject(data.shadow.camera);
  25073. }
  25074. if (data.visible !== undefined) object.visible = data.visible;
  25075. if (data.frustumCulled !== undefined) object.frustumCulled = data.frustumCulled;
  25076. if (data.renderOrder !== undefined) object.renderOrder = data.renderOrder;
  25077. if (data.userData !== undefined) object.userData = data.userData;
  25078. if (data.layers !== undefined) object.layers.mask = data.layers;
  25079. if (data.children !== undefined) {
  25080. var children = data.children;
  25081. for (var i = 0; i < children.length; i++) {
  25082. object.add(this.parseObject(children[i], geometries, materials));
  25083. }
  25084. }
  25085. if (data.type === 'LOD') {
  25086. var levels = data.levels;
  25087. for (var l = 0; l < levels.length; l++) {
  25088. var level = levels[l];
  25089. var child = object.getObjectByProperty('uuid', level.object);
  25090. if (child !== undefined) {
  25091. object.addLevel(child, level.distance);
  25092. }
  25093. }
  25094. }
  25095. return object;
  25096. }
  25097. });
  25098. var TEXTURE_MAPPING = {
  25099. UVMapping: UVMapping,
  25100. CubeReflectionMapping: CubeReflectionMapping,
  25101. CubeRefractionMapping: CubeRefractionMapping,
  25102. EquirectangularReflectionMapping: EquirectangularReflectionMapping,
  25103. EquirectangularRefractionMapping: EquirectangularRefractionMapping,
  25104. SphericalReflectionMapping: SphericalReflectionMapping,
  25105. CubeUVReflectionMapping: CubeUVReflectionMapping,
  25106. CubeUVRefractionMapping: CubeUVRefractionMapping
  25107. };
  25108. var TEXTURE_WRAPPING = {
  25109. RepeatWrapping: RepeatWrapping,
  25110. ClampToEdgeWrapping: ClampToEdgeWrapping,
  25111. MirroredRepeatWrapping: MirroredRepeatWrapping
  25112. };
  25113. var TEXTURE_FILTER = {
  25114. NearestFilter: NearestFilter,
  25115. NearestMipmapNearestFilter: NearestMipmapNearestFilter,
  25116. NearestMipmapLinearFilter: NearestMipmapLinearFilter,
  25117. LinearFilter: LinearFilter,
  25118. LinearMipmapNearestFilter: LinearMipmapNearestFilter,
  25119. LinearMipmapLinearFilter: LinearMipmapLinearFilter
  25120. };
  25121. /**
  25122. * @author thespite / http://clicktorelease.com/
  25123. */
  25124. function ImageBitmapLoader(manager) {
  25125. if (typeof createImageBitmap === 'undefined') {
  25126. console.warn('THREE.ImageBitmapLoader: createImageBitmap() not supported.');
  25127. }
  25128. if (typeof fetch === 'undefined') {
  25129. console.warn('THREE.ImageBitmapLoader: fetch() not supported.');
  25130. }
  25131. Loader.call(this, manager);
  25132. this.options = undefined;
  25133. }
  25134. ImageBitmapLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  25135. constructor: ImageBitmapLoader,
  25136. setOptions: function setOptions(options) {
  25137. this.options = options;
  25138. return this;
  25139. },
  25140. load: function (url, onLoad, onProgress, onError) {
  25141. if (url === undefined) url = '';
  25142. if (this.path !== undefined) url = this.path + url;
  25143. url = this.manager.resolveURL(url);
  25144. var scope = this;
  25145. var cached = Cache.get(url);
  25146. if (cached !== undefined) {
  25147. scope.manager.itemStart(url);
  25148. setTimeout(function () {
  25149. if (onLoad) onLoad(cached);
  25150. scope.manager.itemEnd(url);
  25151. }, 0);
  25152. return cached;
  25153. }
  25154. fetch(url).then(function (res) {
  25155. return res.blob();
  25156. }).then(function (blob) {
  25157. if (scope.options === undefined) {
  25158. // Workaround for FireFox. It causes an error if you pass options.
  25159. return createImageBitmap(blob);
  25160. } else {
  25161. return createImageBitmap(blob, scope.options);
  25162. }
  25163. }).then(function (imageBitmap) {
  25164. Cache.add(url, imageBitmap);
  25165. if (onLoad) onLoad(imageBitmap);
  25166. scope.manager.itemEnd(url);
  25167. }).catch(function (e) {
  25168. if (onError) onError(e);
  25169. scope.manager.itemError(url);
  25170. scope.manager.itemEnd(url);
  25171. });
  25172. scope.manager.itemStart(url);
  25173. }
  25174. });
  25175. /**
  25176. * @author zz85 / http://www.lab4games.net/zz85/blog
  25177. * minimal class for proxing functions to Path. Replaces old "extractSubpaths()"
  25178. **/
  25179. function ShapePath() {
  25180. this.type = 'ShapePath';
  25181. this.color = new Color();
  25182. this.subPaths = [];
  25183. this.currentPath = null;
  25184. }
  25185. Object.assign(ShapePath.prototype, {
  25186. moveTo: function (x, y) {
  25187. this.currentPath = new Path();
  25188. this.subPaths.push(this.currentPath);
  25189. this.currentPath.moveTo(x, y);
  25190. },
  25191. lineTo: function (x, y) {
  25192. this.currentPath.lineTo(x, y);
  25193. },
  25194. quadraticCurveTo: function (aCPx, aCPy, aX, aY) {
  25195. this.currentPath.quadraticCurveTo(aCPx, aCPy, aX, aY);
  25196. },
  25197. bezierCurveTo: function (aCP1x, aCP1y, aCP2x, aCP2y, aX, aY) {
  25198. this.currentPath.bezierCurveTo(aCP1x, aCP1y, aCP2x, aCP2y, aX, aY);
  25199. },
  25200. splineThru: function (pts) {
  25201. this.currentPath.splineThru(pts);
  25202. },
  25203. toShapes: function (isCCW, noHoles) {
  25204. function toShapesNoHoles(inSubpaths) {
  25205. var shapes = [];
  25206. for (var i = 0, l = inSubpaths.length; i < l; i++) {
  25207. var tmpPath = inSubpaths[i];
  25208. var tmpShape = new Shape();
  25209. tmpShape.curves = tmpPath.curves;
  25210. shapes.push(tmpShape);
  25211. }
  25212. return shapes;
  25213. }
  25214. function isPointInsidePolygon(inPt, inPolygon) {
  25215. var polyLen = inPolygon.length; // inPt on polygon contour => immediate success or
  25216. // toggling of inside/outside at every single! intersection point of an edge
  25217. // with the horizontal line through inPt, left of inPt
  25218. // not counting lowerY endpoints of edges and whole edges on that line
  25219. var inside = false;
  25220. for (var p = polyLen - 1, q = 0; q < polyLen; p = q++) {
  25221. var edgeLowPt = inPolygon[p];
  25222. var edgeHighPt = inPolygon[q];
  25223. var edgeDx = edgeHighPt.x - edgeLowPt.x;
  25224. var edgeDy = edgeHighPt.y - edgeLowPt.y;
  25225. if (Math.abs(edgeDy) > Number.EPSILON) {
  25226. // not parallel
  25227. if (edgeDy < 0) {
  25228. edgeLowPt = inPolygon[q];
  25229. edgeDx = -edgeDx;
  25230. edgeHighPt = inPolygon[p];
  25231. edgeDy = -edgeDy;
  25232. }
  25233. if (inPt.y < edgeLowPt.y || inPt.y > edgeHighPt.y) continue;
  25234. if (inPt.y === edgeLowPt.y) {
  25235. if (inPt.x === edgeLowPt.x) return true; // inPt is on contour ?
  25236. // continue; // no intersection or edgeLowPt => doesn't count !!!
  25237. } else {
  25238. var perpEdge = edgeDy * (inPt.x - edgeLowPt.x) - edgeDx * (inPt.y - edgeLowPt.y);
  25239. if (perpEdge === 0) return true; // inPt is on contour ?
  25240. if (perpEdge < 0) continue;
  25241. inside = !inside; // true intersection left of inPt
  25242. }
  25243. } else {
  25244. // parallel or collinear
  25245. if (inPt.y !== edgeLowPt.y) continue; // parallel
  25246. // edge lies on the same horizontal line as inPt
  25247. if (edgeHighPt.x <= inPt.x && inPt.x <= edgeLowPt.x || edgeLowPt.x <= inPt.x && inPt.x <= edgeHighPt.x) return true; // inPt: Point on contour !
  25248. // continue;
  25249. }
  25250. }
  25251. return inside;
  25252. }
  25253. var isClockWise = ShapeUtils.isClockWise;
  25254. var subPaths = this.subPaths;
  25255. if (subPaths.length === 0) return [];
  25256. if (noHoles === true) return toShapesNoHoles(subPaths);
  25257. var solid,
  25258. tmpPath,
  25259. tmpShape,
  25260. shapes = [];
  25261. if (subPaths.length === 1) {
  25262. tmpPath = subPaths[0];
  25263. tmpShape = new Shape();
  25264. tmpShape.curves = tmpPath.curves;
  25265. shapes.push(tmpShape);
  25266. return shapes;
  25267. }
  25268. var holesFirst = !isClockWise(subPaths[0].getPoints());
  25269. holesFirst = isCCW ? !holesFirst : holesFirst; // console.log("Holes first", holesFirst);
  25270. var betterShapeHoles = [];
  25271. var newShapes = [];
  25272. var newShapeHoles = [];
  25273. var mainIdx = 0;
  25274. var tmpPoints;
  25275. newShapes[mainIdx] = undefined;
  25276. newShapeHoles[mainIdx] = [];
  25277. for (var i = 0, l = subPaths.length; i < l; i++) {
  25278. tmpPath = subPaths[i];
  25279. tmpPoints = tmpPath.getPoints();
  25280. solid = isClockWise(tmpPoints);
  25281. solid = isCCW ? !solid : solid;
  25282. if (solid) {
  25283. if (!holesFirst && newShapes[mainIdx]) mainIdx++;
  25284. newShapes[mainIdx] = {
  25285. s: new Shape(),
  25286. p: tmpPoints
  25287. };
  25288. newShapes[mainIdx].s.curves = tmpPath.curves;
  25289. if (holesFirst) mainIdx++;
  25290. newShapeHoles[mainIdx] = []; //console.log('cw', i);
  25291. } else {
  25292. newShapeHoles[mainIdx].push({
  25293. h: tmpPath,
  25294. p: tmpPoints[0]
  25295. }); //console.log('ccw', i);
  25296. }
  25297. } // only Holes? -> probably all Shapes with wrong orientation
  25298. if (!newShapes[0]) return toShapesNoHoles(subPaths);
  25299. if (newShapes.length > 1) {
  25300. var ambiguous = false;
  25301. var toChange = [];
  25302. for (var sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx++) {
  25303. betterShapeHoles[sIdx] = [];
  25304. }
  25305. for (var sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx++) {
  25306. var sho = newShapeHoles[sIdx];
  25307. for (var hIdx = 0; hIdx < sho.length; hIdx++) {
  25308. var ho = sho[hIdx];
  25309. var hole_unassigned = true;
  25310. for (var s2Idx = 0; s2Idx < newShapes.length; s2Idx++) {
  25311. if (isPointInsidePolygon(ho.p, newShapes[s2Idx].p)) {
  25312. if (sIdx !== s2Idx) toChange.push({
  25313. froms: sIdx,
  25314. tos: s2Idx,
  25315. hole: hIdx
  25316. });
  25317. if (hole_unassigned) {
  25318. hole_unassigned = false;
  25319. betterShapeHoles[s2Idx].push(ho);
  25320. } else {
  25321. ambiguous = true;
  25322. }
  25323. }
  25324. }
  25325. if (hole_unassigned) {
  25326. betterShapeHoles[sIdx].push(ho);
  25327. }
  25328. }
  25329. } // console.log("ambiguous: ", ambiguous);
  25330. if (toChange.length > 0) {
  25331. // console.log("to change: ", toChange);
  25332. if (!ambiguous) newShapeHoles = betterShapeHoles;
  25333. }
  25334. }
  25335. var tmpHoles;
  25336. for (var i = 0, il = newShapes.length; i < il; i++) {
  25337. tmpShape = newShapes[i].s;
  25338. shapes.push(tmpShape);
  25339. tmpHoles = newShapeHoles[i];
  25340. for (var j = 0, jl = tmpHoles.length; j < jl; j++) {
  25341. tmpShape.holes.push(tmpHoles[j].h);
  25342. }
  25343. } //console.log("shape", shapes);
  25344. return shapes;
  25345. }
  25346. });
  25347. /**
  25348. * @author zz85 / http://www.lab4games.net/zz85/blog
  25349. * @author mrdoob / http://mrdoob.com/
  25350. */
  25351. function Font(data) {
  25352. this.type = 'Font';
  25353. this.data = data;
  25354. }
  25355. Object.assign(Font.prototype, {
  25356. isFont: true,
  25357. generateShapes: function (text, size) {
  25358. if (size === undefined) size = 100;
  25359. var shapes = [];
  25360. var paths = createPaths(text, size, this.data);
  25361. for (var p = 0, pl = paths.length; p < pl; p++) {
  25362. Array.prototype.push.apply(shapes, paths[p].toShapes());
  25363. }
  25364. return shapes;
  25365. }
  25366. });
  25367. function createPaths(text, size, data) {
  25368. var chars = Array.from ? Array.from(text) : String(text).split(''); // see #13988
  25369. var scale = size / data.resolution;
  25370. var line_height = (data.boundingBox.yMax - data.boundingBox.yMin + data.underlineThickness) * scale;
  25371. var paths = [];
  25372. var offsetX = 0,
  25373. offsetY = 0;
  25374. for (var i = 0; i < chars.length; i++) {
  25375. var char = chars[i];
  25376. if (char === '\n') {
  25377. offsetX = 0;
  25378. offsetY -= line_height;
  25379. } else {
  25380. var ret = createPath(char, scale, offsetX, offsetY, data);
  25381. offsetX += ret.offsetX;
  25382. paths.push(ret.path);
  25383. }
  25384. }
  25385. return paths;
  25386. }
  25387. function createPath(char, scale, offsetX, offsetY, data) {
  25388. var glyph = data.glyphs[char] || data.glyphs['?'];
  25389. if (!glyph) {
  25390. console.error('THREE.Font: character "' + char + '" does not exists in font family ' + data.familyName + '.');
  25391. return;
  25392. }
  25393. var path = new ShapePath();
  25394. var x, y, cpx, cpy, cpx1, cpy1, cpx2, cpy2;
  25395. if (glyph.o) {
  25396. var outline = glyph._cachedOutline || (glyph._cachedOutline = glyph.o.split(' '));
  25397. for (var i = 0, l = outline.length; i < l;) {
  25398. var action = outline[i++];
  25399. switch (action) {
  25400. case 'm':
  25401. // moveTo
  25402. x = outline[i++] * scale + offsetX;
  25403. y = outline[i++] * scale + offsetY;
  25404. path.moveTo(x, y);
  25405. break;
  25406. case 'l':
  25407. // lineTo
  25408. x = outline[i++] * scale + offsetX;
  25409. y = outline[i++] * scale + offsetY;
  25410. path.lineTo(x, y);
  25411. break;
  25412. case 'q':
  25413. // quadraticCurveTo
  25414. cpx = outline[i++] * scale + offsetX;
  25415. cpy = outline[i++] * scale + offsetY;
  25416. cpx1 = outline[i++] * scale + offsetX;
  25417. cpy1 = outline[i++] * scale + offsetY;
  25418. path.quadraticCurveTo(cpx1, cpy1, cpx, cpy);
  25419. break;
  25420. case 'b':
  25421. // bezierCurveTo
  25422. cpx = outline[i++] * scale + offsetX;
  25423. cpy = outline[i++] * scale + offsetY;
  25424. cpx1 = outline[i++] * scale + offsetX;
  25425. cpy1 = outline[i++] * scale + offsetY;
  25426. cpx2 = outline[i++] * scale + offsetX;
  25427. cpy2 = outline[i++] * scale + offsetY;
  25428. path.bezierCurveTo(cpx1, cpy1, cpx2, cpy2, cpx, cpy);
  25429. break;
  25430. }
  25431. }
  25432. }
  25433. return {
  25434. offsetX: glyph.ha * scale,
  25435. path: path
  25436. };
  25437. }
  25438. /**
  25439. * @author mrdoob / http://mrdoob.com/
  25440. */
  25441. function FontLoader(manager) {
  25442. Loader.call(this, manager);
  25443. }
  25444. FontLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  25445. constructor: FontLoader,
  25446. load: function (url, onLoad, onProgress, onError) {
  25447. var scope = this;
  25448. var loader = new FileLoader(this.manager);
  25449. loader.setPath(this.path);
  25450. loader.load(url, function (text) {
  25451. var json;
  25452. try {
  25453. json = JSON.parse(text);
  25454. } catch (e) {
  25455. console.warn('THREE.FontLoader: typeface.js support is being deprecated. Use typeface.json instead.');
  25456. json = JSON.parse(text.substring(65, text.length - 2));
  25457. }
  25458. var font = scope.parse(json);
  25459. if (onLoad) onLoad(font);
  25460. }, onProgress, onError);
  25461. },
  25462. parse: function (json) {
  25463. return new Font(json);
  25464. }
  25465. });
  25466. /**
  25467. * @author mrdoob / http://mrdoob.com/
  25468. */
  25469. var _context;
  25470. var AudioContext = {
  25471. getContext: function () {
  25472. if (_context === undefined) {
  25473. _context = new (window.AudioContext || window.webkitAudioContext)();
  25474. }
  25475. return _context;
  25476. },
  25477. setContext: function (value) {
  25478. _context = value;
  25479. }
  25480. };
  25481. /**
  25482. * @author Reece Aaron Lecrivain / http://reecenotes.com/
  25483. */
  25484. exports.AudioContext = AudioContext;
  25485. function AudioLoader(manager) {
  25486. Loader.call(this, manager);
  25487. }
  25488. AudioLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  25489. constructor: AudioLoader,
  25490. load: function (url, onLoad, onProgress, onError) {
  25491. var loader = new FileLoader(this.manager);
  25492. loader.setResponseType('arraybuffer');
  25493. loader.setPath(this.path);
  25494. loader.load(url, function (buffer) {
  25495. // Create a copy of the buffer. The `decodeAudioData` method
  25496. // detaches the buffer when complete, preventing reuse.
  25497. var bufferCopy = buffer.slice(0);
  25498. var context = AudioContext.getContext();
  25499. context.decodeAudioData(bufferCopy, function (audioBuffer) {
  25500. onLoad(audioBuffer);
  25501. });
  25502. }, onProgress, onError);
  25503. }
  25504. });
  25505. /**
  25506. * @author bhouston / http://clara.io
  25507. * @author WestLangley / http://github.com/WestLangley
  25508. *
  25509. * Primary reference:
  25510. * https://graphics.stanford.edu/papers/envmap/envmap.pdf
  25511. *
  25512. * Secondary reference:
  25513. * https://www.ppsloan.org/publications/StupidSH36.pdf
  25514. */
  25515. // 3-band SH defined by 9 coefficients
  25516. function SphericalHarmonics3() {
  25517. this.coefficients = [];
  25518. for (var i = 0; i < 9; i++) {
  25519. this.coefficients.push(new Vector3());
  25520. }
  25521. }
  25522. Object.assign(SphericalHarmonics3.prototype, {
  25523. isSphericalHarmonics3: true,
  25524. set: function (coefficients) {
  25525. for (var i = 0; i < 9; i++) {
  25526. this.coefficients[i].copy(coefficients[i]);
  25527. }
  25528. return this;
  25529. },
  25530. zero: function () {
  25531. for (var i = 0; i < 9; i++) {
  25532. this.coefficients[i].set(0, 0, 0);
  25533. }
  25534. return this;
  25535. },
  25536. // get the radiance in the direction of the normal
  25537. // target is a Vector3
  25538. getAt: function (normal, target) {
  25539. // normal is assumed to be unit length
  25540. var x = normal.x,
  25541. y = normal.y,
  25542. z = normal.z;
  25543. var coeff = this.coefficients; // band 0
  25544. target.copy(coeff[0]).multiplyScalar(0.282095); // band 1
  25545. target.addScale(coeff[1], 0.488603 * y);
  25546. target.addScale(coeff[2], 0.488603 * z);
  25547. target.addScale(coeff[3], 0.488603 * x); // band 2
  25548. target.addScale(coeff[4], 1.092548 * (x * y));
  25549. target.addScale(coeff[5], 1.092548 * (y * z));
  25550. target.addScale(coeff[6], 0.315392 * (3.0 * z * z - 1.0));
  25551. target.addScale(coeff[7], 1.092548 * (x * z));
  25552. target.addScale(coeff[8], 0.546274 * (x * x - y * y));
  25553. return target;
  25554. },
  25555. // get the irradiance (radiance convolved with cosine lobe) in the direction of the normal
  25556. // target is a Vector3
  25557. // https://graphics.stanford.edu/papers/envmap/envmap.pdf
  25558. getIrradianceAt: function (normal, target) {
  25559. // normal is assumed to be unit length
  25560. var x = normal.x,
  25561. y = normal.y,
  25562. z = normal.z;
  25563. var coeff = this.coefficients; // band 0
  25564. target.copy(coeff[0]).multiplyScalar(0.886227); // π * 0.282095
  25565. // band 1
  25566. target.addScale(coeff[1], 2.0 * 0.511664 * y); // ( 2 * π / 3 ) * 0.488603
  25567. target.addScale(coeff[2], 2.0 * 0.511664 * z);
  25568. target.addScale(coeff[3], 2.0 * 0.511664 * x); // band 2
  25569. target.addScale(coeff[4], 2.0 * 0.429043 * x * y); // ( π / 4 ) * 1.092548
  25570. target.addScale(coeff[5], 2.0 * 0.429043 * y * z);
  25571. target.addScale(coeff[6], 0.743125 * z * z - 0.247708); // ( π / 4 ) * 0.315392 * 3
  25572. target.addScale(coeff[7], 2.0 * 0.429043 * x * z);
  25573. target.addScale(coeff[8], 0.429043 * (x * x - y * y)); // ( π / 4 ) * 0.546274
  25574. return target;
  25575. },
  25576. add: function (sh) {
  25577. for (var i = 0; i < 9; i++) {
  25578. this.coefficients[i].add(sh.coefficients[i]);
  25579. }
  25580. return this;
  25581. },
  25582. scale: function (s) {
  25583. for (var i = 0; i < 9; i++) {
  25584. this.coefficients[i].multiplyScalar(s);
  25585. }
  25586. return this;
  25587. },
  25588. lerp: function (sh, alpha) {
  25589. for (var i = 0; i < 9; i++) {
  25590. this.coefficients[i].lerp(sh.coefficients[i], alpha);
  25591. }
  25592. return this;
  25593. },
  25594. equals: function (sh) {
  25595. for (var i = 0; i < 9; i++) {
  25596. if (!this.coefficients[i].equals(sh.coefficients[i])) {
  25597. return false;
  25598. }
  25599. }
  25600. return true;
  25601. },
  25602. copy: function (sh) {
  25603. return this.set(sh.coefficients);
  25604. },
  25605. clone: function () {
  25606. return new this.constructor().copy(this);
  25607. },
  25608. fromArray: function (array, offset) {
  25609. if (offset === undefined) offset = 0;
  25610. var coefficients = this.coefficients;
  25611. for (var i = 0; i < 9; i++) {
  25612. coefficients[i].fromArray(array, offset + i * 3);
  25613. }
  25614. return this;
  25615. },
  25616. toArray: function (array, offset) {
  25617. if (array === undefined) array = [];
  25618. if (offset === undefined) offset = 0;
  25619. var coefficients = this.coefficients;
  25620. for (var i = 0; i < 9; i++) {
  25621. coefficients[i].toArray(array, offset + i * 3);
  25622. }
  25623. return array;
  25624. }
  25625. });
  25626. Object.assign(SphericalHarmonics3, {
  25627. // evaluate the basis functions
  25628. // shBasis is an Array[ 9 ]
  25629. getBasisAt: function (normal, shBasis) {
  25630. // normal is assumed to be unit length
  25631. var x = normal.x,
  25632. y = normal.y,
  25633. z = normal.z; // band 0
  25634. shBasis[0] = 0.282095; // band 1
  25635. shBasis[1] = 0.488603 * y;
  25636. shBasis[2] = 0.488603 * z;
  25637. shBasis[3] = 0.488603 * x; // band 2
  25638. shBasis[4] = 1.092548 * x * y;
  25639. shBasis[5] = 1.092548 * y * z;
  25640. shBasis[6] = 0.315392 * (3 * z * z - 1);
  25641. shBasis[7] = 1.092548 * x * z;
  25642. shBasis[8] = 0.546274 * (x * x - y * y);
  25643. }
  25644. });
  25645. /**
  25646. * @author WestLangley / http://github.com/WestLangley
  25647. *
  25648. * A LightProbe is a source of indirect-diffuse light
  25649. */
  25650. function LightProbe(sh, intensity) {
  25651. Light.call(this, undefined, intensity);
  25652. this.sh = sh !== undefined ? sh : new SphericalHarmonics3();
  25653. }
  25654. LightProbe.prototype = Object.assign(Object.create(Light.prototype), {
  25655. constructor: LightProbe,
  25656. isLightProbe: true,
  25657. copy: function (source) {
  25658. Light.prototype.copy.call(this, source);
  25659. this.sh.copy(source.sh);
  25660. this.intensity = source.intensity;
  25661. return this;
  25662. },
  25663. toJSON: function (meta) {
  25664. var data = Light.prototype.toJSON.call(this, meta); // data.sh = this.sh.toArray(); // todo
  25665. return data;
  25666. }
  25667. });
  25668. /**
  25669. * @author WestLangley / http://github.com/WestLangley
  25670. */
  25671. function HemisphereLightProbe(skyColor, groundColor, intensity) {
  25672. LightProbe.call(this, undefined, intensity);
  25673. var color1 = new Color().set(skyColor);
  25674. var color2 = new Color().set(groundColor);
  25675. var sky = new Vector3(color1.r, color1.g, color1.b);
  25676. var ground = new Vector3(color2.r, color2.g, color2.b); // without extra factor of PI in the shader, should = 1 / Math.sqrt( Math.PI );
  25677. var c0 = Math.sqrt(Math.PI);
  25678. var c1 = c0 * Math.sqrt(0.75);
  25679. this.sh.coefficients[0].copy(sky).add(ground).multiplyScalar(c0);
  25680. this.sh.coefficients[1].copy(sky).sub(ground).multiplyScalar(c1);
  25681. }
  25682. HemisphereLightProbe.prototype = Object.assign(Object.create(LightProbe.prototype), {
  25683. constructor: HemisphereLightProbe,
  25684. isHemisphereLightProbe: true,
  25685. copy: function (source) {
  25686. // modifying colors not currently supported
  25687. LightProbe.prototype.copy.call(this, source);
  25688. return this;
  25689. },
  25690. toJSON: function (meta) {
  25691. var data = LightProbe.prototype.toJSON.call(this, meta); // data.sh = this.sh.toArray(); // todo
  25692. return data;
  25693. }
  25694. });
  25695. /**
  25696. * @author WestLangley / http://github.com/WestLangley
  25697. */
  25698. function AmbientLightProbe(color, intensity) {
  25699. LightProbe.call(this, undefined, intensity);
  25700. var color1 = new Color().set(color); // without extra factor of PI in the shader, would be 2 / Math.sqrt( Math.PI );
  25701. this.sh.coefficients[0].set(color1.r, color1.g, color1.b).multiplyScalar(2 * Math.sqrt(Math.PI));
  25702. }
  25703. AmbientLightProbe.prototype = Object.assign(Object.create(LightProbe.prototype), {
  25704. constructor: AmbientLightProbe,
  25705. isAmbientLightProbe: true,
  25706. copy: function (source) {
  25707. // modifying color not currently supported
  25708. LightProbe.prototype.copy.call(this, source);
  25709. return this;
  25710. },
  25711. toJSON: function (meta) {
  25712. var data = LightProbe.prototype.toJSON.call(this, meta); // data.sh = this.sh.toArray(); // todo
  25713. return data;
  25714. }
  25715. });
  25716. var _eyeRight = new Matrix4();
  25717. var _eyeLeft = new Matrix4();
  25718. /**
  25719. * @author mrdoob / http://mrdoob.com/
  25720. */
  25721. function StereoCamera() {
  25722. this.type = 'StereoCamera';
  25723. this.aspect = 1;
  25724. this.eyeSep = 0.064;
  25725. this.cameraL = new PerspectiveCamera();
  25726. this.cameraL.layers.enable(1);
  25727. this.cameraL.matrixAutoUpdate = false;
  25728. this.cameraR = new PerspectiveCamera();
  25729. this.cameraR.layers.enable(2);
  25730. this.cameraR.matrixAutoUpdate = false;
  25731. this._cache = {
  25732. focus: null,
  25733. fov: null,
  25734. aspect: null,
  25735. near: null,
  25736. far: null,
  25737. zoom: null,
  25738. eyeSep: null
  25739. };
  25740. }
  25741. Object.assign(StereoCamera.prototype, {
  25742. update: function (camera) {
  25743. var cache = this._cache;
  25744. 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;
  25745. if (needsUpdate) {
  25746. cache.focus = camera.focus;
  25747. cache.fov = camera.fov;
  25748. cache.aspect = camera.aspect * this.aspect;
  25749. cache.near = camera.near;
  25750. cache.far = camera.far;
  25751. cache.zoom = camera.zoom;
  25752. cache.eyeSep = this.eyeSep; // Off-axis stereoscopic effect based on
  25753. // http://paulbourke.net/stereographics/stereorender/
  25754. var projectionMatrix = camera.projectionMatrix.clone();
  25755. var eyeSepHalf = cache.eyeSep / 2;
  25756. var eyeSepOnProjection = eyeSepHalf * cache.near / cache.focus;
  25757. var ymax = cache.near * Math.tan(_Math.DEG2RAD * cache.fov * 0.5) / cache.zoom;
  25758. var xmin, xmax; // translate xOffset
  25759. _eyeLeft.elements[12] = -eyeSepHalf;
  25760. _eyeRight.elements[12] = eyeSepHalf; // for left eye
  25761. xmin = -ymax * cache.aspect + eyeSepOnProjection;
  25762. xmax = ymax * cache.aspect + eyeSepOnProjection;
  25763. projectionMatrix.elements[0] = 2 * cache.near / (xmax - xmin);
  25764. projectionMatrix.elements[8] = (xmax + xmin) / (xmax - xmin);
  25765. this.cameraL.projectionMatrix.copy(projectionMatrix); // for right eye
  25766. xmin = -ymax * cache.aspect - eyeSepOnProjection;
  25767. xmax = ymax * cache.aspect - eyeSepOnProjection;
  25768. projectionMatrix.elements[0] = 2 * cache.near / (xmax - xmin);
  25769. projectionMatrix.elements[8] = (xmax + xmin) / (xmax - xmin);
  25770. this.cameraR.projectionMatrix.copy(projectionMatrix);
  25771. }
  25772. this.cameraL.matrixWorld.copy(camera.matrixWorld).multiply(_eyeLeft);
  25773. this.cameraR.matrixWorld.copy(camera.matrixWorld).multiply(_eyeRight);
  25774. }
  25775. });
  25776. /**
  25777. * @author alteredq / http://alteredqualia.com/
  25778. */
  25779. function Clock(autoStart) {
  25780. this.autoStart = autoStart !== undefined ? autoStart : true;
  25781. this.startTime = 0;
  25782. this.oldTime = 0;
  25783. this.elapsedTime = 0;
  25784. this.running = false;
  25785. }
  25786. Object.assign(Clock.prototype, {
  25787. start: function () {
  25788. this.startTime = (typeof performance === 'undefined' ? Date : performance).now(); // see #10732
  25789. this.oldTime = this.startTime;
  25790. this.elapsedTime = 0;
  25791. this.running = true;
  25792. },
  25793. stop: function () {
  25794. this.getElapsedTime();
  25795. this.running = false;
  25796. this.autoStart = false;
  25797. },
  25798. getElapsedTime: function () {
  25799. this.getDelta();
  25800. return this.elapsedTime;
  25801. },
  25802. getDelta: function () {
  25803. var diff = 0;
  25804. if (this.autoStart && !this.running) {
  25805. this.start();
  25806. return 0;
  25807. }
  25808. if (this.running) {
  25809. var newTime = (typeof performance === 'undefined' ? Date : performance).now();
  25810. diff = (newTime - this.oldTime) / 1000;
  25811. this.oldTime = newTime;
  25812. this.elapsedTime += diff;
  25813. }
  25814. return diff;
  25815. }
  25816. });
  25817. /**
  25818. * @author mrdoob / http://mrdoob.com/
  25819. */
  25820. var _position$2 = new Vector3();
  25821. var _quaternion$3 = new Quaternion();
  25822. var _scale$1 = new Vector3();
  25823. var _orientation = new Vector3();
  25824. function AudioListener() {
  25825. Object3D.call(this);
  25826. this.type = 'AudioListener';
  25827. this.context = AudioContext.getContext();
  25828. this.gain = this.context.createGain();
  25829. this.gain.connect(this.context.destination);
  25830. this.filter = null;
  25831. this.timeDelta = 0; // private
  25832. this._clock = new Clock();
  25833. }
  25834. AudioListener.prototype = Object.assign(Object.create(Object3D.prototype), {
  25835. constructor: AudioListener,
  25836. getInput: function () {
  25837. return this.gain;
  25838. },
  25839. removeFilter: function () {
  25840. if (this.filter !== null) {
  25841. this.gain.disconnect(this.filter);
  25842. this.filter.disconnect(this.context.destination);
  25843. this.gain.connect(this.context.destination);
  25844. this.filter = null;
  25845. }
  25846. return this;
  25847. },
  25848. getFilter: function () {
  25849. return this.filter;
  25850. },
  25851. setFilter: function (value) {
  25852. if (this.filter !== null) {
  25853. this.gain.disconnect(this.filter);
  25854. this.filter.disconnect(this.context.destination);
  25855. } else {
  25856. this.gain.disconnect(this.context.destination);
  25857. }
  25858. this.filter = value;
  25859. this.gain.connect(this.filter);
  25860. this.filter.connect(this.context.destination);
  25861. return this;
  25862. },
  25863. getMasterVolume: function () {
  25864. return this.gain.gain.value;
  25865. },
  25866. setMasterVolume: function (value) {
  25867. this.gain.gain.setTargetAtTime(value, this.context.currentTime, 0.01);
  25868. return this;
  25869. },
  25870. updateMatrixWorld: function (force) {
  25871. Object3D.prototype.updateMatrixWorld.call(this, force);
  25872. var listener = this.context.listener;
  25873. var up = this.up;
  25874. this.timeDelta = this._clock.getDelta();
  25875. this.matrixWorld.decompose(_position$2, _quaternion$3, _scale$1);
  25876. _orientation.set(0, 0, -1).applyQuaternion(_quaternion$3);
  25877. if (listener.positionX) {
  25878. // code path for Chrome (see #14393)
  25879. var endTime = this.context.currentTime + this.timeDelta;
  25880. listener.positionX.linearRampToValueAtTime(_position$2.x, endTime);
  25881. listener.positionY.linearRampToValueAtTime(_position$2.y, endTime);
  25882. listener.positionZ.linearRampToValueAtTime(_position$2.z, endTime);
  25883. listener.forwardX.linearRampToValueAtTime(_orientation.x, endTime);
  25884. listener.forwardY.linearRampToValueAtTime(_orientation.y, endTime);
  25885. listener.forwardZ.linearRampToValueAtTime(_orientation.z, endTime);
  25886. listener.upX.linearRampToValueAtTime(up.x, endTime);
  25887. listener.upY.linearRampToValueAtTime(up.y, endTime);
  25888. listener.upZ.linearRampToValueAtTime(up.z, endTime);
  25889. } else {
  25890. listener.setPosition(_position$2.x, _position$2.y, _position$2.z);
  25891. listener.setOrientation(_orientation.x, _orientation.y, _orientation.z, up.x, up.y, up.z);
  25892. }
  25893. }
  25894. });
  25895. /**
  25896. * @author mrdoob / http://mrdoob.com/
  25897. * @author Reece Aaron Lecrivain / http://reecenotes.com/
  25898. */
  25899. function Audio(listener) {
  25900. Object3D.call(this);
  25901. this.type = 'Audio';
  25902. this.listener = listener;
  25903. this.context = listener.context;
  25904. this.gain = this.context.createGain();
  25905. this.gain.connect(listener.getInput());
  25906. this.autoplay = false;
  25907. this.buffer = null;
  25908. this.detune = 0;
  25909. this.loop = false;
  25910. this.startTime = 0;
  25911. this.offset = 0;
  25912. this.duration = undefined;
  25913. this.playbackRate = 1;
  25914. this.isPlaying = false;
  25915. this.hasPlaybackControl = true;
  25916. this.sourceType = 'empty';
  25917. this.filters = [];
  25918. }
  25919. Audio.prototype = Object.assign(Object.create(Object3D.prototype), {
  25920. constructor: Audio,
  25921. getOutput: function () {
  25922. return this.gain;
  25923. },
  25924. setNodeSource: function (audioNode) {
  25925. this.hasPlaybackControl = false;
  25926. this.sourceType = 'audioNode';
  25927. this.source = audioNode;
  25928. this.connect();
  25929. return this;
  25930. },
  25931. setMediaElementSource: function (mediaElement) {
  25932. this.hasPlaybackControl = false;
  25933. this.sourceType = 'mediaNode';
  25934. this.source = this.context.createMediaElementSource(mediaElement);
  25935. this.connect();
  25936. return this;
  25937. },
  25938. setMediaStreamSource: function (mediaStream) {
  25939. this.hasPlaybackControl = false;
  25940. this.sourceType = 'mediaStreamNode';
  25941. this.source = this.context.createMediaStreamSource(mediaStream);
  25942. this.connect();
  25943. return this;
  25944. },
  25945. setBuffer: function (audioBuffer) {
  25946. this.buffer = audioBuffer;
  25947. this.sourceType = 'buffer';
  25948. if (this.autoplay) this.play();
  25949. return this;
  25950. },
  25951. play: function () {
  25952. if (this.isPlaying === true) {
  25953. console.warn('THREE.Audio: Audio is already playing.');
  25954. return;
  25955. }
  25956. if (this.hasPlaybackControl === false) {
  25957. console.warn('THREE.Audio: this Audio has no playback control.');
  25958. return;
  25959. }
  25960. var source = this.context.createBufferSource();
  25961. source.buffer = this.buffer;
  25962. source.loop = this.loop;
  25963. source.onended = this.onEnded.bind(this);
  25964. this.startTime = this.context.currentTime;
  25965. source.start(this.startTime, this.offset, this.duration);
  25966. this.isPlaying = true;
  25967. this.source = source;
  25968. this.setDetune(this.detune);
  25969. this.setPlaybackRate(this.playbackRate);
  25970. return this.connect();
  25971. },
  25972. pause: function () {
  25973. if (this.hasPlaybackControl === false) {
  25974. console.warn('THREE.Audio: this Audio has no playback control.');
  25975. return;
  25976. }
  25977. if (this.isPlaying === true) {
  25978. this.source.stop();
  25979. this.source.onended = null;
  25980. this.offset += (this.context.currentTime - this.startTime) * this.playbackRate;
  25981. this.isPlaying = false;
  25982. }
  25983. return this;
  25984. },
  25985. stop: function () {
  25986. if (this.hasPlaybackControl === false) {
  25987. console.warn('THREE.Audio: this Audio has no playback control.');
  25988. return;
  25989. }
  25990. this.source.stop();
  25991. this.source.onended = null;
  25992. this.offset = 0;
  25993. this.isPlaying = false;
  25994. return this;
  25995. },
  25996. connect: function () {
  25997. if (this.filters.length > 0) {
  25998. this.source.connect(this.filters[0]);
  25999. for (var i = 1, l = this.filters.length; i < l; i++) {
  26000. this.filters[i - 1].connect(this.filters[i]);
  26001. }
  26002. this.filters[this.filters.length - 1].connect(this.getOutput());
  26003. } else {
  26004. this.source.connect(this.getOutput());
  26005. }
  26006. return this;
  26007. },
  26008. disconnect: function () {
  26009. if (this.filters.length > 0) {
  26010. this.source.disconnect(this.filters[0]);
  26011. for (var i = 1, l = this.filters.length; i < l; i++) {
  26012. this.filters[i - 1].disconnect(this.filters[i]);
  26013. }
  26014. this.filters[this.filters.length - 1].disconnect(this.getOutput());
  26015. } else {
  26016. this.source.disconnect(this.getOutput());
  26017. }
  26018. return this;
  26019. },
  26020. getFilters: function () {
  26021. return this.filters;
  26022. },
  26023. setFilters: function (value) {
  26024. if (!value) value = [];
  26025. if (this.isPlaying === true) {
  26026. this.disconnect();
  26027. this.filters = value;
  26028. this.connect();
  26029. } else {
  26030. this.filters = value;
  26031. }
  26032. return this;
  26033. },
  26034. setDetune: function (value) {
  26035. this.detune = value;
  26036. if (this.source.detune === undefined) return; // only set detune when available
  26037. if (this.isPlaying === true) {
  26038. this.source.detune.setTargetAtTime(this.detune, this.context.currentTime, 0.01);
  26039. }
  26040. return this;
  26041. },
  26042. getDetune: function () {
  26043. return this.detune;
  26044. },
  26045. getFilter: function () {
  26046. return this.getFilters()[0];
  26047. },
  26048. setFilter: function (filter) {
  26049. return this.setFilters(filter ? [filter] : []);
  26050. },
  26051. setPlaybackRate: function (value) {
  26052. if (this.hasPlaybackControl === false) {
  26053. console.warn('THREE.Audio: this Audio has no playback control.');
  26054. return;
  26055. }
  26056. this.playbackRate = value;
  26057. if (this.isPlaying === true) {
  26058. this.source.playbackRate.setTargetAtTime(this.playbackRate, this.context.currentTime, 0.01);
  26059. }
  26060. return this;
  26061. },
  26062. getPlaybackRate: function () {
  26063. return this.playbackRate;
  26064. },
  26065. onEnded: function () {
  26066. this.isPlaying = false;
  26067. },
  26068. getLoop: function () {
  26069. if (this.hasPlaybackControl === false) {
  26070. console.warn('THREE.Audio: this Audio has no playback control.');
  26071. return false;
  26072. }
  26073. return this.loop;
  26074. },
  26075. setLoop: function (value) {
  26076. if (this.hasPlaybackControl === false) {
  26077. console.warn('THREE.Audio: this Audio has no playback control.');
  26078. return;
  26079. }
  26080. this.loop = value;
  26081. if (this.isPlaying === true) {
  26082. this.source.loop = this.loop;
  26083. }
  26084. return this;
  26085. },
  26086. getVolume: function () {
  26087. return this.gain.gain.value;
  26088. },
  26089. setVolume: function (value) {
  26090. this.gain.gain.setTargetAtTime(value, this.context.currentTime, 0.01);
  26091. return this;
  26092. }
  26093. });
  26094. /**
  26095. * @author mrdoob / http://mrdoob.com/
  26096. */
  26097. var _position$3 = new Vector3();
  26098. var _quaternion$4 = new Quaternion();
  26099. var _scale$2 = new Vector3();
  26100. var _orientation$1 = new Vector3();
  26101. function PositionalAudio(listener) {
  26102. Audio.call(this, listener);
  26103. this.panner = this.context.createPanner();
  26104. this.panner.panningModel = 'HRTF';
  26105. this.panner.connect(this.gain);
  26106. }
  26107. PositionalAudio.prototype = Object.assign(Object.create(Audio.prototype), {
  26108. constructor: PositionalAudio,
  26109. getOutput: function () {
  26110. return this.panner;
  26111. },
  26112. getRefDistance: function () {
  26113. return this.panner.refDistance;
  26114. },
  26115. setRefDistance: function (value) {
  26116. this.panner.refDistance = value;
  26117. return this;
  26118. },
  26119. getRolloffFactor: function () {
  26120. return this.panner.rolloffFactor;
  26121. },
  26122. setRolloffFactor: function (value) {
  26123. this.panner.rolloffFactor = value;
  26124. return this;
  26125. },
  26126. getDistanceModel: function () {
  26127. return this.panner.distanceModel;
  26128. },
  26129. setDistanceModel: function (value) {
  26130. this.panner.distanceModel = value;
  26131. return this;
  26132. },
  26133. getMaxDistance: function () {
  26134. return this.panner.maxDistance;
  26135. },
  26136. setMaxDistance: function (value) {
  26137. this.panner.maxDistance = value;
  26138. return this;
  26139. },
  26140. setDirectionalCone: function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  26141. this.panner.coneInnerAngle = coneInnerAngle;
  26142. this.panner.coneOuterAngle = coneOuterAngle;
  26143. this.panner.coneOuterGain = coneOuterGain;
  26144. return this;
  26145. },
  26146. updateMatrixWorld: function (force) {
  26147. Object3D.prototype.updateMatrixWorld.call(this, force);
  26148. if (this.hasPlaybackControl === true && this.isPlaying === false) return;
  26149. this.matrixWorld.decompose(_position$3, _quaternion$4, _scale$2);
  26150. _orientation$1.set(0, 0, 1).applyQuaternion(_quaternion$4);
  26151. var panner = this.panner;
  26152. if (panner.positionX) {
  26153. // code path for Chrome and Firefox (see #14393)
  26154. var endTime = this.context.currentTime + this.listener.timeDelta;
  26155. panner.positionX.linearRampToValueAtTime(_position$3.x, endTime);
  26156. panner.positionY.linearRampToValueAtTime(_position$3.y, endTime);
  26157. panner.positionZ.linearRampToValueAtTime(_position$3.z, endTime);
  26158. panner.orientationX.linearRampToValueAtTime(_orientation$1.x, endTime);
  26159. panner.orientationY.linearRampToValueAtTime(_orientation$1.y, endTime);
  26160. panner.orientationZ.linearRampToValueAtTime(_orientation$1.z, endTime);
  26161. } else {
  26162. panner.setPosition(_position$3.x, _position$3.y, _position$3.z);
  26163. panner.setOrientation(_orientation$1.x, _orientation$1.y, _orientation$1.z);
  26164. }
  26165. }
  26166. });
  26167. /**
  26168. * @author mrdoob / http://mrdoob.com/
  26169. */
  26170. function AudioAnalyser(audio, fftSize) {
  26171. this.analyser = audio.context.createAnalyser();
  26172. this.analyser.fftSize = fftSize !== undefined ? fftSize : 2048;
  26173. this.data = new Uint8Array(this.analyser.frequencyBinCount);
  26174. audio.getOutput().connect(this.analyser);
  26175. }
  26176. Object.assign(AudioAnalyser.prototype, {
  26177. getFrequencyData: function () {
  26178. this.analyser.getByteFrequencyData(this.data);
  26179. return this.data;
  26180. },
  26181. getAverageFrequency: function () {
  26182. var value = 0,
  26183. data = this.getFrequencyData();
  26184. for (var i = 0; i < data.length; i++) {
  26185. value += data[i];
  26186. }
  26187. return value / data.length;
  26188. }
  26189. });
  26190. /**
  26191. *
  26192. * Buffered scene graph property that allows weighted accumulation.
  26193. *
  26194. *
  26195. * @author Ben Houston / http://clara.io/
  26196. * @author David Sarno / http://lighthaus.us/
  26197. * @author tschw
  26198. */
  26199. function PropertyMixer(binding, typeName, valueSize) {
  26200. this.binding = binding;
  26201. this.valueSize = valueSize;
  26202. var bufferType = Float64Array,
  26203. mixFunction;
  26204. switch (typeName) {
  26205. case 'quaternion':
  26206. mixFunction = this._slerp;
  26207. break;
  26208. case 'string':
  26209. case 'bool':
  26210. bufferType = Array;
  26211. mixFunction = this._select;
  26212. break;
  26213. default:
  26214. mixFunction = this._lerp;
  26215. }
  26216. this.buffer = new bufferType(valueSize * 4); // layout: [ incoming | accu0 | accu1 | orig ]
  26217. //
  26218. // interpolators can use .buffer as their .result
  26219. // the data then goes to 'incoming'
  26220. //
  26221. // 'accu0' and 'accu1' are used frame-interleaved for
  26222. // the cumulative result and are compared to detect
  26223. // changes
  26224. //
  26225. // 'orig' stores the original state of the property
  26226. this._mixBufferRegion = mixFunction;
  26227. this.cumulativeWeight = 0;
  26228. this.useCount = 0;
  26229. this.referenceCount = 0;
  26230. }
  26231. Object.assign(PropertyMixer.prototype, {
  26232. // accumulate data in the 'incoming' region into 'accu<i>'
  26233. accumulate: function (accuIndex, weight) {
  26234. // note: happily accumulating nothing when weight = 0, the caller knows
  26235. // the weight and shouldn't have made the call in the first place
  26236. var buffer = this.buffer,
  26237. stride = this.valueSize,
  26238. offset = accuIndex * stride + stride,
  26239. currentWeight = this.cumulativeWeight;
  26240. if (currentWeight === 0) {
  26241. // accuN := incoming * weight
  26242. for (var i = 0; i !== stride; ++i) {
  26243. buffer[offset + i] = buffer[i];
  26244. }
  26245. currentWeight = weight;
  26246. } else {
  26247. // accuN := accuN + incoming * weight
  26248. currentWeight += weight;
  26249. var mix = weight / currentWeight;
  26250. this._mixBufferRegion(buffer, offset, 0, mix, stride);
  26251. }
  26252. this.cumulativeWeight = currentWeight;
  26253. },
  26254. // apply the state of 'accu<i>' to the binding when accus differ
  26255. apply: function (accuIndex) {
  26256. var stride = this.valueSize,
  26257. buffer = this.buffer,
  26258. offset = accuIndex * stride + stride,
  26259. weight = this.cumulativeWeight,
  26260. binding = this.binding;
  26261. this.cumulativeWeight = 0;
  26262. if (weight < 1) {
  26263. // accuN := accuN + original * ( 1 - cumulativeWeight )
  26264. var originalValueOffset = stride * 3;
  26265. this._mixBufferRegion(buffer, offset, originalValueOffset, 1 - weight, stride);
  26266. }
  26267. for (var i = stride, e = stride + stride; i !== e; ++i) {
  26268. if (buffer[i] !== buffer[i + stride]) {
  26269. // value has changed -> update scene graph
  26270. binding.setValue(buffer, offset);
  26271. break;
  26272. }
  26273. }
  26274. },
  26275. // remember the state of the bound property and copy it to both accus
  26276. saveOriginalState: function () {
  26277. var binding = this.binding;
  26278. var buffer = this.buffer,
  26279. stride = this.valueSize,
  26280. originalValueOffset = stride * 3;
  26281. binding.getValue(buffer, originalValueOffset); // accu[0..1] := orig -- initially detect changes against the original
  26282. for (var i = stride, e = originalValueOffset; i !== e; ++i) {
  26283. buffer[i] = buffer[originalValueOffset + i % stride];
  26284. }
  26285. this.cumulativeWeight = 0;
  26286. },
  26287. // apply the state previously taken via 'saveOriginalState' to the binding
  26288. restoreOriginalState: function () {
  26289. var originalValueOffset = this.valueSize * 3;
  26290. this.binding.setValue(this.buffer, originalValueOffset);
  26291. },
  26292. // mix functions
  26293. _select: function (buffer, dstOffset, srcOffset, t, stride) {
  26294. if (t >= 0.5) {
  26295. for (var i = 0; i !== stride; ++i) {
  26296. buffer[dstOffset + i] = buffer[srcOffset + i];
  26297. }
  26298. }
  26299. },
  26300. _slerp: function (buffer, dstOffset, srcOffset, t) {
  26301. Quaternion.slerpFlat(buffer, dstOffset, buffer, dstOffset, buffer, srcOffset, t);
  26302. },
  26303. _lerp: function (buffer, dstOffset, srcOffset, t, stride) {
  26304. var s = 1 - t;
  26305. for (var i = 0; i !== stride; ++i) {
  26306. var j = dstOffset + i;
  26307. buffer[j] = buffer[j] * s + buffer[srcOffset + i] * t;
  26308. }
  26309. }
  26310. });
  26311. /**
  26312. *
  26313. * A reference to a real property in the scene graph.
  26314. *
  26315. *
  26316. * @author Ben Houston / http://clara.io/
  26317. * @author David Sarno / http://lighthaus.us/
  26318. * @author tschw
  26319. */
  26320. // Characters [].:/ are reserved for track binding syntax.
  26321. var _RESERVED_CHARS_RE = '\\[\\]\\.:\\/';
  26322. var _reservedRe = new RegExp('[' + _RESERVED_CHARS_RE + ']', 'g'); // Attempts to allow node names from any language. ES5's `\w` regexp matches
  26323. // only latin characters, and the unicode \p{L} is not yet supported. So
  26324. // instead, we exclude reserved characters and match everything else.
  26325. var _wordChar = '[^' + _RESERVED_CHARS_RE + ']';
  26326. var _wordCharOrDot = '[^' + _RESERVED_CHARS_RE.replace('\\.', '') + ']'; // Parent directories, delimited by '/' or ':'. Currently unused, but must
  26327. // be matched to parse the rest of the track name.
  26328. var _directoryRe = /((?:WC+[\/:])*)/.source.replace('WC', _wordChar); // Target node. May contain word characters (a-zA-Z0-9_) and '.' or '-'.
  26329. var _nodeRe = /(WCOD+)?/.source.replace('WCOD', _wordCharOrDot); // Object on target node, and accessor. May not contain reserved
  26330. // characters. Accessor may contain any character except closing bracket.
  26331. var _objectRe = /(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace('WC', _wordChar); // Property and accessor. May not contain reserved characters. Accessor may
  26332. // contain any non-bracket characters.
  26333. var _propertyRe = /\.(WC+)(?:\[(.+)\])?/.source.replace('WC', _wordChar);
  26334. var _trackRe = new RegExp('' + '^' + _directoryRe + _nodeRe + _objectRe + _propertyRe + '$');
  26335. var _supportedObjectNames = ['material', 'materials', 'bones'];
  26336. function Composite(targetGroup, path, optionalParsedPath) {
  26337. var parsedPath = optionalParsedPath || PropertyBinding.parseTrackName(path);
  26338. this._targetGroup = targetGroup;
  26339. this._bindings = targetGroup.subscribe_(path, parsedPath);
  26340. }
  26341. Object.assign(Composite.prototype, {
  26342. getValue: function (array, offset) {
  26343. this.bind(); // bind all binding
  26344. var firstValidIndex = this._targetGroup.nCachedObjects_,
  26345. binding = this._bindings[firstValidIndex]; // and only call .getValue on the first
  26346. if (binding !== undefined) binding.getValue(array, offset);
  26347. },
  26348. setValue: function (array, offset) {
  26349. var bindings = this._bindings;
  26350. for (var i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++i) {
  26351. bindings[i].setValue(array, offset);
  26352. }
  26353. },
  26354. bind: function () {
  26355. var bindings = this._bindings;
  26356. for (var i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++i) {
  26357. bindings[i].bind();
  26358. }
  26359. },
  26360. unbind: function () {
  26361. var bindings = this._bindings;
  26362. for (var i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++i) {
  26363. bindings[i].unbind();
  26364. }
  26365. }
  26366. });
  26367. function PropertyBinding(rootNode, path, parsedPath) {
  26368. this.path = path;
  26369. this.parsedPath = parsedPath || PropertyBinding.parseTrackName(path);
  26370. this.node = PropertyBinding.findNode(rootNode, this.parsedPath.nodeName) || rootNode;
  26371. this.rootNode = rootNode;
  26372. }
  26373. Object.assign(PropertyBinding, {
  26374. Composite: Composite,
  26375. create: function (root, path, parsedPath) {
  26376. if (!(root && root.isAnimationObjectGroup)) {
  26377. return new PropertyBinding(root, path, parsedPath);
  26378. } else {
  26379. return new PropertyBinding.Composite(root, path, parsedPath);
  26380. }
  26381. },
  26382. /**
  26383. * Replaces spaces with underscores and removes unsupported characters from
  26384. * node names, to ensure compatibility with parseTrackName().
  26385. *
  26386. * @param {string} name Node name to be sanitized.
  26387. * @return {string}
  26388. */
  26389. sanitizeNodeName: function (name) {
  26390. return name.replace(/\s/g, '_').replace(_reservedRe, '');
  26391. },
  26392. parseTrackName: function (trackName) {
  26393. var matches = _trackRe.exec(trackName);
  26394. if (!matches) {
  26395. throw new Error('PropertyBinding: Cannot parse trackName: ' + trackName);
  26396. }
  26397. var results = {
  26398. // directoryName: matches[ 1 ], // (tschw) currently unused
  26399. nodeName: matches[2],
  26400. objectName: matches[3],
  26401. objectIndex: matches[4],
  26402. propertyName: matches[5],
  26403. // required
  26404. propertyIndex: matches[6]
  26405. };
  26406. var lastDot = results.nodeName && results.nodeName.lastIndexOf('.');
  26407. if (lastDot !== undefined && lastDot !== -1) {
  26408. var objectName = results.nodeName.substring(lastDot + 1); // Object names must be checked against a whitelist. Otherwise, there
  26409. // is no way to parse 'foo.bar.baz': 'baz' must be a property, but
  26410. // 'bar' could be the objectName, or part of a nodeName (which can
  26411. // include '.' characters).
  26412. if (_supportedObjectNames.indexOf(objectName) !== -1) {
  26413. results.nodeName = results.nodeName.substring(0, lastDot);
  26414. results.objectName = objectName;
  26415. }
  26416. }
  26417. if (results.propertyName === null || results.propertyName.length === 0) {
  26418. throw new Error('PropertyBinding: can not parse propertyName from trackName: ' + trackName);
  26419. }
  26420. return results;
  26421. },
  26422. findNode: function (root, nodeName) {
  26423. if (!nodeName || nodeName === "" || nodeName === "root" || nodeName === "." || nodeName === -1 || nodeName === root.name || nodeName === root.uuid) {
  26424. return root;
  26425. } // search into skeleton bones.
  26426. if (root.skeleton) {
  26427. var bone = root.skeleton.getBoneByName(nodeName);
  26428. if (bone !== undefined) {
  26429. return bone;
  26430. }
  26431. } // search into node subtree.
  26432. if (root.children) {
  26433. var searchNodeSubtree = function (children) {
  26434. for (var i = 0; i < children.length; i++) {
  26435. var childNode = children[i];
  26436. if (childNode.name === nodeName || childNode.uuid === nodeName) {
  26437. return childNode;
  26438. }
  26439. var result = searchNodeSubtree(childNode.children);
  26440. if (result) return result;
  26441. }
  26442. return null;
  26443. };
  26444. var subTreeNode = searchNodeSubtree(root.children);
  26445. if (subTreeNode) {
  26446. return subTreeNode;
  26447. }
  26448. }
  26449. return null;
  26450. }
  26451. });
  26452. Object.assign(PropertyBinding.prototype, {
  26453. // prototype, continued
  26454. // these are used to "bind" a nonexistent property
  26455. _getValue_unavailable: function () {},
  26456. _setValue_unavailable: function () {},
  26457. BindingType: {
  26458. Direct: 0,
  26459. EntireArray: 1,
  26460. ArrayElement: 2,
  26461. HasFromToArray: 3
  26462. },
  26463. Versioning: {
  26464. None: 0,
  26465. NeedsUpdate: 1,
  26466. MatrixWorldNeedsUpdate: 2
  26467. },
  26468. GetterByBindingType: [function getValue_direct(buffer, offset) {
  26469. buffer[offset] = this.node[this.propertyName];
  26470. }, function getValue_array(buffer, offset) {
  26471. var source = this.resolvedProperty;
  26472. for (var i = 0, n = source.length; i !== n; ++i) {
  26473. buffer[offset++] = source[i];
  26474. }
  26475. }, function getValue_arrayElement(buffer, offset) {
  26476. buffer[offset] = this.resolvedProperty[this.propertyIndex];
  26477. }, function getValue_toArray(buffer, offset) {
  26478. this.resolvedProperty.toArray(buffer, offset);
  26479. }],
  26480. SetterByBindingTypeAndVersioning: [[// Direct
  26481. function setValue_direct(buffer, offset) {
  26482. this.targetObject[this.propertyName] = buffer[offset];
  26483. }, function setValue_direct_setNeedsUpdate(buffer, offset) {
  26484. this.targetObject[this.propertyName] = buffer[offset];
  26485. this.targetObject.needsUpdate = true;
  26486. }, function setValue_direct_setMatrixWorldNeedsUpdate(buffer, offset) {
  26487. this.targetObject[this.propertyName] = buffer[offset];
  26488. this.targetObject.matrixWorldNeedsUpdate = true;
  26489. }], [// EntireArray
  26490. function setValue_array(buffer, offset) {
  26491. var dest = this.resolvedProperty;
  26492. for (var i = 0, n = dest.length; i !== n; ++i) {
  26493. dest[i] = buffer[offset++];
  26494. }
  26495. }, function setValue_array_setNeedsUpdate(buffer, offset) {
  26496. var dest = this.resolvedProperty;
  26497. for (var i = 0, n = dest.length; i !== n; ++i) {
  26498. dest[i] = buffer[offset++];
  26499. }
  26500. this.targetObject.needsUpdate = true;
  26501. }, function setValue_array_setMatrixWorldNeedsUpdate(buffer, offset) {
  26502. var dest = this.resolvedProperty;
  26503. for (var i = 0, n = dest.length; i !== n; ++i) {
  26504. dest[i] = buffer[offset++];
  26505. }
  26506. this.targetObject.matrixWorldNeedsUpdate = true;
  26507. }], [// ArrayElement
  26508. function setValue_arrayElement(buffer, offset) {
  26509. this.resolvedProperty[this.propertyIndex] = buffer[offset];
  26510. }, function setValue_arrayElement_setNeedsUpdate(buffer, offset) {
  26511. this.resolvedProperty[this.propertyIndex] = buffer[offset];
  26512. this.targetObject.needsUpdate = true;
  26513. }, function setValue_arrayElement_setMatrixWorldNeedsUpdate(buffer, offset) {
  26514. this.resolvedProperty[this.propertyIndex] = buffer[offset];
  26515. this.targetObject.matrixWorldNeedsUpdate = true;
  26516. }], [// HasToFromArray
  26517. function setValue_fromArray(buffer, offset) {
  26518. this.resolvedProperty.fromArray(buffer, offset);
  26519. }, function setValue_fromArray_setNeedsUpdate(buffer, offset) {
  26520. this.resolvedProperty.fromArray(buffer, offset);
  26521. this.targetObject.needsUpdate = true;
  26522. }, function setValue_fromArray_setMatrixWorldNeedsUpdate(buffer, offset) {
  26523. this.resolvedProperty.fromArray(buffer, offset);
  26524. this.targetObject.matrixWorldNeedsUpdate = true;
  26525. }]],
  26526. getValue: function getValue_unbound(targetArray, offset) {
  26527. this.bind();
  26528. this.getValue(targetArray, offset); // Note: This class uses a State pattern on a per-method basis:
  26529. // 'bind' sets 'this.getValue' / 'setValue' and shadows the
  26530. // prototype version of these methods with one that represents
  26531. // the bound state. When the property is not found, the methods
  26532. // become no-ops.
  26533. },
  26534. setValue: function getValue_unbound(sourceArray, offset) {
  26535. this.bind();
  26536. this.setValue(sourceArray, offset);
  26537. },
  26538. // create getter / setter pair for a property in the scene graph
  26539. bind: function () {
  26540. var targetObject = this.node,
  26541. parsedPath = this.parsedPath,
  26542. objectName = parsedPath.objectName,
  26543. propertyName = parsedPath.propertyName,
  26544. propertyIndex = parsedPath.propertyIndex;
  26545. if (!targetObject) {
  26546. targetObject = PropertyBinding.findNode(this.rootNode, parsedPath.nodeName) || this.rootNode;
  26547. this.node = targetObject;
  26548. } // set fail state so we can just 'return' on error
  26549. this.getValue = this._getValue_unavailable;
  26550. this.setValue = this._setValue_unavailable; // ensure there is a value node
  26551. if (!targetObject) {
  26552. console.error('THREE.PropertyBinding: Trying to update node for track: ' + this.path + ' but it wasn\'t found.');
  26553. return;
  26554. }
  26555. if (objectName) {
  26556. var objectIndex = parsedPath.objectIndex; // special cases were we need to reach deeper into the hierarchy to get the face materials....
  26557. switch (objectName) {
  26558. case 'materials':
  26559. if (!targetObject.material) {
  26560. console.error('THREE.PropertyBinding: Can not bind to material as node does not have a material.', this);
  26561. return;
  26562. }
  26563. if (!targetObject.material.materials) {
  26564. console.error('THREE.PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.', this);
  26565. return;
  26566. }
  26567. targetObject = targetObject.material.materials;
  26568. break;
  26569. case 'bones':
  26570. if (!targetObject.skeleton) {
  26571. console.error('THREE.PropertyBinding: Can not bind to bones as node does not have a skeleton.', this);
  26572. return;
  26573. } // potential future optimization: skip this if propertyIndex is already an integer
  26574. // and convert the integer string to a true integer.
  26575. targetObject = targetObject.skeleton.bones; // support resolving morphTarget names into indices.
  26576. for (var i = 0; i < targetObject.length; i++) {
  26577. if (targetObject[i].name === objectIndex) {
  26578. objectIndex = i;
  26579. break;
  26580. }
  26581. }
  26582. break;
  26583. default:
  26584. if (targetObject[objectName] === undefined) {
  26585. console.error('THREE.PropertyBinding: Can not bind to objectName of node undefined.', this);
  26586. return;
  26587. }
  26588. targetObject = targetObject[objectName];
  26589. }
  26590. if (objectIndex !== undefined) {
  26591. if (targetObject[objectIndex] === undefined) {
  26592. console.error('THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.', this, targetObject);
  26593. return;
  26594. }
  26595. targetObject = targetObject[objectIndex];
  26596. }
  26597. } // resolve property
  26598. var nodeProperty = targetObject[propertyName];
  26599. if (nodeProperty === undefined) {
  26600. var nodeName = parsedPath.nodeName;
  26601. console.error('THREE.PropertyBinding: Trying to update property for track: ' + nodeName + '.' + propertyName + ' but it wasn\'t found.', targetObject);
  26602. return;
  26603. } // determine versioning scheme
  26604. var versioning = this.Versioning.None;
  26605. this.targetObject = targetObject;
  26606. if (targetObject.needsUpdate !== undefined) {
  26607. // material
  26608. versioning = this.Versioning.NeedsUpdate;
  26609. } else if (targetObject.matrixWorldNeedsUpdate !== undefined) {
  26610. // node transform
  26611. versioning = this.Versioning.MatrixWorldNeedsUpdate;
  26612. } // determine how the property gets bound
  26613. var bindingType = this.BindingType.Direct;
  26614. if (propertyIndex !== undefined) {
  26615. // access a sub element of the property array (only primitives are supported right now)
  26616. if (propertyName === "morphTargetInfluences") {
  26617. // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer.
  26618. // support resolving morphTarget names into indices.
  26619. if (!targetObject.geometry) {
  26620. console.error('THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.', this);
  26621. return;
  26622. }
  26623. if (targetObject.geometry.isBufferGeometry) {
  26624. if (!targetObject.geometry.morphAttributes) {
  26625. console.error('THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.', this);
  26626. return;
  26627. }
  26628. for (var i = 0; i < this.node.geometry.morphAttributes.position.length; i++) {
  26629. if (targetObject.geometry.morphAttributes.position[i].name === propertyIndex) {
  26630. propertyIndex = i;
  26631. break;
  26632. }
  26633. }
  26634. } else {
  26635. if (!targetObject.geometry.morphTargets) {
  26636. console.error('THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphTargets.', this);
  26637. return;
  26638. }
  26639. for (var i = 0; i < this.node.geometry.morphTargets.length; i++) {
  26640. if (targetObject.geometry.morphTargets[i].name === propertyIndex) {
  26641. propertyIndex = i;
  26642. break;
  26643. }
  26644. }
  26645. }
  26646. }
  26647. bindingType = this.BindingType.ArrayElement;
  26648. this.resolvedProperty = nodeProperty;
  26649. this.propertyIndex = propertyIndex;
  26650. } else if (nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined) {
  26651. // must use copy for Object3D.Euler/Quaternion
  26652. bindingType = this.BindingType.HasFromToArray;
  26653. this.resolvedProperty = nodeProperty;
  26654. } else if (Array.isArray(nodeProperty)) {
  26655. bindingType = this.BindingType.EntireArray;
  26656. this.resolvedProperty = nodeProperty;
  26657. } else {
  26658. this.propertyName = propertyName;
  26659. } // select getter / setter
  26660. this.getValue = this.GetterByBindingType[bindingType];
  26661. this.setValue = this.SetterByBindingTypeAndVersioning[bindingType][versioning];
  26662. },
  26663. unbind: function () {
  26664. this.node = null; // back to the prototype version of getValue / setValue
  26665. // note: avoiding to mutate the shape of 'this' via 'delete'
  26666. this.getValue = this._getValue_unbound;
  26667. this.setValue = this._setValue_unbound;
  26668. }
  26669. }); //!\ DECLARE ALIAS AFTER assign prototype !
  26670. Object.assign(PropertyBinding.prototype, {
  26671. // initial state of these methods that calls 'bind'
  26672. _getValue_unbound: PropertyBinding.prototype.getValue,
  26673. _setValue_unbound: PropertyBinding.prototype.setValue
  26674. });
  26675. /**
  26676. *
  26677. * A group of objects that receives a shared animation state.
  26678. *
  26679. * Usage:
  26680. *
  26681. * - Add objects you would otherwise pass as 'root' to the
  26682. * constructor or the .clipAction method of AnimationMixer.
  26683. *
  26684. * - Instead pass this object as 'root'.
  26685. *
  26686. * - You can also add and remove objects later when the mixer
  26687. * is running.
  26688. *
  26689. * Note:
  26690. *
  26691. * Objects of this class appear as one object to the mixer,
  26692. * so cache control of the individual objects must be done
  26693. * on the group.
  26694. *
  26695. * Limitation:
  26696. *
  26697. * - The animated properties must be compatible among the
  26698. * all objects in the group.
  26699. *
  26700. * - A single property can either be controlled through a
  26701. * target group or directly, but not both.
  26702. *
  26703. * @author tschw
  26704. */
  26705. function AnimationObjectGroup() {
  26706. this.uuid = _Math.generateUUID(); // cached objects followed by the active ones
  26707. this._objects = Array.prototype.slice.call(arguments);
  26708. this.nCachedObjects_ = 0; // threshold
  26709. // note: read by PropertyBinding.Composite
  26710. var indices = {};
  26711. this._indicesByUUID = indices; // for bookkeeping
  26712. for (var i = 0, n = arguments.length; i !== n; ++i) {
  26713. indices[arguments[i].uuid] = i;
  26714. }
  26715. this._paths = []; // inside: string
  26716. this._parsedPaths = []; // inside: { we don't care, here }
  26717. this._bindings = []; // inside: Array< PropertyBinding >
  26718. this._bindingsIndicesByPath = {}; // inside: indices in these arrays
  26719. var scope = this;
  26720. this.stats = {
  26721. objects: {
  26722. get total() {
  26723. return scope._objects.length;
  26724. },
  26725. get inUse() {
  26726. return this.total - scope.nCachedObjects_;
  26727. }
  26728. },
  26729. get bindingsPerObject() {
  26730. return scope._bindings.length;
  26731. }
  26732. };
  26733. }
  26734. Object.assign(AnimationObjectGroup.prototype, {
  26735. isAnimationObjectGroup: true,
  26736. add: function () {
  26737. var objects = this._objects,
  26738. nObjects = objects.length,
  26739. nCachedObjects = this.nCachedObjects_,
  26740. indicesByUUID = this._indicesByUUID,
  26741. paths = this._paths,
  26742. parsedPaths = this._parsedPaths,
  26743. bindings = this._bindings,
  26744. nBindings = bindings.length,
  26745. knownObject = undefined;
  26746. for (var i = 0, n = arguments.length; i !== n; ++i) {
  26747. var object = arguments[i],
  26748. uuid = object.uuid,
  26749. index = indicesByUUID[uuid];
  26750. if (index === undefined) {
  26751. // unknown object -> add it to the ACTIVE region
  26752. index = nObjects++;
  26753. indicesByUUID[uuid] = index;
  26754. objects.push(object); // accounting is done, now do the same for all bindings
  26755. for (var j = 0, m = nBindings; j !== m; ++j) {
  26756. bindings[j].push(new PropertyBinding(object, paths[j], parsedPaths[j]));
  26757. }
  26758. } else if (index < nCachedObjects) {
  26759. knownObject = objects[index]; // move existing object to the ACTIVE region
  26760. var firstActiveIndex = --nCachedObjects,
  26761. lastCachedObject = objects[firstActiveIndex];
  26762. indicesByUUID[lastCachedObject.uuid] = index;
  26763. objects[index] = lastCachedObject;
  26764. indicesByUUID[uuid] = firstActiveIndex;
  26765. objects[firstActiveIndex] = object; // accounting is done, now do the same for all bindings
  26766. for (var j = 0, m = nBindings; j !== m; ++j) {
  26767. var bindingsForPath = bindings[j],
  26768. lastCached = bindingsForPath[firstActiveIndex],
  26769. binding = bindingsForPath[index];
  26770. bindingsForPath[index] = lastCached;
  26771. if (binding === undefined) {
  26772. // since we do not bother to create new bindings
  26773. // for objects that are cached, the binding may
  26774. // or may not exist
  26775. binding = new PropertyBinding(object, paths[j], parsedPaths[j]);
  26776. }
  26777. bindingsForPath[firstActiveIndex] = binding;
  26778. }
  26779. } else if (objects[index] !== knownObject) {
  26780. console.error('THREE.AnimationObjectGroup: Different objects with the same UUID ' + 'detected. Clean the caches or recreate your infrastructure when reloading scenes.');
  26781. } // else the object is already where we want it to be
  26782. } // for arguments
  26783. this.nCachedObjects_ = nCachedObjects;
  26784. },
  26785. remove: function () {
  26786. var objects = this._objects,
  26787. nCachedObjects = this.nCachedObjects_,
  26788. indicesByUUID = this._indicesByUUID,
  26789. bindings = this._bindings,
  26790. nBindings = bindings.length;
  26791. for (var i = 0, n = arguments.length; i !== n; ++i) {
  26792. var object = arguments[i],
  26793. uuid = object.uuid,
  26794. index = indicesByUUID[uuid];
  26795. if (index !== undefined && index >= nCachedObjects) {
  26796. // move existing object into the CACHED region
  26797. var lastCachedIndex = nCachedObjects++,
  26798. firstActiveObject = objects[lastCachedIndex];
  26799. indicesByUUID[firstActiveObject.uuid] = index;
  26800. objects[index] = firstActiveObject;
  26801. indicesByUUID[uuid] = lastCachedIndex;
  26802. objects[lastCachedIndex] = object; // accounting is done, now do the same for all bindings
  26803. for (var j = 0, m = nBindings; j !== m; ++j) {
  26804. var bindingsForPath = bindings[j],
  26805. firstActive = bindingsForPath[lastCachedIndex],
  26806. binding = bindingsForPath[index];
  26807. bindingsForPath[index] = firstActive;
  26808. bindingsForPath[lastCachedIndex] = binding;
  26809. }
  26810. }
  26811. } // for arguments
  26812. this.nCachedObjects_ = nCachedObjects;
  26813. },
  26814. // remove & forget
  26815. uncache: function () {
  26816. var objects = this._objects,
  26817. nObjects = objects.length,
  26818. nCachedObjects = this.nCachedObjects_,
  26819. indicesByUUID = this._indicesByUUID,
  26820. bindings = this._bindings,
  26821. nBindings = bindings.length;
  26822. for (var i = 0, n = arguments.length; i !== n; ++i) {
  26823. var object = arguments[i],
  26824. uuid = object.uuid,
  26825. index = indicesByUUID[uuid];
  26826. if (index !== undefined) {
  26827. delete indicesByUUID[uuid];
  26828. if (index < nCachedObjects) {
  26829. // object is cached, shrink the CACHED region
  26830. var firstActiveIndex = --nCachedObjects,
  26831. lastCachedObject = objects[firstActiveIndex],
  26832. lastIndex = --nObjects,
  26833. lastObject = objects[lastIndex]; // last cached object takes this object's place
  26834. indicesByUUID[lastCachedObject.uuid] = index;
  26835. objects[index] = lastCachedObject; // last object goes to the activated slot and pop
  26836. indicesByUUID[lastObject.uuid] = firstActiveIndex;
  26837. objects[firstActiveIndex] = lastObject;
  26838. objects.pop(); // accounting is done, now do the same for all bindings
  26839. for (var j = 0, m = nBindings; j !== m; ++j) {
  26840. var bindingsForPath = bindings[j],
  26841. lastCached = bindingsForPath[firstActiveIndex],
  26842. last = bindingsForPath[lastIndex];
  26843. bindingsForPath[index] = lastCached;
  26844. bindingsForPath[firstActiveIndex] = last;
  26845. bindingsForPath.pop();
  26846. }
  26847. } else {
  26848. // object is active, just swap with the last and pop
  26849. var lastIndex = --nObjects,
  26850. lastObject = objects[lastIndex];
  26851. indicesByUUID[lastObject.uuid] = index;
  26852. objects[index] = lastObject;
  26853. objects.pop(); // accounting is done, now do the same for all bindings
  26854. for (var j = 0, m = nBindings; j !== m; ++j) {
  26855. var bindingsForPath = bindings[j];
  26856. bindingsForPath[index] = bindingsForPath[lastIndex];
  26857. bindingsForPath.pop();
  26858. }
  26859. } // cached or active
  26860. } // if object is known
  26861. } // for arguments
  26862. this.nCachedObjects_ = nCachedObjects;
  26863. },
  26864. // Internal interface used by befriended PropertyBinding.Composite:
  26865. subscribe_: function (path, parsedPath) {
  26866. // returns an array of bindings for the given path that is changed
  26867. // according to the contained objects in the group
  26868. var indicesByPath = this._bindingsIndicesByPath,
  26869. index = indicesByPath[path],
  26870. bindings = this._bindings;
  26871. if (index !== undefined) return bindings[index];
  26872. var paths = this._paths,
  26873. parsedPaths = this._parsedPaths,
  26874. objects = this._objects,
  26875. nObjects = objects.length,
  26876. nCachedObjects = this.nCachedObjects_,
  26877. bindingsForPath = new Array(nObjects);
  26878. index = bindings.length;
  26879. indicesByPath[path] = index;
  26880. paths.push(path);
  26881. parsedPaths.push(parsedPath);
  26882. bindings.push(bindingsForPath);
  26883. for (var i = nCachedObjects, n = objects.length; i !== n; ++i) {
  26884. var object = objects[i];
  26885. bindingsForPath[i] = new PropertyBinding(object, path, parsedPath);
  26886. }
  26887. return bindingsForPath;
  26888. },
  26889. unsubscribe_: function (path) {
  26890. // tells the group to forget about a property path and no longer
  26891. // update the array previously obtained with 'subscribe_'
  26892. var indicesByPath = this._bindingsIndicesByPath,
  26893. index = indicesByPath[path];
  26894. if (index !== undefined) {
  26895. var paths = this._paths,
  26896. parsedPaths = this._parsedPaths,
  26897. bindings = this._bindings,
  26898. lastBindingsIndex = bindings.length - 1,
  26899. lastBindings = bindings[lastBindingsIndex],
  26900. lastBindingsPath = path[lastBindingsIndex];
  26901. indicesByPath[lastBindingsPath] = index;
  26902. bindings[index] = lastBindings;
  26903. bindings.pop();
  26904. parsedPaths[index] = parsedPaths[lastBindingsIndex];
  26905. parsedPaths.pop();
  26906. paths[index] = paths[lastBindingsIndex];
  26907. paths.pop();
  26908. }
  26909. }
  26910. });
  26911. /**
  26912. *
  26913. * Action provided by AnimationMixer for scheduling clip playback on specific
  26914. * objects.
  26915. *
  26916. * @author Ben Houston / http://clara.io/
  26917. * @author David Sarno / http://lighthaus.us/
  26918. * @author tschw
  26919. *
  26920. */
  26921. function AnimationAction(mixer, clip, localRoot) {
  26922. this._mixer = mixer;
  26923. this._clip = clip;
  26924. this._localRoot = localRoot || null;
  26925. var tracks = clip.tracks,
  26926. nTracks = tracks.length,
  26927. interpolants = new Array(nTracks);
  26928. var interpolantSettings = {
  26929. endingStart: ZeroCurvatureEnding,
  26930. endingEnd: ZeroCurvatureEnding
  26931. };
  26932. for (var i = 0; i !== nTracks; ++i) {
  26933. var interpolant = tracks[i].createInterpolant(null);
  26934. interpolants[i] = interpolant;
  26935. interpolant.settings = interpolantSettings;
  26936. }
  26937. this._interpolantSettings = interpolantSettings;
  26938. this._interpolants = interpolants; // bound by the mixer
  26939. // inside: PropertyMixer (managed by the mixer)
  26940. this._propertyBindings = new Array(nTracks);
  26941. this._cacheIndex = null; // for the memory manager
  26942. this._byClipCacheIndex = null; // for the memory manager
  26943. this._timeScaleInterpolant = null;
  26944. this._weightInterpolant = null;
  26945. this.loop = LoopRepeat;
  26946. this._loopCount = -1; // global mixer time when the action is to be started
  26947. // it's set back to 'null' upon start of the action
  26948. this._startTime = null; // scaled local time of the action
  26949. // gets clamped or wrapped to 0..clip.duration according to loop
  26950. this.time = 0;
  26951. this.timeScale = 1;
  26952. this._effectiveTimeScale = 1;
  26953. this.weight = 1;
  26954. this._effectiveWeight = 1;
  26955. this.repetitions = Infinity; // no. of repetitions when looping
  26956. this.paused = false; // true -> zero effective time scale
  26957. this.enabled = true; // false -> zero effective weight
  26958. this.clampWhenFinished = false; // keep feeding the last frame?
  26959. this.zeroSlopeAtStart = true; // for smooth interpolation w/o separate
  26960. this.zeroSlopeAtEnd = true; // clips for start, loop and end
  26961. }
  26962. Object.assign(AnimationAction.prototype, {
  26963. // State & Scheduling
  26964. play: function () {
  26965. this._mixer._activateAction(this);
  26966. return this;
  26967. },
  26968. stop: function () {
  26969. this._mixer._deactivateAction(this);
  26970. return this.reset();
  26971. },
  26972. reset: function () {
  26973. this.paused = false;
  26974. this.enabled = true;
  26975. this.time = 0; // restart clip
  26976. this._loopCount = -1; // forget previous loops
  26977. this._startTime = null; // forget scheduling
  26978. return this.stopFading().stopWarping();
  26979. },
  26980. isRunning: function () {
  26981. return this.enabled && !this.paused && this.timeScale !== 0 && this._startTime === null && this._mixer._isActiveAction(this);
  26982. },
  26983. // return true when play has been called
  26984. isScheduled: function () {
  26985. return this._mixer._isActiveAction(this);
  26986. },
  26987. startAt: function (time) {
  26988. this._startTime = time;
  26989. return this;
  26990. },
  26991. setLoop: function (mode, repetitions) {
  26992. this.loop = mode;
  26993. this.repetitions = repetitions;
  26994. return this;
  26995. },
  26996. // Weight
  26997. // set the weight stopping any scheduled fading
  26998. // although .enabled = false yields an effective weight of zero, this
  26999. // method does *not* change .enabled, because it would be confusing
  27000. setEffectiveWeight: function (weight) {
  27001. this.weight = weight; // note: same logic as when updated at runtime
  27002. this._effectiveWeight = this.enabled ? weight : 0;
  27003. return this.stopFading();
  27004. },
  27005. // return the weight considering fading and .enabled
  27006. getEffectiveWeight: function () {
  27007. return this._effectiveWeight;
  27008. },
  27009. fadeIn: function (duration) {
  27010. return this._scheduleFading(duration, 0, 1);
  27011. },
  27012. fadeOut: function (duration) {
  27013. return this._scheduleFading(duration, 1, 0);
  27014. },
  27015. crossFadeFrom: function (fadeOutAction, duration, warp) {
  27016. fadeOutAction.fadeOut(duration);
  27017. this.fadeIn(duration);
  27018. if (warp) {
  27019. var fadeInDuration = this._clip.duration,
  27020. fadeOutDuration = fadeOutAction._clip.duration,
  27021. startEndRatio = fadeOutDuration / fadeInDuration,
  27022. endStartRatio = fadeInDuration / fadeOutDuration;
  27023. fadeOutAction.warp(1.0, startEndRatio, duration);
  27024. this.warp(endStartRatio, 1.0, duration);
  27025. }
  27026. return this;
  27027. },
  27028. crossFadeTo: function (fadeInAction, duration, warp) {
  27029. return fadeInAction.crossFadeFrom(this, duration, warp);
  27030. },
  27031. stopFading: function () {
  27032. var weightInterpolant = this._weightInterpolant;
  27033. if (weightInterpolant !== null) {
  27034. this._weightInterpolant = null;
  27035. this._mixer._takeBackControlInterpolant(weightInterpolant);
  27036. }
  27037. return this;
  27038. },
  27039. // Time Scale Control
  27040. // set the time scale stopping any scheduled warping
  27041. // although .paused = true yields an effective time scale of zero, this
  27042. // method does *not* change .paused, because it would be confusing
  27043. setEffectiveTimeScale: function (timeScale) {
  27044. this.timeScale = timeScale;
  27045. this._effectiveTimeScale = this.paused ? 0 : timeScale;
  27046. return this.stopWarping();
  27047. },
  27048. // return the time scale considering warping and .paused
  27049. getEffectiveTimeScale: function () {
  27050. return this._effectiveTimeScale;
  27051. },
  27052. setDuration: function (duration) {
  27053. this.timeScale = this._clip.duration / duration;
  27054. return this.stopWarping();
  27055. },
  27056. syncWith: function (action) {
  27057. this.time = action.time;
  27058. this.timeScale = action.timeScale;
  27059. return this.stopWarping();
  27060. },
  27061. halt: function (duration) {
  27062. return this.warp(this._effectiveTimeScale, 0, duration);
  27063. },
  27064. warp: function (startTimeScale, endTimeScale, duration) {
  27065. var mixer = this._mixer,
  27066. now = mixer.time,
  27067. interpolant = this._timeScaleInterpolant,
  27068. timeScale = this.timeScale;
  27069. if (interpolant === null) {
  27070. interpolant = mixer._lendControlInterpolant();
  27071. this._timeScaleInterpolant = interpolant;
  27072. }
  27073. var times = interpolant.parameterPositions,
  27074. values = interpolant.sampleValues;
  27075. times[0] = now;
  27076. times[1] = now + duration;
  27077. values[0] = startTimeScale / timeScale;
  27078. values[1] = endTimeScale / timeScale;
  27079. return this;
  27080. },
  27081. stopWarping: function () {
  27082. var timeScaleInterpolant = this._timeScaleInterpolant;
  27083. if (timeScaleInterpolant !== null) {
  27084. this._timeScaleInterpolant = null;
  27085. this._mixer._takeBackControlInterpolant(timeScaleInterpolant);
  27086. }
  27087. return this;
  27088. },
  27089. // Object Accessors
  27090. getMixer: function () {
  27091. return this._mixer;
  27092. },
  27093. getClip: function () {
  27094. return this._clip;
  27095. },
  27096. getRoot: function () {
  27097. return this._localRoot || this._mixer._root;
  27098. },
  27099. // Interna
  27100. _update: function (time, deltaTime, timeDirection, accuIndex) {
  27101. // called by the mixer
  27102. if (!this.enabled) {
  27103. // call ._updateWeight() to update ._effectiveWeight
  27104. this._updateWeight(time);
  27105. return;
  27106. }
  27107. var startTime = this._startTime;
  27108. if (startTime !== null) {
  27109. // check for scheduled start of action
  27110. var timeRunning = (time - startTime) * timeDirection;
  27111. if (timeRunning < 0 || timeDirection === 0) {
  27112. return; // yet to come / don't decide when delta = 0
  27113. } // start
  27114. this._startTime = null; // unschedule
  27115. deltaTime = timeDirection * timeRunning;
  27116. } // apply time scale and advance time
  27117. deltaTime *= this._updateTimeScale(time);
  27118. var clipTime = this._updateTime(deltaTime); // note: _updateTime may disable the action resulting in
  27119. // an effective weight of 0
  27120. var weight = this._updateWeight(time);
  27121. if (weight > 0) {
  27122. var interpolants = this._interpolants;
  27123. var propertyMixers = this._propertyBindings;
  27124. for (var j = 0, m = interpolants.length; j !== m; ++j) {
  27125. interpolants[j].evaluate(clipTime);
  27126. propertyMixers[j].accumulate(accuIndex, weight);
  27127. }
  27128. }
  27129. },
  27130. _updateWeight: function (time) {
  27131. var weight = 0;
  27132. if (this.enabled) {
  27133. weight = this.weight;
  27134. var interpolant = this._weightInterpolant;
  27135. if (interpolant !== null) {
  27136. var interpolantValue = interpolant.evaluate(time)[0];
  27137. weight *= interpolantValue;
  27138. if (time > interpolant.parameterPositions[1]) {
  27139. this.stopFading();
  27140. if (interpolantValue === 0) {
  27141. // faded out, disable
  27142. this.enabled = false;
  27143. }
  27144. }
  27145. }
  27146. }
  27147. this._effectiveWeight = weight;
  27148. return weight;
  27149. },
  27150. _updateTimeScale: function (time) {
  27151. var timeScale = 0;
  27152. if (!this.paused) {
  27153. timeScale = this.timeScale;
  27154. var interpolant = this._timeScaleInterpolant;
  27155. if (interpolant !== null) {
  27156. var interpolantValue = interpolant.evaluate(time)[0];
  27157. timeScale *= interpolantValue;
  27158. if (time > interpolant.parameterPositions[1]) {
  27159. this.stopWarping();
  27160. if (timeScale === 0) {
  27161. // motion has halted, pause
  27162. this.paused = true;
  27163. } else {
  27164. // warp done - apply final time scale
  27165. this.timeScale = timeScale;
  27166. }
  27167. }
  27168. }
  27169. }
  27170. this._effectiveTimeScale = timeScale;
  27171. return timeScale;
  27172. },
  27173. _updateTime: function (deltaTime) {
  27174. var time = this.time + deltaTime;
  27175. var duration = this._clip.duration;
  27176. var loop = this.loop;
  27177. var loopCount = this._loopCount;
  27178. var pingPong = loop === LoopPingPong;
  27179. if (deltaTime === 0) {
  27180. if (loopCount === -1) return time;
  27181. return pingPong && (loopCount & 1) === 1 ? duration - time : time;
  27182. }
  27183. if (loop === LoopOnce) {
  27184. if (loopCount === -1) {
  27185. // just started
  27186. this._loopCount = 0;
  27187. this._setEndings(true, true, false);
  27188. }
  27189. handle_stop: {
  27190. if (time >= duration) {
  27191. time = duration;
  27192. } else if (time < 0) {
  27193. time = 0;
  27194. } else {
  27195. this.time = time;
  27196. break handle_stop;
  27197. }
  27198. if (this.clampWhenFinished) this.paused = true;else this.enabled = false;
  27199. this.time = time;
  27200. this._mixer.dispatchEvent({
  27201. type: 'finished',
  27202. action: this,
  27203. direction: deltaTime < 0 ? -1 : 1
  27204. });
  27205. }
  27206. } else {
  27207. // repetitive Repeat or PingPong
  27208. if (loopCount === -1) {
  27209. // just started
  27210. if (deltaTime >= 0) {
  27211. loopCount = 0;
  27212. this._setEndings(true, this.repetitions === 0, pingPong);
  27213. } else {
  27214. // when looping in reverse direction, the initial
  27215. // transition through zero counts as a repetition,
  27216. // so leave loopCount at -1
  27217. this._setEndings(this.repetitions === 0, true, pingPong);
  27218. }
  27219. }
  27220. if (time >= duration || time < 0) {
  27221. // wrap around
  27222. var loopDelta = Math.floor(time / duration); // signed
  27223. time -= duration * loopDelta;
  27224. loopCount += Math.abs(loopDelta);
  27225. var pending = this.repetitions - loopCount;
  27226. if (pending <= 0) {
  27227. // have to stop (switch state, clamp time, fire event)
  27228. if (this.clampWhenFinished) this.paused = true;else this.enabled = false;
  27229. time = deltaTime > 0 ? duration : 0;
  27230. this.time = time;
  27231. this._mixer.dispatchEvent({
  27232. type: 'finished',
  27233. action: this,
  27234. direction: deltaTime > 0 ? 1 : -1
  27235. });
  27236. } else {
  27237. // keep running
  27238. if (pending === 1) {
  27239. // entering the last round
  27240. var atStart = deltaTime < 0;
  27241. this._setEndings(atStart, !atStart, pingPong);
  27242. } else {
  27243. this._setEndings(false, false, pingPong);
  27244. }
  27245. this._loopCount = loopCount;
  27246. this.time = time;
  27247. this._mixer.dispatchEvent({
  27248. type: 'loop',
  27249. action: this,
  27250. loopDelta: loopDelta
  27251. });
  27252. }
  27253. } else {
  27254. this.time = time;
  27255. }
  27256. if (pingPong && (loopCount & 1) === 1) {
  27257. // invert time for the "pong round"
  27258. return duration - time;
  27259. }
  27260. }
  27261. return time;
  27262. },
  27263. _setEndings: function (atStart, atEnd, pingPong) {
  27264. var settings = this._interpolantSettings;
  27265. if (pingPong) {
  27266. settings.endingStart = ZeroSlopeEnding;
  27267. settings.endingEnd = ZeroSlopeEnding;
  27268. } else {
  27269. // assuming for LoopOnce atStart == atEnd == true
  27270. if (atStart) {
  27271. settings.endingStart = this.zeroSlopeAtStart ? ZeroSlopeEnding : ZeroCurvatureEnding;
  27272. } else {
  27273. settings.endingStart = WrapAroundEnding;
  27274. }
  27275. if (atEnd) {
  27276. settings.endingEnd = this.zeroSlopeAtEnd ? ZeroSlopeEnding : ZeroCurvatureEnding;
  27277. } else {
  27278. settings.endingEnd = WrapAroundEnding;
  27279. }
  27280. }
  27281. },
  27282. _scheduleFading: function (duration, weightNow, weightThen) {
  27283. var mixer = this._mixer,
  27284. now = mixer.time,
  27285. interpolant = this._weightInterpolant;
  27286. if (interpolant === null) {
  27287. interpolant = mixer._lendControlInterpolant();
  27288. this._weightInterpolant = interpolant;
  27289. }
  27290. var times = interpolant.parameterPositions,
  27291. values = interpolant.sampleValues;
  27292. times[0] = now;
  27293. values[0] = weightNow;
  27294. times[1] = now + duration;
  27295. values[1] = weightThen;
  27296. return this;
  27297. }
  27298. });
  27299. /**
  27300. *
  27301. * Player for AnimationClips.
  27302. *
  27303. *
  27304. * @author Ben Houston / http://clara.io/
  27305. * @author David Sarno / http://lighthaus.us/
  27306. * @author tschw
  27307. */
  27308. function AnimationMixer(root) {
  27309. this._root = root;
  27310. this._initMemoryManager();
  27311. this._accuIndex = 0;
  27312. this.time = 0;
  27313. this.timeScale = 1.0;
  27314. }
  27315. AnimationMixer.prototype = Object.assign(Object.create(EventDispatcher.prototype), {
  27316. constructor: AnimationMixer,
  27317. _bindAction: function (action, prototypeAction) {
  27318. var root = action._localRoot || this._root,
  27319. tracks = action._clip.tracks,
  27320. nTracks = tracks.length,
  27321. bindings = action._propertyBindings,
  27322. interpolants = action._interpolants,
  27323. rootUuid = root.uuid,
  27324. bindingsByRoot = this._bindingsByRootAndName,
  27325. bindingsByName = bindingsByRoot[rootUuid];
  27326. if (bindingsByName === undefined) {
  27327. bindingsByName = {};
  27328. bindingsByRoot[rootUuid] = bindingsByName;
  27329. }
  27330. for (var i = 0; i !== nTracks; ++i) {
  27331. var track = tracks[i],
  27332. trackName = track.name,
  27333. binding = bindingsByName[trackName];
  27334. if (binding !== undefined) {
  27335. bindings[i] = binding;
  27336. } else {
  27337. binding = bindings[i];
  27338. if (binding !== undefined) {
  27339. // existing binding, make sure the cache knows
  27340. if (binding._cacheIndex === null) {
  27341. ++binding.referenceCount;
  27342. this._addInactiveBinding(binding, rootUuid, trackName);
  27343. }
  27344. continue;
  27345. }
  27346. var path = prototypeAction && prototypeAction._propertyBindings[i].binding.parsedPath;
  27347. binding = new PropertyMixer(PropertyBinding.create(root, trackName, path), track.ValueTypeName, track.getValueSize());
  27348. ++binding.referenceCount;
  27349. this._addInactiveBinding(binding, rootUuid, trackName);
  27350. bindings[i] = binding;
  27351. }
  27352. interpolants[i].resultBuffer = binding.buffer;
  27353. }
  27354. },
  27355. _activateAction: function (action) {
  27356. if (!this._isActiveAction(action)) {
  27357. if (action._cacheIndex === null) {
  27358. // this action has been forgotten by the cache, but the user
  27359. // appears to be still using it -> rebind
  27360. var rootUuid = (action._localRoot || this._root).uuid,
  27361. clipUuid = action._clip.uuid,
  27362. actionsForClip = this._actionsByClip[clipUuid];
  27363. this._bindAction(action, actionsForClip && actionsForClip.knownActions[0]);
  27364. this._addInactiveAction(action, clipUuid, rootUuid);
  27365. }
  27366. var bindings = action._propertyBindings; // increment reference counts / sort out state
  27367. for (var i = 0, n = bindings.length; i !== n; ++i) {
  27368. var binding = bindings[i];
  27369. if (binding.useCount++ === 0) {
  27370. this._lendBinding(binding);
  27371. binding.saveOriginalState();
  27372. }
  27373. }
  27374. this._lendAction(action);
  27375. }
  27376. },
  27377. _deactivateAction: function (action) {
  27378. if (this._isActiveAction(action)) {
  27379. var bindings = action._propertyBindings; // decrement reference counts / sort out state
  27380. for (var i = 0, n = bindings.length; i !== n; ++i) {
  27381. var binding = bindings[i];
  27382. if (--binding.useCount === 0) {
  27383. binding.restoreOriginalState();
  27384. this._takeBackBinding(binding);
  27385. }
  27386. }
  27387. this._takeBackAction(action);
  27388. }
  27389. },
  27390. // Memory manager
  27391. _initMemoryManager: function () {
  27392. this._actions = []; // 'nActiveActions' followed by inactive ones
  27393. this._nActiveActions = 0;
  27394. this._actionsByClip = {}; // inside:
  27395. // {
  27396. // knownActions: Array< AnimationAction > - used as prototypes
  27397. // actionByRoot: AnimationAction - lookup
  27398. // }
  27399. this._bindings = []; // 'nActiveBindings' followed by inactive ones
  27400. this._nActiveBindings = 0;
  27401. this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer >
  27402. this._controlInterpolants = []; // same game as above
  27403. this._nActiveControlInterpolants = 0;
  27404. var scope = this;
  27405. this.stats = {
  27406. actions: {
  27407. get total() {
  27408. return scope._actions.length;
  27409. },
  27410. get inUse() {
  27411. return scope._nActiveActions;
  27412. }
  27413. },
  27414. bindings: {
  27415. get total() {
  27416. return scope._bindings.length;
  27417. },
  27418. get inUse() {
  27419. return scope._nActiveBindings;
  27420. }
  27421. },
  27422. controlInterpolants: {
  27423. get total() {
  27424. return scope._controlInterpolants.length;
  27425. },
  27426. get inUse() {
  27427. return scope._nActiveControlInterpolants;
  27428. }
  27429. }
  27430. };
  27431. },
  27432. // Memory management for AnimationAction objects
  27433. _isActiveAction: function (action) {
  27434. var index = action._cacheIndex;
  27435. return index !== null && index < this._nActiveActions;
  27436. },
  27437. _addInactiveAction: function (action, clipUuid, rootUuid) {
  27438. var actions = this._actions,
  27439. actionsByClip = this._actionsByClip,
  27440. actionsForClip = actionsByClip[clipUuid];
  27441. if (actionsForClip === undefined) {
  27442. actionsForClip = {
  27443. knownActions: [action],
  27444. actionByRoot: {}
  27445. };
  27446. action._byClipCacheIndex = 0;
  27447. actionsByClip[clipUuid] = actionsForClip;
  27448. } else {
  27449. var knownActions = actionsForClip.knownActions;
  27450. action._byClipCacheIndex = knownActions.length;
  27451. knownActions.push(action);
  27452. }
  27453. action._cacheIndex = actions.length;
  27454. actions.push(action);
  27455. actionsForClip.actionByRoot[rootUuid] = action;
  27456. },
  27457. _removeInactiveAction: function (action) {
  27458. var actions = this._actions,
  27459. lastInactiveAction = actions[actions.length - 1],
  27460. cacheIndex = action._cacheIndex;
  27461. lastInactiveAction._cacheIndex = cacheIndex;
  27462. actions[cacheIndex] = lastInactiveAction;
  27463. actions.pop();
  27464. action._cacheIndex = null;
  27465. var clipUuid = action._clip.uuid,
  27466. actionsByClip = this._actionsByClip,
  27467. actionsForClip = actionsByClip[clipUuid],
  27468. knownActionsForClip = actionsForClip.knownActions,
  27469. lastKnownAction = knownActionsForClip[knownActionsForClip.length - 1],
  27470. byClipCacheIndex = action._byClipCacheIndex;
  27471. lastKnownAction._byClipCacheIndex = byClipCacheIndex;
  27472. knownActionsForClip[byClipCacheIndex] = lastKnownAction;
  27473. knownActionsForClip.pop();
  27474. action._byClipCacheIndex = null;
  27475. var actionByRoot = actionsForClip.actionByRoot,
  27476. rootUuid = (action._localRoot || this._root).uuid;
  27477. delete actionByRoot[rootUuid];
  27478. if (knownActionsForClip.length === 0) {
  27479. delete actionsByClip[clipUuid];
  27480. }
  27481. this._removeInactiveBindingsForAction(action);
  27482. },
  27483. _removeInactiveBindingsForAction: function (action) {
  27484. var bindings = action._propertyBindings;
  27485. for (var i = 0, n = bindings.length; i !== n; ++i) {
  27486. var binding = bindings[i];
  27487. if (--binding.referenceCount === 0) {
  27488. this._removeInactiveBinding(binding);
  27489. }
  27490. }
  27491. },
  27492. _lendAction: function (action) {
  27493. // [ active actions | inactive actions ]
  27494. // [ active actions >| inactive actions ]
  27495. // s a
  27496. // <-swap->
  27497. // a s
  27498. var actions = this._actions,
  27499. prevIndex = action._cacheIndex,
  27500. lastActiveIndex = this._nActiveActions++,
  27501. firstInactiveAction = actions[lastActiveIndex];
  27502. action._cacheIndex = lastActiveIndex;
  27503. actions[lastActiveIndex] = action;
  27504. firstInactiveAction._cacheIndex = prevIndex;
  27505. actions[prevIndex] = firstInactiveAction;
  27506. },
  27507. _takeBackAction: function (action) {
  27508. // [ active actions | inactive actions ]
  27509. // [ active actions |< inactive actions ]
  27510. // a s
  27511. // <-swap->
  27512. // s a
  27513. var actions = this._actions,
  27514. prevIndex = action._cacheIndex,
  27515. firstInactiveIndex = --this._nActiveActions,
  27516. lastActiveAction = actions[firstInactiveIndex];
  27517. action._cacheIndex = firstInactiveIndex;
  27518. actions[firstInactiveIndex] = action;
  27519. lastActiveAction._cacheIndex = prevIndex;
  27520. actions[prevIndex] = lastActiveAction;
  27521. },
  27522. // Memory management for PropertyMixer objects
  27523. _addInactiveBinding: function (binding, rootUuid, trackName) {
  27524. var bindingsByRoot = this._bindingsByRootAndName,
  27525. bindingByName = bindingsByRoot[rootUuid],
  27526. bindings = this._bindings;
  27527. if (bindingByName === undefined) {
  27528. bindingByName = {};
  27529. bindingsByRoot[rootUuid] = bindingByName;
  27530. }
  27531. bindingByName[trackName] = binding;
  27532. binding._cacheIndex = bindings.length;
  27533. bindings.push(binding);
  27534. },
  27535. _removeInactiveBinding: function (binding) {
  27536. var bindings = this._bindings,
  27537. propBinding = binding.binding,
  27538. rootUuid = propBinding.rootNode.uuid,
  27539. trackName = propBinding.path,
  27540. bindingsByRoot = this._bindingsByRootAndName,
  27541. bindingByName = bindingsByRoot[rootUuid],
  27542. lastInactiveBinding = bindings[bindings.length - 1],
  27543. cacheIndex = binding._cacheIndex;
  27544. lastInactiveBinding._cacheIndex = cacheIndex;
  27545. bindings[cacheIndex] = lastInactiveBinding;
  27546. bindings.pop();
  27547. delete bindingByName[trackName];
  27548. if (Object.keys(bindingByName).length === 0) {
  27549. delete bindingsByRoot[rootUuid];
  27550. }
  27551. },
  27552. _lendBinding: function (binding) {
  27553. var bindings = this._bindings,
  27554. prevIndex = binding._cacheIndex,
  27555. lastActiveIndex = this._nActiveBindings++,
  27556. firstInactiveBinding = bindings[lastActiveIndex];
  27557. binding._cacheIndex = lastActiveIndex;
  27558. bindings[lastActiveIndex] = binding;
  27559. firstInactiveBinding._cacheIndex = prevIndex;
  27560. bindings[prevIndex] = firstInactiveBinding;
  27561. },
  27562. _takeBackBinding: function (binding) {
  27563. var bindings = this._bindings,
  27564. prevIndex = binding._cacheIndex,
  27565. firstInactiveIndex = --this._nActiveBindings,
  27566. lastActiveBinding = bindings[firstInactiveIndex];
  27567. binding._cacheIndex = firstInactiveIndex;
  27568. bindings[firstInactiveIndex] = binding;
  27569. lastActiveBinding._cacheIndex = prevIndex;
  27570. bindings[prevIndex] = lastActiveBinding;
  27571. },
  27572. // Memory management of Interpolants for weight and time scale
  27573. _lendControlInterpolant: function () {
  27574. var interpolants = this._controlInterpolants,
  27575. lastActiveIndex = this._nActiveControlInterpolants++,
  27576. interpolant = interpolants[lastActiveIndex];
  27577. if (interpolant === undefined) {
  27578. interpolant = new LinearInterpolant(new Float32Array(2), new Float32Array(2), 1, this._controlInterpolantsResultBuffer);
  27579. interpolant.__cacheIndex = lastActiveIndex;
  27580. interpolants[lastActiveIndex] = interpolant;
  27581. }
  27582. return interpolant;
  27583. },
  27584. _takeBackControlInterpolant: function (interpolant) {
  27585. var interpolants = this._controlInterpolants,
  27586. prevIndex = interpolant.__cacheIndex,
  27587. firstInactiveIndex = --this._nActiveControlInterpolants,
  27588. lastActiveInterpolant = interpolants[firstInactiveIndex];
  27589. interpolant.__cacheIndex = firstInactiveIndex;
  27590. interpolants[firstInactiveIndex] = interpolant;
  27591. lastActiveInterpolant.__cacheIndex = prevIndex;
  27592. interpolants[prevIndex] = lastActiveInterpolant;
  27593. },
  27594. _controlInterpolantsResultBuffer: new Float32Array(1),
  27595. // return an action for a clip optionally using a custom root target
  27596. // object (this method allocates a lot of dynamic memory in case a
  27597. // previously unknown clip/root combination is specified)
  27598. clipAction: function (clip, optionalRoot) {
  27599. var root = optionalRoot || this._root,
  27600. rootUuid = root.uuid,
  27601. clipObject = typeof clip === 'string' ? AnimationClip.findByName(root, clip) : clip,
  27602. clipUuid = clipObject !== null ? clipObject.uuid : clip,
  27603. actionsForClip = this._actionsByClip[clipUuid],
  27604. prototypeAction = null;
  27605. if (actionsForClip !== undefined) {
  27606. var existingAction = actionsForClip.actionByRoot[rootUuid];
  27607. if (existingAction !== undefined) {
  27608. return existingAction;
  27609. } // we know the clip, so we don't have to parse all
  27610. // the bindings again but can just copy
  27611. prototypeAction = actionsForClip.knownActions[0]; // also, take the clip from the prototype action
  27612. if (clipObject === null) clipObject = prototypeAction._clip;
  27613. } // clip must be known when specified via string
  27614. if (clipObject === null) return null; // allocate all resources required to run it
  27615. var newAction = new AnimationAction(this, clipObject, optionalRoot);
  27616. this._bindAction(newAction, prototypeAction); // and make the action known to the memory manager
  27617. this._addInactiveAction(newAction, clipUuid, rootUuid);
  27618. return newAction;
  27619. },
  27620. // get an existing action
  27621. existingAction: function (clip, optionalRoot) {
  27622. var root = optionalRoot || this._root,
  27623. rootUuid = root.uuid,
  27624. clipObject = typeof clip === 'string' ? AnimationClip.findByName(root, clip) : clip,
  27625. clipUuid = clipObject ? clipObject.uuid : clip,
  27626. actionsForClip = this._actionsByClip[clipUuid];
  27627. if (actionsForClip !== undefined) {
  27628. return actionsForClip.actionByRoot[rootUuid] || null;
  27629. }
  27630. return null;
  27631. },
  27632. // deactivates all previously scheduled actions
  27633. stopAllAction: function () {
  27634. var actions = this._actions,
  27635. nActions = this._nActiveActions,
  27636. bindings = this._bindings,
  27637. nBindings = this._nActiveBindings;
  27638. this._nActiveActions = 0;
  27639. this._nActiveBindings = 0;
  27640. for (var i = 0; i !== nActions; ++i) {
  27641. actions[i].reset();
  27642. }
  27643. for (var i = 0; i !== nBindings; ++i) {
  27644. bindings[i].useCount = 0;
  27645. }
  27646. return this;
  27647. },
  27648. // advance the time and update apply the animation
  27649. update: function (deltaTime) {
  27650. deltaTime *= this.timeScale;
  27651. var actions = this._actions,
  27652. nActions = this._nActiveActions,
  27653. time = this.time += deltaTime,
  27654. timeDirection = Math.sign(deltaTime),
  27655. accuIndex = this._accuIndex ^= 1; // run active actions
  27656. for (var i = 0; i !== nActions; ++i) {
  27657. var action = actions[i];
  27658. action._update(time, deltaTime, timeDirection, accuIndex);
  27659. } // update scene graph
  27660. var bindings = this._bindings,
  27661. nBindings = this._nActiveBindings;
  27662. for (var i = 0; i !== nBindings; ++i) {
  27663. bindings[i].apply(accuIndex);
  27664. }
  27665. return this;
  27666. },
  27667. // Allows you to seek to a specific time in an animation.
  27668. setTime: function (timeInSeconds) {
  27669. this.time = 0; // Zero out time attribute for AnimationMixer object;
  27670. for (var i = 0; i < this._actions.length; i++) {
  27671. this._actions[i].time = 0; // Zero out time attribute for all associated AnimationAction objects.
  27672. }
  27673. return this.update(timeInSeconds); // Update used to set exact time. Returns "this" AnimationMixer object.
  27674. },
  27675. // return this mixer's root target object
  27676. getRoot: function () {
  27677. return this._root;
  27678. },
  27679. // free all resources specific to a particular clip
  27680. uncacheClip: function (clip) {
  27681. var actions = this._actions,
  27682. clipUuid = clip.uuid,
  27683. actionsByClip = this._actionsByClip,
  27684. actionsForClip = actionsByClip[clipUuid];
  27685. if (actionsForClip !== undefined) {
  27686. // note: just calling _removeInactiveAction would mess up the
  27687. // iteration state and also require updating the state we can
  27688. // just throw away
  27689. var actionsToRemove = actionsForClip.knownActions;
  27690. for (var i = 0, n = actionsToRemove.length; i !== n; ++i) {
  27691. var action = actionsToRemove[i];
  27692. this._deactivateAction(action);
  27693. var cacheIndex = action._cacheIndex,
  27694. lastInactiveAction = actions[actions.length - 1];
  27695. action._cacheIndex = null;
  27696. action._byClipCacheIndex = null;
  27697. lastInactiveAction._cacheIndex = cacheIndex;
  27698. actions[cacheIndex] = lastInactiveAction;
  27699. actions.pop();
  27700. this._removeInactiveBindingsForAction(action);
  27701. }
  27702. delete actionsByClip[clipUuid];
  27703. }
  27704. },
  27705. // free all resources specific to a particular root target object
  27706. uncacheRoot: function (root) {
  27707. var rootUuid = root.uuid,
  27708. actionsByClip = this._actionsByClip;
  27709. for (var clipUuid in actionsByClip) {
  27710. var actionByRoot = actionsByClip[clipUuid].actionByRoot,
  27711. action = actionByRoot[rootUuid];
  27712. if (action !== undefined) {
  27713. this._deactivateAction(action);
  27714. this._removeInactiveAction(action);
  27715. }
  27716. }
  27717. var bindingsByRoot = this._bindingsByRootAndName,
  27718. bindingByName = bindingsByRoot[rootUuid];
  27719. if (bindingByName !== undefined) {
  27720. for (var trackName in bindingByName) {
  27721. var binding = bindingByName[trackName];
  27722. binding.restoreOriginalState();
  27723. this._removeInactiveBinding(binding);
  27724. }
  27725. }
  27726. },
  27727. // remove a targeted clip from the cache
  27728. uncacheAction: function (clip, optionalRoot) {
  27729. var action = this.existingAction(clip, optionalRoot);
  27730. if (action !== null) {
  27731. this._deactivateAction(action);
  27732. this._removeInactiveAction(action);
  27733. }
  27734. }
  27735. });
  27736. /**
  27737. * @author mrdoob / http://mrdoob.com/
  27738. */
  27739. function Uniform(value) {
  27740. if (typeof value === 'string') {
  27741. console.warn('THREE.Uniform: Type parameter is no longer needed.');
  27742. value = arguments[1];
  27743. }
  27744. this.value = value;
  27745. }
  27746. Uniform.prototype.clone = function () {
  27747. return new Uniform(this.value.clone === undefined ? this.value : this.value.clone());
  27748. };
  27749. /**
  27750. * @author benaadams / https://twitter.com/ben_a_adams
  27751. */
  27752. function InstancedInterleavedBuffer(array, stride, meshPerAttribute) {
  27753. InterleavedBuffer.call(this, array, stride);
  27754. this.meshPerAttribute = meshPerAttribute || 1;
  27755. }
  27756. InstancedInterleavedBuffer.prototype = Object.assign(Object.create(InterleavedBuffer.prototype), {
  27757. constructor: InstancedInterleavedBuffer,
  27758. isInstancedInterleavedBuffer: true,
  27759. copy: function (source) {
  27760. InterleavedBuffer.prototype.copy.call(this, source);
  27761. this.meshPerAttribute = source.meshPerAttribute;
  27762. return this;
  27763. }
  27764. });
  27765. /**
  27766. * @author mrdoob / http://mrdoob.com/
  27767. * @author bhouston / http://clara.io/
  27768. * @author stephomi / http://stephaneginier.com/
  27769. */
  27770. function Raycaster(origin, direction, near, far) {
  27771. this.ray = new Ray(origin, direction); // direction is assumed to be normalized (for accurate distance calculations)
  27772. this.near = near || 0;
  27773. this.far = far || Infinity;
  27774. this.camera = null;
  27775. this.params = {
  27776. Mesh: {},
  27777. Line: {},
  27778. LOD: {},
  27779. Points: {
  27780. threshold: 1
  27781. },
  27782. Sprite: {}
  27783. };
  27784. Object.defineProperties(this.params, {
  27785. PointCloud: {
  27786. get: function () {
  27787. console.warn('THREE.Raycaster: params.PointCloud has been renamed to params.Points.');
  27788. return this.Points;
  27789. }
  27790. }
  27791. });
  27792. }
  27793. function ascSort(a, b) {
  27794. return a.distance - b.distance;
  27795. }
  27796. function intersectObject(object, raycaster, intersects, recursive) {
  27797. if (object.visible === false) return;
  27798. object.raycast(raycaster, intersects);
  27799. if (recursive === true) {
  27800. var children = object.children;
  27801. for (var i = 0, l = children.length; i < l; i++) {
  27802. intersectObject(children[i], raycaster, intersects, true);
  27803. }
  27804. }
  27805. }
  27806. Object.assign(Raycaster.prototype, {
  27807. linePrecision: 1,
  27808. set: function (origin, direction) {
  27809. // direction is assumed to be normalized (for accurate distance calculations)
  27810. this.ray.set(origin, direction);
  27811. },
  27812. setFromCamera: function (coords, camera) {
  27813. if (camera && camera.isPerspectiveCamera) {
  27814. this.ray.origin.setFromMatrixPosition(camera.matrixWorld);
  27815. this.ray.direction.set(coords.x, coords.y, 0.5).unproject(camera).sub(this.ray.origin).normalize();
  27816. this.camera = camera;
  27817. } else if (camera && camera.isOrthographicCamera) {
  27818. this.ray.origin.set(coords.x, coords.y, (camera.near + camera.far) / (camera.near - camera.far)).unproject(camera); // set origin in plane of camera
  27819. this.ray.direction.set(0, 0, -1).transformDirection(camera.matrixWorld);
  27820. this.camera = camera;
  27821. } else {
  27822. console.error('THREE.Raycaster: Unsupported camera type.');
  27823. }
  27824. },
  27825. intersectObject: function (object, recursive, optionalTarget) {
  27826. var intersects = optionalTarget || [];
  27827. intersectObject(object, this, intersects, recursive);
  27828. intersects.sort(ascSort);
  27829. return intersects;
  27830. },
  27831. intersectObjects: function (objects, recursive, optionalTarget) {
  27832. var intersects = optionalTarget || [];
  27833. if (Array.isArray(objects) === false) {
  27834. console.warn('THREE.Raycaster.intersectObjects: objects is not an Array.');
  27835. return intersects;
  27836. }
  27837. for (var i = 0, l = objects.length; i < l; i++) {
  27838. intersectObject(objects[i], this, intersects, recursive);
  27839. }
  27840. intersects.sort(ascSort);
  27841. return intersects;
  27842. }
  27843. });
  27844. /**
  27845. * @author bhouston / http://clara.io
  27846. * @author WestLangley / http://github.com/WestLangley
  27847. *
  27848. * Ref: https://en.wikipedia.org/wiki/Spherical_coordinate_system
  27849. *
  27850. * The polar angle (phi) is measured from the positive y-axis. The positive y-axis is up.
  27851. * The azimuthal angle (theta) is measured from the positive z-axiz.
  27852. */
  27853. function Spherical(radius, phi, theta) {
  27854. this.radius = radius !== undefined ? radius : 1.0;
  27855. this.phi = phi !== undefined ? phi : 0; // polar angle
  27856. this.theta = theta !== undefined ? theta : 0; // azimuthal angle
  27857. return this;
  27858. }
  27859. Object.assign(Spherical.prototype, {
  27860. set: function (radius, phi, theta) {
  27861. this.radius = radius;
  27862. this.phi = phi;
  27863. this.theta = theta;
  27864. return this;
  27865. },
  27866. clone: function () {
  27867. return new this.constructor().copy(this);
  27868. },
  27869. copy: function (other) {
  27870. this.radius = other.radius;
  27871. this.phi = other.phi;
  27872. this.theta = other.theta;
  27873. return this;
  27874. },
  27875. // restrict phi to be betwee EPS and PI-EPS
  27876. makeSafe: function () {
  27877. var EPS = 0.000001;
  27878. this.phi = Math.max(EPS, Math.min(Math.PI - EPS, this.phi));
  27879. return this;
  27880. },
  27881. setFromVector3: function (v) {
  27882. return this.setFromCartesianCoords(v.x, v.y, v.z);
  27883. },
  27884. setFromCartesianCoords: function (x, y, z) {
  27885. this.radius = Math.sqrt(x * x + y * y + z * z);
  27886. if (this.radius === 0) {
  27887. this.theta = 0;
  27888. this.phi = 0;
  27889. } else {
  27890. this.theta = Math.atan2(x, z);
  27891. this.phi = Math.acos(_Math.clamp(y / this.radius, -1, 1));
  27892. }
  27893. return this;
  27894. }
  27895. });
  27896. /**
  27897. * @author Mugen87 / https://github.com/Mugen87
  27898. *
  27899. * Ref: https://en.wikipedia.org/wiki/Cylindrical_coordinate_system
  27900. *
  27901. */
  27902. function Cylindrical(radius, theta, y) {
  27903. this.radius = radius !== undefined ? radius : 1.0; // distance from the origin to a point in the x-z plane
  27904. this.theta = theta !== undefined ? theta : 0; // counterclockwise angle in the x-z plane measured in radians from the positive z-axis
  27905. this.y = y !== undefined ? y : 0; // height above the x-z plane
  27906. return this;
  27907. }
  27908. Object.assign(Cylindrical.prototype, {
  27909. set: function (radius, theta, y) {
  27910. this.radius = radius;
  27911. this.theta = theta;
  27912. this.y = y;
  27913. return this;
  27914. },
  27915. clone: function () {
  27916. return new this.constructor().copy(this);
  27917. },
  27918. copy: function (other) {
  27919. this.radius = other.radius;
  27920. this.theta = other.theta;
  27921. this.y = other.y;
  27922. return this;
  27923. },
  27924. setFromVector3: function (v) {
  27925. return this.setFromCartesianCoords(v.x, v.y, v.z);
  27926. },
  27927. setFromCartesianCoords: function (x, y, z) {
  27928. this.radius = Math.sqrt(x * x + z * z);
  27929. this.theta = Math.atan2(x, z);
  27930. this.y = y;
  27931. return this;
  27932. }
  27933. });
  27934. /**
  27935. * @author bhouston / http://clara.io
  27936. */
  27937. var _vector$6 = new Vector2();
  27938. function Box2(min, max) {
  27939. this.min = min !== undefined ? min : new Vector2(+Infinity, +Infinity);
  27940. this.max = max !== undefined ? max : new Vector2(-Infinity, -Infinity);
  27941. }
  27942. Object.assign(Box2.prototype, {
  27943. set: function (min, max) {
  27944. this.min.copy(min);
  27945. this.max.copy(max);
  27946. return this;
  27947. },
  27948. setFromPoints: function (points) {
  27949. this.makeEmpty();
  27950. for (var i = 0, il = points.length; i < il; i++) {
  27951. this.expandByPoint(points[i]);
  27952. }
  27953. return this;
  27954. },
  27955. setFromCenterAndSize: function (center, size) {
  27956. var halfSize = _vector$6.copy(size).multiplyScalar(0.5);
  27957. this.min.copy(center).sub(halfSize);
  27958. this.max.copy(center).add(halfSize);
  27959. return this;
  27960. },
  27961. clone: function () {
  27962. return new this.constructor().copy(this);
  27963. },
  27964. copy: function (box) {
  27965. this.min.copy(box.min);
  27966. this.max.copy(box.max);
  27967. return this;
  27968. },
  27969. makeEmpty: function () {
  27970. this.min.x = this.min.y = +Infinity;
  27971. this.max.x = this.max.y = -Infinity;
  27972. return this;
  27973. },
  27974. isEmpty: function () {
  27975. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  27976. return this.max.x < this.min.x || this.max.y < this.min.y;
  27977. },
  27978. getCenter: function (target) {
  27979. if (target === undefined) {
  27980. console.warn('THREE.Box2: .getCenter() target is now required');
  27981. target = new Vector2();
  27982. }
  27983. return this.isEmpty() ? target.set(0, 0) : target.addVectors(this.min, this.max).multiplyScalar(0.5);
  27984. },
  27985. getSize: function (target) {
  27986. if (target === undefined) {
  27987. console.warn('THREE.Box2: .getSize() target is now required');
  27988. target = new Vector2();
  27989. }
  27990. return this.isEmpty() ? target.set(0, 0) : target.subVectors(this.max, this.min);
  27991. },
  27992. expandByPoint: function (point) {
  27993. this.min.min(point);
  27994. this.max.max(point);
  27995. return this;
  27996. },
  27997. expandByVector: function (vector) {
  27998. this.min.sub(vector);
  27999. this.max.add(vector);
  28000. return this;
  28001. },
  28002. expandByScalar: function (scalar) {
  28003. this.min.addScalar(-scalar);
  28004. this.max.addScalar(scalar);
  28005. return this;
  28006. },
  28007. containsPoint: function (point) {
  28008. return point.x < this.min.x || point.x > this.max.x || point.y < this.min.y || point.y > this.max.y ? false : true;
  28009. },
  28010. containsBox: function (box) {
  28011. 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;
  28012. },
  28013. getParameter: function (point, target) {
  28014. // This can potentially have a divide by zero if the box
  28015. // has a size dimension of 0.
  28016. if (target === undefined) {
  28017. console.warn('THREE.Box2: .getParameter() target is now required');
  28018. target = new Vector2();
  28019. }
  28020. 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));
  28021. },
  28022. intersectsBox: function (box) {
  28023. // using 4 splitting planes to rule out intersections
  28024. 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;
  28025. },
  28026. clampPoint: function (point, target) {
  28027. if (target === undefined) {
  28028. console.warn('THREE.Box2: .clampPoint() target is now required');
  28029. target = new Vector2();
  28030. }
  28031. return target.copy(point).clamp(this.min, this.max);
  28032. },
  28033. distanceToPoint: function (point) {
  28034. var clampedPoint = _vector$6.copy(point).clamp(this.min, this.max);
  28035. return clampedPoint.sub(point).length();
  28036. },
  28037. intersect: function (box) {
  28038. this.min.max(box.min);
  28039. this.max.min(box.max);
  28040. return this;
  28041. },
  28042. union: function (box) {
  28043. this.min.min(box.min);
  28044. this.max.max(box.max);
  28045. return this;
  28046. },
  28047. translate: function (offset) {
  28048. this.min.add(offset);
  28049. this.max.add(offset);
  28050. return this;
  28051. },
  28052. equals: function (box) {
  28053. return box.min.equals(this.min) && box.max.equals(this.max);
  28054. }
  28055. });
  28056. /**
  28057. * @author bhouston / http://clara.io
  28058. */
  28059. var _startP = new Vector3();
  28060. var _startEnd = new Vector3();
  28061. function Line3(start, end) {
  28062. this.start = start !== undefined ? start : new Vector3();
  28063. this.end = end !== undefined ? end : new Vector3();
  28064. }
  28065. Object.assign(Line3.prototype, {
  28066. set: function (start, end) {
  28067. this.start.copy(start);
  28068. this.end.copy(end);
  28069. return this;
  28070. },
  28071. clone: function () {
  28072. return new this.constructor().copy(this);
  28073. },
  28074. copy: function (line) {
  28075. this.start.copy(line.start);
  28076. this.end.copy(line.end);
  28077. return this;
  28078. },
  28079. getCenter: function (target) {
  28080. if (target === undefined) {
  28081. console.warn('THREE.Line3: .getCenter() target is now required');
  28082. target = new Vector3();
  28083. }
  28084. return target.addVectors(this.start, this.end).multiplyScalar(0.5);
  28085. },
  28086. delta: function (target) {
  28087. if (target === undefined) {
  28088. console.warn('THREE.Line3: .delta() target is now required');
  28089. target = new Vector3();
  28090. }
  28091. return target.subVectors(this.end, this.start);
  28092. },
  28093. distanceSq: function () {
  28094. return this.start.distanceToSquared(this.end);
  28095. },
  28096. distance: function () {
  28097. return this.start.distanceTo(this.end);
  28098. },
  28099. at: function (t, target) {
  28100. if (target === undefined) {
  28101. console.warn('THREE.Line3: .at() target is now required');
  28102. target = new Vector3();
  28103. }
  28104. return this.delta(target).multiplyScalar(t).add(this.start);
  28105. },
  28106. closestPointToPointParameter: function (point, clampToLine) {
  28107. _startP.subVectors(point, this.start);
  28108. _startEnd.subVectors(this.end, this.start);
  28109. var startEnd2 = _startEnd.dot(_startEnd);
  28110. var startEnd_startP = _startEnd.dot(_startP);
  28111. var t = startEnd_startP / startEnd2;
  28112. if (clampToLine) {
  28113. t = _Math.clamp(t, 0, 1);
  28114. }
  28115. return t;
  28116. },
  28117. closestPointToPoint: function (point, clampToLine, target) {
  28118. var t = this.closestPointToPointParameter(point, clampToLine);
  28119. if (target === undefined) {
  28120. console.warn('THREE.Line3: .closestPointToPoint() target is now required');
  28121. target = new Vector3();
  28122. }
  28123. return this.delta(target).multiplyScalar(t).add(this.start);
  28124. },
  28125. applyMatrix4: function (matrix) {
  28126. this.start.applyMatrix4(matrix);
  28127. this.end.applyMatrix4(matrix);
  28128. return this;
  28129. },
  28130. equals: function (line) {
  28131. return line.start.equals(this.start) && line.end.equals(this.end);
  28132. }
  28133. });
  28134. /**
  28135. * @author alteredq / http://alteredqualia.com/
  28136. */
  28137. function ImmediateRenderObject(material) {
  28138. Object3D.call(this);
  28139. this.material = material;
  28140. this.render = function ()
  28141. /* renderCallback */
  28142. {};
  28143. }
  28144. ImmediateRenderObject.prototype = Object.create(Object3D.prototype);
  28145. ImmediateRenderObject.prototype.constructor = ImmediateRenderObject;
  28146. ImmediateRenderObject.prototype.isImmediateRenderObject = true;
  28147. /**
  28148. * @author mrdoob / http://mrdoob.com/
  28149. * @author WestLangley / http://github.com/WestLangley
  28150. */
  28151. var _v1$5 = new Vector3();
  28152. var _v2$3 = new Vector3();
  28153. var _normalMatrix$1 = new Matrix3();
  28154. var _keys = ['a', 'b', 'c'];
  28155. function VertexNormalsHelper(object, size, hex, linewidth) {
  28156. this.object = object;
  28157. this.size = size !== undefined ? size : 1;
  28158. var color = hex !== undefined ? hex : 0xff0000;
  28159. var width = linewidth !== undefined ? linewidth : 1; //
  28160. var nNormals = 0;
  28161. var objGeometry = this.object.geometry;
  28162. if (objGeometry && objGeometry.isGeometry) {
  28163. nNormals = objGeometry.faces.length * 3;
  28164. } else if (objGeometry && objGeometry.isBufferGeometry) {
  28165. nNormals = objGeometry.attributes.normal.count;
  28166. } //
  28167. var geometry = new BufferGeometry();
  28168. var positions = new Float32BufferAttribute(nNormals * 2 * 3, 3);
  28169. geometry.addAttribute('position', positions);
  28170. LineSegments.call(this, geometry, new LineBasicMaterial({
  28171. color: color,
  28172. linewidth: width
  28173. })); //
  28174. this.matrixAutoUpdate = false;
  28175. this.update();
  28176. }
  28177. VertexNormalsHelper.prototype = Object.create(LineSegments.prototype);
  28178. VertexNormalsHelper.prototype.constructor = VertexNormalsHelper;
  28179. VertexNormalsHelper.prototype.update = function () {
  28180. this.object.updateMatrixWorld(true);
  28181. _normalMatrix$1.getNormalMatrix(this.object.matrixWorld);
  28182. var matrixWorld = this.object.matrixWorld;
  28183. var position = this.geometry.attributes.position; //
  28184. var objGeometry = this.object.geometry;
  28185. if (objGeometry && objGeometry.isGeometry) {
  28186. var vertices = objGeometry.vertices;
  28187. var faces = objGeometry.faces;
  28188. var idx = 0;
  28189. for (var i = 0, l = faces.length; i < l; i++) {
  28190. var face = faces[i];
  28191. for (var j = 0, jl = face.vertexNormals.length; j < jl; j++) {
  28192. var vertex = vertices[face[_keys[j]]];
  28193. var normal = face.vertexNormals[j];
  28194. _v1$5.copy(vertex).applyMatrix4(matrixWorld);
  28195. _v2$3.copy(normal).applyMatrix3(_normalMatrix$1).normalize().multiplyScalar(this.size).add(_v1$5);
  28196. position.setXYZ(idx, _v1$5.x, _v1$5.y, _v1$5.z);
  28197. idx = idx + 1;
  28198. position.setXYZ(idx, _v2$3.x, _v2$3.y, _v2$3.z);
  28199. idx = idx + 1;
  28200. }
  28201. }
  28202. } else if (objGeometry && objGeometry.isBufferGeometry) {
  28203. var objPos = objGeometry.attributes.position;
  28204. var objNorm = objGeometry.attributes.normal;
  28205. var idx = 0; // for simplicity, ignore index and drawcalls, and render every normal
  28206. for (var j = 0, jl = objPos.count; j < jl; j++) {
  28207. _v1$5.set(objPos.getX(j), objPos.getY(j), objPos.getZ(j)).applyMatrix4(matrixWorld);
  28208. _v2$3.set(objNorm.getX(j), objNorm.getY(j), objNorm.getZ(j));
  28209. _v2$3.applyMatrix3(_normalMatrix$1).normalize().multiplyScalar(this.size).add(_v1$5);
  28210. position.setXYZ(idx, _v1$5.x, _v1$5.y, _v1$5.z);
  28211. idx = idx + 1;
  28212. position.setXYZ(idx, _v2$3.x, _v2$3.y, _v2$3.z);
  28213. idx = idx + 1;
  28214. }
  28215. }
  28216. position.needsUpdate = true;
  28217. };
  28218. /**
  28219. * @author alteredq / http://alteredqualia.com/
  28220. * @author mrdoob / http://mrdoob.com/
  28221. * @author WestLangley / http://github.com/WestLangley
  28222. */
  28223. var _vector$7 = new Vector3();
  28224. function SpotLightHelper(light, color) {
  28225. Object3D.call(this);
  28226. this.light = light;
  28227. this.light.updateMatrixWorld();
  28228. this.matrix = light.matrixWorld;
  28229. this.matrixAutoUpdate = false;
  28230. this.color = color;
  28231. var geometry = new BufferGeometry();
  28232. 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];
  28233. for (var i = 0, j = 1, l = 32; i < l; i++, j++) {
  28234. var p1 = i / l * Math.PI * 2;
  28235. var p2 = j / l * Math.PI * 2;
  28236. positions.push(Math.cos(p1), Math.sin(p1), 1, Math.cos(p2), Math.sin(p2), 1);
  28237. }
  28238. geometry.addAttribute('position', new Float32BufferAttribute(positions, 3));
  28239. var material = new LineBasicMaterial({
  28240. fog: false
  28241. });
  28242. this.cone = new LineSegments(geometry, material);
  28243. this.add(this.cone);
  28244. this.update();
  28245. }
  28246. SpotLightHelper.prototype = Object.create(Object3D.prototype);
  28247. SpotLightHelper.prototype.constructor = SpotLightHelper;
  28248. SpotLightHelper.prototype.dispose = function () {
  28249. this.cone.geometry.dispose();
  28250. this.cone.material.dispose();
  28251. };
  28252. SpotLightHelper.prototype.update = function () {
  28253. this.light.updateMatrixWorld();
  28254. var coneLength = this.light.distance ? this.light.distance : 1000;
  28255. var coneWidth = coneLength * Math.tan(this.light.angle);
  28256. this.cone.scale.set(coneWidth, coneWidth, coneLength);
  28257. _vector$7.setFromMatrixPosition(this.light.target.matrixWorld);
  28258. this.cone.lookAt(_vector$7);
  28259. if (this.color !== undefined) {
  28260. this.cone.material.color.set(this.color);
  28261. } else {
  28262. this.cone.material.color.copy(this.light.color);
  28263. }
  28264. };
  28265. /**
  28266. * @author Sean Griffin / http://twitter.com/sgrif
  28267. * @author Michael Guerrero / http://realitymeltdown.com
  28268. * @author mrdoob / http://mrdoob.com/
  28269. * @author ikerr / http://verold.com
  28270. * @author Mugen87 / https://github.com/Mugen87
  28271. */
  28272. var _vector$8 = new Vector3();
  28273. var _boneMatrix = new Matrix4();
  28274. var _matrixWorldInv = new Matrix4();
  28275. function getBoneList(object) {
  28276. var boneList = [];
  28277. if (object && object.isBone) {
  28278. boneList.push(object);
  28279. }
  28280. for (var i = 0; i < object.children.length; i++) {
  28281. boneList.push.apply(boneList, getBoneList(object.children[i]));
  28282. }
  28283. return boneList;
  28284. }
  28285. function SkeletonHelper(object) {
  28286. var bones = getBoneList(object);
  28287. var geometry = new BufferGeometry();
  28288. var vertices = [];
  28289. var colors = [];
  28290. var color1 = new Color(0, 0, 1);
  28291. var color2 = new Color(0, 1, 0);
  28292. for (var i = 0; i < bones.length; i++) {
  28293. var bone = bones[i];
  28294. if (bone.parent && bone.parent.isBone) {
  28295. vertices.push(0, 0, 0);
  28296. vertices.push(0, 0, 0);
  28297. colors.push(color1.r, color1.g, color1.b);
  28298. colors.push(color2.r, color2.g, color2.b);
  28299. }
  28300. }
  28301. geometry.addAttribute('position', new Float32BufferAttribute(vertices, 3));
  28302. geometry.addAttribute('color', new Float32BufferAttribute(colors, 3));
  28303. var material = new LineBasicMaterial({
  28304. vertexColors: VertexColors,
  28305. depthTest: false,
  28306. depthWrite: false,
  28307. transparent: true
  28308. });
  28309. LineSegments.call(this, geometry, material);
  28310. this.root = object;
  28311. this.bones = bones;
  28312. this.matrix = object.matrixWorld;
  28313. this.matrixAutoUpdate = false;
  28314. }
  28315. SkeletonHelper.prototype = Object.create(LineSegments.prototype);
  28316. SkeletonHelper.prototype.constructor = SkeletonHelper;
  28317. SkeletonHelper.prototype.updateMatrixWorld = function (force) {
  28318. var bones = this.bones;
  28319. var geometry = this.geometry;
  28320. var position = geometry.getAttribute('position');
  28321. _matrixWorldInv.getInverse(this.root.matrixWorld);
  28322. for (var i = 0, j = 0; i < bones.length; i++) {
  28323. var bone = bones[i];
  28324. if (bone.parent && bone.parent.isBone) {
  28325. _boneMatrix.multiplyMatrices(_matrixWorldInv, bone.matrixWorld);
  28326. _vector$8.setFromMatrixPosition(_boneMatrix);
  28327. position.setXYZ(j, _vector$8.x, _vector$8.y, _vector$8.z);
  28328. _boneMatrix.multiplyMatrices(_matrixWorldInv, bone.parent.matrixWorld);
  28329. _vector$8.setFromMatrixPosition(_boneMatrix);
  28330. position.setXYZ(j + 1, _vector$8.x, _vector$8.y, _vector$8.z);
  28331. j += 2;
  28332. }
  28333. }
  28334. geometry.getAttribute('position').needsUpdate = true;
  28335. Object3D.prototype.updateMatrixWorld.call(this, force);
  28336. };
  28337. /**
  28338. * @author alteredq / http://alteredqualia.com/
  28339. * @author mrdoob / http://mrdoob.com/
  28340. */
  28341. function PointLightHelper(light, sphereSize, color) {
  28342. this.light = light;
  28343. this.light.updateMatrixWorld();
  28344. this.color = color;
  28345. var geometry = new SphereBufferGeometry(sphereSize, 4, 2);
  28346. var material = new MeshBasicMaterial({
  28347. wireframe: true,
  28348. fog: false
  28349. });
  28350. Mesh.call(this, geometry, material);
  28351. this.matrix = this.light.matrixWorld;
  28352. this.matrixAutoUpdate = false;
  28353. this.update();
  28354. /*
  28355. var distanceGeometry = new THREE.IcosahedronBufferGeometry( 1, 2 );
  28356. var distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  28357. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  28358. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  28359. var d = light.distance;
  28360. if ( d === 0.0 ) {
  28361. this.lightDistance.visible = false;
  28362. } else {
  28363. this.lightDistance.scale.set( d, d, d );
  28364. }
  28365. this.add( this.lightDistance );
  28366. */
  28367. }
  28368. PointLightHelper.prototype = Object.create(Mesh.prototype);
  28369. PointLightHelper.prototype.constructor = PointLightHelper;
  28370. PointLightHelper.prototype.dispose = function () {
  28371. this.geometry.dispose();
  28372. this.material.dispose();
  28373. };
  28374. PointLightHelper.prototype.update = function () {
  28375. if (this.color !== undefined) {
  28376. this.material.color.set(this.color);
  28377. } else {
  28378. this.material.color.copy(this.light.color);
  28379. }
  28380. /*
  28381. var d = this.light.distance;
  28382. if ( d === 0.0 ) {
  28383. this.lightDistance.visible = false;
  28384. } else {
  28385. this.lightDistance.visible = true;
  28386. this.lightDistance.scale.set( d, d, d );
  28387. }
  28388. */
  28389. };
  28390. /**
  28391. * @author abelnation / http://github.com/abelnation
  28392. * @author Mugen87 / http://github.com/Mugen87
  28393. * @author WestLangley / http://github.com/WestLangley
  28394. *
  28395. * This helper must be added as a child of the light
  28396. */
  28397. function RectAreaLightHelper(light, color) {
  28398. this.type = 'RectAreaLightHelper';
  28399. this.light = light;
  28400. this.color = color; // optional hardwired color for the helper
  28401. var positions = [1, 1, 0, -1, 1, 0, -1, -1, 0, 1, -1, 0, 1, 1, 0];
  28402. var geometry = new BufferGeometry();
  28403. geometry.addAttribute('position', new Float32BufferAttribute(positions, 3));
  28404. geometry.computeBoundingSphere();
  28405. var material = new LineBasicMaterial({
  28406. fog: false
  28407. });
  28408. Line.call(this, geometry, material); //
  28409. var positions2 = [1, 1, 0, -1, 1, 0, -1, -1, 0, 1, 1, 0, -1, -1, 0, 1, -1, 0];
  28410. var geometry2 = new BufferGeometry();
  28411. geometry2.addAttribute('position', new Float32BufferAttribute(positions2, 3));
  28412. geometry2.computeBoundingSphere();
  28413. this.add(new Mesh(geometry2, new MeshBasicMaterial({
  28414. side: BackSide,
  28415. fog: false
  28416. })));
  28417. this.update();
  28418. }
  28419. RectAreaLightHelper.prototype = Object.create(Line.prototype);
  28420. RectAreaLightHelper.prototype.constructor = RectAreaLightHelper;
  28421. RectAreaLightHelper.prototype.update = function () {
  28422. this.scale.set(0.5 * this.light.width, 0.5 * this.light.height, 1);
  28423. if (this.color !== undefined) {
  28424. this.material.color.set(this.color);
  28425. this.children[0].material.color.set(this.color);
  28426. } else {
  28427. this.material.color.copy(this.light.color).multiplyScalar(this.light.intensity); // prevent hue shift
  28428. var c = this.material.color;
  28429. var max = Math.max(c.r, c.g, c.b);
  28430. if (max > 1) c.multiplyScalar(1 / max);
  28431. this.children[0].material.color.copy(this.material.color);
  28432. }
  28433. };
  28434. RectAreaLightHelper.prototype.dispose = function () {
  28435. this.geometry.dispose();
  28436. this.material.dispose();
  28437. this.children[0].geometry.dispose();
  28438. this.children[0].material.dispose();
  28439. };
  28440. /**
  28441. * @author alteredq / http://alteredqualia.com/
  28442. * @author mrdoob / http://mrdoob.com/
  28443. * @author Mugen87 / https://github.com/Mugen87
  28444. */
  28445. var _vector$9 = new Vector3();
  28446. var _color1 = new Color();
  28447. var _color2 = new Color();
  28448. function HemisphereLightHelper(light, size, color) {
  28449. Object3D.call(this);
  28450. this.light = light;
  28451. this.light.updateMatrixWorld();
  28452. this.matrix = light.matrixWorld;
  28453. this.matrixAutoUpdate = false;
  28454. this.color = color;
  28455. var geometry = new OctahedronBufferGeometry(size);
  28456. geometry.rotateY(Math.PI * 0.5);
  28457. this.material = new MeshBasicMaterial({
  28458. wireframe: true,
  28459. fog: false
  28460. });
  28461. if (this.color === undefined) this.material.vertexColors = VertexColors;
  28462. var position = geometry.getAttribute('position');
  28463. var colors = new Float32Array(position.count * 3);
  28464. geometry.addAttribute('color', new BufferAttribute(colors, 3));
  28465. this.add(new Mesh(geometry, this.material));
  28466. this.update();
  28467. }
  28468. HemisphereLightHelper.prototype = Object.create(Object3D.prototype);
  28469. HemisphereLightHelper.prototype.constructor = HemisphereLightHelper;
  28470. HemisphereLightHelper.prototype.dispose = function () {
  28471. this.children[0].geometry.dispose();
  28472. this.children[0].material.dispose();
  28473. };
  28474. HemisphereLightHelper.prototype.update = function () {
  28475. var mesh = this.children[0];
  28476. if (this.color !== undefined) {
  28477. this.material.color.set(this.color);
  28478. } else {
  28479. var colors = mesh.geometry.getAttribute('color');
  28480. _color1.copy(this.light.color);
  28481. _color2.copy(this.light.groundColor);
  28482. for (var i = 0, l = colors.count; i < l; i++) {
  28483. var color = i < l / 2 ? _color1 : _color2;
  28484. colors.setXYZ(i, color.r, color.g, color.b);
  28485. }
  28486. colors.needsUpdate = true;
  28487. }
  28488. mesh.lookAt(_vector$9.setFromMatrixPosition(this.light.matrixWorld).negate());
  28489. };
  28490. /**
  28491. * @author WestLangley / http://github.com/WestLangley
  28492. */
  28493. function LightProbeHelper(lightProbe, size) {
  28494. this.lightProbe = lightProbe;
  28495. this.size = size;
  28496. var defines = {};
  28497. defines['GAMMA_OUTPUT'] = ""; // material
  28498. var material = new ShaderMaterial({
  28499. defines: defines,
  28500. uniforms: {
  28501. sh: {
  28502. value: this.lightProbe.sh.coefficients
  28503. },
  28504. // by reference
  28505. intensity: {
  28506. value: this.lightProbe.intensity
  28507. }
  28508. },
  28509. vertexShader: ['varying vec3 vNormal;', 'void main() {', ' vNormal = normalize( normalMatrix * normal );', ' gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );', '}'].join('\n'),
  28510. 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')
  28511. });
  28512. var geometry = new SphereBufferGeometry(1, 32, 16);
  28513. Mesh.call(this, geometry, material);
  28514. this.onBeforeRender();
  28515. }
  28516. LightProbeHelper.prototype = Object.create(Mesh.prototype);
  28517. LightProbeHelper.prototype.constructor = LightProbeHelper;
  28518. LightProbeHelper.prototype.dispose = function () {
  28519. this.geometry.dispose();
  28520. this.material.dispose();
  28521. };
  28522. LightProbeHelper.prototype.onBeforeRender = function () {
  28523. this.position.copy(this.lightProbe.position);
  28524. this.scale.set(1, 1, 1).multiplyScalar(this.size);
  28525. this.material.uniforms.intensity.value = this.lightProbe.intensity;
  28526. };
  28527. /**
  28528. * @author mrdoob / http://mrdoob.com/
  28529. */
  28530. function GridHelper(size, divisions, color1, color2) {
  28531. size = size || 10;
  28532. divisions = divisions || 10;
  28533. color1 = new Color(color1 !== undefined ? color1 : 0x444444);
  28534. color2 = new Color(color2 !== undefined ? color2 : 0x888888);
  28535. var center = divisions / 2;
  28536. var step = size / divisions;
  28537. var halfSize = size / 2;
  28538. var vertices = [],
  28539. colors = [];
  28540. for (var i = 0, j = 0, k = -halfSize; i <= divisions; i++, k += step) {
  28541. vertices.push(-halfSize, 0, k, halfSize, 0, k);
  28542. vertices.push(k, 0, -halfSize, k, 0, halfSize);
  28543. var color = i === center ? color1 : color2;
  28544. color.toArray(colors, j);
  28545. j += 3;
  28546. color.toArray(colors, j);
  28547. j += 3;
  28548. color.toArray(colors, j);
  28549. j += 3;
  28550. color.toArray(colors, j);
  28551. j += 3;
  28552. }
  28553. var geometry = new BufferGeometry();
  28554. geometry.addAttribute('position', new Float32BufferAttribute(vertices, 3));
  28555. geometry.addAttribute('color', new Float32BufferAttribute(colors, 3));
  28556. var material = new LineBasicMaterial({
  28557. vertexColors: VertexColors
  28558. });
  28559. LineSegments.call(this, geometry, material);
  28560. }
  28561. GridHelper.prototype = Object.assign(Object.create(LineSegments.prototype), {
  28562. constructor: GridHelper,
  28563. copy: function (source) {
  28564. LineSegments.prototype.copy.call(this, source);
  28565. this.geometry.copy(source.geometry);
  28566. this.material.copy(source.material);
  28567. return this;
  28568. },
  28569. clone: function () {
  28570. return new this.constructor().copy(this);
  28571. }
  28572. });
  28573. /**
  28574. * @author mrdoob / http://mrdoob.com/
  28575. * @author Mugen87 / http://github.com/Mugen87
  28576. * @author Hectate / http://www.github.com/Hectate
  28577. */
  28578. function PolarGridHelper(radius, radials, circles, divisions, color1, color2) {
  28579. radius = radius || 10;
  28580. radials = radials || 16;
  28581. circles = circles || 8;
  28582. divisions = divisions || 64;
  28583. color1 = new Color(color1 !== undefined ? color1 : 0x444444);
  28584. color2 = new Color(color2 !== undefined ? color2 : 0x888888);
  28585. var vertices = [];
  28586. var colors = [];
  28587. var x, z;
  28588. var v, i, j, r, color; // create the radials
  28589. for (i = 0; i <= radials; i++) {
  28590. v = i / radials * (Math.PI * 2);
  28591. x = Math.sin(v) * radius;
  28592. z = Math.cos(v) * radius;
  28593. vertices.push(0, 0, 0);
  28594. vertices.push(x, 0, z);
  28595. color = i & 1 ? color1 : color2;
  28596. colors.push(color.r, color.g, color.b);
  28597. colors.push(color.r, color.g, color.b);
  28598. } // create the circles
  28599. for (i = 0; i <= circles; i++) {
  28600. color = i & 1 ? color1 : color2;
  28601. r = radius - radius / circles * i;
  28602. for (j = 0; j < divisions; j++) {
  28603. // first vertex
  28604. v = j / divisions * (Math.PI * 2);
  28605. x = Math.sin(v) * r;
  28606. z = Math.cos(v) * r;
  28607. vertices.push(x, 0, z);
  28608. colors.push(color.r, color.g, color.b); // second vertex
  28609. v = (j + 1) / divisions * (Math.PI * 2);
  28610. x = Math.sin(v) * r;
  28611. z = Math.cos(v) * r;
  28612. vertices.push(x, 0, z);
  28613. colors.push(color.r, color.g, color.b);
  28614. }
  28615. }
  28616. var geometry = new BufferGeometry();
  28617. geometry.addAttribute('position', new Float32BufferAttribute(vertices, 3));
  28618. geometry.addAttribute('color', new Float32BufferAttribute(colors, 3));
  28619. var material = new LineBasicMaterial({
  28620. vertexColors: VertexColors
  28621. });
  28622. LineSegments.call(this, geometry, material);
  28623. }
  28624. PolarGridHelper.prototype = Object.create(LineSegments.prototype);
  28625. PolarGridHelper.prototype.constructor = PolarGridHelper;
  28626. /**
  28627. * @author Mugen87 / http://github.com/Mugen87
  28628. */
  28629. function PositionalAudioHelper(audio, range, divisionsInnerAngle, divisionsOuterAngle) {
  28630. this.audio = audio;
  28631. this.range = range || 1;
  28632. this.divisionsInnerAngle = divisionsInnerAngle || 16;
  28633. this.divisionsOuterAngle = divisionsOuterAngle || 2;
  28634. var geometry = new BufferGeometry();
  28635. var divisions = this.divisionsInnerAngle + this.divisionsOuterAngle * 2;
  28636. var positions = new Float32Array((divisions * 3 + 3) * 3);
  28637. geometry.addAttribute('position', new BufferAttribute(positions, 3));
  28638. var materialInnerAngle = new LineBasicMaterial({
  28639. color: 0x00ff00
  28640. });
  28641. var materialOuterAngle = new LineBasicMaterial({
  28642. color: 0xffff00
  28643. });
  28644. Line.call(this, geometry, [materialOuterAngle, materialInnerAngle]);
  28645. this.update();
  28646. }
  28647. PositionalAudioHelper.prototype = Object.create(Line.prototype);
  28648. PositionalAudioHelper.prototype.constructor = PositionalAudioHelper;
  28649. PositionalAudioHelper.prototype.update = function () {
  28650. var audio = this.audio;
  28651. var range = this.range;
  28652. var divisionsInnerAngle = this.divisionsInnerAngle;
  28653. var divisionsOuterAngle = this.divisionsOuterAngle;
  28654. var coneInnerAngle = _Math.degToRad(audio.panner.coneInnerAngle);
  28655. var coneOuterAngle = _Math.degToRad(audio.panner.coneOuterAngle);
  28656. var halfConeInnerAngle = coneInnerAngle / 2;
  28657. var halfConeOuterAngle = coneOuterAngle / 2;
  28658. var start = 0;
  28659. var count = 0;
  28660. var i, stride;
  28661. var geometry = this.geometry;
  28662. var positionAttribute = geometry.attributes.position;
  28663. geometry.clearGroups(); //
  28664. function generateSegment(from, to, divisions, materialIndex) {
  28665. var step = (to - from) / divisions;
  28666. positionAttribute.setXYZ(start, 0, 0, 0);
  28667. count++;
  28668. for (i = from; i < to; i += step) {
  28669. stride = start + count;
  28670. positionAttribute.setXYZ(stride, Math.sin(i) * range, 0, Math.cos(i) * range);
  28671. positionAttribute.setXYZ(stride + 1, Math.sin(Math.min(i + step, to)) * range, 0, Math.cos(Math.min(i + step, to)) * range);
  28672. positionAttribute.setXYZ(stride + 2, 0, 0, 0);
  28673. count += 3;
  28674. }
  28675. geometry.addGroup(start, count, materialIndex);
  28676. start += count;
  28677. count = 0;
  28678. } //
  28679. generateSegment(-halfConeOuterAngle, -halfConeInnerAngle, divisionsOuterAngle, 0);
  28680. generateSegment(-halfConeInnerAngle, halfConeInnerAngle, divisionsInnerAngle, 1);
  28681. generateSegment(halfConeInnerAngle, halfConeOuterAngle, divisionsOuterAngle, 0); //
  28682. positionAttribute.needsUpdate = true;
  28683. if (coneInnerAngle === coneOuterAngle) this.material[0].visible = false;
  28684. };
  28685. PositionalAudioHelper.prototype.dispose = function () {
  28686. this.geometry.dispose();
  28687. this.material[0].dispose();
  28688. this.material[1].dispose();
  28689. };
  28690. /**
  28691. * @author mrdoob / http://mrdoob.com/
  28692. * @author WestLangley / http://github.com/WestLangley
  28693. */
  28694. var _v1$6 = new Vector3();
  28695. var _v2$4 = new Vector3();
  28696. var _normalMatrix$2 = new Matrix3();
  28697. function FaceNormalsHelper(object, size, hex, linewidth) {
  28698. // FaceNormalsHelper only supports THREE.Geometry
  28699. this.object = object;
  28700. this.size = size !== undefined ? size : 1;
  28701. var color = hex !== undefined ? hex : 0xffff00;
  28702. var width = linewidth !== undefined ? linewidth : 1; //
  28703. var nNormals = 0;
  28704. var objGeometry = this.object.geometry;
  28705. if (objGeometry && objGeometry.isGeometry) {
  28706. nNormals = objGeometry.faces.length;
  28707. } else {
  28708. console.warn('THREE.FaceNormalsHelper: only THREE.Geometry is supported. Use THREE.VertexNormalsHelper, instead.');
  28709. } //
  28710. var geometry = new BufferGeometry();
  28711. var positions = new Float32BufferAttribute(nNormals * 2 * 3, 3);
  28712. geometry.addAttribute('position', positions);
  28713. LineSegments.call(this, geometry, new LineBasicMaterial({
  28714. color: color,
  28715. linewidth: width
  28716. })); //
  28717. this.matrixAutoUpdate = false;
  28718. this.update();
  28719. }
  28720. FaceNormalsHelper.prototype = Object.create(LineSegments.prototype);
  28721. FaceNormalsHelper.prototype.constructor = FaceNormalsHelper;
  28722. FaceNormalsHelper.prototype.update = function () {
  28723. this.object.updateMatrixWorld(true);
  28724. _normalMatrix$2.getNormalMatrix(this.object.matrixWorld);
  28725. var matrixWorld = this.object.matrixWorld;
  28726. var position = this.geometry.attributes.position; //
  28727. var objGeometry = this.object.geometry;
  28728. var vertices = objGeometry.vertices;
  28729. var faces = objGeometry.faces;
  28730. var idx = 0;
  28731. for (var i = 0, l = faces.length; i < l; i++) {
  28732. var face = faces[i];
  28733. var normal = face.normal;
  28734. _v1$6.copy(vertices[face.a]).add(vertices[face.b]).add(vertices[face.c]).divideScalar(3).applyMatrix4(matrixWorld);
  28735. _v2$4.copy(normal).applyMatrix3(_normalMatrix$2).normalize().multiplyScalar(this.size).add(_v1$6);
  28736. position.setXYZ(idx, _v1$6.x, _v1$6.y, _v1$6.z);
  28737. idx = idx + 1;
  28738. position.setXYZ(idx, _v2$4.x, _v2$4.y, _v2$4.z);
  28739. idx = idx + 1;
  28740. }
  28741. position.needsUpdate = true;
  28742. };
  28743. /**
  28744. * @author alteredq / http://alteredqualia.com/
  28745. * @author mrdoob / http://mrdoob.com/
  28746. * @author WestLangley / http://github.com/WestLangley
  28747. */
  28748. var _v1$7 = new Vector3();
  28749. var _v2$5 = new Vector3();
  28750. var _v3$1 = new Vector3();
  28751. function DirectionalLightHelper(light, size, color) {
  28752. Object3D.call(this);
  28753. this.light = light;
  28754. this.light.updateMatrixWorld();
  28755. this.matrix = light.matrixWorld;
  28756. this.matrixAutoUpdate = false;
  28757. this.color = color;
  28758. if (size === undefined) size = 1;
  28759. var geometry = new BufferGeometry();
  28760. geometry.addAttribute('position', new Float32BufferAttribute([-size, size, 0, size, size, 0, size, -size, 0, -size, -size, 0, -size, size, 0], 3));
  28761. var material = new LineBasicMaterial({
  28762. fog: false
  28763. });
  28764. this.lightPlane = new Line(geometry, material);
  28765. this.add(this.lightPlane);
  28766. geometry = new BufferGeometry();
  28767. geometry.addAttribute('position', new Float32BufferAttribute([0, 0, 0, 0, 0, 1], 3));
  28768. this.targetLine = new Line(geometry, material);
  28769. this.add(this.targetLine);
  28770. this.update();
  28771. }
  28772. DirectionalLightHelper.prototype = Object.create(Object3D.prototype);
  28773. DirectionalLightHelper.prototype.constructor = DirectionalLightHelper;
  28774. DirectionalLightHelper.prototype.dispose = function () {
  28775. this.lightPlane.geometry.dispose();
  28776. this.lightPlane.material.dispose();
  28777. this.targetLine.geometry.dispose();
  28778. this.targetLine.material.dispose();
  28779. };
  28780. DirectionalLightHelper.prototype.update = function () {
  28781. _v1$7.setFromMatrixPosition(this.light.matrixWorld);
  28782. _v2$5.setFromMatrixPosition(this.light.target.matrixWorld);
  28783. _v3$1.subVectors(_v2$5, _v1$7);
  28784. this.lightPlane.lookAt(_v2$5);
  28785. if (this.color !== undefined) {
  28786. this.lightPlane.material.color.set(this.color);
  28787. this.targetLine.material.color.set(this.color);
  28788. } else {
  28789. this.lightPlane.material.color.copy(this.light.color);
  28790. this.targetLine.material.color.copy(this.light.color);
  28791. }
  28792. this.targetLine.lookAt(_v2$5);
  28793. this.targetLine.scale.z = _v3$1.length();
  28794. };
  28795. /**
  28796. * @author alteredq / http://alteredqualia.com/
  28797. * @author Mugen87 / https://github.com/Mugen87
  28798. *
  28799. * - shows frustum, line of sight and up of the camera
  28800. * - suitable for fast updates
  28801. * - based on frustum visualization in lightgl.js shadowmap example
  28802. * http://evanw.github.com/lightgl.js/tests/shadowmap.html
  28803. */
  28804. var _vector$a = new Vector3();
  28805. var _camera = new Camera();
  28806. function CameraHelper(camera) {
  28807. var geometry = new BufferGeometry();
  28808. var material = new LineBasicMaterial({
  28809. color: 0xffffff,
  28810. vertexColors: FaceColors
  28811. });
  28812. var vertices = [];
  28813. var colors = [];
  28814. var pointMap = {}; // colors
  28815. var colorFrustum = new Color(0xffaa00);
  28816. var colorCone = new Color(0xff0000);
  28817. var colorUp = new Color(0x00aaff);
  28818. var colorTarget = new Color(0xffffff);
  28819. var colorCross = new Color(0x333333); // near
  28820. addLine('n1', 'n2', colorFrustum);
  28821. addLine('n2', 'n4', colorFrustum);
  28822. addLine('n4', 'n3', colorFrustum);
  28823. addLine('n3', 'n1', colorFrustum); // far
  28824. addLine('f1', 'f2', colorFrustum);
  28825. addLine('f2', 'f4', colorFrustum);
  28826. addLine('f4', 'f3', colorFrustum);
  28827. addLine('f3', 'f1', colorFrustum); // sides
  28828. addLine('n1', 'f1', colorFrustum);
  28829. addLine('n2', 'f2', colorFrustum);
  28830. addLine('n3', 'f3', colorFrustum);
  28831. addLine('n4', 'f4', colorFrustum); // cone
  28832. addLine('p', 'n1', colorCone);
  28833. addLine('p', 'n2', colorCone);
  28834. addLine('p', 'n3', colorCone);
  28835. addLine('p', 'n4', colorCone); // up
  28836. addLine('u1', 'u2', colorUp);
  28837. addLine('u2', 'u3', colorUp);
  28838. addLine('u3', 'u1', colorUp); // target
  28839. addLine('c', 't', colorTarget);
  28840. addLine('p', 'c', colorCross); // cross
  28841. addLine('cn1', 'cn2', colorCross);
  28842. addLine('cn3', 'cn4', colorCross);
  28843. addLine('cf1', 'cf2', colorCross);
  28844. addLine('cf3', 'cf4', colorCross);
  28845. function addLine(a, b, color) {
  28846. addPoint(a, color);
  28847. addPoint(b, color);
  28848. }
  28849. function addPoint(id, color) {
  28850. vertices.push(0, 0, 0);
  28851. colors.push(color.r, color.g, color.b);
  28852. if (pointMap[id] === undefined) {
  28853. pointMap[id] = [];
  28854. }
  28855. pointMap[id].push(vertices.length / 3 - 1);
  28856. }
  28857. geometry.addAttribute('position', new Float32BufferAttribute(vertices, 3));
  28858. geometry.addAttribute('color', new Float32BufferAttribute(colors, 3));
  28859. LineSegments.call(this, geometry, material);
  28860. this.camera = camera;
  28861. if (this.camera.updateProjectionMatrix) this.camera.updateProjectionMatrix();
  28862. this.matrix = camera.matrixWorld;
  28863. this.matrixAutoUpdate = false;
  28864. this.pointMap = pointMap;
  28865. this.update();
  28866. }
  28867. CameraHelper.prototype = Object.create(LineSegments.prototype);
  28868. CameraHelper.prototype.constructor = CameraHelper;
  28869. CameraHelper.prototype.update = function () {
  28870. var geometry = this.geometry;
  28871. var pointMap = this.pointMap;
  28872. var w = 1,
  28873. h = 1; // we need just camera projection matrix inverse
  28874. // world matrix must be identity
  28875. _camera.projectionMatrixInverse.copy(this.camera.projectionMatrixInverse); // center / target
  28876. setPoint('c', pointMap, geometry, _camera, 0, 0, -1);
  28877. setPoint('t', pointMap, geometry, _camera, 0, 0, 1); // near
  28878. setPoint('n1', pointMap, geometry, _camera, -w, -h, -1);
  28879. setPoint('n2', pointMap, geometry, _camera, w, -h, -1);
  28880. setPoint('n3', pointMap, geometry, _camera, -w, h, -1);
  28881. setPoint('n4', pointMap, geometry, _camera, w, h, -1); // far
  28882. setPoint('f1', pointMap, geometry, _camera, -w, -h, 1);
  28883. setPoint('f2', pointMap, geometry, _camera, w, -h, 1);
  28884. setPoint('f3', pointMap, geometry, _camera, -w, h, 1);
  28885. setPoint('f4', pointMap, geometry, _camera, w, h, 1); // up
  28886. setPoint('u1', pointMap, geometry, _camera, w * 0.7, h * 1.1, -1);
  28887. setPoint('u2', pointMap, geometry, _camera, -w * 0.7, h * 1.1, -1);
  28888. setPoint('u3', pointMap, geometry, _camera, 0, h * 2, -1); // cross
  28889. setPoint('cf1', pointMap, geometry, _camera, -w, 0, 1);
  28890. setPoint('cf2', pointMap, geometry, _camera, w, 0, 1);
  28891. setPoint('cf3', pointMap, geometry, _camera, 0, -h, 1);
  28892. setPoint('cf4', pointMap, geometry, _camera, 0, h, 1);
  28893. setPoint('cn1', pointMap, geometry, _camera, -w, 0, -1);
  28894. setPoint('cn2', pointMap, geometry, _camera, w, 0, -1);
  28895. setPoint('cn3', pointMap, geometry, _camera, 0, -h, -1);
  28896. setPoint('cn4', pointMap, geometry, _camera, 0, h, -1);
  28897. geometry.getAttribute('position').needsUpdate = true;
  28898. };
  28899. function setPoint(point, pointMap, geometry, camera, x, y, z) {
  28900. _vector$a.set(x, y, z).unproject(camera);
  28901. var points = pointMap[point];
  28902. if (points !== undefined) {
  28903. var position = geometry.getAttribute('position');
  28904. for (var i = 0, l = points.length; i < l; i++) {
  28905. position.setXYZ(points[i], _vector$a.x, _vector$a.y, _vector$a.z);
  28906. }
  28907. }
  28908. }
  28909. /**
  28910. * @author mrdoob / http://mrdoob.com/
  28911. * @author Mugen87 / http://github.com/Mugen87
  28912. */
  28913. var _box$2 = new Box3();
  28914. function BoxHelper(object, color) {
  28915. this.object = object;
  28916. if (color === undefined) color = 0xffff00;
  28917. 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]);
  28918. var positions = new Float32Array(8 * 3);
  28919. var geometry = new BufferGeometry();
  28920. geometry.setIndex(new BufferAttribute(indices, 1));
  28921. geometry.addAttribute('position', new BufferAttribute(positions, 3));
  28922. LineSegments.call(this, geometry, new LineBasicMaterial({
  28923. color: color
  28924. }));
  28925. this.matrixAutoUpdate = false;
  28926. this.update();
  28927. }
  28928. BoxHelper.prototype = Object.create(LineSegments.prototype);
  28929. BoxHelper.prototype.constructor = BoxHelper;
  28930. BoxHelper.prototype.update = function (object) {
  28931. if (object !== undefined) {
  28932. console.warn('THREE.BoxHelper: .update() has no longer arguments.');
  28933. }
  28934. if (this.object !== undefined) {
  28935. _box$2.setFromObject(this.object);
  28936. }
  28937. if (_box$2.isEmpty()) return;
  28938. var min = _box$2.min;
  28939. var max = _box$2.max;
  28940. /*
  28941. 5____4
  28942. 1/___0/|
  28943. | 6__|_7
  28944. 2/___3/
  28945. 0: max.x, max.y, max.z
  28946. 1: min.x, max.y, max.z
  28947. 2: min.x, min.y, max.z
  28948. 3: max.x, min.y, max.z
  28949. 4: max.x, max.y, min.z
  28950. 5: min.x, max.y, min.z
  28951. 6: min.x, min.y, min.z
  28952. 7: max.x, min.y, min.z
  28953. */
  28954. var position = this.geometry.attributes.position;
  28955. var array = position.array;
  28956. array[0] = max.x;
  28957. array[1] = max.y;
  28958. array[2] = max.z;
  28959. array[3] = min.x;
  28960. array[4] = max.y;
  28961. array[5] = max.z;
  28962. array[6] = min.x;
  28963. array[7] = min.y;
  28964. array[8] = max.z;
  28965. array[9] = max.x;
  28966. array[10] = min.y;
  28967. array[11] = max.z;
  28968. array[12] = max.x;
  28969. array[13] = max.y;
  28970. array[14] = min.z;
  28971. array[15] = min.x;
  28972. array[16] = max.y;
  28973. array[17] = min.z;
  28974. array[18] = min.x;
  28975. array[19] = min.y;
  28976. array[20] = min.z;
  28977. array[21] = max.x;
  28978. array[22] = min.y;
  28979. array[23] = min.z;
  28980. position.needsUpdate = true;
  28981. this.geometry.computeBoundingSphere();
  28982. };
  28983. BoxHelper.prototype.setFromObject = function (object) {
  28984. this.object = object;
  28985. this.update();
  28986. return this;
  28987. };
  28988. BoxHelper.prototype.copy = function (source) {
  28989. LineSegments.prototype.copy.call(this, source);
  28990. this.object = source.object;
  28991. return this;
  28992. };
  28993. BoxHelper.prototype.clone = function () {
  28994. return new this.constructor().copy(this);
  28995. };
  28996. /**
  28997. * @author WestLangley / http://github.com/WestLangley
  28998. */
  28999. function Box3Helper(box, color) {
  29000. this.type = 'Box3Helper';
  29001. this.box = box;
  29002. color = color || 0xffff00;
  29003. 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]);
  29004. 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];
  29005. var geometry = new BufferGeometry();
  29006. geometry.setIndex(new BufferAttribute(indices, 1));
  29007. geometry.addAttribute('position', new Float32BufferAttribute(positions, 3));
  29008. LineSegments.call(this, geometry, new LineBasicMaterial({
  29009. color: color
  29010. }));
  29011. this.geometry.computeBoundingSphere();
  29012. }
  29013. Box3Helper.prototype = Object.create(LineSegments.prototype);
  29014. Box3Helper.prototype.constructor = Box3Helper;
  29015. Box3Helper.prototype.updateMatrixWorld = function (force) {
  29016. var box = this.box;
  29017. if (box.isEmpty()) return;
  29018. box.getCenter(this.position);
  29019. box.getSize(this.scale);
  29020. this.scale.multiplyScalar(0.5);
  29021. Object3D.prototype.updateMatrixWorld.call(this, force);
  29022. };
  29023. /**
  29024. * @author WestLangley / http://github.com/WestLangley
  29025. */
  29026. function PlaneHelper(plane, size, hex) {
  29027. this.type = 'PlaneHelper';
  29028. this.plane = plane;
  29029. this.size = size === undefined ? 1 : size;
  29030. var color = hex !== undefined ? hex : 0xffff00;
  29031. 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];
  29032. var geometry = new BufferGeometry();
  29033. geometry.addAttribute('position', new Float32BufferAttribute(positions, 3));
  29034. geometry.computeBoundingSphere();
  29035. Line.call(this, geometry, new LineBasicMaterial({
  29036. color: color
  29037. })); //
  29038. var positions2 = [1, 1, 1, -1, 1, 1, -1, -1, 1, 1, 1, 1, -1, -1, 1, 1, -1, 1];
  29039. var geometry2 = new BufferGeometry();
  29040. geometry2.addAttribute('position', new Float32BufferAttribute(positions2, 3));
  29041. geometry2.computeBoundingSphere();
  29042. this.add(new Mesh(geometry2, new MeshBasicMaterial({
  29043. color: color,
  29044. opacity: 0.2,
  29045. transparent: true,
  29046. depthWrite: false
  29047. })));
  29048. }
  29049. PlaneHelper.prototype = Object.create(Line.prototype);
  29050. PlaneHelper.prototype.constructor = PlaneHelper;
  29051. PlaneHelper.prototype.updateMatrixWorld = function (force) {
  29052. var scale = -this.plane.constant;
  29053. if (Math.abs(scale) < 1e-8) scale = 1e-8; // sign does not matter
  29054. this.scale.set(0.5 * this.size, 0.5 * this.size, scale);
  29055. this.children[0].material.side = scale < 0 ? BackSide : FrontSide; // renderer flips side when determinant < 0; flipping not wanted here
  29056. this.lookAt(this.plane.normal);
  29057. Object3D.prototype.updateMatrixWorld.call(this, force);
  29058. };
  29059. /**
  29060. * @author WestLangley / http://github.com/WestLangley
  29061. * @author zz85 / http://github.com/zz85
  29062. * @author bhouston / http://clara.io
  29063. *
  29064. * Creates an arrow for visualizing directions
  29065. *
  29066. * Parameters:
  29067. * dir - Vector3
  29068. * origin - Vector3
  29069. * length - Number
  29070. * color - color in hex value
  29071. * headLength - Number
  29072. * headWidth - Number
  29073. */
  29074. var _axis = new Vector3();
  29075. var _lineGeometry, _coneGeometry;
  29076. function ArrowHelper(dir, origin, length, color, headLength, headWidth) {
  29077. // dir is assumed to be normalized
  29078. Object3D.call(this);
  29079. if (dir === undefined) dir = new Vector3(0, 0, 1);
  29080. if (origin === undefined) origin = new Vector3(0, 0, 0);
  29081. if (length === undefined) length = 1;
  29082. if (color === undefined) color = 0xffff00;
  29083. if (headLength === undefined) headLength = 0.2 * length;
  29084. if (headWidth === undefined) headWidth = 0.2 * headLength;
  29085. if (_lineGeometry === undefined) {
  29086. _lineGeometry = new BufferGeometry();
  29087. _lineGeometry.addAttribute('position', new Float32BufferAttribute([0, 0, 0, 0, 1, 0], 3));
  29088. _coneGeometry = new CylinderBufferGeometry(0, 0.5, 1, 5, 1);
  29089. _coneGeometry.translate(0, -0.5, 0);
  29090. }
  29091. this.position.copy(origin);
  29092. this.line = new Line(_lineGeometry, new LineBasicMaterial({
  29093. color: color
  29094. }));
  29095. this.line.matrixAutoUpdate = false;
  29096. this.add(this.line);
  29097. this.cone = new Mesh(_coneGeometry, new MeshBasicMaterial({
  29098. color: color
  29099. }));
  29100. this.cone.matrixAutoUpdate = false;
  29101. this.add(this.cone);
  29102. this.setDirection(dir);
  29103. this.setLength(length, headLength, headWidth);
  29104. }
  29105. ArrowHelper.prototype = Object.create(Object3D.prototype);
  29106. ArrowHelper.prototype.constructor = ArrowHelper;
  29107. ArrowHelper.prototype.setDirection = function (dir) {
  29108. // dir is assumed to be normalized
  29109. if (dir.y > 0.99999) {
  29110. this.quaternion.set(0, 0, 0, 1);
  29111. } else if (dir.y < -0.99999) {
  29112. this.quaternion.set(1, 0, 0, 0);
  29113. } else {
  29114. _axis.set(dir.z, 0, -dir.x).normalize();
  29115. var radians = Math.acos(dir.y);
  29116. this.quaternion.setFromAxisAngle(_axis, radians);
  29117. }
  29118. };
  29119. ArrowHelper.prototype.setLength = function (length, headLength, headWidth) {
  29120. if (headLength === undefined) headLength = 0.2 * length;
  29121. if (headWidth === undefined) headWidth = 0.2 * headLength;
  29122. this.line.scale.set(1, Math.max(0.0001, length - headLength), 1); // see #17458
  29123. this.line.updateMatrix();
  29124. this.cone.scale.set(headWidth, headLength, headWidth);
  29125. this.cone.position.y = length;
  29126. this.cone.updateMatrix();
  29127. };
  29128. ArrowHelper.prototype.setColor = function (color) {
  29129. this.line.material.color.set(color);
  29130. this.cone.material.color.set(color);
  29131. };
  29132. ArrowHelper.prototype.copy = function (source) {
  29133. Object3D.prototype.copy.call(this, source, false);
  29134. this.line.copy(source.line);
  29135. this.cone.copy(source.cone);
  29136. return this;
  29137. };
  29138. ArrowHelper.prototype.clone = function () {
  29139. return new this.constructor().copy(this);
  29140. };
  29141. /**
  29142. * @author sroucheray / http://sroucheray.org/
  29143. * @author mrdoob / http://mrdoob.com/
  29144. */
  29145. function AxesHelper(size) {
  29146. size = size || 1;
  29147. var vertices = [0, 0, 0, size, 0, 0, 0, 0, 0, 0, size, 0, 0, 0, 0, 0, 0, size];
  29148. var colors = [1, 0, 0, 1, 0.6, 0, 0, 1, 0, 0.6, 1, 0, 0, 0, 1, 0, 0.6, 1];
  29149. var geometry = new BufferGeometry();
  29150. geometry.addAttribute('position', new Float32BufferAttribute(vertices, 3));
  29151. geometry.addAttribute('color', new Float32BufferAttribute(colors, 3));
  29152. var material = new LineBasicMaterial({
  29153. vertexColors: VertexColors
  29154. });
  29155. LineSegments.call(this, geometry, material);
  29156. }
  29157. AxesHelper.prototype = Object.create(LineSegments.prototype);
  29158. AxesHelper.prototype.constructor = AxesHelper;
  29159. /**
  29160. * @author mrdoob / http://mrdoob.com/
  29161. */
  29162. function Face4(a, b, c, d, normal, color, materialIndex) {
  29163. console.warn('THREE.Face4 has been removed. A THREE.Face3 will be created instead.');
  29164. return new Face3(a, b, c, normal, color, materialIndex);
  29165. }
  29166. var LineStrip = 0;
  29167. exports.LineStrip = LineStrip;
  29168. var LinePieces = 1;
  29169. exports.LinePieces = LinePieces;
  29170. function MeshFaceMaterial(materials) {
  29171. console.warn('THREE.MeshFaceMaterial has been removed. Use an Array instead.');
  29172. return materials;
  29173. }
  29174. function MultiMaterial(materials) {
  29175. if (materials === undefined) materials = [];
  29176. console.warn('THREE.MultiMaterial has been removed. Use an Array instead.');
  29177. materials.isMultiMaterial = true;
  29178. materials.materials = materials;
  29179. materials.clone = function () {
  29180. return materials.slice();
  29181. };
  29182. return materials;
  29183. }
  29184. function PointCloud(geometry, material) {
  29185. console.warn('THREE.PointCloud has been renamed to THREE.Points.');
  29186. return new Points(geometry, material);
  29187. }
  29188. function Particle(material) {
  29189. console.warn('THREE.Particle has been renamed to THREE.Sprite.');
  29190. return new Sprite(material);
  29191. }
  29192. function ParticleSystem(geometry, material) {
  29193. console.warn('THREE.ParticleSystem has been renamed to THREE.Points.');
  29194. return new Points(geometry, material);
  29195. }
  29196. function PointCloudMaterial(parameters) {
  29197. console.warn('THREE.PointCloudMaterial has been renamed to THREE.PointsMaterial.');
  29198. return new PointsMaterial(parameters);
  29199. }
  29200. function ParticleBasicMaterial(parameters) {
  29201. console.warn('THREE.ParticleBasicMaterial has been renamed to THREE.PointsMaterial.');
  29202. return new PointsMaterial(parameters);
  29203. }
  29204. function ParticleSystemMaterial(parameters) {
  29205. console.warn('THREE.ParticleSystemMaterial has been renamed to THREE.PointsMaterial.');
  29206. return new PointsMaterial(parameters);
  29207. }
  29208. function Vertex(x, y, z) {
  29209. console.warn('THREE.Vertex has been removed. Use THREE.Vector3 instead.');
  29210. return new Vector3(x, y, z);
  29211. } //
  29212. function DynamicBufferAttribute(array, itemSize) {
  29213. console.warn('THREE.DynamicBufferAttribute has been removed. Use new THREE.BufferAttribute().setDynamic( true ) instead.');
  29214. return new BufferAttribute(array, itemSize).setDynamic(true);
  29215. }
  29216. function Int8Attribute(array, itemSize) {
  29217. console.warn('THREE.Int8Attribute has been removed. Use new THREE.Int8BufferAttribute() instead.');
  29218. return new Int8BufferAttribute(array, itemSize);
  29219. }
  29220. function Uint8Attribute(array, itemSize) {
  29221. console.warn('THREE.Uint8Attribute has been removed. Use new THREE.Uint8BufferAttribute() instead.');
  29222. return new Uint8BufferAttribute(array, itemSize);
  29223. }
  29224. function Uint8ClampedAttribute(array, itemSize) {
  29225. console.warn('THREE.Uint8ClampedAttribute has been removed. Use new THREE.Uint8ClampedBufferAttribute() instead.');
  29226. return new Uint8ClampedBufferAttribute(array, itemSize);
  29227. }
  29228. function Int16Attribute(array, itemSize) {
  29229. console.warn('THREE.Int16Attribute has been removed. Use new THREE.Int16BufferAttribute() instead.');
  29230. return new Int16BufferAttribute(array, itemSize);
  29231. }
  29232. function Uint16Attribute(array, itemSize) {
  29233. console.warn('THREE.Uint16Attribute has been removed. Use new THREE.Uint16BufferAttribute() instead.');
  29234. return new Uint16BufferAttribute(array, itemSize);
  29235. }
  29236. function Int32Attribute(array, itemSize) {
  29237. console.warn('THREE.Int32Attribute has been removed. Use new THREE.Int32BufferAttribute() instead.');
  29238. return new Int32BufferAttribute(array, itemSize);
  29239. }
  29240. function Uint32Attribute(array, itemSize) {
  29241. console.warn('THREE.Uint32Attribute has been removed. Use new THREE.Uint32BufferAttribute() instead.');
  29242. return new Uint32BufferAttribute(array, itemSize);
  29243. }
  29244. function Float32Attribute(array, itemSize) {
  29245. console.warn('THREE.Float32Attribute has been removed. Use new THREE.Float32BufferAttribute() instead.');
  29246. return new Float32BufferAttribute(array, itemSize);
  29247. }
  29248. function Float64Attribute(array, itemSize) {
  29249. console.warn('THREE.Float64Attribute has been removed. Use new THREE.Float64BufferAttribute() instead.');
  29250. return new Float64BufferAttribute(array, itemSize);
  29251. } //
  29252. Curve.create = function (construct, getPoint) {
  29253. console.log('THREE.Curve.create() has been deprecated');
  29254. construct.prototype = Object.create(Curve.prototype);
  29255. construct.prototype.constructor = construct;
  29256. construct.prototype.getPoint = getPoint;
  29257. return construct;
  29258. }; //
  29259. Object.assign(CurvePath.prototype, {
  29260. createPointsGeometry: function (divisions) {
  29261. 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)
  29262. var pts = this.getPoints(divisions);
  29263. return this.createGeometry(pts);
  29264. },
  29265. createSpacedPointsGeometry: function (divisions) {
  29266. console.warn('THREE.CurvePath: .createSpacedPointsGeometry() has been removed. Use new THREE.Geometry().setFromPoints( points ) instead.'); // generate geometry from equidistant sampling along the path
  29267. var pts = this.getSpacedPoints(divisions);
  29268. return this.createGeometry(pts);
  29269. },
  29270. createGeometry: function (points) {
  29271. console.warn('THREE.CurvePath: .createGeometry() has been removed. Use new THREE.Geometry().setFromPoints( points ) instead.');
  29272. var geometry = new Geometry();
  29273. for (var i = 0, l = points.length; i < l; i++) {
  29274. var point = points[i];
  29275. geometry.vertices.push(new Vector3(point.x, point.y, point.z || 0));
  29276. }
  29277. return geometry;
  29278. }
  29279. }); //
  29280. Object.assign(Path.prototype, {
  29281. fromPoints: function (points) {
  29282. console.warn('THREE.Path: .fromPoints() has been renamed to .setFromPoints().');
  29283. this.setFromPoints(points);
  29284. }
  29285. }); //
  29286. function ClosedSplineCurve3(points) {
  29287. console.warn('THREE.ClosedSplineCurve3 has been deprecated. Use THREE.CatmullRomCurve3 instead.');
  29288. CatmullRomCurve3.call(this, points);
  29289. this.type = 'catmullrom';
  29290. this.closed = true;
  29291. }
  29292. ClosedSplineCurve3.prototype = Object.create(CatmullRomCurve3.prototype); //
  29293. function SplineCurve3(points) {
  29294. console.warn('THREE.SplineCurve3 has been deprecated. Use THREE.CatmullRomCurve3 instead.');
  29295. CatmullRomCurve3.call(this, points);
  29296. this.type = 'catmullrom';
  29297. }
  29298. SplineCurve3.prototype = Object.create(CatmullRomCurve3.prototype); //
  29299. function Spline(points) {
  29300. console.warn('THREE.Spline has been removed. Use THREE.CatmullRomCurve3 instead.');
  29301. CatmullRomCurve3.call(this, points);
  29302. this.type = 'catmullrom';
  29303. }
  29304. Spline.prototype = Object.create(CatmullRomCurve3.prototype);
  29305. Object.assign(Spline.prototype, {
  29306. initFromArray: function ()
  29307. /* a */
  29308. {
  29309. console.error('THREE.Spline: .initFromArray() has been removed.');
  29310. },
  29311. getControlPointsArray: function ()
  29312. /* optionalTarget */
  29313. {
  29314. console.error('THREE.Spline: .getControlPointsArray() has been removed.');
  29315. },
  29316. reparametrizeByArcLength: function ()
  29317. /* samplingCoef */
  29318. {
  29319. console.error('THREE.Spline: .reparametrizeByArcLength() has been removed.');
  29320. }
  29321. }); //
  29322. function AxisHelper(size) {
  29323. console.warn('THREE.AxisHelper has been renamed to THREE.AxesHelper.');
  29324. return new AxesHelper(size);
  29325. }
  29326. function BoundingBoxHelper(object, color) {
  29327. console.warn('THREE.BoundingBoxHelper has been deprecated. Creating a THREE.BoxHelper instead.');
  29328. return new BoxHelper(object, color);
  29329. }
  29330. function EdgesHelper(object, hex) {
  29331. console.warn('THREE.EdgesHelper has been removed. Use THREE.EdgesGeometry instead.');
  29332. return new LineSegments(new EdgesGeometry(object.geometry), new LineBasicMaterial({
  29333. color: hex !== undefined ? hex : 0xffffff
  29334. }));
  29335. }
  29336. GridHelper.prototype.setColors = function () {
  29337. console.error('THREE.GridHelper: setColors() has been deprecated, pass them in the constructor instead.');
  29338. };
  29339. SkeletonHelper.prototype.update = function () {
  29340. console.error('THREE.SkeletonHelper: update() no longer needs to be called.');
  29341. };
  29342. function WireframeHelper(object, hex) {
  29343. console.warn('THREE.WireframeHelper has been removed. Use THREE.WireframeGeometry instead.');
  29344. return new LineSegments(new WireframeGeometry(object.geometry), new LineBasicMaterial({
  29345. color: hex !== undefined ? hex : 0xffffff
  29346. }));
  29347. } //
  29348. Object.assign(Loader.prototype, {
  29349. extractUrlBase: function (url) {
  29350. console.warn('THREE.Loader: .extractUrlBase() has been deprecated. Use THREE.LoaderUtils.extractUrlBase() instead.');
  29351. return LoaderUtils.extractUrlBase(url);
  29352. }
  29353. });
  29354. Loader.Handlers = {
  29355. add: function ()
  29356. /* regex, loader */
  29357. {
  29358. console.error('THREE.Loader: Handlers.add() has been removed. Use LoadingManager.addHandler() instead.');
  29359. },
  29360. get: function ()
  29361. /* file */
  29362. {
  29363. console.error('THREE.Loader: Handlers.get() has been removed. Use LoadingManager.getHandler() instead.');
  29364. }
  29365. };
  29366. function XHRLoader(manager) {
  29367. console.warn('THREE.XHRLoader has been renamed to THREE.FileLoader.');
  29368. return new FileLoader(manager);
  29369. }
  29370. function BinaryTextureLoader(manager) {
  29371. console.warn('THREE.BinaryTextureLoader has been renamed to THREE.DataTextureLoader.');
  29372. return new DataTextureLoader(manager);
  29373. }
  29374. Object.assign(ObjectLoader.prototype, {
  29375. setTexturePath: function (value) {
  29376. console.warn('THREE.ObjectLoader: .setTexturePath() has been renamed to .setResourcePath().');
  29377. return this.setResourcePath(value);
  29378. }
  29379. }); //
  29380. Object.assign(Box2.prototype, {
  29381. center: function (optionalTarget) {
  29382. console.warn('THREE.Box2: .center() has been renamed to .getCenter().');
  29383. return this.getCenter(optionalTarget);
  29384. },
  29385. empty: function () {
  29386. console.warn('THREE.Box2: .empty() has been renamed to .isEmpty().');
  29387. return this.isEmpty();
  29388. },
  29389. isIntersectionBox: function (box) {
  29390. console.warn('THREE.Box2: .isIntersectionBox() has been renamed to .intersectsBox().');
  29391. return this.intersectsBox(box);
  29392. },
  29393. size: function (optionalTarget) {
  29394. console.warn('THREE.Box2: .size() has been renamed to .getSize().');
  29395. return this.getSize(optionalTarget);
  29396. }
  29397. });
  29398. Object.assign(Box3.prototype, {
  29399. center: function (optionalTarget) {
  29400. console.warn('THREE.Box3: .center() has been renamed to .getCenter().');
  29401. return this.getCenter(optionalTarget);
  29402. },
  29403. empty: function () {
  29404. console.warn('THREE.Box3: .empty() has been renamed to .isEmpty().');
  29405. return this.isEmpty();
  29406. },
  29407. isIntersectionBox: function (box) {
  29408. console.warn('THREE.Box3: .isIntersectionBox() has been renamed to .intersectsBox().');
  29409. return this.intersectsBox(box);
  29410. },
  29411. isIntersectionSphere: function (sphere) {
  29412. console.warn('THREE.Box3: .isIntersectionSphere() has been renamed to .intersectsSphere().');
  29413. return this.intersectsSphere(sphere);
  29414. },
  29415. size: function (optionalTarget) {
  29416. console.warn('THREE.Box3: .size() has been renamed to .getSize().');
  29417. return this.getSize(optionalTarget);
  29418. }
  29419. });
  29420. Line3.prototype.center = function (optionalTarget) {
  29421. console.warn('THREE.Line3: .center() has been renamed to .getCenter().');
  29422. return this.getCenter(optionalTarget);
  29423. };
  29424. Object.assign(_Math, {
  29425. random16: function () {
  29426. console.warn('THREE.Math: .random16() has been deprecated. Use Math.random() instead.');
  29427. return Math.random();
  29428. },
  29429. nearestPowerOfTwo: function (value) {
  29430. console.warn('THREE.Math: .nearestPowerOfTwo() has been renamed to .floorPowerOfTwo().');
  29431. return _Math.floorPowerOfTwo(value);
  29432. },
  29433. nextPowerOfTwo: function (value) {
  29434. console.warn('THREE.Math: .nextPowerOfTwo() has been renamed to .ceilPowerOfTwo().');
  29435. return _Math.ceilPowerOfTwo(value);
  29436. }
  29437. });
  29438. Object.assign(Matrix3.prototype, {
  29439. flattenToArrayOffset: function (array, offset) {
  29440. console.warn("THREE.Matrix3: .flattenToArrayOffset() has been deprecated. Use .toArray() instead.");
  29441. return this.toArray(array, offset);
  29442. },
  29443. multiplyVector3: function (vector) {
  29444. console.warn('THREE.Matrix3: .multiplyVector3() has been removed. Use vector.applyMatrix3( matrix ) instead.');
  29445. return vector.applyMatrix3(this);
  29446. },
  29447. multiplyVector3Array: function ()
  29448. /* a */
  29449. {
  29450. console.error('THREE.Matrix3: .multiplyVector3Array() has been removed.');
  29451. },
  29452. applyToBuffer: function (buffer
  29453. /*, offset, length */
  29454. ) {
  29455. console.warn('THREE.Matrix3: .applyToBuffer() has been removed. Use matrix.applyToBufferAttribute( attribute ) instead.');
  29456. return this.applyToBufferAttribute(buffer);
  29457. },
  29458. applyToVector3Array: function ()
  29459. /* array, offset, length */
  29460. {
  29461. console.error('THREE.Matrix3: .applyToVector3Array() has been removed.');
  29462. }
  29463. });
  29464. Object.assign(Matrix4.prototype, {
  29465. extractPosition: function (m) {
  29466. console.warn('THREE.Matrix4: .extractPosition() has been renamed to .copyPosition().');
  29467. return this.copyPosition(m);
  29468. },
  29469. flattenToArrayOffset: function (array, offset) {
  29470. console.warn("THREE.Matrix4: .flattenToArrayOffset() has been deprecated. Use .toArray() instead.");
  29471. return this.toArray(array, offset);
  29472. },
  29473. getPosition: function () {
  29474. console.warn('THREE.Matrix4: .getPosition() has been removed. Use Vector3.setFromMatrixPosition( matrix ) instead.');
  29475. return new Vector3().setFromMatrixColumn(this, 3);
  29476. },
  29477. setRotationFromQuaternion: function (q) {
  29478. console.warn('THREE.Matrix4: .setRotationFromQuaternion() has been renamed to .makeRotationFromQuaternion().');
  29479. return this.makeRotationFromQuaternion(q);
  29480. },
  29481. multiplyToArray: function () {
  29482. console.warn('THREE.Matrix4: .multiplyToArray() has been removed.');
  29483. },
  29484. multiplyVector3: function (vector) {
  29485. console.warn('THREE.Matrix4: .multiplyVector3() has been removed. Use vector.applyMatrix4( matrix ) instead.');
  29486. return vector.applyMatrix4(this);
  29487. },
  29488. multiplyVector4: function (vector) {
  29489. console.warn('THREE.Matrix4: .multiplyVector4() has been removed. Use vector.applyMatrix4( matrix ) instead.');
  29490. return vector.applyMatrix4(this);
  29491. },
  29492. multiplyVector3Array: function ()
  29493. /* a */
  29494. {
  29495. console.error('THREE.Matrix4: .multiplyVector3Array() has been removed.');
  29496. },
  29497. rotateAxis: function (v) {
  29498. console.warn('THREE.Matrix4: .rotateAxis() has been removed. Use Vector3.transformDirection( matrix ) instead.');
  29499. v.transformDirection(this);
  29500. },
  29501. crossVector: function (vector) {
  29502. console.warn('THREE.Matrix4: .crossVector() has been removed. Use vector.applyMatrix4( matrix ) instead.');
  29503. return vector.applyMatrix4(this);
  29504. },
  29505. translate: function () {
  29506. console.error('THREE.Matrix4: .translate() has been removed.');
  29507. },
  29508. rotateX: function () {
  29509. console.error('THREE.Matrix4: .rotateX() has been removed.');
  29510. },
  29511. rotateY: function () {
  29512. console.error('THREE.Matrix4: .rotateY() has been removed.');
  29513. },
  29514. rotateZ: function () {
  29515. console.error('THREE.Matrix4: .rotateZ() has been removed.');
  29516. },
  29517. rotateByAxis: function () {
  29518. console.error('THREE.Matrix4: .rotateByAxis() has been removed.');
  29519. },
  29520. applyToBuffer: function (buffer
  29521. /*, offset, length */
  29522. ) {
  29523. console.warn('THREE.Matrix4: .applyToBuffer() has been removed. Use matrix.applyToBufferAttribute( attribute ) instead.');
  29524. return this.applyToBufferAttribute(buffer);
  29525. },
  29526. applyToVector3Array: function ()
  29527. /* array, offset, length */
  29528. {
  29529. console.error('THREE.Matrix4: .applyToVector3Array() has been removed.');
  29530. },
  29531. makeFrustum: function (left, right, bottom, top, near, far) {
  29532. console.warn('THREE.Matrix4: .makeFrustum() has been removed. Use .makePerspective( left, right, top, bottom, near, far ) instead.');
  29533. return this.makePerspective(left, right, top, bottom, near, far);
  29534. }
  29535. });
  29536. Plane.prototype.isIntersectionLine = function (line) {
  29537. console.warn('THREE.Plane: .isIntersectionLine() has been renamed to .intersectsLine().');
  29538. return this.intersectsLine(line);
  29539. };
  29540. Quaternion.prototype.multiplyVector3 = function (vector) {
  29541. console.warn('THREE.Quaternion: .multiplyVector3() has been removed. Use is now vector.applyQuaternion( quaternion ) instead.');
  29542. return vector.applyQuaternion(this);
  29543. };
  29544. Object.assign(Ray.prototype, {
  29545. isIntersectionBox: function (box) {
  29546. console.warn('THREE.Ray: .isIntersectionBox() has been renamed to .intersectsBox().');
  29547. return this.intersectsBox(box);
  29548. },
  29549. isIntersectionPlane: function (plane) {
  29550. console.warn('THREE.Ray: .isIntersectionPlane() has been renamed to .intersectsPlane().');
  29551. return this.intersectsPlane(plane);
  29552. },
  29553. isIntersectionSphere: function (sphere) {
  29554. console.warn('THREE.Ray: .isIntersectionSphere() has been renamed to .intersectsSphere().');
  29555. return this.intersectsSphere(sphere);
  29556. }
  29557. });
  29558. Object.assign(Triangle.prototype, {
  29559. area: function () {
  29560. console.warn('THREE.Triangle: .area() has been renamed to .getArea().');
  29561. return this.getArea();
  29562. },
  29563. barycoordFromPoint: function (point, target) {
  29564. console.warn('THREE.Triangle: .barycoordFromPoint() has been renamed to .getBarycoord().');
  29565. return this.getBarycoord(point, target);
  29566. },
  29567. midpoint: function (target) {
  29568. console.warn('THREE.Triangle: .midpoint() has been renamed to .getMidpoint().');
  29569. return this.getMidpoint(target);
  29570. },
  29571. normal: function (target) {
  29572. console.warn('THREE.Triangle: .normal() has been renamed to .getNormal().');
  29573. return this.getNormal(target);
  29574. },
  29575. plane: function (target) {
  29576. console.warn('THREE.Triangle: .plane() has been renamed to .getPlane().');
  29577. return this.getPlane(target);
  29578. }
  29579. });
  29580. Object.assign(Triangle, {
  29581. barycoordFromPoint: function (point, a, b, c, target) {
  29582. console.warn('THREE.Triangle: .barycoordFromPoint() has been renamed to .getBarycoord().');
  29583. return Triangle.getBarycoord(point, a, b, c, target);
  29584. },
  29585. normal: function (a, b, c, target) {
  29586. console.warn('THREE.Triangle: .normal() has been renamed to .getNormal().');
  29587. return Triangle.getNormal(a, b, c, target);
  29588. }
  29589. });
  29590. Object.assign(Shape.prototype, {
  29591. extractAllPoints: function (divisions) {
  29592. console.warn('THREE.Shape: .extractAllPoints() has been removed. Use .extractPoints() instead.');
  29593. return this.extractPoints(divisions);
  29594. },
  29595. extrude: function (options) {
  29596. console.warn('THREE.Shape: .extrude() has been removed. Use ExtrudeGeometry() instead.');
  29597. return new ExtrudeGeometry(this, options);
  29598. },
  29599. makeGeometry: function (options) {
  29600. console.warn('THREE.Shape: .makeGeometry() has been removed. Use ShapeGeometry() instead.');
  29601. return new ShapeGeometry(this, options);
  29602. }
  29603. });
  29604. Object.assign(Vector2.prototype, {
  29605. fromAttribute: function (attribute, index, offset) {
  29606. console.warn('THREE.Vector2: .fromAttribute() has been renamed to .fromBufferAttribute().');
  29607. return this.fromBufferAttribute(attribute, index, offset);
  29608. },
  29609. distanceToManhattan: function (v) {
  29610. console.warn('THREE.Vector2: .distanceToManhattan() has been renamed to .manhattanDistanceTo().');
  29611. return this.manhattanDistanceTo(v);
  29612. },
  29613. lengthManhattan: function () {
  29614. console.warn('THREE.Vector2: .lengthManhattan() has been renamed to .manhattanLength().');
  29615. return this.manhattanLength();
  29616. }
  29617. });
  29618. Object.assign(Vector3.prototype, {
  29619. setEulerFromRotationMatrix: function () {
  29620. console.error('THREE.Vector3: .setEulerFromRotationMatrix() has been removed. Use Euler.setFromRotationMatrix() instead.');
  29621. },
  29622. setEulerFromQuaternion: function () {
  29623. console.error('THREE.Vector3: .setEulerFromQuaternion() has been removed. Use Euler.setFromQuaternion() instead.');
  29624. },
  29625. getPositionFromMatrix: function (m) {
  29626. console.warn('THREE.Vector3: .getPositionFromMatrix() has been renamed to .setFromMatrixPosition().');
  29627. return this.setFromMatrixPosition(m);
  29628. },
  29629. getScaleFromMatrix: function (m) {
  29630. console.warn('THREE.Vector3: .getScaleFromMatrix() has been renamed to .setFromMatrixScale().');
  29631. return this.setFromMatrixScale(m);
  29632. },
  29633. getColumnFromMatrix: function (index, matrix) {
  29634. console.warn('THREE.Vector3: .getColumnFromMatrix() has been renamed to .setFromMatrixColumn().');
  29635. return this.setFromMatrixColumn(matrix, index);
  29636. },
  29637. applyProjection: function (m) {
  29638. console.warn('THREE.Vector3: .applyProjection() has been removed. Use .applyMatrix4( m ) instead.');
  29639. return this.applyMatrix4(m);
  29640. },
  29641. fromAttribute: function (attribute, index, offset) {
  29642. console.warn('THREE.Vector3: .fromAttribute() has been renamed to .fromBufferAttribute().');
  29643. return this.fromBufferAttribute(attribute, index, offset);
  29644. },
  29645. distanceToManhattan: function (v) {
  29646. console.warn('THREE.Vector3: .distanceToManhattan() has been renamed to .manhattanDistanceTo().');
  29647. return this.manhattanDistanceTo(v);
  29648. },
  29649. lengthManhattan: function () {
  29650. console.warn('THREE.Vector3: .lengthManhattan() has been renamed to .manhattanLength().');
  29651. return this.manhattanLength();
  29652. }
  29653. });
  29654. Object.assign(Vector4.prototype, {
  29655. fromAttribute: function (attribute, index, offset) {
  29656. console.warn('THREE.Vector4: .fromAttribute() has been renamed to .fromBufferAttribute().');
  29657. return this.fromBufferAttribute(attribute, index, offset);
  29658. },
  29659. lengthManhattan: function () {
  29660. console.warn('THREE.Vector4: .lengthManhattan() has been renamed to .manhattanLength().');
  29661. return this.manhattanLength();
  29662. }
  29663. }); //
  29664. Object.assign(Geometry.prototype, {
  29665. computeTangents: function () {
  29666. console.error('THREE.Geometry: .computeTangents() has been removed.');
  29667. },
  29668. computeLineDistances: function () {
  29669. console.error('THREE.Geometry: .computeLineDistances() has been removed. Use THREE.Line.computeLineDistances() instead.');
  29670. }
  29671. });
  29672. Object.assign(Object3D.prototype, {
  29673. getChildByName: function (name) {
  29674. console.warn('THREE.Object3D: .getChildByName() has been renamed to .getObjectByName().');
  29675. return this.getObjectByName(name);
  29676. },
  29677. renderDepth: function () {
  29678. console.warn('THREE.Object3D: .renderDepth has been removed. Use .renderOrder, instead.');
  29679. },
  29680. translate: function (distance, axis) {
  29681. console.warn('THREE.Object3D: .translate() has been removed. Use .translateOnAxis( axis, distance ) instead.');
  29682. return this.translateOnAxis(axis, distance);
  29683. },
  29684. getWorldRotation: function () {
  29685. console.error('THREE.Object3D: .getWorldRotation() has been removed. Use THREE.Object3D.getWorldQuaternion( target ) instead.');
  29686. }
  29687. });
  29688. Object.defineProperties(Object3D.prototype, {
  29689. eulerOrder: {
  29690. get: function () {
  29691. console.warn('THREE.Object3D: .eulerOrder is now .rotation.order.');
  29692. return this.rotation.order;
  29693. },
  29694. set: function (value) {
  29695. console.warn('THREE.Object3D: .eulerOrder is now .rotation.order.');
  29696. this.rotation.order = value;
  29697. }
  29698. },
  29699. useQuaternion: {
  29700. get: function () {
  29701. console.warn('THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.');
  29702. },
  29703. set: function () {
  29704. console.warn('THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.');
  29705. }
  29706. }
  29707. });
  29708. Object.defineProperties(LOD.prototype, {
  29709. objects: {
  29710. get: function () {
  29711. console.warn('THREE.LOD: .objects has been renamed to .levels.');
  29712. return this.levels;
  29713. }
  29714. }
  29715. });
  29716. Object.defineProperty(Skeleton.prototype, 'useVertexTexture', {
  29717. get: function () {
  29718. console.warn('THREE.Skeleton: useVertexTexture has been removed.');
  29719. },
  29720. set: function () {
  29721. console.warn('THREE.Skeleton: useVertexTexture has been removed.');
  29722. }
  29723. });
  29724. SkinnedMesh.prototype.initBones = function () {
  29725. console.error('THREE.SkinnedMesh: initBones() has been removed.');
  29726. };
  29727. Object.defineProperty(Curve.prototype, '__arcLengthDivisions', {
  29728. get: function () {
  29729. console.warn('THREE.Curve: .__arcLengthDivisions is now .arcLengthDivisions.');
  29730. return this.arcLengthDivisions;
  29731. },
  29732. set: function (value) {
  29733. console.warn('THREE.Curve: .__arcLengthDivisions is now .arcLengthDivisions.');
  29734. this.arcLengthDivisions = value;
  29735. }
  29736. }); //
  29737. PerspectiveCamera.prototype.setLens = function (focalLength, filmGauge) {
  29738. console.warn("THREE.PerspectiveCamera.setLens is deprecated. " + "Use .setFocalLength and .filmGauge for a photographic setup.");
  29739. if (filmGauge !== undefined) this.filmGauge = filmGauge;
  29740. this.setFocalLength(focalLength);
  29741. }; //
  29742. Object.defineProperties(Light.prototype, {
  29743. onlyShadow: {
  29744. set: function () {
  29745. console.warn('THREE.Light: .onlyShadow has been removed.');
  29746. }
  29747. },
  29748. shadowCameraFov: {
  29749. set: function (value) {
  29750. console.warn('THREE.Light: .shadowCameraFov is now .shadow.camera.fov.');
  29751. this.shadow.camera.fov = value;
  29752. }
  29753. },
  29754. shadowCameraLeft: {
  29755. set: function (value) {
  29756. console.warn('THREE.Light: .shadowCameraLeft is now .shadow.camera.left.');
  29757. this.shadow.camera.left = value;
  29758. }
  29759. },
  29760. shadowCameraRight: {
  29761. set: function (value) {
  29762. console.warn('THREE.Light: .shadowCameraRight is now .shadow.camera.right.');
  29763. this.shadow.camera.right = value;
  29764. }
  29765. },
  29766. shadowCameraTop: {
  29767. set: function (value) {
  29768. console.warn('THREE.Light: .shadowCameraTop is now .shadow.camera.top.');
  29769. this.shadow.camera.top = value;
  29770. }
  29771. },
  29772. shadowCameraBottom: {
  29773. set: function (value) {
  29774. console.warn('THREE.Light: .shadowCameraBottom is now .shadow.camera.bottom.');
  29775. this.shadow.camera.bottom = value;
  29776. }
  29777. },
  29778. shadowCameraNear: {
  29779. set: function (value) {
  29780. console.warn('THREE.Light: .shadowCameraNear is now .shadow.camera.near.');
  29781. this.shadow.camera.near = value;
  29782. }
  29783. },
  29784. shadowCameraFar: {
  29785. set: function (value) {
  29786. console.warn('THREE.Light: .shadowCameraFar is now .shadow.camera.far.');
  29787. this.shadow.camera.far = value;
  29788. }
  29789. },
  29790. shadowCameraVisible: {
  29791. set: function () {
  29792. console.warn('THREE.Light: .shadowCameraVisible has been removed. Use new THREE.CameraHelper( light.shadow.camera ) instead.');
  29793. }
  29794. },
  29795. shadowBias: {
  29796. set: function (value) {
  29797. console.warn('THREE.Light: .shadowBias is now .shadow.bias.');
  29798. this.shadow.bias = value;
  29799. }
  29800. },
  29801. shadowDarkness: {
  29802. set: function () {
  29803. console.warn('THREE.Light: .shadowDarkness has been removed.');
  29804. }
  29805. },
  29806. shadowMapWidth: {
  29807. set: function (value) {
  29808. console.warn('THREE.Light: .shadowMapWidth is now .shadow.mapSize.width.');
  29809. this.shadow.mapSize.width = value;
  29810. }
  29811. },
  29812. shadowMapHeight: {
  29813. set: function (value) {
  29814. console.warn('THREE.Light: .shadowMapHeight is now .shadow.mapSize.height.');
  29815. this.shadow.mapSize.height = value;
  29816. }
  29817. }
  29818. }); //
  29819. Object.defineProperties(BufferAttribute.prototype, {
  29820. length: {
  29821. get: function () {
  29822. console.warn('THREE.BufferAttribute: .length has been deprecated. Use .count instead.');
  29823. return this.array.length;
  29824. }
  29825. }
  29826. });
  29827. Object.assign(BufferAttribute.prototype, {
  29828. copyIndicesArray: function ()
  29829. /* indices */
  29830. {
  29831. console.error('THREE.BufferAttribute: .copyIndicesArray() has been removed.');
  29832. },
  29833. setArray: function (array) {
  29834. console.warn('THREE.BufferAttribute: .setArray has been deprecated. Use BufferGeometry .setAttribute to replace/resize attribute buffers');
  29835. this.count = array !== undefined ? array.length / this.itemSize : 0;
  29836. this.array = array;
  29837. return this;
  29838. }
  29839. });
  29840. Object.assign(BufferGeometry.prototype, {
  29841. addIndex: function (index) {
  29842. console.warn('THREE.BufferGeometry: .addIndex() has been renamed to .setIndex().');
  29843. this.setIndex(index);
  29844. },
  29845. addDrawCall: function (start, count, indexOffset) {
  29846. if (indexOffset !== undefined) {
  29847. console.warn('THREE.BufferGeometry: .addDrawCall() no longer supports indexOffset.');
  29848. }
  29849. console.warn('THREE.BufferGeometry: .addDrawCall() is now .addGroup().');
  29850. this.addGroup(start, count);
  29851. },
  29852. clearDrawCalls: function () {
  29853. console.warn('THREE.BufferGeometry: .clearDrawCalls() is now .clearGroups().');
  29854. this.clearGroups();
  29855. },
  29856. computeTangents: function () {
  29857. console.warn('THREE.BufferGeometry: .computeTangents() has been removed.');
  29858. },
  29859. computeOffsets: function () {
  29860. console.warn('THREE.BufferGeometry: .computeOffsets() has been removed.');
  29861. }
  29862. });
  29863. Object.defineProperties(BufferGeometry.prototype, {
  29864. drawcalls: {
  29865. get: function () {
  29866. console.error('THREE.BufferGeometry: .drawcalls has been renamed to .groups.');
  29867. return this.groups;
  29868. }
  29869. },
  29870. offsets: {
  29871. get: function () {
  29872. console.warn('THREE.BufferGeometry: .offsets has been renamed to .groups.');
  29873. return this.groups;
  29874. }
  29875. }
  29876. });
  29877. Object.assign(InterleavedBuffer.prototype, {
  29878. setArray: function (array) {
  29879. console.warn('THREE.InterleavedBuffer: .setArray has been deprecated. Use BufferGeometry .setAttribute to replace/resize attribute buffers');
  29880. this.count = array !== undefined ? array.length / this.stride : 0;
  29881. this.array = array;
  29882. return this;
  29883. }
  29884. }); //
  29885. Object.assign(ExtrudeBufferGeometry.prototype, {
  29886. getArrays: function () {
  29887. console.error('THREE.ExtrudeBufferGeometry: .getArrays() has been removed.');
  29888. },
  29889. addShapeList: function () {
  29890. console.error('THREE.ExtrudeBufferGeometry: .addShapeList() has been removed.');
  29891. },
  29892. addShape: function () {
  29893. console.error('THREE.ExtrudeBufferGeometry: .addShape() has been removed.');
  29894. }
  29895. }); //
  29896. Object.defineProperties(Uniform.prototype, {
  29897. dynamic: {
  29898. set: function () {
  29899. console.warn('THREE.Uniform: .dynamic has been removed. Use object.onBeforeRender() instead.');
  29900. }
  29901. },
  29902. onUpdate: {
  29903. value: function () {
  29904. console.warn('THREE.Uniform: .onUpdate() has been removed. Use object.onBeforeRender() instead.');
  29905. return this;
  29906. }
  29907. }
  29908. }); //
  29909. Object.defineProperties(Material.prototype, {
  29910. wrapAround: {
  29911. get: function () {
  29912. console.warn('THREE.Material: .wrapAround has been removed.');
  29913. },
  29914. set: function () {
  29915. console.warn('THREE.Material: .wrapAround has been removed.');
  29916. }
  29917. },
  29918. overdraw: {
  29919. get: function () {
  29920. console.warn('THREE.Material: .overdraw has been removed.');
  29921. },
  29922. set: function () {
  29923. console.warn('THREE.Material: .overdraw has been removed.');
  29924. }
  29925. },
  29926. wrapRGB: {
  29927. get: function () {
  29928. console.warn('THREE.Material: .wrapRGB has been removed.');
  29929. return new Color();
  29930. }
  29931. },
  29932. shading: {
  29933. get: function () {
  29934. console.error('THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.');
  29935. },
  29936. set: function (value) {
  29937. console.warn('THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.');
  29938. this.flatShading = value === FlatShading;
  29939. }
  29940. },
  29941. stencilMask: {
  29942. get: function () {
  29943. console.warn('THREE.' + this.type + ': .stencilMask has been removed. Use .stencilFuncMask instead.');
  29944. return this.stencilFuncMask;
  29945. },
  29946. set: function (value) {
  29947. console.warn('THREE.' + this.type + ': .stencilMask has been removed. Use .stencilFuncMask instead.');
  29948. this.stencilFuncMask = value;
  29949. }
  29950. }
  29951. });
  29952. Object.defineProperties(MeshPhongMaterial.prototype, {
  29953. metal: {
  29954. get: function () {
  29955. console.warn('THREE.MeshPhongMaterial: .metal has been removed. Use THREE.MeshStandardMaterial instead.');
  29956. return false;
  29957. },
  29958. set: function () {
  29959. console.warn('THREE.MeshPhongMaterial: .metal has been removed. Use THREE.MeshStandardMaterial instead');
  29960. }
  29961. }
  29962. });
  29963. Object.defineProperties(ShaderMaterial.prototype, {
  29964. derivatives: {
  29965. get: function () {
  29966. console.warn('THREE.ShaderMaterial: .derivatives has been moved to .extensions.derivatives.');
  29967. return this.extensions.derivatives;
  29968. },
  29969. set: function (value) {
  29970. console.warn('THREE. ShaderMaterial: .derivatives has been moved to .extensions.derivatives.');
  29971. this.extensions.derivatives = value;
  29972. }
  29973. }
  29974. }); //
  29975. Object.assign(WebGLRenderer.prototype, {
  29976. clearTarget: function (renderTarget, color, depth, stencil) {
  29977. console.warn('THREE.WebGLRenderer: .clearTarget() has been deprecated. Use .setRenderTarget() and .clear() instead.');
  29978. this.setRenderTarget(renderTarget);
  29979. this.clear(color, depth, stencil);
  29980. },
  29981. animate: function (callback) {
  29982. console.warn('THREE.WebGLRenderer: .animate() is now .setAnimationLoop().');
  29983. this.setAnimationLoop(callback);
  29984. },
  29985. getCurrentRenderTarget: function () {
  29986. console.warn('THREE.WebGLRenderer: .getCurrentRenderTarget() is now .getRenderTarget().');
  29987. return this.getRenderTarget();
  29988. },
  29989. getMaxAnisotropy: function () {
  29990. console.warn('THREE.WebGLRenderer: .getMaxAnisotropy() is now .capabilities.getMaxAnisotropy().');
  29991. return this.capabilities.getMaxAnisotropy();
  29992. },
  29993. getPrecision: function () {
  29994. console.warn('THREE.WebGLRenderer: .getPrecision() is now .capabilities.precision.');
  29995. return this.capabilities.precision;
  29996. },
  29997. resetGLState: function () {
  29998. console.warn('THREE.WebGLRenderer: .resetGLState() is now .state.reset().');
  29999. return this.state.reset();
  30000. },
  30001. supportsFloatTextures: function () {
  30002. console.warn('THREE.WebGLRenderer: .supportsFloatTextures() is now .extensions.get( \'OES_texture_float\' ).');
  30003. return this.extensions.get('OES_texture_float');
  30004. },
  30005. supportsHalfFloatTextures: function () {
  30006. console.warn('THREE.WebGLRenderer: .supportsHalfFloatTextures() is now .extensions.get( \'OES_texture_half_float\' ).');
  30007. return this.extensions.get('OES_texture_half_float');
  30008. },
  30009. supportsStandardDerivatives: function () {
  30010. console.warn('THREE.WebGLRenderer: .supportsStandardDerivatives() is now .extensions.get( \'OES_standard_derivatives\' ).');
  30011. return this.extensions.get('OES_standard_derivatives');
  30012. },
  30013. supportsCompressedTextureS3TC: function () {
  30014. console.warn('THREE.WebGLRenderer: .supportsCompressedTextureS3TC() is now .extensions.get( \'WEBGL_compressed_texture_s3tc\' ).');
  30015. return this.extensions.get('WEBGL_compressed_texture_s3tc');
  30016. },
  30017. supportsCompressedTexturePVRTC: function () {
  30018. console.warn('THREE.WebGLRenderer: .supportsCompressedTexturePVRTC() is now .extensions.get( \'WEBGL_compressed_texture_pvrtc\' ).');
  30019. return this.extensions.get('WEBGL_compressed_texture_pvrtc');
  30020. },
  30021. supportsBlendMinMax: function () {
  30022. console.warn('THREE.WebGLRenderer: .supportsBlendMinMax() is now .extensions.get( \'EXT_blend_minmax\' ).');
  30023. return this.extensions.get('EXT_blend_minmax');
  30024. },
  30025. supportsVertexTextures: function () {
  30026. console.warn('THREE.WebGLRenderer: .supportsVertexTextures() is now .capabilities.vertexTextures.');
  30027. return this.capabilities.vertexTextures;
  30028. },
  30029. supportsInstancedArrays: function () {
  30030. console.warn('THREE.WebGLRenderer: .supportsInstancedArrays() is now .extensions.get( \'ANGLE_instanced_arrays\' ).');
  30031. return this.extensions.get('ANGLE_instanced_arrays');
  30032. },
  30033. enableScissorTest: function (boolean) {
  30034. console.warn('THREE.WebGLRenderer: .enableScissorTest() is now .setScissorTest().');
  30035. this.setScissorTest(boolean);
  30036. },
  30037. initMaterial: function () {
  30038. console.warn('THREE.WebGLRenderer: .initMaterial() has been removed.');
  30039. },
  30040. addPrePlugin: function () {
  30041. console.warn('THREE.WebGLRenderer: .addPrePlugin() has been removed.');
  30042. },
  30043. addPostPlugin: function () {
  30044. console.warn('THREE.WebGLRenderer: .addPostPlugin() has been removed.');
  30045. },
  30046. updateShadowMap: function () {
  30047. console.warn('THREE.WebGLRenderer: .updateShadowMap() has been removed.');
  30048. },
  30049. setFaceCulling: function () {
  30050. console.warn('THREE.WebGLRenderer: .setFaceCulling() has been removed.');
  30051. },
  30052. allocTextureUnit: function () {
  30053. console.warn('THREE.WebGLRenderer: .allocTextureUnit() has been removed.');
  30054. },
  30055. setTexture: function () {
  30056. console.warn('THREE.WebGLRenderer: .setTexture() has been removed.');
  30057. },
  30058. setTexture2D: function () {
  30059. console.warn('THREE.WebGLRenderer: .setTexture2D() has been removed.');
  30060. },
  30061. setTextureCube: function () {
  30062. console.warn('THREE.WebGLRenderer: .setTextureCube() has been removed.');
  30063. },
  30064. getActiveMipMapLevel: function () {
  30065. console.warn('THREE.WebGLRenderer: .getActiveMipMapLevel() is now .getActiveMipmapLevel().');
  30066. return this.getActiveMipmapLevel();
  30067. }
  30068. });
  30069. Object.defineProperties(WebGLRenderer.prototype, {
  30070. shadowMapEnabled: {
  30071. get: function () {
  30072. return this.shadowMap.enabled;
  30073. },
  30074. set: function (value) {
  30075. console.warn('THREE.WebGLRenderer: .shadowMapEnabled is now .shadowMap.enabled.');
  30076. this.shadowMap.enabled = value;
  30077. }
  30078. },
  30079. shadowMapType: {
  30080. get: function () {
  30081. return this.shadowMap.type;
  30082. },
  30083. set: function (value) {
  30084. console.warn('THREE.WebGLRenderer: .shadowMapType is now .shadowMap.type.');
  30085. this.shadowMap.type = value;
  30086. }
  30087. },
  30088. shadowMapCullFace: {
  30089. get: function () {
  30090. console.warn('THREE.WebGLRenderer: .shadowMapCullFace has been removed. Set Material.shadowSide instead.');
  30091. return undefined;
  30092. },
  30093. set: function ()
  30094. /* value */
  30095. {
  30096. console.warn('THREE.WebGLRenderer: .shadowMapCullFace has been removed. Set Material.shadowSide instead.');
  30097. }
  30098. },
  30099. context: {
  30100. get: function () {
  30101. console.warn('THREE.WebGLRenderer: .context has been removed. Use .getContext() instead.');
  30102. return this.getContext();
  30103. }
  30104. }
  30105. });
  30106. Object.defineProperties(WebGLShadowMap.prototype, {
  30107. cullFace: {
  30108. get: function () {
  30109. console.warn('THREE.WebGLRenderer: .shadowMap.cullFace has been removed. Set Material.shadowSide instead.');
  30110. return undefined;
  30111. },
  30112. set: function ()
  30113. /* cullFace */
  30114. {
  30115. console.warn('THREE.WebGLRenderer: .shadowMap.cullFace has been removed. Set Material.shadowSide instead.');
  30116. }
  30117. },
  30118. renderReverseSided: {
  30119. get: function () {
  30120. console.warn('THREE.WebGLRenderer: .shadowMap.renderReverseSided has been removed. Set Material.shadowSide instead.');
  30121. return undefined;
  30122. },
  30123. set: function () {
  30124. console.warn('THREE.WebGLRenderer: .shadowMap.renderReverseSided has been removed. Set Material.shadowSide instead.');
  30125. }
  30126. },
  30127. renderSingleSided: {
  30128. get: function () {
  30129. console.warn('THREE.WebGLRenderer: .shadowMap.renderSingleSided has been removed. Set Material.shadowSide instead.');
  30130. return undefined;
  30131. },
  30132. set: function () {
  30133. console.warn('THREE.WebGLRenderer: .shadowMap.renderSingleSided has been removed. Set Material.shadowSide instead.');
  30134. }
  30135. }
  30136. }); //
  30137. Object.defineProperties(WebGLRenderTargetCube.prototype, {
  30138. activeCubeFace: {
  30139. set: function ()
  30140. /* value */
  30141. {
  30142. console.warn('THREE.WebGLRenderTargetCube: .activeCubeFace has been removed. It is now the second parameter of WebGLRenderer.setRenderTarget().');
  30143. }
  30144. },
  30145. activeMipMapLevel: {
  30146. set: function ()
  30147. /* value */
  30148. {
  30149. console.warn('THREE.WebGLRenderTargetCube: .activeMipMapLevel has been removed. It is now the third parameter of WebGLRenderer.setRenderTarget().');
  30150. }
  30151. }
  30152. }); //
  30153. Object.defineProperties(WebGLRenderTarget.prototype, {
  30154. wrapS: {
  30155. get: function () {
  30156. console.warn('THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.');
  30157. return this.texture.wrapS;
  30158. },
  30159. set: function (value) {
  30160. console.warn('THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.');
  30161. this.texture.wrapS = value;
  30162. }
  30163. },
  30164. wrapT: {
  30165. get: function () {
  30166. console.warn('THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.');
  30167. return this.texture.wrapT;
  30168. },
  30169. set: function (value) {
  30170. console.warn('THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.');
  30171. this.texture.wrapT = value;
  30172. }
  30173. },
  30174. magFilter: {
  30175. get: function () {
  30176. console.warn('THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.');
  30177. return this.texture.magFilter;
  30178. },
  30179. set: function (value) {
  30180. console.warn('THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.');
  30181. this.texture.magFilter = value;
  30182. }
  30183. },
  30184. minFilter: {
  30185. get: function () {
  30186. console.warn('THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.');
  30187. return this.texture.minFilter;
  30188. },
  30189. set: function (value) {
  30190. console.warn('THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.');
  30191. this.texture.minFilter = value;
  30192. }
  30193. },
  30194. anisotropy: {
  30195. get: function () {
  30196. console.warn('THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.');
  30197. return this.texture.anisotropy;
  30198. },
  30199. set: function (value) {
  30200. console.warn('THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.');
  30201. this.texture.anisotropy = value;
  30202. }
  30203. },
  30204. offset: {
  30205. get: function () {
  30206. console.warn('THREE.WebGLRenderTarget: .offset is now .texture.offset.');
  30207. return this.texture.offset;
  30208. },
  30209. set: function (value) {
  30210. console.warn('THREE.WebGLRenderTarget: .offset is now .texture.offset.');
  30211. this.texture.offset = value;
  30212. }
  30213. },
  30214. repeat: {
  30215. get: function () {
  30216. console.warn('THREE.WebGLRenderTarget: .repeat is now .texture.repeat.');
  30217. return this.texture.repeat;
  30218. },
  30219. set: function (value) {
  30220. console.warn('THREE.WebGLRenderTarget: .repeat is now .texture.repeat.');
  30221. this.texture.repeat = value;
  30222. }
  30223. },
  30224. format: {
  30225. get: function () {
  30226. console.warn('THREE.WebGLRenderTarget: .format is now .texture.format.');
  30227. return this.texture.format;
  30228. },
  30229. set: function (value) {
  30230. console.warn('THREE.WebGLRenderTarget: .format is now .texture.format.');
  30231. this.texture.format = value;
  30232. }
  30233. },
  30234. type: {
  30235. get: function () {
  30236. console.warn('THREE.WebGLRenderTarget: .type is now .texture.type.');
  30237. return this.texture.type;
  30238. },
  30239. set: function (value) {
  30240. console.warn('THREE.WebGLRenderTarget: .type is now .texture.type.');
  30241. this.texture.type = value;
  30242. }
  30243. },
  30244. generateMipmaps: {
  30245. get: function () {
  30246. console.warn('THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.');
  30247. return this.texture.generateMipmaps;
  30248. },
  30249. set: function (value) {
  30250. console.warn('THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.');
  30251. this.texture.generateMipmaps = value;
  30252. }
  30253. }
  30254. }); //
  30255. Object.defineProperties(WebVRManager.prototype, {
  30256. standing: {
  30257. set: function ()
  30258. /* value */
  30259. {
  30260. console.warn('THREE.WebVRManager: .standing has been removed.');
  30261. }
  30262. },
  30263. userHeight: {
  30264. set: function ()
  30265. /* value */
  30266. {
  30267. console.warn('THREE.WebVRManager: .userHeight has been removed.');
  30268. }
  30269. }
  30270. }); //
  30271. Audio.prototype.load = function (file) {
  30272. console.warn('THREE.Audio: .load has been deprecated. Use THREE.AudioLoader instead.');
  30273. var scope = this;
  30274. var audioLoader = new AudioLoader();
  30275. audioLoader.load(file, function (buffer) {
  30276. scope.setBuffer(buffer);
  30277. });
  30278. return this;
  30279. };
  30280. AudioAnalyser.prototype.getData = function () {
  30281. console.warn('THREE.AudioAnalyser: .getData() is now .getFrequencyData().');
  30282. return this.getFrequencyData();
  30283. }; //
  30284. CubeCamera.prototype.updateCubeMap = function (renderer, scene) {
  30285. console.warn('THREE.CubeCamera: .updateCubeMap() is now .update().');
  30286. return this.update(renderer, scene);
  30287. }; //
  30288. var GeometryUtils = {
  30289. merge: function (geometry1, geometry2, materialIndexOffset) {
  30290. console.warn('THREE.GeometryUtils: .merge() has been moved to Geometry. Use geometry.merge( geometry2, matrix, materialIndexOffset ) instead.');
  30291. var matrix;
  30292. if (geometry2.isMesh) {
  30293. geometry2.matrixAutoUpdate && geometry2.updateMatrix();
  30294. matrix = geometry2.matrix;
  30295. geometry2 = geometry2.geometry;
  30296. }
  30297. geometry1.merge(geometry2, matrix, materialIndexOffset);
  30298. },
  30299. center: function (geometry) {
  30300. console.warn('THREE.GeometryUtils: .center() has been moved to Geometry. Use geometry.center() instead.');
  30301. return geometry.center();
  30302. }
  30303. };
  30304. exports.GeometryUtils = GeometryUtils;
  30305. ImageUtils.crossOrigin = undefined;
  30306. ImageUtils.loadTexture = function (url, mapping, onLoad, onError) {
  30307. console.warn('THREE.ImageUtils.loadTexture has been deprecated. Use THREE.TextureLoader() instead.');
  30308. var loader = new TextureLoader();
  30309. loader.setCrossOrigin(this.crossOrigin);
  30310. var texture = loader.load(url, onLoad, undefined, onError);
  30311. if (mapping) texture.mapping = mapping;
  30312. return texture;
  30313. };
  30314. ImageUtils.loadTextureCube = function (urls, mapping, onLoad, onError) {
  30315. console.warn('THREE.ImageUtils.loadTextureCube has been deprecated. Use THREE.CubeTextureLoader() instead.');
  30316. var loader = new CubeTextureLoader();
  30317. loader.setCrossOrigin(this.crossOrigin);
  30318. var texture = loader.load(urls, onLoad, undefined, onError);
  30319. if (mapping) texture.mapping = mapping;
  30320. return texture;
  30321. };
  30322. ImageUtils.loadCompressedTexture = function () {
  30323. console.error('THREE.ImageUtils.loadCompressedTexture has been removed. Use THREE.DDSLoader instead.');
  30324. };
  30325. ImageUtils.loadCompressedTextureCube = function () {
  30326. console.error('THREE.ImageUtils.loadCompressedTextureCube has been removed. Use THREE.DDSLoader instead.');
  30327. }; //
  30328. function CanvasRenderer() {
  30329. console.error('THREE.CanvasRenderer has been removed');
  30330. } //
  30331. function JSONLoader() {
  30332. console.error('THREE.JSONLoader has been removed.');
  30333. } //
  30334. var SceneUtils = {
  30335. createMultiMaterialObject: function ()
  30336. /* geometry, materials */
  30337. {
  30338. console.error('THREE.SceneUtils has been moved to /examples/js/utils/SceneUtils.js');
  30339. },
  30340. detach: function ()
  30341. /* child, parent, scene */
  30342. {
  30343. console.error('THREE.SceneUtils has been moved to /examples/js/utils/SceneUtils.js');
  30344. },
  30345. attach: function ()
  30346. /* child, scene, parent */
  30347. {
  30348. console.error('THREE.SceneUtils has been moved to /examples/js/utils/SceneUtils.js');
  30349. }
  30350. }; //
  30351. exports.SceneUtils = SceneUtils;
  30352. function LensFlare() {
  30353. console.error('THREE.LensFlare has been moved to /examples/js/objects/Lensflare.js');
  30354. }
  30355. if (typeof __THREE_DEVTOOLS__ !== 'undefined') {
  30356. /* eslint-disable no-undef */
  30357. __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent('register', {
  30358. detail: {
  30359. revision: REVISION
  30360. }
  30361. }));
  30362. /* eslint-enable no-undef */
  30363. }
  30364. },{}],"../node_modules/three/examples/jsm/loaders/GLTFLoader.js":[function(require,module,exports) {
  30365. "use strict";
  30366. Object.defineProperty(exports, "__esModule", {
  30367. value: true
  30368. });
  30369. exports.GLTFLoader = void 0;
  30370. var _threeModule = require("../../../build/three.module.js");
  30371. /**
  30372. * @author Rich Tibbett / https://github.com/richtr
  30373. * @author mrdoob / http://mrdoob.com/
  30374. * @author Tony Parisi / http://www.tonyparisi.com/
  30375. * @author Takahiro / https://github.com/takahirox
  30376. * @author Don McCurdy / https://www.donmccurdy.com
  30377. */
  30378. var GLTFLoader = function () {
  30379. function GLTFLoader(manager) {
  30380. _threeModule.Loader.call(this, manager);
  30381. this.dracoLoader = null;
  30382. this.ddsLoader = null;
  30383. }
  30384. GLTFLoader.prototype = Object.assign(Object.create(_threeModule.Loader.prototype), {
  30385. constructor: GLTFLoader,
  30386. load: function (url, onLoad, onProgress, onError) {
  30387. var scope = this;
  30388. var resourcePath;
  30389. if (this.resourcePath !== '') {
  30390. resourcePath = this.resourcePath;
  30391. } else if (this.path !== '') {
  30392. resourcePath = this.path;
  30393. } else {
  30394. resourcePath = _threeModule.LoaderUtils.extractUrlBase(url);
  30395. } // Tells the LoadingManager to track an extra item, which resolves after
  30396. // the model is fully loaded. This means the count of items loaded will
  30397. // be incorrect, but ensures manager.onLoad() does not fire early.
  30398. scope.manager.itemStart(url);
  30399. var _onError = function (e) {
  30400. if (onError) {
  30401. onError(e);
  30402. } else {
  30403. console.error(e);
  30404. }
  30405. scope.manager.itemError(url);
  30406. scope.manager.itemEnd(url);
  30407. };
  30408. var loader = new _threeModule.FileLoader(scope.manager);
  30409. loader.setPath(this.path);
  30410. loader.setResponseType('arraybuffer');
  30411. if (scope.crossOrigin === 'use-credentials') {
  30412. loader.setWithCredentials(true);
  30413. }
  30414. loader.load(url, function (data) {
  30415. try {
  30416. scope.parse(data, resourcePath, function (gltf) {
  30417. onLoad(gltf);
  30418. scope.manager.itemEnd(url);
  30419. }, _onError);
  30420. } catch (e) {
  30421. _onError(e);
  30422. }
  30423. }, onProgress, _onError);
  30424. },
  30425. setDRACOLoader: function (dracoLoader) {
  30426. this.dracoLoader = dracoLoader;
  30427. return this;
  30428. },
  30429. setDDSLoader: function (ddsLoader) {
  30430. this.ddsLoader = ddsLoader;
  30431. return this;
  30432. },
  30433. parse: function (data, path, onLoad, onError) {
  30434. var content;
  30435. var extensions = {};
  30436. if (typeof data === 'string') {
  30437. content = data;
  30438. } else {
  30439. var magic = _threeModule.LoaderUtils.decodeText(new Uint8Array(data, 0, 4));
  30440. if (magic === BINARY_EXTENSION_HEADER_MAGIC) {
  30441. try {
  30442. extensions[EXTENSIONS.KHR_BINARY_GLTF] = new GLTFBinaryExtension(data);
  30443. } catch (error) {
  30444. if (onError) onError(error);
  30445. return;
  30446. }
  30447. content = extensions[EXTENSIONS.KHR_BINARY_GLTF].content;
  30448. } else {
  30449. content = _threeModule.LoaderUtils.decodeText(new Uint8Array(data));
  30450. }
  30451. }
  30452. var json = JSON.parse(content);
  30453. if (json.asset === undefined || json.asset.version[0] < 2) {
  30454. if (onError) onError(new Error('THREE.GLTFLoader: Unsupported asset. glTF versions >=2.0 are supported. Use LegacyGLTFLoader instead.'));
  30455. return;
  30456. }
  30457. if (json.extensionsUsed) {
  30458. for (var i = 0; i < json.extensionsUsed.length; ++i) {
  30459. var extensionName = json.extensionsUsed[i];
  30460. var extensionsRequired = json.extensionsRequired || [];
  30461. switch (extensionName) {
  30462. case EXTENSIONS.KHR_LIGHTS_PUNCTUAL:
  30463. extensions[extensionName] = new GLTFLightsExtension(json);
  30464. break;
  30465. case EXTENSIONS.KHR_MATERIALS_UNLIT:
  30466. extensions[extensionName] = new GLTFMaterialsUnlitExtension();
  30467. break;
  30468. case EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS:
  30469. extensions[extensionName] = new GLTFMaterialsPbrSpecularGlossinessExtension();
  30470. break;
  30471. case EXTENSIONS.KHR_DRACO_MESH_COMPRESSION:
  30472. extensions[extensionName] = new GLTFDracoMeshCompressionExtension(json, this.dracoLoader);
  30473. break;
  30474. case EXTENSIONS.MSFT_TEXTURE_DDS:
  30475. extensions[EXTENSIONS.MSFT_TEXTURE_DDS] = new GLTFTextureDDSExtension(this.ddsLoader);
  30476. break;
  30477. case EXTENSIONS.KHR_TEXTURE_TRANSFORM:
  30478. extensions[EXTENSIONS.KHR_TEXTURE_TRANSFORM] = new GLTFTextureTransformExtension();
  30479. break;
  30480. default:
  30481. if (extensionsRequired.indexOf(extensionName) >= 0) {
  30482. console.warn('THREE.GLTFLoader: Unknown extension "' + extensionName + '".');
  30483. }
  30484. }
  30485. }
  30486. }
  30487. var parser = new GLTFParser(json, extensions, {
  30488. path: path || this.resourcePath || '',
  30489. crossOrigin: this.crossOrigin,
  30490. manager: this.manager
  30491. });
  30492. parser.parse(onLoad, onError);
  30493. }
  30494. });
  30495. /* GLTFREGISTRY */
  30496. function GLTFRegistry() {
  30497. var objects = {};
  30498. return {
  30499. get: function (key) {
  30500. return objects[key];
  30501. },
  30502. add: function (key, object) {
  30503. objects[key] = object;
  30504. },
  30505. remove: function (key) {
  30506. delete objects[key];
  30507. },
  30508. removeAll: function () {
  30509. objects = {};
  30510. }
  30511. };
  30512. }
  30513. /*********************************/
  30514. /********** EXTENSIONS ***********/
  30515. /*********************************/
  30516. var EXTENSIONS = {
  30517. KHR_BINARY_GLTF: 'KHR_binary_glTF',
  30518. KHR_DRACO_MESH_COMPRESSION: 'KHR_draco_mesh_compression',
  30519. KHR_LIGHTS_PUNCTUAL: 'KHR_lights_punctual',
  30520. KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS: 'KHR_materials_pbrSpecularGlossiness',
  30521. KHR_MATERIALS_UNLIT: 'KHR_materials_unlit',
  30522. KHR_TEXTURE_TRANSFORM: 'KHR_texture_transform',
  30523. MSFT_TEXTURE_DDS: 'MSFT_texture_dds'
  30524. };
  30525. /**
  30526. * DDS Texture Extension
  30527. *
  30528. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/MSFT_texture_dds
  30529. *
  30530. */
  30531. function GLTFTextureDDSExtension(ddsLoader) {
  30532. if (!ddsLoader) {
  30533. throw new Error('THREE.GLTFLoader: Attempting to load .dds texture without importing DDSLoader');
  30534. }
  30535. this.name = EXTENSIONS.MSFT_TEXTURE_DDS;
  30536. this.ddsLoader = ddsLoader;
  30537. }
  30538. /**
  30539. * Punctual Lights Extension
  30540. *
  30541. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_lights_punctual
  30542. */
  30543. function GLTFLightsExtension(json) {
  30544. this.name = EXTENSIONS.KHR_LIGHTS_PUNCTUAL;
  30545. var extension = json.extensions && json.extensions[EXTENSIONS.KHR_LIGHTS_PUNCTUAL] || {};
  30546. this.lightDefs = extension.lights || [];
  30547. }
  30548. GLTFLightsExtension.prototype.loadLight = function (lightIndex) {
  30549. var lightDef = this.lightDefs[lightIndex];
  30550. var lightNode;
  30551. var color = new _threeModule.Color(0xffffff);
  30552. if (lightDef.color !== undefined) color.fromArray(lightDef.color);
  30553. var range = lightDef.range !== undefined ? lightDef.range : 0;
  30554. switch (lightDef.type) {
  30555. case 'directional':
  30556. lightNode = new _threeModule.DirectionalLight(color);
  30557. lightNode.target.position.set(0, 0, -1);
  30558. lightNode.add(lightNode.target);
  30559. break;
  30560. case 'point':
  30561. lightNode = new _threeModule.PointLight(color);
  30562. lightNode.distance = range;
  30563. break;
  30564. case 'spot':
  30565. lightNode = new _threeModule.SpotLight(color);
  30566. lightNode.distance = range; // Handle spotlight properties.
  30567. lightDef.spot = lightDef.spot || {};
  30568. lightDef.spot.innerConeAngle = lightDef.spot.innerConeAngle !== undefined ? lightDef.spot.innerConeAngle : 0;
  30569. lightDef.spot.outerConeAngle = lightDef.spot.outerConeAngle !== undefined ? lightDef.spot.outerConeAngle : Math.PI / 4.0;
  30570. lightNode.angle = lightDef.spot.outerConeAngle;
  30571. lightNode.penumbra = 1.0 - lightDef.spot.innerConeAngle / lightDef.spot.outerConeAngle;
  30572. lightNode.target.position.set(0, 0, -1);
  30573. lightNode.add(lightNode.target);
  30574. break;
  30575. default:
  30576. throw new Error('THREE.GLTFLoader: Unexpected light type, "' + lightDef.type + '".');
  30577. } // Some lights (e.g. spot) default to a position other than the origin. Reset the position
  30578. // here, because node-level parsing will only override position if explicitly specified.
  30579. lightNode.position.set(0, 0, 0);
  30580. lightNode.decay = 2;
  30581. if (lightDef.intensity !== undefined) lightNode.intensity = lightDef.intensity;
  30582. lightNode.name = lightDef.name || 'light_' + lightIndex;
  30583. return Promise.resolve(lightNode);
  30584. };
  30585. /**
  30586. * Unlit Materials Extension
  30587. *
  30588. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_unlit
  30589. */
  30590. function GLTFMaterialsUnlitExtension() {
  30591. this.name = EXTENSIONS.KHR_MATERIALS_UNLIT;
  30592. }
  30593. GLTFMaterialsUnlitExtension.prototype.getMaterialType = function () {
  30594. return _threeModule.MeshBasicMaterial;
  30595. };
  30596. GLTFMaterialsUnlitExtension.prototype.extendParams = function (materialParams, materialDef, parser) {
  30597. var pending = [];
  30598. materialParams.color = new _threeModule.Color(1.0, 1.0, 1.0);
  30599. materialParams.opacity = 1.0;
  30600. var metallicRoughness = materialDef.pbrMetallicRoughness;
  30601. if (metallicRoughness) {
  30602. if (Array.isArray(metallicRoughness.baseColorFactor)) {
  30603. var array = metallicRoughness.baseColorFactor;
  30604. materialParams.color.fromArray(array);
  30605. materialParams.opacity = array[3];
  30606. }
  30607. if (metallicRoughness.baseColorTexture !== undefined) {
  30608. pending.push(parser.assignTexture(materialParams, 'map', metallicRoughness.baseColorTexture));
  30609. }
  30610. }
  30611. return Promise.all(pending);
  30612. };
  30613. /* BINARY EXTENSION */
  30614. var BINARY_EXTENSION_HEADER_MAGIC = 'glTF';
  30615. var BINARY_EXTENSION_HEADER_LENGTH = 12;
  30616. var BINARY_EXTENSION_CHUNK_TYPES = {
  30617. JSON: 0x4E4F534A,
  30618. BIN: 0x004E4942
  30619. };
  30620. function GLTFBinaryExtension(data) {
  30621. this.name = EXTENSIONS.KHR_BINARY_GLTF;
  30622. this.content = null;
  30623. this.body = null;
  30624. var headerView = new DataView(data, 0, BINARY_EXTENSION_HEADER_LENGTH);
  30625. this.header = {
  30626. magic: _threeModule.LoaderUtils.decodeText(new Uint8Array(data.slice(0, 4))),
  30627. version: headerView.getUint32(4, true),
  30628. length: headerView.getUint32(8, true)
  30629. };
  30630. if (this.header.magic !== BINARY_EXTENSION_HEADER_MAGIC) {
  30631. throw new Error('THREE.GLTFLoader: Unsupported glTF-Binary header.');
  30632. } else if (this.header.version < 2.0) {
  30633. throw new Error('THREE.GLTFLoader: Legacy binary file detected. Use LegacyGLTFLoader instead.');
  30634. }
  30635. var chunkView = new DataView(data, BINARY_EXTENSION_HEADER_LENGTH);
  30636. var chunkIndex = 0;
  30637. while (chunkIndex < chunkView.byteLength) {
  30638. var chunkLength = chunkView.getUint32(chunkIndex, true);
  30639. chunkIndex += 4;
  30640. var chunkType = chunkView.getUint32(chunkIndex, true);
  30641. chunkIndex += 4;
  30642. if (chunkType === BINARY_EXTENSION_CHUNK_TYPES.JSON) {
  30643. var contentArray = new Uint8Array(data, BINARY_EXTENSION_HEADER_LENGTH + chunkIndex, chunkLength);
  30644. this.content = _threeModule.LoaderUtils.decodeText(contentArray);
  30645. } else if (chunkType === BINARY_EXTENSION_CHUNK_TYPES.BIN) {
  30646. var byteOffset = BINARY_EXTENSION_HEADER_LENGTH + chunkIndex;
  30647. this.body = data.slice(byteOffset, byteOffset + chunkLength);
  30648. } // Clients must ignore chunks with unknown types.
  30649. chunkIndex += chunkLength;
  30650. }
  30651. if (this.content === null) {
  30652. throw new Error('THREE.GLTFLoader: JSON content not found.');
  30653. }
  30654. }
  30655. /**
  30656. * DRACO Mesh Compression Extension
  30657. *
  30658. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_draco_mesh_compression
  30659. */
  30660. function GLTFDracoMeshCompressionExtension(json, dracoLoader) {
  30661. if (!dracoLoader) {
  30662. throw new Error('THREE.GLTFLoader: No DRACOLoader instance provided.');
  30663. }
  30664. this.name = EXTENSIONS.KHR_DRACO_MESH_COMPRESSION;
  30665. this.json = json;
  30666. this.dracoLoader = dracoLoader;
  30667. }
  30668. GLTFDracoMeshCompressionExtension.prototype.decodePrimitive = function (primitive, parser) {
  30669. var json = this.json;
  30670. var dracoLoader = this.dracoLoader;
  30671. var bufferViewIndex = primitive.extensions[this.name].bufferView;
  30672. var gltfAttributeMap = primitive.extensions[this.name].attributes;
  30673. var threeAttributeMap = {};
  30674. var attributeNormalizedMap = {};
  30675. var attributeTypeMap = {};
  30676. for (var attributeName in gltfAttributeMap) {
  30677. var threeAttributeName = ATTRIBUTES[attributeName] || attributeName.toLowerCase();
  30678. threeAttributeMap[threeAttributeName] = gltfAttributeMap[attributeName];
  30679. }
  30680. for (attributeName in primitive.attributes) {
  30681. var threeAttributeName = ATTRIBUTES[attributeName] || attributeName.toLowerCase();
  30682. if (gltfAttributeMap[attributeName] !== undefined) {
  30683. var accessorDef = json.accessors[primitive.attributes[attributeName]];
  30684. var componentType = WEBGL_COMPONENT_TYPES[accessorDef.componentType];
  30685. attributeTypeMap[threeAttributeName] = componentType;
  30686. attributeNormalizedMap[threeAttributeName] = accessorDef.normalized === true;
  30687. }
  30688. }
  30689. return parser.getDependency('bufferView', bufferViewIndex).then(function (bufferView) {
  30690. return new Promise(function (resolve) {
  30691. dracoLoader.decodeDracoFile(bufferView, function (geometry) {
  30692. for (var attributeName in geometry.attributes) {
  30693. var attribute = geometry.attributes[attributeName];
  30694. var normalized = attributeNormalizedMap[attributeName];
  30695. if (normalized !== undefined) attribute.normalized = normalized;
  30696. }
  30697. resolve(geometry);
  30698. }, threeAttributeMap, attributeTypeMap);
  30699. });
  30700. });
  30701. };
  30702. /**
  30703. * Texture Transform Extension
  30704. *
  30705. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_texture_transform
  30706. */
  30707. function GLTFTextureTransformExtension() {
  30708. this.name = EXTENSIONS.KHR_TEXTURE_TRANSFORM;
  30709. }
  30710. GLTFTextureTransformExtension.prototype.extendTexture = function (texture, transform) {
  30711. texture = texture.clone();
  30712. if (transform.offset !== undefined) {
  30713. texture.offset.fromArray(transform.offset);
  30714. }
  30715. if (transform.rotation !== undefined) {
  30716. texture.rotation = transform.rotation;
  30717. }
  30718. if (transform.scale !== undefined) {
  30719. texture.repeat.fromArray(transform.scale);
  30720. }
  30721. if (transform.texCoord !== undefined) {
  30722. console.warn('THREE.GLTFLoader: Custom UV sets in "' + this.name + '" extension not yet supported.');
  30723. }
  30724. texture.needsUpdate = true;
  30725. return texture;
  30726. };
  30727. /**
  30728. * Specular-Glossiness Extension
  30729. *
  30730. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_pbrSpecularGlossiness
  30731. */
  30732. function GLTFMaterialsPbrSpecularGlossinessExtension() {
  30733. return {
  30734. name: EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS,
  30735. specularGlossinessParams: ['color', 'map', 'lightMap', 'lightMapIntensity', 'aoMap', 'aoMapIntensity', 'emissive', 'emissiveIntensity', 'emissiveMap', 'bumpMap', 'bumpScale', 'normalMap', 'displacementMap', 'displacementScale', 'displacementBias', 'specularMap', 'specular', 'glossinessMap', 'glossiness', 'alphaMap', 'envMap', 'envMapIntensity', 'refractionRatio'],
  30736. getMaterialType: function () {
  30737. return _threeModule.ShaderMaterial;
  30738. },
  30739. extendParams: function (materialParams, materialDef, parser) {
  30740. var pbrSpecularGlossiness = materialDef.extensions[this.name];
  30741. var shader = _threeModule.ShaderLib['standard'];
  30742. var uniforms = _threeModule.UniformsUtils.clone(shader.uniforms);
  30743. var specularMapParsFragmentChunk = ['#ifdef USE_SPECULARMAP', ' uniform sampler2D specularMap;', '#endif'].join('\n');
  30744. var glossinessMapParsFragmentChunk = ['#ifdef USE_GLOSSINESSMAP', ' uniform sampler2D glossinessMap;', '#endif'].join('\n');
  30745. 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');
  30746. 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');
  30747. var lightPhysicalFragmentChunk = ['PhysicalMaterial material;', 'material.diffuseColor = diffuseColor.rgb;', 'material.specularRoughness = clamp( 1.0 - glossinessFactor, 0.04, 1.0 );', 'material.specularColor = specularFactor.rgb;'].join('\n');
  30748. 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);
  30749. delete uniforms.roughness;
  30750. delete uniforms.metalness;
  30751. delete uniforms.roughnessMap;
  30752. delete uniforms.metalnessMap;
  30753. uniforms.specular = {
  30754. value: new _threeModule.Color().setHex(0x111111)
  30755. };
  30756. uniforms.glossiness = {
  30757. value: 0.5
  30758. };
  30759. uniforms.specularMap = {
  30760. value: null
  30761. };
  30762. uniforms.glossinessMap = {
  30763. value: null
  30764. };
  30765. materialParams.vertexShader = shader.vertexShader;
  30766. materialParams.fragmentShader = fragmentShader;
  30767. materialParams.uniforms = uniforms;
  30768. materialParams.defines = {
  30769. 'STANDARD': ''
  30770. };
  30771. materialParams.color = new _threeModule.Color(1.0, 1.0, 1.0);
  30772. materialParams.opacity = 1.0;
  30773. var pending = [];
  30774. if (Array.isArray(pbrSpecularGlossiness.diffuseFactor)) {
  30775. var array = pbrSpecularGlossiness.diffuseFactor;
  30776. materialParams.color.fromArray(array);
  30777. materialParams.opacity = array[3];
  30778. }
  30779. if (pbrSpecularGlossiness.diffuseTexture !== undefined) {
  30780. pending.push(parser.assignTexture(materialParams, 'map', pbrSpecularGlossiness.diffuseTexture));
  30781. }
  30782. materialParams.emissive = new _threeModule.Color(0.0, 0.0, 0.0);
  30783. materialParams.glossiness = pbrSpecularGlossiness.glossinessFactor !== undefined ? pbrSpecularGlossiness.glossinessFactor : 1.0;
  30784. materialParams.specular = new _threeModule.Color(1.0, 1.0, 1.0);
  30785. if (Array.isArray(pbrSpecularGlossiness.specularFactor)) {
  30786. materialParams.specular.fromArray(pbrSpecularGlossiness.specularFactor);
  30787. }
  30788. if (pbrSpecularGlossiness.specularGlossinessTexture !== undefined) {
  30789. var specGlossMapDef = pbrSpecularGlossiness.specularGlossinessTexture;
  30790. pending.push(parser.assignTexture(materialParams, 'glossinessMap', specGlossMapDef));
  30791. pending.push(parser.assignTexture(materialParams, 'specularMap', specGlossMapDef));
  30792. }
  30793. return Promise.all(pending);
  30794. },
  30795. createMaterial: function (params) {
  30796. // setup material properties based on MeshStandardMaterial for Specular-Glossiness
  30797. var material = new _threeModule.ShaderMaterial({
  30798. defines: params.defines,
  30799. vertexShader: params.vertexShader,
  30800. fragmentShader: params.fragmentShader,
  30801. uniforms: params.uniforms,
  30802. fog: true,
  30803. lights: true,
  30804. opacity: params.opacity,
  30805. transparent: params.transparent
  30806. });
  30807. material.isGLTFSpecularGlossinessMaterial = true;
  30808. material.color = params.color;
  30809. material.map = params.map === undefined ? null : params.map;
  30810. material.lightMap = null;
  30811. material.lightMapIntensity = 1.0;
  30812. material.aoMap = params.aoMap === undefined ? null : params.aoMap;
  30813. material.aoMapIntensity = 1.0;
  30814. material.emissive = params.emissive;
  30815. material.emissiveIntensity = 1.0;
  30816. material.emissiveMap = params.emissiveMap === undefined ? null : params.emissiveMap;
  30817. material.bumpMap = params.bumpMap === undefined ? null : params.bumpMap;
  30818. material.bumpScale = 1;
  30819. material.normalMap = params.normalMap === undefined ? null : params.normalMap;
  30820. if (params.normalScale) material.normalScale = params.normalScale;
  30821. material.displacementMap = null;
  30822. material.displacementScale = 1;
  30823. material.displacementBias = 0;
  30824. material.specularMap = params.specularMap === undefined ? null : params.specularMap;
  30825. material.specular = params.specular;
  30826. material.glossinessMap = params.glossinessMap === undefined ? null : params.glossinessMap;
  30827. material.glossiness = params.glossiness;
  30828. material.alphaMap = null;
  30829. material.envMap = params.envMap === undefined ? null : params.envMap;
  30830. material.envMapIntensity = 1.0;
  30831. material.refractionRatio = 0.98;
  30832. material.extensions.derivatives = true;
  30833. return material;
  30834. },
  30835. /**
  30836. * Clones a GLTFSpecularGlossinessMaterial instance. The ShaderMaterial.copy() method can
  30837. * copy only properties it knows about or inherits, and misses many properties that would
  30838. * normally be defined by MeshStandardMaterial.
  30839. *
  30840. * This method allows GLTFSpecularGlossinessMaterials to be cloned in the process of
  30841. * loading a glTF model, but cloning later (e.g. by the user) would require these changes
  30842. * AND also updating `.onBeforeRender` on the parent mesh.
  30843. *
  30844. * @param {ShaderMaterial} source
  30845. * @return {ShaderMaterial}
  30846. */
  30847. cloneMaterial: function (source) {
  30848. var target = source.clone();
  30849. target.isGLTFSpecularGlossinessMaterial = true;
  30850. var params = this.specularGlossinessParams;
  30851. for (var i = 0, il = params.length; i < il; i++) {
  30852. var value = source[params[i]];
  30853. target[params[i]] = value && value.isColor ? value.clone() : value;
  30854. }
  30855. return target;
  30856. },
  30857. // Here's based on refreshUniformsCommon() and refreshUniformsStandard() in WebGLRenderer.
  30858. refreshUniforms: function (renderer, scene, camera, geometry, material) {
  30859. if (material.isGLTFSpecularGlossinessMaterial !== true) {
  30860. return;
  30861. }
  30862. var uniforms = material.uniforms;
  30863. var defines = material.defines;
  30864. uniforms.opacity.value = material.opacity;
  30865. uniforms.diffuse.value.copy(material.color);
  30866. uniforms.emissive.value.copy(material.emissive).multiplyScalar(material.emissiveIntensity);
  30867. uniforms.map.value = material.map;
  30868. uniforms.specularMap.value = material.specularMap;
  30869. uniforms.alphaMap.value = material.alphaMap;
  30870. uniforms.lightMap.value = material.lightMap;
  30871. uniforms.lightMapIntensity.value = material.lightMapIntensity;
  30872. uniforms.aoMap.value = material.aoMap;
  30873. uniforms.aoMapIntensity.value = material.aoMapIntensity; // uv repeat and offset setting priorities
  30874. // 1. color map
  30875. // 2. specular map
  30876. // 3. normal map
  30877. // 4. bump map
  30878. // 5. alpha map
  30879. // 6. emissive map
  30880. var uvScaleMap;
  30881. if (material.map) {
  30882. uvScaleMap = material.map;
  30883. } else if (material.specularMap) {
  30884. uvScaleMap = material.specularMap;
  30885. } else if (material.displacementMap) {
  30886. uvScaleMap = material.displacementMap;
  30887. } else if (material.normalMap) {
  30888. uvScaleMap = material.normalMap;
  30889. } else if (material.bumpMap) {
  30890. uvScaleMap = material.bumpMap;
  30891. } else if (material.glossinessMap) {
  30892. uvScaleMap = material.glossinessMap;
  30893. } else if (material.alphaMap) {
  30894. uvScaleMap = material.alphaMap;
  30895. } else if (material.emissiveMap) {
  30896. uvScaleMap = material.emissiveMap;
  30897. }
  30898. if (uvScaleMap !== undefined) {
  30899. // backwards compatibility
  30900. if (uvScaleMap.isWebGLRenderTarget) {
  30901. uvScaleMap = uvScaleMap.texture;
  30902. }
  30903. if (uvScaleMap.matrixAutoUpdate === true) {
  30904. uvScaleMap.updateMatrix();
  30905. }
  30906. uniforms.uvTransform.value.copy(uvScaleMap.matrix);
  30907. }
  30908. if (material.envMap) {
  30909. uniforms.envMap.value = material.envMap;
  30910. uniforms.envMapIntensity.value = material.envMapIntensity; // don't flip CubeTexture envMaps, flip everything else:
  30911. // WebGLRenderTargetCube will be flipped for backwards compatibility
  30912. // WebGLRenderTargetCube.texture will be flipped because it's a Texture and NOT a CubeTexture
  30913. // this check must be handled differently, or removed entirely, if WebGLRenderTargetCube uses a CubeTexture in the future
  30914. uniforms.flipEnvMap.value = material.envMap.isCubeTexture ? -1 : 1;
  30915. uniforms.reflectivity.value = material.reflectivity;
  30916. uniforms.refractionRatio.value = material.refractionRatio;
  30917. uniforms.maxMipLevel.value = renderer.properties.get(material.envMap).__maxMipLevel;
  30918. }
  30919. uniforms.specular.value.copy(material.specular);
  30920. uniforms.glossiness.value = material.glossiness;
  30921. uniforms.glossinessMap.value = material.glossinessMap;
  30922. uniforms.emissiveMap.value = material.emissiveMap;
  30923. uniforms.bumpMap.value = material.bumpMap;
  30924. uniforms.normalMap.value = material.normalMap;
  30925. uniforms.displacementMap.value = material.displacementMap;
  30926. uniforms.displacementScale.value = material.displacementScale;
  30927. uniforms.displacementBias.value = material.displacementBias;
  30928. if (uniforms.glossinessMap.value !== null && defines.USE_GLOSSINESSMAP === undefined) {
  30929. defines.USE_GLOSSINESSMAP = ''; // set USE_ROUGHNESSMAP to enable vUv
  30930. defines.USE_ROUGHNESSMAP = '';
  30931. }
  30932. if (uniforms.glossinessMap.value === null && defines.USE_GLOSSINESSMAP !== undefined) {
  30933. delete defines.USE_GLOSSINESSMAP;
  30934. delete defines.USE_ROUGHNESSMAP;
  30935. }
  30936. }
  30937. };
  30938. }
  30939. /*********************************/
  30940. /********** INTERPOLATION ********/
  30941. /*********************************/
  30942. // Spline Interpolation
  30943. // Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#appendix-c-spline-interpolation
  30944. function GLTFCubicSplineInterpolant(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  30945. _threeModule.Interpolant.call(this, parameterPositions, sampleValues, sampleSize, resultBuffer);
  30946. }
  30947. GLTFCubicSplineInterpolant.prototype = Object.create(_threeModule.Interpolant.prototype);
  30948. GLTFCubicSplineInterpolant.prototype.constructor = GLTFCubicSplineInterpolant;
  30949. GLTFCubicSplineInterpolant.prototype.copySampleValue_ = function (index) {
  30950. // Copies a sample value to the result buffer. See description of glTF
  30951. // CUBICSPLINE values layout in interpolate_() function below.
  30952. var result = this.resultBuffer,
  30953. values = this.sampleValues,
  30954. valueSize = this.valueSize,
  30955. offset = index * valueSize * 3 + valueSize;
  30956. for (var i = 0; i !== valueSize; i++) {
  30957. result[i] = values[offset + i];
  30958. }
  30959. return result;
  30960. };
  30961. GLTFCubicSplineInterpolant.prototype.beforeStart_ = GLTFCubicSplineInterpolant.prototype.copySampleValue_;
  30962. GLTFCubicSplineInterpolant.prototype.afterEnd_ = GLTFCubicSplineInterpolant.prototype.copySampleValue_;
  30963. GLTFCubicSplineInterpolant.prototype.interpolate_ = function (i1, t0, t, t1) {
  30964. var result = this.resultBuffer;
  30965. var values = this.sampleValues;
  30966. var stride = this.valueSize;
  30967. var stride2 = stride * 2;
  30968. var stride3 = stride * 3;
  30969. var td = t1 - t0;
  30970. var p = (t - t0) / td;
  30971. var pp = p * p;
  30972. var ppp = pp * p;
  30973. var offset1 = i1 * stride3;
  30974. var offset0 = offset1 - stride3;
  30975. var s2 = -2 * ppp + 3 * pp;
  30976. var s3 = ppp - pp;
  30977. var s0 = 1 - s2;
  30978. var s1 = s3 - pp + p; // Layout of keyframe output values for CUBICSPLINE animations:
  30979. // [ inTangent_1, splineVertex_1, outTangent_1, inTangent_2, splineVertex_2, ... ]
  30980. for (var i = 0; i !== stride; i++) {
  30981. var p0 = values[offset0 + i + stride]; // splineVertex_k
  30982. var m0 = values[offset0 + i + stride2] * td; // outTangent_k * (t_k+1 - t_k)
  30983. var p1 = values[offset1 + i + stride]; // splineVertex_k+1
  30984. var m1 = values[offset1 + i] * td; // inTangent_k+1 * (t_k+1 - t_k)
  30985. result[i] = s0 * p0 + s1 * m0 + s2 * p1 + s3 * m1;
  30986. }
  30987. return result;
  30988. };
  30989. /*********************************/
  30990. /********** INTERNALS ************/
  30991. /*********************************/
  30992. /* CONSTANTS */
  30993. var WEBGL_CONSTANTS = {
  30994. FLOAT: 5126,
  30995. //FLOAT_MAT2: 35674,
  30996. FLOAT_MAT3: 35675,
  30997. FLOAT_MAT4: 35676,
  30998. FLOAT_VEC2: 35664,
  30999. FLOAT_VEC3: 35665,
  31000. FLOAT_VEC4: 35666,
  31001. LINEAR: 9729,
  31002. REPEAT: 10497,
  31003. SAMPLER_2D: 35678,
  31004. POINTS: 0,
  31005. LINES: 1,
  31006. LINE_LOOP: 2,
  31007. LINE_STRIP: 3,
  31008. TRIANGLES: 4,
  31009. TRIANGLE_STRIP: 5,
  31010. TRIANGLE_FAN: 6,
  31011. UNSIGNED_BYTE: 5121,
  31012. UNSIGNED_SHORT: 5123
  31013. };
  31014. var WEBGL_COMPONENT_TYPES = {
  31015. 5120: Int8Array,
  31016. 5121: Uint8Array,
  31017. 5122: Int16Array,
  31018. 5123: Uint16Array,
  31019. 5125: Uint32Array,
  31020. 5126: Float32Array
  31021. };
  31022. var WEBGL_FILTERS = {
  31023. 9728: _threeModule.NearestFilter,
  31024. 9729: _threeModule.LinearFilter,
  31025. 9984: _threeModule.NearestMipmapNearestFilter,
  31026. 9985: _threeModule.LinearMipmapNearestFilter,
  31027. 9986: _threeModule.NearestMipmapLinearFilter,
  31028. 9987: _threeModule.LinearMipmapLinearFilter
  31029. };
  31030. var WEBGL_WRAPPINGS = {
  31031. 33071: _threeModule.ClampToEdgeWrapping,
  31032. 33648: _threeModule.MirroredRepeatWrapping,
  31033. 10497: _threeModule.RepeatWrapping
  31034. };
  31035. var WEBGL_TYPE_SIZES = {
  31036. 'SCALAR': 1,
  31037. 'VEC2': 2,
  31038. 'VEC3': 3,
  31039. 'VEC4': 4,
  31040. 'MAT2': 4,
  31041. 'MAT3': 9,
  31042. 'MAT4': 16
  31043. };
  31044. var ATTRIBUTES = {
  31045. POSITION: 'position',
  31046. NORMAL: 'normal',
  31047. TANGENT: 'tangent',
  31048. TEXCOORD_0: 'uv',
  31049. TEXCOORD_1: 'uv2',
  31050. COLOR_0: 'color',
  31051. WEIGHTS_0: 'skinWeight',
  31052. JOINTS_0: 'skinIndex'
  31053. };
  31054. var PATH_PROPERTIES = {
  31055. scale: 'scale',
  31056. translation: 'position',
  31057. rotation: 'quaternion',
  31058. weights: 'morphTargetInfluences'
  31059. };
  31060. var INTERPOLATION = {
  31061. CUBICSPLINE: undefined,
  31062. // We use a custom interpolant (GLTFCubicSplineInterpolation) for CUBICSPLINE tracks. Each
  31063. // keyframe track will be initialized with a default interpolation type, then modified.
  31064. LINEAR: _threeModule.InterpolateLinear,
  31065. STEP: _threeModule.InterpolateDiscrete
  31066. };
  31067. var ALPHA_MODES = {
  31068. OPAQUE: 'OPAQUE',
  31069. MASK: 'MASK',
  31070. BLEND: 'BLEND'
  31071. };
  31072. var MIME_TYPE_FORMATS = {
  31073. 'image/png': _threeModule.RGBAFormat,
  31074. 'image/jpeg': _threeModule.RGBFormat
  31075. };
  31076. /* UTILITY FUNCTIONS */
  31077. function resolveURL(url, path) {
  31078. // Invalid URL
  31079. if (typeof url !== 'string' || url === '') return ''; // Host Relative URL
  31080. if (/^https?:\/\//i.test(path) && /^\//.test(url)) {
  31081. path = path.replace(/(^https?:\/\/[^\/]+).*/i, '$1');
  31082. } // Absolute URL http://,https://,//
  31083. if (/^(https?:)?\/\//i.test(url)) return url; // Data URI
  31084. if (/^data:.*,.*$/i.test(url)) return url; // Blob URL
  31085. if (/^blob:.*$/i.test(url)) return url; // Relative URL
  31086. return path + url;
  31087. }
  31088. var defaultMaterial;
  31089. /**
  31090. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#default-material
  31091. */
  31092. function createDefaultMaterial() {
  31093. defaultMaterial = defaultMaterial || new _threeModule.MeshStandardMaterial({
  31094. color: 0xFFFFFF,
  31095. emissive: 0x000000,
  31096. metalness: 1,
  31097. roughness: 1,
  31098. transparent: false,
  31099. depthTest: true,
  31100. side: _threeModule.FrontSide
  31101. });
  31102. return defaultMaterial;
  31103. }
  31104. function addUnknownExtensionsToUserData(knownExtensions, object, objectDef) {
  31105. // Add unknown glTF extensions to an object's userData.
  31106. for (var name in objectDef.extensions) {
  31107. if (knownExtensions[name] === undefined) {
  31108. object.userData.gltfExtensions = object.userData.gltfExtensions || {};
  31109. object.userData.gltfExtensions[name] = objectDef.extensions[name];
  31110. }
  31111. }
  31112. }
  31113. /**
  31114. * @param {Object3D|Material|BufferGeometry} object
  31115. * @param {GLTF.definition} gltfDef
  31116. */
  31117. function assignExtrasToUserData(object, gltfDef) {
  31118. if (gltfDef.extras !== undefined) {
  31119. if (typeof gltfDef.extras === 'object') {
  31120. Object.assign(object.userData, gltfDef.extras);
  31121. } else {
  31122. console.warn('THREE.GLTFLoader: Ignoring primitive type .extras, ' + gltfDef.extras);
  31123. }
  31124. }
  31125. }
  31126. /**
  31127. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#morph-targets
  31128. *
  31129. * @param {BufferGeometry} geometry
  31130. * @param {Array<GLTF.Target>} targets
  31131. * @param {GLTFParser} parser
  31132. * @return {Promise<BufferGeometry>}
  31133. */
  31134. function addMorphTargets(geometry, targets, parser) {
  31135. var hasMorphPosition = false;
  31136. var hasMorphNormal = false;
  31137. for (var i = 0, il = targets.length; i < il; i++) {
  31138. var target = targets[i];
  31139. if (target.POSITION !== undefined) hasMorphPosition = true;
  31140. if (target.NORMAL !== undefined) hasMorphNormal = true;
  31141. if (hasMorphPosition && hasMorphNormal) break;
  31142. }
  31143. if (!hasMorphPosition && !hasMorphNormal) return Promise.resolve(geometry);
  31144. var pendingPositionAccessors = [];
  31145. var pendingNormalAccessors = [];
  31146. for (var i = 0, il = targets.length; i < il; i++) {
  31147. var target = targets[i];
  31148. if (hasMorphPosition) {
  31149. var pendingAccessor = target.POSITION !== undefined ? parser.getDependency('accessor', target.POSITION) : geometry.attributes.position;
  31150. pendingPositionAccessors.push(pendingAccessor);
  31151. }
  31152. if (hasMorphNormal) {
  31153. var pendingAccessor = target.NORMAL !== undefined ? parser.getDependency('accessor', target.NORMAL) : geometry.attributes.normal;
  31154. pendingNormalAccessors.push(pendingAccessor);
  31155. }
  31156. }
  31157. return Promise.all([Promise.all(pendingPositionAccessors), Promise.all(pendingNormalAccessors)]).then(function (accessors) {
  31158. var morphPositions = accessors[0];
  31159. var morphNormals = accessors[1]; // Clone morph target accessors before modifying them.
  31160. for (var i = 0, il = morphPositions.length; i < il; i++) {
  31161. if (geometry.attributes.position === morphPositions[i]) continue;
  31162. morphPositions[i] = cloneBufferAttribute(morphPositions[i]);
  31163. }
  31164. for (var i = 0, il = morphNormals.length; i < il; i++) {
  31165. if (geometry.attributes.normal === morphNormals[i]) continue;
  31166. morphNormals[i] = cloneBufferAttribute(morphNormals[i]);
  31167. }
  31168. for (var i = 0, il = targets.length; i < il; i++) {
  31169. var target = targets[i];
  31170. var attributeName = 'morphTarget' + i;
  31171. if (hasMorphPosition) {
  31172. // Three.js morph position is absolute value. The formula is
  31173. // basePosition
  31174. // + weight0 * ( morphPosition0 - basePosition )
  31175. // + weight1 * ( morphPosition1 - basePosition )
  31176. // ...
  31177. // while the glTF one is relative
  31178. // basePosition
  31179. // + weight0 * glTFmorphPosition0
  31180. // + weight1 * glTFmorphPosition1
  31181. // ...
  31182. // then we need to convert from relative to absolute here.
  31183. if (target.POSITION !== undefined) {
  31184. var positionAttribute = morphPositions[i];
  31185. positionAttribute.name = attributeName;
  31186. var position = geometry.attributes.position;
  31187. for (var j = 0, jl = positionAttribute.count; j < jl; j++) {
  31188. positionAttribute.setXYZ(j, positionAttribute.getX(j) + position.getX(j), positionAttribute.getY(j) + position.getY(j), positionAttribute.getZ(j) + position.getZ(j));
  31189. }
  31190. }
  31191. }
  31192. if (hasMorphNormal) {
  31193. // see target.POSITION's comment
  31194. if (target.NORMAL !== undefined) {
  31195. var normalAttribute = morphNormals[i];
  31196. normalAttribute.name = attributeName;
  31197. var normal = geometry.attributes.normal;
  31198. for (var j = 0, jl = normalAttribute.count; j < jl; j++) {
  31199. normalAttribute.setXYZ(j, normalAttribute.getX(j) + normal.getX(j), normalAttribute.getY(j) + normal.getY(j), normalAttribute.getZ(j) + normal.getZ(j));
  31200. }
  31201. }
  31202. }
  31203. }
  31204. if (hasMorphPosition) geometry.morphAttributes.position = morphPositions;
  31205. if (hasMorphNormal) geometry.morphAttributes.normal = morphNormals;
  31206. return geometry;
  31207. });
  31208. }
  31209. /**
  31210. * @param {Mesh} mesh
  31211. * @param {GLTF.Mesh} meshDef
  31212. */
  31213. function updateMorphTargets(mesh, meshDef) {
  31214. mesh.updateMorphTargets();
  31215. if (meshDef.weights !== undefined) {
  31216. for (var i = 0, il = meshDef.weights.length; i < il; i++) {
  31217. mesh.morphTargetInfluences[i] = meshDef.weights[i];
  31218. }
  31219. } // .extras has user-defined data, so check that .extras.targetNames is an array.
  31220. if (meshDef.extras && Array.isArray(meshDef.extras.targetNames)) {
  31221. var targetNames = meshDef.extras.targetNames;
  31222. if (mesh.morphTargetInfluences.length === targetNames.length) {
  31223. mesh.morphTargetDictionary = {};
  31224. for (var i = 0, il = targetNames.length; i < il; i++) {
  31225. mesh.morphTargetDictionary[targetNames[i]] = i;
  31226. }
  31227. } else {
  31228. console.warn('THREE.GLTFLoader: Invalid extras.targetNames length. Ignoring names.');
  31229. }
  31230. }
  31231. }
  31232. function createPrimitiveKey(primitiveDef) {
  31233. var dracoExtension = primitiveDef.extensions && primitiveDef.extensions[EXTENSIONS.KHR_DRACO_MESH_COMPRESSION];
  31234. var geometryKey;
  31235. if (dracoExtension) {
  31236. geometryKey = 'draco:' + dracoExtension.bufferView + ':' + dracoExtension.indices + ':' + createAttributesKey(dracoExtension.attributes);
  31237. } else {
  31238. geometryKey = primitiveDef.indices + ':' + createAttributesKey(primitiveDef.attributes) + ':' + primitiveDef.mode;
  31239. }
  31240. return geometryKey;
  31241. }
  31242. function createAttributesKey(attributes) {
  31243. var attributesKey = '';
  31244. var keys = Object.keys(attributes).sort();
  31245. for (var i = 0, il = keys.length; i < il; i++) {
  31246. attributesKey += keys[i] + ':' + attributes[keys[i]] + ';';
  31247. }
  31248. return attributesKey;
  31249. }
  31250. function cloneBufferAttribute(attribute) {
  31251. if (attribute.isInterleavedBufferAttribute) {
  31252. var count = attribute.count;
  31253. var itemSize = attribute.itemSize;
  31254. var array = attribute.array.slice(0, count * itemSize);
  31255. for (var i = 0, j = 0; i < count; ++i) {
  31256. array[j++] = attribute.getX(i);
  31257. if (itemSize >= 2) array[j++] = attribute.getY(i);
  31258. if (itemSize >= 3) array[j++] = attribute.getZ(i);
  31259. if (itemSize >= 4) array[j++] = attribute.getW(i);
  31260. }
  31261. return new _threeModule.BufferAttribute(array, itemSize, attribute.normalized);
  31262. }
  31263. return attribute.clone();
  31264. }
  31265. /* GLTF PARSER */
  31266. function GLTFParser(json, extensions, options) {
  31267. this.json = json || {};
  31268. this.extensions = extensions || {};
  31269. this.options = options || {}; // loader object cache
  31270. this.cache = new GLTFRegistry(); // BufferGeometry caching
  31271. this.primitiveCache = {};
  31272. this.textureLoader = new _threeModule.TextureLoader(this.options.manager);
  31273. this.textureLoader.setCrossOrigin(this.options.crossOrigin);
  31274. this.fileLoader = new _threeModule.FileLoader(this.options.manager);
  31275. this.fileLoader.setResponseType('arraybuffer');
  31276. if (this.options.crossOrigin === 'use-credentials') {
  31277. this.fileLoader.setWithCredentials(true);
  31278. }
  31279. }
  31280. GLTFParser.prototype.parse = function (onLoad, onError) {
  31281. var parser = this;
  31282. var json = this.json;
  31283. var extensions = this.extensions; // Clear the loader cache
  31284. this.cache.removeAll(); // Mark the special nodes/meshes in json for efficient parse
  31285. this.markDefs();
  31286. Promise.all([this.getDependencies('scene'), this.getDependencies('animation'), this.getDependencies('camera')]).then(function (dependencies) {
  31287. var result = {
  31288. scene: dependencies[0][json.scene || 0],
  31289. scenes: dependencies[0],
  31290. animations: dependencies[1],
  31291. cameras: dependencies[2],
  31292. asset: json.asset,
  31293. parser: parser,
  31294. userData: {}
  31295. };
  31296. addUnknownExtensionsToUserData(extensions, result, json);
  31297. assignExtrasToUserData(result, json);
  31298. onLoad(result);
  31299. }).catch(onError);
  31300. };
  31301. /**
  31302. * Marks the special nodes/meshes in json for efficient parse.
  31303. */
  31304. GLTFParser.prototype.markDefs = function () {
  31305. var nodeDefs = this.json.nodes || [];
  31306. var skinDefs = this.json.skins || [];
  31307. var meshDefs = this.json.meshes || [];
  31308. var meshReferences = {};
  31309. var meshUses = {}; // Nothing in the node definition indicates whether it is a Bone or an
  31310. // Object3D. Use the skins' joint references to mark bones.
  31311. for (var skinIndex = 0, skinLength = skinDefs.length; skinIndex < skinLength; skinIndex++) {
  31312. var joints = skinDefs[skinIndex].joints;
  31313. for (var i = 0, il = joints.length; i < il; i++) {
  31314. nodeDefs[joints[i]].isBone = true;
  31315. }
  31316. } // Meshes can (and should) be reused by multiple nodes in a glTF asset. To
  31317. // avoid having more than one Mesh with the same name, count
  31318. // references and rename instances below.
  31319. //
  31320. // Example: CesiumMilkTruck sample model reuses "Wheel" meshes.
  31321. for (var nodeIndex = 0, nodeLength = nodeDefs.length; nodeIndex < nodeLength; nodeIndex++) {
  31322. var nodeDef = nodeDefs[nodeIndex];
  31323. if (nodeDef.mesh !== undefined) {
  31324. if (meshReferences[nodeDef.mesh] === undefined) {
  31325. meshReferences[nodeDef.mesh] = meshUses[nodeDef.mesh] = 0;
  31326. }
  31327. meshReferences[nodeDef.mesh]++; // Nothing in the mesh definition indicates whether it is
  31328. // a SkinnedMesh or Mesh. Use the node's mesh reference
  31329. // to mark SkinnedMesh if node has skin.
  31330. if (nodeDef.skin !== undefined) {
  31331. meshDefs[nodeDef.mesh].isSkinnedMesh = true;
  31332. }
  31333. }
  31334. }
  31335. this.json.meshReferences = meshReferences;
  31336. this.json.meshUses = meshUses;
  31337. };
  31338. /**
  31339. * Requests the specified dependency asynchronously, with caching.
  31340. * @param {string} type
  31341. * @param {number} index
  31342. * @return {Promise<Object3D|Material|THREE.Texture|AnimationClip|ArrayBuffer|Object>}
  31343. */
  31344. GLTFParser.prototype.getDependency = function (type, index) {
  31345. var cacheKey = type + ':' + index;
  31346. var dependency = this.cache.get(cacheKey);
  31347. if (!dependency) {
  31348. switch (type) {
  31349. case 'scene':
  31350. dependency = this.loadScene(index);
  31351. break;
  31352. case 'node':
  31353. dependency = this.loadNode(index);
  31354. break;
  31355. case 'mesh':
  31356. dependency = this.loadMesh(index);
  31357. break;
  31358. case 'accessor':
  31359. dependency = this.loadAccessor(index);
  31360. break;
  31361. case 'bufferView':
  31362. dependency = this.loadBufferView(index);
  31363. break;
  31364. case 'buffer':
  31365. dependency = this.loadBuffer(index);
  31366. break;
  31367. case 'material':
  31368. dependency = this.loadMaterial(index);
  31369. break;
  31370. case 'texture':
  31371. dependency = this.loadTexture(index);
  31372. break;
  31373. case 'skin':
  31374. dependency = this.loadSkin(index);
  31375. break;
  31376. case 'animation':
  31377. dependency = this.loadAnimation(index);
  31378. break;
  31379. case 'camera':
  31380. dependency = this.loadCamera(index);
  31381. break;
  31382. case 'light':
  31383. dependency = this.extensions[EXTENSIONS.KHR_LIGHTS_PUNCTUAL].loadLight(index);
  31384. break;
  31385. default:
  31386. throw new Error('Unknown type: ' + type);
  31387. }
  31388. this.cache.add(cacheKey, dependency);
  31389. }
  31390. return dependency;
  31391. };
  31392. /**
  31393. * Requests all dependencies of the specified type asynchronously, with caching.
  31394. * @param {string} type
  31395. * @return {Promise<Array<Object>>}
  31396. */
  31397. GLTFParser.prototype.getDependencies = function (type) {
  31398. var dependencies = this.cache.get(type);
  31399. if (!dependencies) {
  31400. var parser = this;
  31401. var defs = this.json[type + (type === 'mesh' ? 'es' : 's')] || [];
  31402. dependencies = Promise.all(defs.map(function (def, index) {
  31403. return parser.getDependency(type, index);
  31404. }));
  31405. this.cache.add(type, dependencies);
  31406. }
  31407. return dependencies;
  31408. };
  31409. /**
  31410. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#buffers-and-buffer-views
  31411. * @param {number} bufferIndex
  31412. * @return {Promise<ArrayBuffer>}
  31413. */
  31414. GLTFParser.prototype.loadBuffer = function (bufferIndex) {
  31415. var bufferDef = this.json.buffers[bufferIndex];
  31416. var loader = this.fileLoader;
  31417. if (bufferDef.type && bufferDef.type !== 'arraybuffer') {
  31418. throw new Error('THREE.GLTFLoader: ' + bufferDef.type + ' buffer type is not supported.');
  31419. } // If present, GLB container is required to be the first buffer.
  31420. if (bufferDef.uri === undefined && bufferIndex === 0) {
  31421. return Promise.resolve(this.extensions[EXTENSIONS.KHR_BINARY_GLTF].body);
  31422. }
  31423. var options = this.options;
  31424. return new Promise(function (resolve, reject) {
  31425. loader.load(resolveURL(bufferDef.uri, options.path), resolve, undefined, function () {
  31426. reject(new Error('THREE.GLTFLoader: Failed to load buffer "' + bufferDef.uri + '".'));
  31427. });
  31428. });
  31429. };
  31430. /**
  31431. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#buffers-and-buffer-views
  31432. * @param {number} bufferViewIndex
  31433. * @return {Promise<ArrayBuffer>}
  31434. */
  31435. GLTFParser.prototype.loadBufferView = function (bufferViewIndex) {
  31436. var bufferViewDef = this.json.bufferViews[bufferViewIndex];
  31437. return this.getDependency('buffer', bufferViewDef.buffer).then(function (buffer) {
  31438. var byteLength = bufferViewDef.byteLength || 0;
  31439. var byteOffset = bufferViewDef.byteOffset || 0;
  31440. return buffer.slice(byteOffset, byteOffset + byteLength);
  31441. });
  31442. };
  31443. /**
  31444. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#accessors
  31445. * @param {number} accessorIndex
  31446. * @return {Promise<BufferAttribute|InterleavedBufferAttribute>}
  31447. */
  31448. GLTFParser.prototype.loadAccessor = function (accessorIndex) {
  31449. var parser = this;
  31450. var json = this.json;
  31451. var accessorDef = this.json.accessors[accessorIndex];
  31452. if (accessorDef.bufferView === undefined && accessorDef.sparse === undefined) {
  31453. // Ignore empty accessors, which may be used to declare runtime
  31454. // information about attributes coming from another source (e.g. Draco
  31455. // compression extension).
  31456. return Promise.resolve(null);
  31457. }
  31458. var pendingBufferViews = [];
  31459. if (accessorDef.bufferView !== undefined) {
  31460. pendingBufferViews.push(this.getDependency('bufferView', accessorDef.bufferView));
  31461. } else {
  31462. pendingBufferViews.push(null);
  31463. }
  31464. if (accessorDef.sparse !== undefined) {
  31465. pendingBufferViews.push(this.getDependency('bufferView', accessorDef.sparse.indices.bufferView));
  31466. pendingBufferViews.push(this.getDependency('bufferView', accessorDef.sparse.values.bufferView));
  31467. }
  31468. return Promise.all(pendingBufferViews).then(function (bufferViews) {
  31469. var bufferView = bufferViews[0];
  31470. var itemSize = WEBGL_TYPE_SIZES[accessorDef.type];
  31471. var TypedArray = WEBGL_COMPONENT_TYPES[accessorDef.componentType]; // For VEC3: itemSize is 3, elementBytes is 4, itemBytes is 12.
  31472. var elementBytes = TypedArray.BYTES_PER_ELEMENT;
  31473. var itemBytes = elementBytes * itemSize;
  31474. var byteOffset = accessorDef.byteOffset || 0;
  31475. var byteStride = accessorDef.bufferView !== undefined ? json.bufferViews[accessorDef.bufferView].byteStride : undefined;
  31476. var normalized = accessorDef.normalized === true;
  31477. var array, bufferAttribute; // The buffer is not interleaved if the stride is the item size in bytes.
  31478. if (byteStride && byteStride !== itemBytes) {
  31479. // Each "slice" of the buffer, as defined by 'count' elements of 'byteStride' bytes, gets its own InterleavedBuffer
  31480. // This makes sure that IBA.count reflects accessor.count properly
  31481. var ibSlice = Math.floor(byteOffset / byteStride);
  31482. var ibCacheKey = 'InterleavedBuffer:' + accessorDef.bufferView + ':' + accessorDef.componentType + ':' + ibSlice + ':' + accessorDef.count;
  31483. var ib = parser.cache.get(ibCacheKey);
  31484. if (!ib) {
  31485. array = new TypedArray(bufferView, ibSlice * byteStride, accessorDef.count * byteStride / elementBytes); // Integer parameters to IB/IBA are in array elements, not bytes.
  31486. ib = new _threeModule.InterleavedBuffer(array, byteStride / elementBytes);
  31487. parser.cache.add(ibCacheKey, ib);
  31488. }
  31489. bufferAttribute = new _threeModule.InterleavedBufferAttribute(ib, itemSize, byteOffset % byteStride / elementBytes, normalized);
  31490. } else {
  31491. if (bufferView === null) {
  31492. array = new TypedArray(accessorDef.count * itemSize);
  31493. } else {
  31494. array = new TypedArray(bufferView, byteOffset, accessorDef.count * itemSize);
  31495. }
  31496. bufferAttribute = new _threeModule.BufferAttribute(array, itemSize, normalized);
  31497. } // https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#sparse-accessors
  31498. if (accessorDef.sparse !== undefined) {
  31499. var itemSizeIndices = WEBGL_TYPE_SIZES.SCALAR;
  31500. var TypedArrayIndices = WEBGL_COMPONENT_TYPES[accessorDef.sparse.indices.componentType];
  31501. var byteOffsetIndices = accessorDef.sparse.indices.byteOffset || 0;
  31502. var byteOffsetValues = accessorDef.sparse.values.byteOffset || 0;
  31503. var sparseIndices = new TypedArrayIndices(bufferViews[1], byteOffsetIndices, accessorDef.sparse.count * itemSizeIndices);
  31504. var sparseValues = new TypedArray(bufferViews[2], byteOffsetValues, accessorDef.sparse.count * itemSize);
  31505. if (bufferView !== null) {
  31506. // Avoid modifying the original ArrayBuffer, if the bufferView wasn't initialized with zeroes.
  31507. bufferAttribute = new _threeModule.BufferAttribute(bufferAttribute.array.slice(), bufferAttribute.itemSize, bufferAttribute.normalized);
  31508. }
  31509. for (var i = 0, il = sparseIndices.length; i < il; i++) {
  31510. var index = sparseIndices[i];
  31511. bufferAttribute.setX(index, sparseValues[i * itemSize]);
  31512. if (itemSize >= 2) bufferAttribute.setY(index, sparseValues[i * itemSize + 1]);
  31513. if (itemSize >= 3) bufferAttribute.setZ(index, sparseValues[i * itemSize + 2]);
  31514. if (itemSize >= 4) bufferAttribute.setW(index, sparseValues[i * itemSize + 3]);
  31515. if (itemSize >= 5) throw new Error('THREE.GLTFLoader: Unsupported itemSize in sparse BufferAttribute.');
  31516. }
  31517. }
  31518. return bufferAttribute;
  31519. });
  31520. };
  31521. /**
  31522. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#textures
  31523. * @param {number} textureIndex
  31524. * @return {Promise<THREE.Texture>}
  31525. */
  31526. GLTFParser.prototype.loadTexture = function (textureIndex) {
  31527. var parser = this;
  31528. var json = this.json;
  31529. var options = this.options;
  31530. var textureLoader = this.textureLoader;
  31531. var URL = window.URL || window.webkitURL;
  31532. var textureDef = json.textures[textureIndex];
  31533. var textureExtensions = textureDef.extensions || {};
  31534. var source;
  31535. if (textureExtensions[EXTENSIONS.MSFT_TEXTURE_DDS]) {
  31536. source = json.images[textureExtensions[EXTENSIONS.MSFT_TEXTURE_DDS].source];
  31537. } else {
  31538. source = json.images[textureDef.source];
  31539. }
  31540. var sourceURI = source.uri;
  31541. var isObjectURL = false;
  31542. if (source.bufferView !== undefined) {
  31543. // Load binary image data from bufferView, if provided.
  31544. sourceURI = parser.getDependency('bufferView', source.bufferView).then(function (bufferView) {
  31545. isObjectURL = true;
  31546. var blob = new Blob([bufferView], {
  31547. type: source.mimeType
  31548. });
  31549. sourceURI = URL.createObjectURL(blob);
  31550. return sourceURI;
  31551. });
  31552. }
  31553. return Promise.resolve(sourceURI).then(function (sourceURI) {
  31554. // Load Texture resource.
  31555. var loader = options.manager.getHandler(sourceURI);
  31556. if (!loader) {
  31557. loader = textureExtensions[EXTENSIONS.MSFT_TEXTURE_DDS] ? parser.extensions[EXTENSIONS.MSFT_TEXTURE_DDS].ddsLoader : textureLoader;
  31558. }
  31559. return new Promise(function (resolve, reject) {
  31560. loader.load(resolveURL(sourceURI, options.path), resolve, undefined, reject);
  31561. });
  31562. }).then(function (texture) {
  31563. // Clean up resources and configure Texture.
  31564. if (isObjectURL === true) {
  31565. URL.revokeObjectURL(sourceURI);
  31566. }
  31567. texture.flipY = false;
  31568. if (textureDef.name !== undefined) texture.name = textureDef.name; // Ignore unknown mime types, like DDS files.
  31569. if (source.mimeType in MIME_TYPE_FORMATS) {
  31570. texture.format = MIME_TYPE_FORMATS[source.mimeType];
  31571. }
  31572. var samplers = json.samplers || {};
  31573. var sampler = samplers[textureDef.sampler] || {};
  31574. texture.magFilter = WEBGL_FILTERS[sampler.magFilter] || _threeModule.LinearFilter;
  31575. texture.minFilter = WEBGL_FILTERS[sampler.minFilter] || _threeModule.LinearMipmapLinearFilter;
  31576. texture.wrapS = WEBGL_WRAPPINGS[sampler.wrapS] || _threeModule.RepeatWrapping;
  31577. texture.wrapT = WEBGL_WRAPPINGS[sampler.wrapT] || _threeModule.RepeatWrapping;
  31578. return texture;
  31579. });
  31580. };
  31581. /**
  31582. * Asynchronously assigns a texture to the given material parameters.
  31583. * @param {Object} materialParams
  31584. * @param {string} mapName
  31585. * @param {Object} mapDef
  31586. * @return {Promise}
  31587. */
  31588. GLTFParser.prototype.assignTexture = function (materialParams, mapName, mapDef) {
  31589. var parser = this;
  31590. return this.getDependency('texture', mapDef.index).then(function (texture) {
  31591. if (!texture.isCompressedTexture) {
  31592. switch (mapName) {
  31593. case 'aoMap':
  31594. case 'emissiveMap':
  31595. case 'metalnessMap':
  31596. case 'normalMap':
  31597. case 'roughnessMap':
  31598. texture.format = _threeModule.RGBFormat;
  31599. break;
  31600. }
  31601. }
  31602. if (parser.extensions[EXTENSIONS.KHR_TEXTURE_TRANSFORM]) {
  31603. var transform = mapDef.extensions !== undefined ? mapDef.extensions[EXTENSIONS.KHR_TEXTURE_TRANSFORM] : undefined;
  31604. if (transform) {
  31605. texture = parser.extensions[EXTENSIONS.KHR_TEXTURE_TRANSFORM].extendTexture(texture, transform);
  31606. }
  31607. }
  31608. materialParams[mapName] = texture;
  31609. });
  31610. };
  31611. /**
  31612. * Assigns final material to a Mesh, Line, or Points instance. The instance
  31613. * already has a material (generated from the glTF material options alone)
  31614. * but reuse of the same glTF material may require multiple threejs materials
  31615. * to accomodate different primitive types, defines, etc. New materials will
  31616. * be created if necessary, and reused from a cache.
  31617. * @param {Object3D} mesh Mesh, Line, or Points instance.
  31618. */
  31619. GLTFParser.prototype.assignFinalMaterial = function (mesh) {
  31620. var geometry = mesh.geometry;
  31621. var material = mesh.material;
  31622. var extensions = this.extensions;
  31623. var useVertexTangents = geometry.attributes.tangent !== undefined;
  31624. var useVertexColors = geometry.attributes.color !== undefined;
  31625. var useFlatShading = geometry.attributes.normal === undefined;
  31626. var useSkinning = mesh.isSkinnedMesh === true;
  31627. var useMorphTargets = Object.keys(geometry.morphAttributes).length > 0;
  31628. var useMorphNormals = useMorphTargets && geometry.morphAttributes.normal !== undefined;
  31629. if (mesh.isPoints) {
  31630. var cacheKey = 'PointsMaterial:' + material.uuid;
  31631. var pointsMaterial = this.cache.get(cacheKey);
  31632. if (!pointsMaterial) {
  31633. pointsMaterial = new _threeModule.PointsMaterial();
  31634. _threeModule.Material.prototype.copy.call(pointsMaterial, material);
  31635. pointsMaterial.color.copy(material.color);
  31636. pointsMaterial.map = material.map;
  31637. pointsMaterial.sizeAttenuation = false; // glTF spec says points should be 1px
  31638. this.cache.add(cacheKey, pointsMaterial);
  31639. }
  31640. material = pointsMaterial;
  31641. } else if (mesh.isLine) {
  31642. var cacheKey = 'LineBasicMaterial:' + material.uuid;
  31643. var lineMaterial = this.cache.get(cacheKey);
  31644. if (!lineMaterial) {
  31645. lineMaterial = new _threeModule.LineBasicMaterial();
  31646. _threeModule.Material.prototype.copy.call(lineMaterial, material);
  31647. lineMaterial.color.copy(material.color);
  31648. this.cache.add(cacheKey, lineMaterial);
  31649. }
  31650. material = lineMaterial;
  31651. } // Clone the material if it will be modified
  31652. if (useVertexTangents || useVertexColors || useFlatShading || useSkinning || useMorphTargets) {
  31653. var cacheKey = 'ClonedMaterial:' + material.uuid + ':';
  31654. if (material.isGLTFSpecularGlossinessMaterial) cacheKey += 'specular-glossiness:';
  31655. if (useSkinning) cacheKey += 'skinning:';
  31656. if (useVertexTangents) cacheKey += 'vertex-tangents:';
  31657. if (useVertexColors) cacheKey += 'vertex-colors:';
  31658. if (useFlatShading) cacheKey += 'flat-shading:';
  31659. if (useMorphTargets) cacheKey += 'morph-targets:';
  31660. if (useMorphNormals) cacheKey += 'morph-normals:';
  31661. var cachedMaterial = this.cache.get(cacheKey);
  31662. if (!cachedMaterial) {
  31663. cachedMaterial = material.isGLTFSpecularGlossinessMaterial ? extensions[EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS].cloneMaterial(material) : material.clone();
  31664. if (useSkinning) cachedMaterial.skinning = true;
  31665. if (useVertexTangents) cachedMaterial.vertexTangents = true;
  31666. if (useVertexColors) cachedMaterial.vertexColors = _threeModule.VertexColors;
  31667. if (useFlatShading) cachedMaterial.flatShading = true;
  31668. if (useMorphTargets) cachedMaterial.morphTargets = true;
  31669. if (useMorphNormals) cachedMaterial.morphNormals = true;
  31670. this.cache.add(cacheKey, cachedMaterial);
  31671. }
  31672. material = cachedMaterial;
  31673. } // workarounds for mesh and geometry
  31674. if (material.aoMap && geometry.attributes.uv2 === undefined && geometry.attributes.uv !== undefined) {
  31675. console.log('THREE.GLTFLoader: Duplicating UVs to support aoMap.');
  31676. geometry.addAttribute('uv2', new _threeModule.BufferAttribute(geometry.attributes.uv.array, 2));
  31677. }
  31678. if (material.isGLTFSpecularGlossinessMaterial) {
  31679. // for GLTFSpecularGlossinessMaterial(ShaderMaterial) uniforms runtime update
  31680. mesh.onBeforeRender = extensions[EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS].refreshUniforms;
  31681. }
  31682. mesh.material = material;
  31683. };
  31684. /**
  31685. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#materials
  31686. * @param {number} materialIndex
  31687. * @return {Promise<Material>}
  31688. */
  31689. GLTFParser.prototype.loadMaterial = function (materialIndex) {
  31690. var parser = this;
  31691. var json = this.json;
  31692. var extensions = this.extensions;
  31693. var materialDef = json.materials[materialIndex];
  31694. var materialType;
  31695. var materialParams = {};
  31696. var materialExtensions = materialDef.extensions || {};
  31697. var pending = [];
  31698. if (materialExtensions[EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS]) {
  31699. var sgExtension = extensions[EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS];
  31700. materialType = sgExtension.getMaterialType();
  31701. pending.push(sgExtension.extendParams(materialParams, materialDef, parser));
  31702. } else if (materialExtensions[EXTENSIONS.KHR_MATERIALS_UNLIT]) {
  31703. var kmuExtension = extensions[EXTENSIONS.KHR_MATERIALS_UNLIT];
  31704. materialType = kmuExtension.getMaterialType();
  31705. pending.push(kmuExtension.extendParams(materialParams, materialDef, parser));
  31706. } else {
  31707. // Specification:
  31708. // https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#metallic-roughness-material
  31709. materialType = _threeModule.MeshStandardMaterial;
  31710. var metallicRoughness = materialDef.pbrMetallicRoughness || {};
  31711. materialParams.color = new _threeModule.Color(1.0, 1.0, 1.0);
  31712. materialParams.opacity = 1.0;
  31713. if (Array.isArray(metallicRoughness.baseColorFactor)) {
  31714. var array = metallicRoughness.baseColorFactor;
  31715. materialParams.color.fromArray(array);
  31716. materialParams.opacity = array[3];
  31717. }
  31718. if (metallicRoughness.baseColorTexture !== undefined) {
  31719. pending.push(parser.assignTexture(materialParams, 'map', metallicRoughness.baseColorTexture));
  31720. }
  31721. materialParams.metalness = metallicRoughness.metallicFactor !== undefined ? metallicRoughness.metallicFactor : 1.0;
  31722. materialParams.roughness = metallicRoughness.roughnessFactor !== undefined ? metallicRoughness.roughnessFactor : 1.0;
  31723. if (metallicRoughness.metallicRoughnessTexture !== undefined) {
  31724. pending.push(parser.assignTexture(materialParams, 'metalnessMap', metallicRoughness.metallicRoughnessTexture));
  31725. pending.push(parser.assignTexture(materialParams, 'roughnessMap', metallicRoughness.metallicRoughnessTexture));
  31726. }
  31727. }
  31728. if (materialDef.doubleSided === true) {
  31729. materialParams.side = _threeModule.DoubleSide;
  31730. }
  31731. var alphaMode = materialDef.alphaMode || ALPHA_MODES.OPAQUE;
  31732. if (alphaMode === ALPHA_MODES.BLEND) {
  31733. materialParams.transparent = true;
  31734. } else {
  31735. materialParams.transparent = false;
  31736. if (alphaMode === ALPHA_MODES.MASK) {
  31737. materialParams.alphaTest = materialDef.alphaCutoff !== undefined ? materialDef.alphaCutoff : 0.5;
  31738. }
  31739. }
  31740. if (materialDef.normalTexture !== undefined && materialType !== _threeModule.MeshBasicMaterial) {
  31741. pending.push(parser.assignTexture(materialParams, 'normalMap', materialDef.normalTexture));
  31742. materialParams.normalScale = new _threeModule.Vector2(1, 1);
  31743. if (materialDef.normalTexture.scale !== undefined) {
  31744. materialParams.normalScale.set(materialDef.normalTexture.scale, materialDef.normalTexture.scale);
  31745. }
  31746. }
  31747. if (materialDef.occlusionTexture !== undefined && materialType !== _threeModule.MeshBasicMaterial) {
  31748. pending.push(parser.assignTexture(materialParams, 'aoMap', materialDef.occlusionTexture));
  31749. if (materialDef.occlusionTexture.strength !== undefined) {
  31750. materialParams.aoMapIntensity = materialDef.occlusionTexture.strength;
  31751. }
  31752. }
  31753. if (materialDef.emissiveFactor !== undefined && materialType !== _threeModule.MeshBasicMaterial) {
  31754. materialParams.emissive = new _threeModule.Color().fromArray(materialDef.emissiveFactor);
  31755. }
  31756. if (materialDef.emissiveTexture !== undefined && materialType !== _threeModule.MeshBasicMaterial) {
  31757. pending.push(parser.assignTexture(materialParams, 'emissiveMap', materialDef.emissiveTexture));
  31758. }
  31759. return Promise.all(pending).then(function () {
  31760. var material;
  31761. if (materialType === _threeModule.ShaderMaterial) {
  31762. material = extensions[EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS].createMaterial(materialParams);
  31763. } else {
  31764. material = new materialType(materialParams);
  31765. }
  31766. if (materialDef.name !== undefined) material.name = materialDef.name; // baseColorTexture, emissiveTexture, and specularGlossinessTexture use sRGB encoding.
  31767. if (material.map) material.map.encoding = _threeModule.sRGBEncoding;
  31768. if (material.emissiveMap) material.emissiveMap.encoding = _threeModule.sRGBEncoding;
  31769. if (material.specularMap) material.specularMap.encoding = _threeModule.sRGBEncoding;
  31770. assignExtrasToUserData(material, materialDef);
  31771. if (materialDef.extensions) addUnknownExtensionsToUserData(extensions, material, materialDef);
  31772. return material;
  31773. });
  31774. };
  31775. /**
  31776. * @param {BufferGeometry} geometry
  31777. * @param {GLTF.Primitive} primitiveDef
  31778. * @param {GLTFParser} parser
  31779. * @return {Promise<BufferGeometry>}
  31780. */
  31781. function addPrimitiveAttributes(geometry, primitiveDef, parser) {
  31782. var attributes = primitiveDef.attributes;
  31783. var pending = [];
  31784. function assignAttributeAccessor(accessorIndex, attributeName) {
  31785. return parser.getDependency('accessor', accessorIndex).then(function (accessor) {
  31786. geometry.addAttribute(attributeName, accessor);
  31787. });
  31788. }
  31789. for (var gltfAttributeName in attributes) {
  31790. var threeAttributeName = ATTRIBUTES[gltfAttributeName] || gltfAttributeName.toLowerCase(); // Skip attributes already provided by e.g. Draco extension.
  31791. if (threeAttributeName in geometry.attributes) continue;
  31792. pending.push(assignAttributeAccessor(attributes[gltfAttributeName], threeAttributeName));
  31793. }
  31794. if (primitiveDef.indices !== undefined && !geometry.index) {
  31795. var accessor = parser.getDependency('accessor', primitiveDef.indices).then(function (accessor) {
  31796. geometry.setIndex(accessor);
  31797. });
  31798. pending.push(accessor);
  31799. }
  31800. assignExtrasToUserData(geometry, primitiveDef);
  31801. return Promise.all(pending).then(function () {
  31802. return primitiveDef.targets !== undefined ? addMorphTargets(geometry, primitiveDef.targets, parser) : geometry;
  31803. });
  31804. }
  31805. /**
  31806. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#geometry
  31807. *
  31808. * Creates BufferGeometries from primitives.
  31809. *
  31810. * @param {Array<GLTF.Primitive>} primitives
  31811. * @return {Promise<Array<BufferGeometry>>}
  31812. */
  31813. GLTFParser.prototype.loadGeometries = function (primitives) {
  31814. var parser = this;
  31815. var extensions = this.extensions;
  31816. var cache = this.primitiveCache;
  31817. function createDracoPrimitive(primitive) {
  31818. return extensions[EXTENSIONS.KHR_DRACO_MESH_COMPRESSION].decodePrimitive(primitive, parser).then(function (geometry) {
  31819. return addPrimitiveAttributes(geometry, primitive, parser);
  31820. });
  31821. }
  31822. var pending = [];
  31823. for (var i = 0, il = primitives.length; i < il; i++) {
  31824. var primitive = primitives[i];
  31825. var cacheKey = createPrimitiveKey(primitive); // See if we've already created this geometry
  31826. var cached = cache[cacheKey];
  31827. if (cached) {
  31828. // Use the cached geometry if it exists
  31829. pending.push(cached.promise);
  31830. } else {
  31831. var geometryPromise;
  31832. if (primitive.extensions && primitive.extensions[EXTENSIONS.KHR_DRACO_MESH_COMPRESSION]) {
  31833. // Use DRACO geometry if available
  31834. geometryPromise = createDracoPrimitive(primitive);
  31835. } else {
  31836. // Otherwise create a new geometry
  31837. geometryPromise = addPrimitiveAttributes(new _threeModule.BufferGeometry(), primitive, parser);
  31838. } // Cache this geometry
  31839. cache[cacheKey] = {
  31840. primitive: primitive,
  31841. promise: geometryPromise
  31842. };
  31843. pending.push(geometryPromise);
  31844. }
  31845. }
  31846. return Promise.all(pending);
  31847. };
  31848. /**
  31849. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#meshes
  31850. * @param {number} meshIndex
  31851. * @return {Promise<Group|Mesh|SkinnedMesh>}
  31852. */
  31853. GLTFParser.prototype.loadMesh = function (meshIndex) {
  31854. var parser = this;
  31855. var json = this.json;
  31856. var meshDef = json.meshes[meshIndex];
  31857. var primitives = meshDef.primitives;
  31858. var pending = [];
  31859. for (var i = 0, il = primitives.length; i < il; i++) {
  31860. var material = primitives[i].material === undefined ? createDefaultMaterial() : this.getDependency('material', primitives[i].material);
  31861. pending.push(material);
  31862. }
  31863. return Promise.all(pending).then(function (originalMaterials) {
  31864. return parser.loadGeometries(primitives).then(function (geometries) {
  31865. var meshes = [];
  31866. for (var i = 0, il = geometries.length; i < il; i++) {
  31867. var geometry = geometries[i];
  31868. var primitive = primitives[i]; // 1. create Mesh
  31869. var mesh;
  31870. var material = originalMaterials[i];
  31871. if (primitive.mode === WEBGL_CONSTANTS.TRIANGLES || primitive.mode === WEBGL_CONSTANTS.TRIANGLE_STRIP || primitive.mode === WEBGL_CONSTANTS.TRIANGLE_FAN || primitive.mode === undefined) {
  31872. // .isSkinnedMesh isn't in glTF spec. See .markDefs()
  31873. mesh = meshDef.isSkinnedMesh === true ? new _threeModule.SkinnedMesh(geometry, material) : new _threeModule.Mesh(geometry, material);
  31874. if (mesh.isSkinnedMesh === true && !mesh.geometry.attributes.skinWeight.normalized) {
  31875. // we normalize floating point skin weight array to fix malformed assets (see #15319)
  31876. // it's important to skip this for non-float32 data since normalizeSkinWeights assumes non-normalized inputs
  31877. mesh.normalizeSkinWeights();
  31878. }
  31879. if (primitive.mode === WEBGL_CONSTANTS.TRIANGLE_STRIP) {
  31880. mesh.drawMode = _threeModule.TriangleStripDrawMode;
  31881. } else if (primitive.mode === WEBGL_CONSTANTS.TRIANGLE_FAN) {
  31882. mesh.drawMode = _threeModule.TriangleFanDrawMode;
  31883. }
  31884. } else if (primitive.mode === WEBGL_CONSTANTS.LINES) {
  31885. mesh = new _threeModule.LineSegments(geometry, material);
  31886. } else if (primitive.mode === WEBGL_CONSTANTS.LINE_STRIP) {
  31887. mesh = new _threeModule.Line(geometry, material);
  31888. } else if (primitive.mode === WEBGL_CONSTANTS.LINE_LOOP) {
  31889. mesh = new _threeModule.LineLoop(geometry, material);
  31890. } else if (primitive.mode === WEBGL_CONSTANTS.POINTS) {
  31891. mesh = new _threeModule.Points(geometry, material);
  31892. } else {
  31893. throw new Error('THREE.GLTFLoader: Primitive mode unsupported: ' + primitive.mode);
  31894. }
  31895. if (Object.keys(mesh.geometry.morphAttributes).length > 0) {
  31896. updateMorphTargets(mesh, meshDef);
  31897. }
  31898. mesh.name = meshDef.name || 'mesh_' + meshIndex;
  31899. if (geometries.length > 1) mesh.name += '_' + i;
  31900. assignExtrasToUserData(mesh, meshDef);
  31901. parser.assignFinalMaterial(mesh);
  31902. meshes.push(mesh);
  31903. }
  31904. if (meshes.length === 1) {
  31905. return meshes[0];
  31906. }
  31907. var group = new _threeModule.Group();
  31908. for (var i = 0, il = meshes.length; i < il; i++) {
  31909. group.add(meshes[i]);
  31910. }
  31911. return group;
  31912. });
  31913. });
  31914. };
  31915. /**
  31916. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#cameras
  31917. * @param {number} cameraIndex
  31918. * @return {Promise<THREE.Camera>}
  31919. */
  31920. GLTFParser.prototype.loadCamera = function (cameraIndex) {
  31921. var camera;
  31922. var cameraDef = this.json.cameras[cameraIndex];
  31923. var params = cameraDef[cameraDef.type];
  31924. if (!params) {
  31925. console.warn('THREE.GLTFLoader: Missing camera parameters.');
  31926. return;
  31927. }
  31928. if (cameraDef.type === 'perspective') {
  31929. camera = new _threeModule.PerspectiveCamera(_threeModule.Math.radToDeg(params.yfov), params.aspectRatio || 1, params.znear || 1, params.zfar || 2e6);
  31930. } else if (cameraDef.type === 'orthographic') {
  31931. camera = new _threeModule.OrthographicCamera(params.xmag / -2, params.xmag / 2, params.ymag / 2, params.ymag / -2, params.znear, params.zfar);
  31932. }
  31933. if (cameraDef.name !== undefined) camera.name = cameraDef.name;
  31934. assignExtrasToUserData(camera, cameraDef);
  31935. return Promise.resolve(camera);
  31936. };
  31937. /**
  31938. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins
  31939. * @param {number} skinIndex
  31940. * @return {Promise<Object>}
  31941. */
  31942. GLTFParser.prototype.loadSkin = function (skinIndex) {
  31943. var skinDef = this.json.skins[skinIndex];
  31944. var skinEntry = {
  31945. joints: skinDef.joints
  31946. };
  31947. if (skinDef.inverseBindMatrices === undefined) {
  31948. return Promise.resolve(skinEntry);
  31949. }
  31950. return this.getDependency('accessor', skinDef.inverseBindMatrices).then(function (accessor) {
  31951. skinEntry.inverseBindMatrices = accessor;
  31952. return skinEntry;
  31953. });
  31954. };
  31955. /**
  31956. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#animations
  31957. * @param {number} animationIndex
  31958. * @return {Promise<AnimationClip>}
  31959. */
  31960. GLTFParser.prototype.loadAnimation = function (animationIndex) {
  31961. var json = this.json;
  31962. var animationDef = json.animations[animationIndex];
  31963. var pendingNodes = [];
  31964. var pendingInputAccessors = [];
  31965. var pendingOutputAccessors = [];
  31966. var pendingSamplers = [];
  31967. var pendingTargets = [];
  31968. for (var i = 0, il = animationDef.channels.length; i < il; i++) {
  31969. var channel = animationDef.channels[i];
  31970. var sampler = animationDef.samplers[channel.sampler];
  31971. var target = channel.target;
  31972. var name = target.node !== undefined ? target.node : target.id; // NOTE: target.id is deprecated.
  31973. var input = animationDef.parameters !== undefined ? animationDef.parameters[sampler.input] : sampler.input;
  31974. var output = animationDef.parameters !== undefined ? animationDef.parameters[sampler.output] : sampler.output;
  31975. pendingNodes.push(this.getDependency('node', name));
  31976. pendingInputAccessors.push(this.getDependency('accessor', input));
  31977. pendingOutputAccessors.push(this.getDependency('accessor', output));
  31978. pendingSamplers.push(sampler);
  31979. pendingTargets.push(target);
  31980. }
  31981. return Promise.all([Promise.all(pendingNodes), Promise.all(pendingInputAccessors), Promise.all(pendingOutputAccessors), Promise.all(pendingSamplers), Promise.all(pendingTargets)]).then(function (dependencies) {
  31982. var nodes = dependencies[0];
  31983. var inputAccessors = dependencies[1];
  31984. var outputAccessors = dependencies[2];
  31985. var samplers = dependencies[3];
  31986. var targets = dependencies[4];
  31987. var tracks = [];
  31988. for (var i = 0, il = nodes.length; i < il; i++) {
  31989. var node = nodes[i];
  31990. var inputAccessor = inputAccessors[i];
  31991. var outputAccessor = outputAccessors[i];
  31992. var sampler = samplers[i];
  31993. var target = targets[i];
  31994. if (node === undefined) continue;
  31995. node.updateMatrix();
  31996. node.matrixAutoUpdate = true;
  31997. var TypedKeyframeTrack;
  31998. switch (PATH_PROPERTIES[target.path]) {
  31999. case PATH_PROPERTIES.weights:
  32000. TypedKeyframeTrack = _threeModule.NumberKeyframeTrack;
  32001. break;
  32002. case PATH_PROPERTIES.rotation:
  32003. TypedKeyframeTrack = _threeModule.QuaternionKeyframeTrack;
  32004. break;
  32005. case PATH_PROPERTIES.position:
  32006. case PATH_PROPERTIES.scale:
  32007. default:
  32008. TypedKeyframeTrack = _threeModule.VectorKeyframeTrack;
  32009. break;
  32010. }
  32011. var targetName = node.name ? node.name : node.uuid;
  32012. var interpolation = sampler.interpolation !== undefined ? INTERPOLATION[sampler.interpolation] : _threeModule.InterpolateLinear;
  32013. var targetNames = [];
  32014. if (PATH_PROPERTIES[target.path] === PATH_PROPERTIES.weights) {
  32015. // Node may be a Group (glTF mesh with several primitives) or a Mesh.
  32016. node.traverse(function (object) {
  32017. if (object.isMesh === true && object.morphTargetInfluences) {
  32018. targetNames.push(object.name ? object.name : object.uuid);
  32019. }
  32020. });
  32021. } else {
  32022. targetNames.push(targetName);
  32023. }
  32024. var outputArray = outputAccessor.array;
  32025. if (outputAccessor.normalized) {
  32026. var scale;
  32027. if (outputArray.constructor === Int8Array) {
  32028. scale = 1 / 127;
  32029. } else if (outputArray.constructor === Uint8Array) {
  32030. scale = 1 / 255;
  32031. } else if (outputArray.constructor == Int16Array) {
  32032. scale = 1 / 32767;
  32033. } else if (outputArray.constructor === Uint16Array) {
  32034. scale = 1 / 65535;
  32035. } else {
  32036. throw new Error('THREE.GLTFLoader: Unsupported output accessor component type.');
  32037. }
  32038. var scaled = new Float32Array(outputArray.length);
  32039. for (var j = 0, jl = outputArray.length; j < jl; j++) {
  32040. scaled[j] = outputArray[j] * scale;
  32041. }
  32042. outputArray = scaled;
  32043. }
  32044. for (var j = 0, jl = targetNames.length; j < jl; j++) {
  32045. var track = new TypedKeyframeTrack(targetNames[j] + '.' + PATH_PROPERTIES[target.path], inputAccessor.array, outputArray, interpolation); // Override interpolation with custom factory method.
  32046. if (sampler.interpolation === 'CUBICSPLINE') {
  32047. track.createInterpolant = function InterpolantFactoryMethodGLTFCubicSpline(result) {
  32048. // A CUBICSPLINE keyframe in glTF has three output values for each input value,
  32049. // representing inTangent, splineVertex, and outTangent. As a result, track.getValueSize()
  32050. // must be divided by three to get the interpolant's sampleSize argument.
  32051. return new GLTFCubicSplineInterpolant(this.times, this.values, this.getValueSize() / 3, result);
  32052. }; // Mark as CUBICSPLINE. `track.getInterpolation()` doesn't support custom interpolants.
  32053. track.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline = true;
  32054. }
  32055. tracks.push(track);
  32056. }
  32057. }
  32058. var name = animationDef.name !== undefined ? animationDef.name : 'animation_' + animationIndex;
  32059. return new _threeModule.AnimationClip(name, undefined, tracks);
  32060. });
  32061. };
  32062. /**
  32063. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#nodes-and-hierarchy
  32064. * @param {number} nodeIndex
  32065. * @return {Promise<Object3D>}
  32066. */
  32067. GLTFParser.prototype.loadNode = function (nodeIndex) {
  32068. var json = this.json;
  32069. var extensions = this.extensions;
  32070. var parser = this;
  32071. var meshReferences = json.meshReferences;
  32072. var meshUses = json.meshUses;
  32073. var nodeDef = json.nodes[nodeIndex];
  32074. return function () {
  32075. var pending = [];
  32076. if (nodeDef.mesh !== undefined) {
  32077. pending.push(parser.getDependency('mesh', nodeDef.mesh).then(function (mesh) {
  32078. var node;
  32079. if (meshReferences[nodeDef.mesh] > 1) {
  32080. var instanceNum = meshUses[nodeDef.mesh]++;
  32081. node = mesh.clone();
  32082. node.name += '_instance_' + instanceNum; // onBeforeRender copy for Specular-Glossiness
  32083. node.onBeforeRender = mesh.onBeforeRender;
  32084. for (var i = 0, il = node.children.length; i < il; i++) {
  32085. node.children[i].name += '_instance_' + instanceNum;
  32086. node.children[i].onBeforeRender = mesh.children[i].onBeforeRender;
  32087. }
  32088. } else {
  32089. node = mesh;
  32090. } // if weights are provided on the node, override weights on the mesh.
  32091. if (nodeDef.weights !== undefined) {
  32092. node.traverse(function (o) {
  32093. if (!o.isMesh) return;
  32094. for (var i = 0, il = nodeDef.weights.length; i < il; i++) {
  32095. o.morphTargetInfluences[i] = nodeDef.weights[i];
  32096. }
  32097. });
  32098. }
  32099. return node;
  32100. }));
  32101. }
  32102. if (nodeDef.camera !== undefined) {
  32103. pending.push(parser.getDependency('camera', nodeDef.camera));
  32104. }
  32105. if (nodeDef.extensions && nodeDef.extensions[EXTENSIONS.KHR_LIGHTS_PUNCTUAL] && nodeDef.extensions[EXTENSIONS.KHR_LIGHTS_PUNCTUAL].light !== undefined) {
  32106. pending.push(parser.getDependency('light', nodeDef.extensions[EXTENSIONS.KHR_LIGHTS_PUNCTUAL].light));
  32107. }
  32108. return Promise.all(pending);
  32109. }().then(function (objects) {
  32110. var node; // .isBone isn't in glTF spec. See .markDefs
  32111. if (nodeDef.isBone === true) {
  32112. node = new _threeModule.Bone();
  32113. } else if (objects.length > 1) {
  32114. node = new _threeModule.Group();
  32115. } else if (objects.length === 1) {
  32116. node = objects[0];
  32117. } else {
  32118. node = new _threeModule.Object3D();
  32119. }
  32120. if (node !== objects[0]) {
  32121. for (var i = 0, il = objects.length; i < il; i++) {
  32122. node.add(objects[i]);
  32123. }
  32124. }
  32125. if (nodeDef.name !== undefined) {
  32126. node.userData.name = nodeDef.name;
  32127. node.name = _threeModule.PropertyBinding.sanitizeNodeName(nodeDef.name);
  32128. }
  32129. assignExtrasToUserData(node, nodeDef);
  32130. if (nodeDef.extensions) addUnknownExtensionsToUserData(extensions, node, nodeDef);
  32131. if (nodeDef.matrix !== undefined) {
  32132. var matrix = new _threeModule.Matrix4();
  32133. matrix.fromArray(nodeDef.matrix);
  32134. node.applyMatrix(matrix);
  32135. } else {
  32136. if (nodeDef.translation !== undefined) {
  32137. node.position.fromArray(nodeDef.translation);
  32138. }
  32139. if (nodeDef.rotation !== undefined) {
  32140. node.quaternion.fromArray(nodeDef.rotation);
  32141. }
  32142. if (nodeDef.scale !== undefined) {
  32143. node.scale.fromArray(nodeDef.scale);
  32144. }
  32145. }
  32146. return node;
  32147. });
  32148. };
  32149. /**
  32150. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#scenes
  32151. * @param {number} sceneIndex
  32152. * @return {Promise<Scene>}
  32153. */
  32154. GLTFParser.prototype.loadScene = function () {
  32155. // scene node hierachy builder
  32156. function buildNodeHierachy(nodeId, parentObject, json, parser) {
  32157. var nodeDef = json.nodes[nodeId];
  32158. return parser.getDependency('node', nodeId).then(function (node) {
  32159. if (nodeDef.skin === undefined) return node; // build skeleton here as well
  32160. var skinEntry;
  32161. return parser.getDependency('skin', nodeDef.skin).then(function (skin) {
  32162. skinEntry = skin;
  32163. var pendingJoints = [];
  32164. for (var i = 0, il = skinEntry.joints.length; i < il; i++) {
  32165. pendingJoints.push(parser.getDependency('node', skinEntry.joints[i]));
  32166. }
  32167. return Promise.all(pendingJoints);
  32168. }).then(function (jointNodes) {
  32169. node.traverse(function (mesh) {
  32170. if (!mesh.isMesh) return;
  32171. var bones = [];
  32172. var boneInverses = [];
  32173. for (var j = 0, jl = jointNodes.length; j < jl; j++) {
  32174. var jointNode = jointNodes[j];
  32175. if (jointNode) {
  32176. bones.push(jointNode);
  32177. var mat = new _threeModule.Matrix4();
  32178. if (skinEntry.inverseBindMatrices !== undefined) {
  32179. mat.fromArray(skinEntry.inverseBindMatrices.array, j * 16);
  32180. }
  32181. boneInverses.push(mat);
  32182. } else {
  32183. console.warn('THREE.GLTFLoader: Joint "%s" could not be found.', skinEntry.joints[j]);
  32184. }
  32185. }
  32186. mesh.bind(new _threeModule.Skeleton(bones, boneInverses), mesh.matrixWorld);
  32187. });
  32188. return node;
  32189. });
  32190. }).then(function (node) {
  32191. // build node hierachy
  32192. parentObject.add(node);
  32193. var pending = [];
  32194. if (nodeDef.children) {
  32195. var children = nodeDef.children;
  32196. for (var i = 0, il = children.length; i < il; i++) {
  32197. var child = children[i];
  32198. pending.push(buildNodeHierachy(child, node, json, parser));
  32199. }
  32200. }
  32201. return Promise.all(pending);
  32202. });
  32203. }
  32204. return function loadScene(sceneIndex) {
  32205. var json = this.json;
  32206. var extensions = this.extensions;
  32207. var sceneDef = this.json.scenes[sceneIndex];
  32208. var parser = this;
  32209. var scene = new _threeModule.Scene();
  32210. if (sceneDef.name !== undefined) scene.name = sceneDef.name;
  32211. assignExtrasToUserData(scene, sceneDef);
  32212. if (sceneDef.extensions) addUnknownExtensionsToUserData(extensions, scene, sceneDef);
  32213. var nodeIds = sceneDef.nodes || [];
  32214. var pending = [];
  32215. for (var i = 0, il = nodeIds.length; i < il; i++) {
  32216. pending.push(buildNodeHierachy(nodeIds[i], scene, json, parser));
  32217. }
  32218. return Promise.all(pending).then(function () {
  32219. return scene;
  32220. });
  32221. };
  32222. }();
  32223. return GLTFLoader;
  32224. }();
  32225. exports.GLTFLoader = GLTFLoader;
  32226. },{"../../../build/three.module.js":"../node_modules/three/build/three.module.js"}],"../src/three/ThreeB3DMLoader.js":[function(require,module,exports) {
  32227. "use strict";
  32228. Object.defineProperty(exports, "__esModule", {
  32229. value: true
  32230. });
  32231. exports.ThreeB3DMLoader = void 0;
  32232. var _B3DMLoader = require("../B3DMLoader.js");
  32233. var _GLTFLoader = require("three/examples/jsm/loaders/GLTFLoader.js");
  32234. class ThreeB3DMLoader extends _B3DMLoader.B3DMLoader {
  32235. parse(buffer) {
  32236. const b3dm = super.parse(buffer);
  32237. const gltfBuffer = b3dm.glbBytes.slice().buffer;
  32238. return new Promise((resolve, reject) => {
  32239. new _GLTFLoader.GLTFLoader().parse(gltfBuffer, null, resolve, reject);
  32240. });
  32241. }
  32242. }
  32243. exports.ThreeB3DMLoader = ThreeB3DMLoader;
  32244. },{"../B3DMLoader.js":"../src/B3DMLoader.js","three/examples/jsm/loaders/GLTFLoader.js":"../node_modules/three/examples/jsm/loaders/GLTFLoader.js"}],"../src/three/ThreeTilesRenderer.js":[function(require,module,exports) {
  32245. "use strict";
  32246. Object.defineProperty(exports, "__esModule", {
  32247. value: true
  32248. });
  32249. exports.ThreeTilesRenderer = void 0;
  32250. var _TilesRenderer = require("../TilesRenderer.js");
  32251. var _ThreeB3DMLoader = require("./ThreeB3DMLoader.js");
  32252. var _three = require("three");
  32253. const DEG2RAD = _three.Math.DEG2RAD;
  32254. const tempMat = new _three.Matrix4();
  32255. const tempQuaternion = new _three.Quaternion();
  32256. const tempVector = new _three.Vector3();
  32257. const resVector = new _three.Vector2();
  32258. const vecX = new _three.Vector3();
  32259. const vecY = new _three.Vector3();
  32260. const vecZ = new _three.Vector3();
  32261. const ray = new _three.Ray();
  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: Figure out how to do traversal here -- submit issue to three.js?
  32272. const tilesRenderer = this.tilesRenderer;
  32273. const visibleSet = tilesRenderer.visibleSet;
  32274. const activeSet = tilesRenderer.activeSet;
  32275. activeSet.forEach(scene => {
  32276. if (!visibleSet.has(scene)) {
  32277. raycaster.intersectObject(scene, true, intersects);
  32278. }
  32279. });
  32280. }
  32281. updateMatrixWorld(force) {
  32282. if (this.matrixAutoUpdate) {
  32283. this.updateMatrix();
  32284. }
  32285. if (this.matrixWorldNeedsUpdate || force) {
  32286. if (this.parent === null) {
  32287. tempMat.copy(this.matrix);
  32288. } else {
  32289. tempMat.multiplyMatrices(this.parent.matrixWorld, this.matrix);
  32290. }
  32291. this.matrixWorldNeedsUpdate = false;
  32292. const elA = tempMat.elements;
  32293. const elB = this.matrixWorld.elements;
  32294. let isDifferent = false;
  32295. for (let i = 0; i < 16; i++) {
  32296. const itemA = elA[i];
  32297. const itemB = elB[i];
  32298. const diff = Math.abs(itemA - itemB);
  32299. if (diff > Number.EPSILON) {
  32300. isDifferent = true;
  32301. break;
  32302. }
  32303. }
  32304. if (isDifferent) {
  32305. this.matrixWorld.copy(tempMat); // update children
  32306. // the children will not have to change unless the parent group has updated
  32307. const children = this.children;
  32308. for (let i = 0, l = children.length; i < l; i++) {
  32309. children[i].updateMatrixWorld();
  32310. }
  32311. }
  32312. }
  32313. }
  32314. }
  32315. class ThreeTilesRenderer extends _TilesRenderer.TilesRenderer {
  32316. get displayBounds() {
  32317. return this._displayBounds;
  32318. }
  32319. set displayBounds(val) {
  32320. if (val !== this.displayBounds) {
  32321. this._displayBounds = val;
  32322. this.traverse(t => {
  32323. const scene = t.cached.scene;
  32324. const boxHelper = t.cached.boxHelper;
  32325. if (scene) {
  32326. if (val) {
  32327. scene.add(boxHelper);
  32328. boxHelper.updateMatrixWorld(true);
  32329. } else {
  32330. scene.remove(boxHelper);
  32331. }
  32332. }
  32333. });
  32334. }
  32335. }
  32336. constructor(url, cameras, renderer) {
  32337. super(url);
  32338. this.group = new TilesGroup(this);
  32339. this.cameras = Array.isArray(cameras) ? cameras : [cameras];
  32340. this.frustums = [];
  32341. this.renderer = renderer;
  32342. this.activeSet = new Set();
  32343. this.visibleSet = new Set();
  32344. }
  32345. /* Public API */
  32346. getBounds(box) {
  32347. if (!this.root) {
  32348. return false;
  32349. }
  32350. const cached = this.root.cached;
  32351. const boundingBox = cached.box;
  32352. const obbMat = cached.boxTransform;
  32353. const transformMat = cached.transform;
  32354. box.copy(boundingBox);
  32355. tempMat.multiplyMatrices(transformMat, obbMat);
  32356. box.applyMatrix4(tempMat);
  32357. return true;
  32358. }
  32359. raycast(raycaster, intersects) {
  32360. const activeSet = this.activeSet;
  32361. const group = this.group;
  32362. this.traverse(tile => {
  32363. const cached = tile.cached;
  32364. const groupMatrixWorld = group.matrixWorld;
  32365. const transformMat = cached.transform;
  32366. tempMat.copy(groupMatrixWorld);
  32367. tempMat.multiply(transformMat);
  32368. const sphere = cached.sphere;
  32369. if (sphere) {
  32370. _sphere.copy(sphere);
  32371. _sphere.applyMatrix4(tempMat);
  32372. if (!raycaster.ray.intersectsSphere(_sphere)) {
  32373. return true;
  32374. }
  32375. }
  32376. const boundingBox = cached.box;
  32377. const obbMat = cached.boxTransform;
  32378. if (boundingBox) {
  32379. tempMat.multiply(obbMat);
  32380. tempMat.getInverse(tempMat);
  32381. ray.copy(raycaster.ray).applyMatrix4(tempMat);
  32382. if (!ray.intersectsBox(boundingBox)) {
  32383. return true;
  32384. }
  32385. } // TODO: check region
  32386. // TODO: how do we prevent the child checks from happening?
  32387. const scene = cached.scene;
  32388. if (activeSet.has(scene)) {
  32389. raycaster.intersectObject(scene, true, intersects);
  32390. }
  32391. });
  32392. }
  32393. /* Overriden */
  32394. update() {
  32395. const group = this.group;
  32396. const renderer = this.renderer;
  32397. const cameras = this.cameras;
  32398. const frustums = this.frustums; // automatically scale the array of frustums to match the cameras
  32399. while (frustums.length > cameras.length) {
  32400. frustums.pop();
  32401. }
  32402. while (frustums.length < cameras.length) {
  32403. frustums.push(new _three.Frustum());
  32404. } // store the camera frustums in the 3d tiles root frame
  32405. for (let i = 0, l = frustums.length; i < l; i++) {
  32406. const camera = cameras[i];
  32407. const frustum = frustums[i];
  32408. tempMat.copy(group.matrixWorld);
  32409. tempMat.premultiply(camera.matrixWorldInverse);
  32410. tempMat.premultiply(camera.projectionMatrix);
  32411. frustum.setFromMatrix(tempMat);
  32412. } // store the resolution of the render
  32413. renderer.getSize(resVector);
  32414. resVector.multiplyScalar(renderer.getPixelRatio());
  32415. super.update();
  32416. }
  32417. preprocessNode(tile, parentTile, tileSetDir) {
  32418. super.preprocessNode(tile, parentTile, tileSetDir);
  32419. const transform = new _three.Matrix4();
  32420. if (tile.transform) {
  32421. const transformArr = tile.transform;
  32422. for (let i = 0; i < 16; i++) {
  32423. transform.elements[i] = transformArr[i];
  32424. }
  32425. } else {
  32426. transform.identity();
  32427. }
  32428. if (parentTile) {
  32429. transform.multiply(parentTile.cached.transform);
  32430. }
  32431. let box = null;
  32432. let boxTransform = null;
  32433. if ('box' in tile.boundingVolume) {
  32434. const data = tile.boundingVolume.box;
  32435. box = new _three.Box3();
  32436. boxTransform = new _three.Matrix4(); // get the extents of the bounds in each axis
  32437. vecX.set(data[3], data[4], data[5]);
  32438. vecY.set(data[6], data[7], data[8]);
  32439. vecZ.set(data[9], data[10], data[11]);
  32440. const scaleX = vecX.length();
  32441. const scaleY = vecY.length();
  32442. const scaleZ = vecZ.length();
  32443. vecX.normalize();
  32444. vecY.normalize();
  32445. vecZ.normalize(); // create the oriented frame that the box exists in
  32446. 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
  32447. box.min.set(-scaleX, -scaleY, -scaleZ);
  32448. box.max.set(scaleX, scaleY, scaleZ);
  32449. }
  32450. let sphere = null;
  32451. if ('sphere' in tile.boundingVolume) {
  32452. const data = tile.boundingVolume.sphere;
  32453. sphere = new _three.Sphere();
  32454. sphere.center.set(data[0], data[1], data[2]);
  32455. sphere.radius = data[3];
  32456. } else if ('box' in tile.boundingVolume) {
  32457. sphere = new _three.Sphere();
  32458. box.getBoundingSphere(sphere);
  32459. boxTransform.decompose(sphere.center, tempQuaternion, tempVector);
  32460. }
  32461. let region = null;
  32462. if ('region' in tile.boundingVolume) {
  32463. console.warn('ThreeTilesRenderer: region bounding volume not supported.');
  32464. }
  32465. tile.cached = {
  32466. loadIndex: 0,
  32467. transform,
  32468. active: false,
  32469. box,
  32470. boxTransform,
  32471. sphere,
  32472. region,
  32473. boxHelper: null,
  32474. scene: null
  32475. };
  32476. }
  32477. parseTile(buffer, tile) {
  32478. tile._loadIndex = tile._loadIndex || 0;
  32479. tile._loadIndex++; // TODO: 90 degree rotation must be applied to GLTF file to resolve "up"
  32480. const loadIndex = tile._loadIndex;
  32481. return new _ThreeB3DMLoader.ThreeB3DMLoader().parse(buffer).then(res => {
  32482. if (tile._loadIndex !== loadIndex) {
  32483. return;
  32484. }
  32485. const cached = tile.cached;
  32486. const cachedBox = cached.box;
  32487. const cachedBoxMat = cached.boxTransform; // add a helper group to represent the obb rotation matrix
  32488. const boxHelper = new _three.Box3Helper(cachedBox);
  32489. const boxHelperGroup = new _three.Group();
  32490. cachedBoxMat.decompose(boxHelperGroup.position, boxHelperGroup.quaternion, boxHelperGroup.scale);
  32491. boxHelperGroup.add(boxHelper);
  32492. boxHelperGroup.updateMatrixWorld(true);
  32493. const scene = res.scene;
  32494. cached.transform.decompose(scene.position, scene.quaternion, scene.scale);
  32495. scene.traverse(c => c.frustumCulled = false);
  32496. cached.boxHelper = boxHelperGroup;
  32497. cached.scene = res.scene;
  32498. if (this.displayBounds) {
  32499. cached.scene.add(cached.boxHelper);
  32500. }
  32501. });
  32502. }
  32503. disposeTile(tile) {
  32504. const cached = tile.cached;
  32505. if (cached.scene) {
  32506. const scene = cached.scene;
  32507. if (scene.parent) {
  32508. scene.parent.remove(scene);
  32509. }
  32510. scene.traverse(c => {
  32511. if (c.geometry) {
  32512. c.geometry.dispose();
  32513. }
  32514. if (c.material) {
  32515. c.material.dispose(); // TODO: dispose textures
  32516. }
  32517. });
  32518. cached.scene = null;
  32519. cached.boxHelper = null;
  32520. }
  32521. tile._loadIndex++;
  32522. }
  32523. setTileVisible(tile, visible) {
  32524. const scene = tile.cached.scene;
  32525. const visibleSet = this.visibleSet;
  32526. const group = this.group;
  32527. if (visible) {
  32528. if (scene && !scene.parent) {
  32529. group.add(scene);
  32530. visibleSet.add(scene);
  32531. scene.updateMatrixWorld(true);
  32532. }
  32533. } else {
  32534. group.remove(scene);
  32535. visibleSet.delete(scene);
  32536. }
  32537. }
  32538. setTileActive(tile, active) {
  32539. const cached = tile.cached;
  32540. const activeSet = this.activeSet;
  32541. if (active !== cached.active) {
  32542. cached.active = active;
  32543. if (active) {
  32544. activeSet.add(cached.scene);
  32545. } else {
  32546. activeSet.delete(cached.scene);
  32547. }
  32548. }
  32549. }
  32550. calculateError(tile) {
  32551. const cached = tile.cached;
  32552. const cameras = this.cameras; // TODO: Use the content bounding volume here?
  32553. const boundingVolume = tile.boundingVolume;
  32554. const transformMat = cached.transform;
  32555. if ('box' in boundingVolume) {
  32556. const group = this.group;
  32557. const boundingBox = cached.box;
  32558. const obbMat = cached.boxTransform; // TODO: these can likely be cached? Or the world transform mat can be used
  32559. // transformMat can be rolled into oobMat
  32560. tempMat.copy(transformMat);
  32561. tempMat.multiply(obbMat);
  32562. tempMat.getInverse(tempMat);
  32563. let minError = Infinity;
  32564. for (let i = 0, l = cameras.length; i < l; i++) {
  32565. // transform camera position into local frame of the tile bounding box
  32566. const cam = cameras[i];
  32567. tempVector.copy(cam.position);
  32568. tempVector.applyMatrix4(tempMat);
  32569. let error;
  32570. if (cam.isOrthographic) {
  32571. const w = cam.right - cam.left;
  32572. const h = cam.top - cam.bottom;
  32573. const pixelSize = Math.Max(h, w) / Math.Max(resVector.width, resVector.height);
  32574. error = tile.geometricError / pixelSize;
  32575. } else {
  32576. const distance = boundingBox.distanceToPoint(tempVector); // assume the scales on all axes are uniform.
  32577. let scale; // account for tile scale.
  32578. tempVector.setFromMatrixScale(tempMat);
  32579. scale = tempVector.x; // account for parent group scale. Divide because this matrix has not been inverted like the previous one.
  32580. tempVector.setFromMatrixScale(group.matrixWorld);
  32581. scale /= tempVector.x;
  32582. if (Math.abs(Math.max(scale.x - scale.y, scale.x - scale.z)) > 1e-6) {
  32583. console.warn('ThreeTilesRenderer : Non uniform scale used for tile which may cause issues when claculating screen space error.');
  32584. }
  32585. const scaledDistance = distance * scale;
  32586. const sseDenominator = 2 * Math.tan(0.5 * cam.fov * DEG2RAD);
  32587. error = tile.geometricError * resVector.height / (scaledDistance * sseDenominator);
  32588. }
  32589. minError = Math.min(minError, error);
  32590. }
  32591. return minError;
  32592. } else if ('sphere' in boundingVolume) {
  32593. // const sphere = cached.sphere;
  32594. console.warn('ThreeTilesRenderer : Sphere bounds not supported.');
  32595. } else if ('region' in boundingVolume) {
  32596. // unsupported
  32597. console.warn('ThreeTilesRenderer : Region bounds not supported.');
  32598. }
  32599. return Infinity;
  32600. }
  32601. tileInView(tile) {
  32602. // TODO: we should use the more precise bounding volumes here if possible
  32603. // cache the root-space planes
  32604. const sphere = tile.cached.sphere;
  32605. if (sphere) {
  32606. _sphere.copy(sphere);
  32607. _sphere.applyMatrix4(tile.cached.transform);
  32608. const frustums = this.frustums;
  32609. for (let i = 0, l = frustums.length; i < l; i++) {
  32610. const frustum = frustums[i];
  32611. if (frustum.intersectsSphere(_sphere)) {
  32612. return true;
  32613. }
  32614. }
  32615. return false;
  32616. }
  32617. return true;
  32618. }
  32619. }
  32620. exports.ThreeTilesRenderer = ThreeTilesRenderer;
  32621. },{"../TilesRenderer.js":"../src/TilesRenderer.js","./ThreeB3DMLoader.js":"../src/three/ThreeB3DMLoader.js","three":"../node_modules/three/build/three.module.js"}],"../src/index.js":[function(require,module,exports) {
  32622. "use strict";
  32623. Object.defineProperty(exports, "__esModule", {
  32624. value: true
  32625. });
  32626. Object.defineProperty(exports, "ThreeTilesRenderer", {
  32627. enumerable: true,
  32628. get: function () {
  32629. return _ThreeTilesRenderer.ThreeTilesRenderer;
  32630. }
  32631. });
  32632. Object.defineProperty(exports, "ThreeB3DMLoader", {
  32633. enumerable: true,
  32634. get: function () {
  32635. return _ThreeB3DMLoader.ThreeB3DMLoader;
  32636. }
  32637. });
  32638. Object.defineProperty(exports, "TilesRenderer", {
  32639. enumerable: true,
  32640. get: function () {
  32641. return _TilesRenderer.TilesRenderer;
  32642. }
  32643. });
  32644. Object.defineProperty(exports, "B3DMLoader", {
  32645. enumerable: true,
  32646. get: function () {
  32647. return _B3DMLoader.B3DMLoader;
  32648. }
  32649. });
  32650. var _ThreeTilesRenderer = require("./three/ThreeTilesRenderer.js");
  32651. var _ThreeB3DMLoader = require("./three/ThreeB3DMLoader");
  32652. var _TilesRenderer = require("./TilesRenderer.js");
  32653. var _B3DMLoader = require("./B3DMLoader");
  32654. },{"./three/ThreeTilesRenderer.js":"../src/three/ThreeTilesRenderer.js","./three/ThreeB3DMLoader":"../src/three/ThreeB3DMLoader.js","./TilesRenderer.js":"../src/TilesRenderer.js","./B3DMLoader":"../src/B3DMLoader.js"}],"../node_modules/three/examples/jsm/controls/OrbitControls.js":[function(require,module,exports) {
  32655. "use strict";
  32656. Object.defineProperty(exports, "__esModule", {
  32657. value: true
  32658. });
  32659. exports.MapControls = exports.OrbitControls = void 0;
  32660. var _threeModule = require("../../../build/three.module.js");
  32661. /**
  32662. * @author qiao / https://github.com/qiao
  32663. * @author mrdoob / http://mrdoob.com
  32664. * @author alteredq / http://alteredqualia.com/
  32665. * @author WestLangley / http://github.com/WestLangley
  32666. * @author erich666 / http://erichaines.com
  32667. * @author ScieCode / http://github.com/sciecode
  32668. */
  32669. // This set of controls performs orbiting, dollying (zooming), and panning.
  32670. // Unlike TrackballControls, it maintains the "up" direction object.up (+Y by default).
  32671. //
  32672. // Orbit - left mouse / touch: one-finger move
  32673. // Zoom - middle mouse, or mousewheel / touch: two-finger spread or squish
  32674. // Pan - right mouse, or left mouse + ctrl/meta/shiftKey, or arrow keys / touch: two-finger move
  32675. var OrbitControls = function (object, domElement) {
  32676. this.object = object;
  32677. this.domElement = domElement !== undefined ? domElement : document; // Set to false to disable this control
  32678. this.enabled = true; // "target" sets the location of focus, where the object orbits around
  32679. this.target = new _threeModule.Vector3(); // How far you can dolly in and out ( PerspectiveCamera only )
  32680. this.minDistance = 0;
  32681. this.maxDistance = Infinity; // How far you can zoom in and out ( OrthographicCamera only )
  32682. this.minZoom = 0;
  32683. this.maxZoom = Infinity; // How far you can orbit vertically, upper and lower limits.
  32684. // Range is 0 to Math.PI radians.
  32685. this.minPolarAngle = 0; // radians
  32686. this.maxPolarAngle = Math.PI; // radians
  32687. // How far you can orbit horizontally, upper and lower limits.
  32688. // If set, must be a sub-interval of the interval [ - Math.PI, Math.PI ].
  32689. this.minAzimuthAngle = -Infinity; // radians
  32690. this.maxAzimuthAngle = Infinity; // radians
  32691. // Set to true to enable damping (inertia)
  32692. // If damping is enabled, you must call controls.update() in your animation loop
  32693. this.enableDamping = false;
  32694. this.dampingFactor = 0.05; // This option actually enables dollying in and out; left as "zoom" for backwards compatibility.
  32695. // Set to false to disable zooming
  32696. this.enableZoom = true;
  32697. this.zoomSpeed = 1.0; // Set to false to disable rotating
  32698. this.enableRotate = true;
  32699. this.rotateSpeed = 1.0; // Set to false to disable panning
  32700. this.enablePan = true;
  32701. this.panSpeed = 1.0;
  32702. this.screenSpacePanning = false; // if true, pan in screen-space
  32703. this.keyPanSpeed = 7.0; // pixels moved per arrow key push
  32704. // Set to true to automatically rotate around the target
  32705. // If auto-rotate is enabled, you must call controls.update() in your animation loop
  32706. this.autoRotate = false;
  32707. this.autoRotateSpeed = 2.0; // 30 seconds per round when fps is 60
  32708. // Set to false to disable use of the keys
  32709. this.enableKeys = true; // The four arrow keys
  32710. this.keys = {
  32711. LEFT: 37,
  32712. UP: 38,
  32713. RIGHT: 39,
  32714. BOTTOM: 40
  32715. }; // Mouse buttons
  32716. this.mouseButtons = {
  32717. LEFT: _threeModule.MOUSE.ROTATE,
  32718. MIDDLE: _threeModule.MOUSE.DOLLY,
  32719. RIGHT: _threeModule.MOUSE.PAN
  32720. }; // Touch fingers
  32721. this.touches = {
  32722. ONE: _threeModule.TOUCH.ROTATE,
  32723. TWO: _threeModule.TOUCH.DOLLY_PAN
  32724. }; // for reset
  32725. this.target0 = this.target.clone();
  32726. this.position0 = this.object.position.clone();
  32727. this.zoom0 = this.object.zoom; //
  32728. // public methods
  32729. //
  32730. this.getPolarAngle = function () {
  32731. return spherical.phi;
  32732. };
  32733. this.getAzimuthalAngle = function () {
  32734. return spherical.theta;
  32735. };
  32736. this.saveState = function () {
  32737. scope.target0.copy(scope.target);
  32738. scope.position0.copy(scope.object.position);
  32739. scope.zoom0 = scope.object.zoom;
  32740. };
  32741. this.reset = function () {
  32742. scope.target.copy(scope.target0);
  32743. scope.object.position.copy(scope.position0);
  32744. scope.object.zoom = scope.zoom0;
  32745. scope.object.updateProjectionMatrix();
  32746. scope.dispatchEvent(changeEvent);
  32747. scope.update();
  32748. state = STATE.NONE;
  32749. }; // this method is exposed, but perhaps it would be better if we can make it private...
  32750. this.update = function () {
  32751. var offset = new _threeModule.Vector3(); // so camera.up is the orbit axis
  32752. var quat = new _threeModule.Quaternion().setFromUnitVectors(object.up, new _threeModule.Vector3(0, 1, 0));
  32753. var quatInverse = quat.clone().inverse();
  32754. var lastPosition = new _threeModule.Vector3();
  32755. var lastQuaternion = new _threeModule.Quaternion();
  32756. return function update() {
  32757. var position = scope.object.position;
  32758. offset.copy(position).sub(scope.target); // rotate offset to "y-axis-is-up" space
  32759. offset.applyQuaternion(quat); // angle from z-axis around y-axis
  32760. spherical.setFromVector3(offset);
  32761. if (scope.autoRotate && state === STATE.NONE) {
  32762. rotateLeft(getAutoRotationAngle());
  32763. }
  32764. if (scope.enableDamping) {
  32765. spherical.theta += sphericalDelta.theta * scope.dampingFactor;
  32766. spherical.phi += sphericalDelta.phi * scope.dampingFactor;
  32767. } else {
  32768. spherical.theta += sphericalDelta.theta;
  32769. spherical.phi += sphericalDelta.phi;
  32770. } // restrict theta to be between desired limits
  32771. spherical.theta = Math.max(scope.minAzimuthAngle, Math.min(scope.maxAzimuthAngle, spherical.theta)); // restrict phi to be between desired limits
  32772. spherical.phi = Math.max(scope.minPolarAngle, Math.min(scope.maxPolarAngle, spherical.phi));
  32773. spherical.makeSafe();
  32774. spherical.radius *= scale; // restrict radius to be between desired limits
  32775. spherical.radius = Math.max(scope.minDistance, Math.min(scope.maxDistance, spherical.radius)); // move target to panned location
  32776. if (scope.enableDamping === true) {
  32777. scope.target.addScaledVector(panOffset, scope.dampingFactor);
  32778. } else {
  32779. scope.target.add(panOffset);
  32780. }
  32781. offset.setFromSpherical(spherical); // rotate offset back to "camera-up-vector-is-up" space
  32782. offset.applyQuaternion(quatInverse);
  32783. position.copy(scope.target).add(offset);
  32784. scope.object.lookAt(scope.target);
  32785. if (scope.enableDamping === true) {
  32786. sphericalDelta.theta *= 1 - scope.dampingFactor;
  32787. sphericalDelta.phi *= 1 - scope.dampingFactor;
  32788. panOffset.multiplyScalar(1 - scope.dampingFactor);
  32789. } else {
  32790. sphericalDelta.set(0, 0, 0);
  32791. panOffset.set(0, 0, 0);
  32792. }
  32793. scale = 1; // update condition is:
  32794. // min(camera displacement, camera rotation in radians)^2 > EPS
  32795. // using small-angle approximation cos(x/2) = 1 - x^2 / 8
  32796. if (zoomChanged || lastPosition.distanceToSquared(scope.object.position) > EPS || 8 * (1 - lastQuaternion.dot(scope.object.quaternion)) > EPS) {
  32797. scope.dispatchEvent(changeEvent);
  32798. lastPosition.copy(scope.object.position);
  32799. lastQuaternion.copy(scope.object.quaternion);
  32800. zoomChanged = false;
  32801. return true;
  32802. }
  32803. return false;
  32804. };
  32805. }();
  32806. this.dispose = function () {
  32807. scope.domElement.removeEventListener('contextmenu', onContextMenu, false);
  32808. scope.domElement.removeEventListener('mousedown', onMouseDown, false);
  32809. scope.domElement.removeEventListener('wheel', onMouseWheel, false);
  32810. scope.domElement.removeEventListener('touchstart', onTouchStart, false);
  32811. scope.domElement.removeEventListener('touchend', onTouchEnd, false);
  32812. scope.domElement.removeEventListener('touchmove', onTouchMove, false);
  32813. document.removeEventListener('mousemove', onMouseMove, false);
  32814. document.removeEventListener('mouseup', onMouseUp, false);
  32815. window.removeEventListener('keydown', onKeyDown, false); //scope.dispatchEvent( { type: 'dispose' } ); // should this be added here?
  32816. }; //
  32817. // internals
  32818. //
  32819. var scope = this;
  32820. var changeEvent = {
  32821. type: 'change'
  32822. };
  32823. var startEvent = {
  32824. type: 'start'
  32825. };
  32826. var endEvent = {
  32827. type: 'end'
  32828. };
  32829. var STATE = {
  32830. NONE: -1,
  32831. ROTATE: 0,
  32832. DOLLY: 1,
  32833. PAN: 2,
  32834. TOUCH_ROTATE: 3,
  32835. TOUCH_PAN: 4,
  32836. TOUCH_DOLLY_PAN: 5,
  32837. TOUCH_DOLLY_ROTATE: 6
  32838. };
  32839. var state = STATE.NONE;
  32840. var EPS = 0.000001; // current position in spherical coordinates
  32841. var spherical = new _threeModule.Spherical();
  32842. var sphericalDelta = new _threeModule.Spherical();
  32843. var scale = 1;
  32844. var panOffset = new _threeModule.Vector3();
  32845. var zoomChanged = false;
  32846. var rotateStart = new _threeModule.Vector2();
  32847. var rotateEnd = new _threeModule.Vector2();
  32848. var rotateDelta = new _threeModule.Vector2();
  32849. var panStart = new _threeModule.Vector2();
  32850. var panEnd = new _threeModule.Vector2();
  32851. var panDelta = new _threeModule.Vector2();
  32852. var dollyStart = new _threeModule.Vector2();
  32853. var dollyEnd = new _threeModule.Vector2();
  32854. var dollyDelta = new _threeModule.Vector2();
  32855. function getAutoRotationAngle() {
  32856. return 2 * Math.PI / 60 / 60 * scope.autoRotateSpeed;
  32857. }
  32858. function getZoomScale() {
  32859. return Math.pow(0.95, scope.zoomSpeed);
  32860. }
  32861. function rotateLeft(angle) {
  32862. sphericalDelta.theta -= angle;
  32863. }
  32864. function rotateUp(angle) {
  32865. sphericalDelta.phi -= angle;
  32866. }
  32867. var panLeft = function () {
  32868. var v = new _threeModule.Vector3();
  32869. return function panLeft(distance, objectMatrix) {
  32870. v.setFromMatrixColumn(objectMatrix, 0); // get X column of objectMatrix
  32871. v.multiplyScalar(-distance);
  32872. panOffset.add(v);
  32873. };
  32874. }();
  32875. var panUp = function () {
  32876. var v = new _threeModule.Vector3();
  32877. return function panUp(distance, objectMatrix) {
  32878. if (scope.screenSpacePanning === true) {
  32879. v.setFromMatrixColumn(objectMatrix, 1);
  32880. } else {
  32881. v.setFromMatrixColumn(objectMatrix, 0);
  32882. v.crossVectors(scope.object.up, v);
  32883. }
  32884. v.multiplyScalar(distance);
  32885. panOffset.add(v);
  32886. };
  32887. }(); // deltaX and deltaY are in pixels; right and down are positive
  32888. var pan = function () {
  32889. var offset = new _threeModule.Vector3();
  32890. return function pan(deltaX, deltaY) {
  32891. var element = scope.domElement === document ? scope.domElement.body : scope.domElement;
  32892. if (scope.object.isPerspectiveCamera) {
  32893. // perspective
  32894. var position = scope.object.position;
  32895. offset.copy(position).sub(scope.target);
  32896. var targetDistance = offset.length(); // half of the fov is center to top of screen
  32897. targetDistance *= Math.tan(scope.object.fov / 2 * Math.PI / 180.0); // we use only clientHeight here so aspect ratio does not distort speed
  32898. panLeft(2 * deltaX * targetDistance / element.clientHeight, scope.object.matrix);
  32899. panUp(2 * deltaY * targetDistance / element.clientHeight, scope.object.matrix);
  32900. } else if (scope.object.isOrthographicCamera) {
  32901. // orthographic
  32902. panLeft(deltaX * (scope.object.right - scope.object.left) / scope.object.zoom / element.clientWidth, scope.object.matrix);
  32903. panUp(deltaY * (scope.object.top - scope.object.bottom) / scope.object.zoom / element.clientHeight, scope.object.matrix);
  32904. } else {
  32905. // camera neither orthographic nor perspective
  32906. console.warn('WARNING: OrbitControls.js encountered an unknown camera type - pan disabled.');
  32907. scope.enablePan = false;
  32908. }
  32909. };
  32910. }();
  32911. function dollyIn(dollyScale) {
  32912. if (scope.object.isPerspectiveCamera) {
  32913. scale /= dollyScale;
  32914. } else if (scope.object.isOrthographicCamera) {
  32915. scope.object.zoom = Math.max(scope.minZoom, Math.min(scope.maxZoom, scope.object.zoom * dollyScale));
  32916. scope.object.updateProjectionMatrix();
  32917. zoomChanged = true;
  32918. } else {
  32919. console.warn('WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled.');
  32920. scope.enableZoom = false;
  32921. }
  32922. }
  32923. function dollyOut(dollyScale) {
  32924. if (scope.object.isPerspectiveCamera) {
  32925. scale *= dollyScale;
  32926. } else if (scope.object.isOrthographicCamera) {
  32927. scope.object.zoom = Math.max(scope.minZoom, Math.min(scope.maxZoom, scope.object.zoom / dollyScale));
  32928. scope.object.updateProjectionMatrix();
  32929. zoomChanged = true;
  32930. } else {
  32931. console.warn('WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled.');
  32932. scope.enableZoom = false;
  32933. }
  32934. } //
  32935. // event callbacks - update the object state
  32936. //
  32937. function handleMouseDownRotate(event) {
  32938. rotateStart.set(event.clientX, event.clientY);
  32939. }
  32940. function handleMouseDownDolly(event) {
  32941. dollyStart.set(event.clientX, event.clientY);
  32942. }
  32943. function handleMouseDownPan(event) {
  32944. panStart.set(event.clientX, event.clientY);
  32945. }
  32946. function handleMouseMoveRotate(event) {
  32947. rotateEnd.set(event.clientX, event.clientY);
  32948. rotateDelta.subVectors(rotateEnd, rotateStart).multiplyScalar(scope.rotateSpeed);
  32949. var element = scope.domElement === document ? scope.domElement.body : scope.domElement;
  32950. rotateLeft(2 * Math.PI * rotateDelta.x / element.clientHeight); // yes, height
  32951. rotateUp(2 * Math.PI * rotateDelta.y / element.clientHeight);
  32952. rotateStart.copy(rotateEnd);
  32953. scope.update();
  32954. }
  32955. function handleMouseMoveDolly(event) {
  32956. dollyEnd.set(event.clientX, event.clientY);
  32957. dollyDelta.subVectors(dollyEnd, dollyStart);
  32958. if (dollyDelta.y > 0) {
  32959. dollyIn(getZoomScale());
  32960. } else if (dollyDelta.y < 0) {
  32961. dollyOut(getZoomScale());
  32962. }
  32963. dollyStart.copy(dollyEnd);
  32964. scope.update();
  32965. }
  32966. function handleMouseMovePan(event) {
  32967. panEnd.set(event.clientX, event.clientY);
  32968. panDelta.subVectors(panEnd, panStart).multiplyScalar(scope.panSpeed);
  32969. pan(panDelta.x, panDelta.y);
  32970. panStart.copy(panEnd);
  32971. scope.update();
  32972. }
  32973. function handleMouseUp()
  32974. /*event*/
  32975. {// no-op
  32976. }
  32977. function handleMouseWheel(event) {
  32978. if (event.deltaY < 0) {
  32979. dollyOut(getZoomScale());
  32980. } else if (event.deltaY > 0) {
  32981. dollyIn(getZoomScale());
  32982. }
  32983. scope.update();
  32984. }
  32985. function handleKeyDown(event) {
  32986. var needsUpdate = false;
  32987. switch (event.keyCode) {
  32988. case scope.keys.UP:
  32989. pan(0, scope.keyPanSpeed);
  32990. needsUpdate = true;
  32991. break;
  32992. case scope.keys.BOTTOM:
  32993. pan(0, -scope.keyPanSpeed);
  32994. needsUpdate = true;
  32995. break;
  32996. case scope.keys.LEFT:
  32997. pan(scope.keyPanSpeed, 0);
  32998. needsUpdate = true;
  32999. break;
  33000. case scope.keys.RIGHT:
  33001. pan(-scope.keyPanSpeed, 0);
  33002. needsUpdate = true;
  33003. break;
  33004. }
  33005. if (needsUpdate) {
  33006. // prevent the browser from scrolling on cursor keys
  33007. event.preventDefault();
  33008. scope.update();
  33009. }
  33010. }
  33011. function handleTouchStartRotate(event) {
  33012. if (event.touches.length == 1) {
  33013. rotateStart.set(event.touches[0].pageX, event.touches[0].pageY);
  33014. } else {
  33015. var x = 0.5 * (event.touches[0].pageX + event.touches[1].pageX);
  33016. var y = 0.5 * (event.touches[0].pageY + event.touches[1].pageY);
  33017. rotateStart.set(x, y);
  33018. }
  33019. }
  33020. function handleTouchStartPan(event) {
  33021. if (event.touches.length == 1) {
  33022. panStart.set(event.touches[0].pageX, event.touches[0].pageY);
  33023. } else {
  33024. var x = 0.5 * (event.touches[0].pageX + event.touches[1].pageX);
  33025. var y = 0.5 * (event.touches[0].pageY + event.touches[1].pageY);
  33026. panStart.set(x, y);
  33027. }
  33028. }
  33029. function handleTouchStartDolly(event) {
  33030. var dx = event.touches[0].pageX - event.touches[1].pageX;
  33031. var dy = event.touches[0].pageY - event.touches[1].pageY;
  33032. var distance = Math.sqrt(dx * dx + dy * dy);
  33033. dollyStart.set(0, distance);
  33034. }
  33035. function handleTouchStartDollyPan(event) {
  33036. if (scope.enableZoom) handleTouchStartDolly(event);
  33037. if (scope.enablePan) handleTouchStartPan(event);
  33038. }
  33039. function handleTouchStartDollyRotate(event) {
  33040. if (scope.enableZoom) handleTouchStartDolly(event);
  33041. if (scope.enableRotate) handleTouchStartRotate(event);
  33042. }
  33043. function handleTouchMoveRotate(event) {
  33044. if (event.touches.length == 1) {
  33045. rotateEnd.set(event.touches[0].pageX, event.touches[0].pageY);
  33046. } else {
  33047. var x = 0.5 * (event.touches[0].pageX + event.touches[1].pageX);
  33048. var y = 0.5 * (event.touches[0].pageY + event.touches[1].pageY);
  33049. rotateEnd.set(x, y);
  33050. }
  33051. rotateDelta.subVectors(rotateEnd, rotateStart).multiplyScalar(scope.rotateSpeed);
  33052. var element = scope.domElement === document ? scope.domElement.body : scope.domElement;
  33053. rotateLeft(2 * Math.PI * rotateDelta.x / element.clientHeight); // yes, height
  33054. rotateUp(2 * Math.PI * rotateDelta.y / element.clientHeight);
  33055. rotateStart.copy(rotateEnd);
  33056. }
  33057. function handleTouchMovePan(event) {
  33058. if (event.touches.length == 1) {
  33059. panEnd.set(event.touches[0].pageX, event.touches[0].pageY);
  33060. } else {
  33061. var x = 0.5 * (event.touches[0].pageX + event.touches[1].pageX);
  33062. var y = 0.5 * (event.touches[0].pageY + event.touches[1].pageY);
  33063. panEnd.set(x, y);
  33064. }
  33065. panDelta.subVectors(panEnd, panStart).multiplyScalar(scope.panSpeed);
  33066. pan(panDelta.x, panDelta.y);
  33067. panStart.copy(panEnd);
  33068. }
  33069. function handleTouchMoveDolly(event) {
  33070. var dx = event.touches[0].pageX - event.touches[1].pageX;
  33071. var dy = event.touches[0].pageY - event.touches[1].pageY;
  33072. var distance = Math.sqrt(dx * dx + dy * dy);
  33073. dollyEnd.set(0, distance);
  33074. dollyDelta.set(0, Math.pow(dollyEnd.y / dollyStart.y, scope.zoomSpeed));
  33075. dollyIn(dollyDelta.y);
  33076. dollyStart.copy(dollyEnd);
  33077. }
  33078. function handleTouchMoveDollyPan(event) {
  33079. if (scope.enableZoom) handleTouchMoveDolly(event);
  33080. if (scope.enablePan) handleTouchMovePan(event);
  33081. }
  33082. function handleTouchMoveDollyRotate(event) {
  33083. if (scope.enableZoom) handleTouchMoveDolly(event);
  33084. if (scope.enableRotate) handleTouchMoveRotate(event);
  33085. }
  33086. function handleTouchEnd()
  33087. /*event*/
  33088. {} // no-op
  33089. //
  33090. // event handlers - FSM: listen for events and reset state
  33091. //
  33092. function onMouseDown(event) {
  33093. if (scope.enabled === false) return; // Prevent the browser from scrolling.
  33094. event.preventDefault(); // Manually set the focus since calling preventDefault above
  33095. // prevents the browser from setting it automatically.
  33096. scope.domElement.focus ? scope.domElement.focus() : window.focus();
  33097. switch (event.button) {
  33098. case 0:
  33099. switch (scope.mouseButtons.LEFT) {
  33100. case _threeModule.MOUSE.ROTATE:
  33101. if (event.ctrlKey || event.metaKey || event.shiftKey) {
  33102. if (scope.enablePan === false) return;
  33103. handleMouseDownPan(event);
  33104. state = STATE.PAN;
  33105. } else {
  33106. if (scope.enableRotate === false) return;
  33107. handleMouseDownRotate(event);
  33108. state = STATE.ROTATE;
  33109. }
  33110. break;
  33111. case _threeModule.MOUSE.PAN:
  33112. if (event.ctrlKey || event.metaKey || event.shiftKey) {
  33113. if (scope.enableRotate === false) return;
  33114. handleMouseDownRotate(event);
  33115. state = STATE.ROTATE;
  33116. } else {
  33117. if (scope.enablePan === false) return;
  33118. handleMouseDownPan(event);
  33119. state = STATE.PAN;
  33120. }
  33121. break;
  33122. default:
  33123. state = STATE.NONE;
  33124. }
  33125. break;
  33126. case 1:
  33127. switch (scope.mouseButtons.MIDDLE) {
  33128. case _threeModule.MOUSE.DOLLY:
  33129. if (scope.enableZoom === false) return;
  33130. handleMouseDownDolly(event);
  33131. state = STATE.DOLLY;
  33132. break;
  33133. default:
  33134. state = STATE.NONE;
  33135. }
  33136. break;
  33137. case 2:
  33138. switch (scope.mouseButtons.RIGHT) {
  33139. case _threeModule.MOUSE.ROTATE:
  33140. if (scope.enableRotate === false) return;
  33141. handleMouseDownRotate(event);
  33142. state = STATE.ROTATE;
  33143. break;
  33144. case _threeModule.MOUSE.PAN:
  33145. if (scope.enablePan === false) return;
  33146. handleMouseDownPan(event);
  33147. state = STATE.PAN;
  33148. break;
  33149. default:
  33150. state = STATE.NONE;
  33151. }
  33152. break;
  33153. }
  33154. if (state !== STATE.NONE) {
  33155. document.addEventListener('mousemove', onMouseMove, false);
  33156. document.addEventListener('mouseup', onMouseUp, false);
  33157. scope.dispatchEvent(startEvent);
  33158. }
  33159. }
  33160. function onMouseMove(event) {
  33161. if (scope.enabled === false) return;
  33162. event.preventDefault();
  33163. switch (state) {
  33164. case STATE.ROTATE:
  33165. if (scope.enableRotate === false) return;
  33166. handleMouseMoveRotate(event);
  33167. break;
  33168. case STATE.DOLLY:
  33169. if (scope.enableZoom === false) return;
  33170. handleMouseMoveDolly(event);
  33171. break;
  33172. case STATE.PAN:
  33173. if (scope.enablePan === false) return;
  33174. handleMouseMovePan(event);
  33175. break;
  33176. }
  33177. }
  33178. function onMouseUp(event) {
  33179. if (scope.enabled === false) return;
  33180. handleMouseUp(event);
  33181. document.removeEventListener('mousemove', onMouseMove, false);
  33182. document.removeEventListener('mouseup', onMouseUp, false);
  33183. scope.dispatchEvent(endEvent);
  33184. state = STATE.NONE;
  33185. }
  33186. function onMouseWheel(event) {
  33187. if (scope.enabled === false || scope.enableZoom === false || state !== STATE.NONE && state !== STATE.ROTATE) return;
  33188. event.preventDefault();
  33189. event.stopPropagation();
  33190. scope.dispatchEvent(startEvent);
  33191. handleMouseWheel(event);
  33192. scope.dispatchEvent(endEvent);
  33193. }
  33194. function onKeyDown(event) {
  33195. if (scope.enabled === false || scope.enableKeys === false || scope.enablePan === false) return;
  33196. handleKeyDown(event);
  33197. }
  33198. function onTouchStart(event) {
  33199. if (scope.enabled === false) return;
  33200. event.preventDefault();
  33201. switch (event.touches.length) {
  33202. case 1:
  33203. switch (scope.touches.ONE) {
  33204. case _threeModule.TOUCH.ROTATE:
  33205. if (scope.enableRotate === false) return;
  33206. handleTouchStartRotate(event);
  33207. state = STATE.TOUCH_ROTATE;
  33208. break;
  33209. case _threeModule.TOUCH.PAN:
  33210. if (scope.enablePan === false) return;
  33211. handleTouchStartPan(event);
  33212. state = STATE.TOUCH_PAN;
  33213. break;
  33214. default:
  33215. state = STATE.NONE;
  33216. }
  33217. break;
  33218. case 2:
  33219. switch (scope.touches.TWO) {
  33220. case _threeModule.TOUCH.DOLLY_PAN:
  33221. if (scope.enableZoom === false && scope.enablePan === false) return;
  33222. handleTouchStartDollyPan(event);
  33223. state = STATE.TOUCH_DOLLY_PAN;
  33224. break;
  33225. case _threeModule.TOUCH.DOLLY_ROTATE:
  33226. if (scope.enableZoom === false && scope.enableRotate === false) return;
  33227. handleTouchStartDollyRotate(event);
  33228. state = STATE.TOUCH_DOLLY_ROTATE;
  33229. break;
  33230. default:
  33231. state = STATE.NONE;
  33232. }
  33233. break;
  33234. default:
  33235. state = STATE.NONE;
  33236. }
  33237. if (state !== STATE.NONE) {
  33238. scope.dispatchEvent(startEvent);
  33239. }
  33240. }
  33241. function onTouchMove(event) {
  33242. if (scope.enabled === false) return;
  33243. event.preventDefault();
  33244. event.stopPropagation();
  33245. switch (state) {
  33246. case STATE.TOUCH_ROTATE:
  33247. if (scope.enableRotate === false) return;
  33248. handleTouchMoveRotate(event);
  33249. scope.update();
  33250. break;
  33251. case STATE.TOUCH_PAN:
  33252. if (scope.enablePan === false) return;
  33253. handleTouchMovePan(event);
  33254. scope.update();
  33255. break;
  33256. case STATE.TOUCH_DOLLY_PAN:
  33257. if (scope.enableZoom === false && scope.enablePan === false) return;
  33258. handleTouchMoveDollyPan(event);
  33259. scope.update();
  33260. break;
  33261. case STATE.TOUCH_DOLLY_ROTATE:
  33262. if (scope.enableZoom === false && scope.enableRotate === false) return;
  33263. handleTouchMoveDollyRotate(event);
  33264. scope.update();
  33265. break;
  33266. default:
  33267. state = STATE.NONE;
  33268. }
  33269. }
  33270. function onTouchEnd(event) {
  33271. if (scope.enabled === false) return;
  33272. handleTouchEnd(event);
  33273. scope.dispatchEvent(endEvent);
  33274. state = STATE.NONE;
  33275. }
  33276. function onContextMenu(event) {
  33277. if (scope.enabled === false) return;
  33278. event.preventDefault();
  33279. } //
  33280. scope.domElement.addEventListener('contextmenu', onContextMenu, false);
  33281. scope.domElement.addEventListener('mousedown', onMouseDown, false);
  33282. scope.domElement.addEventListener('wheel', onMouseWheel, false);
  33283. scope.domElement.addEventListener('touchstart', onTouchStart, false);
  33284. scope.domElement.addEventListener('touchend', onTouchEnd, false);
  33285. scope.domElement.addEventListener('touchmove', onTouchMove, false);
  33286. window.addEventListener('keydown', onKeyDown, false); // force an update at start
  33287. this.update();
  33288. };
  33289. exports.OrbitControls = OrbitControls;
  33290. OrbitControls.prototype = Object.create(_threeModule.EventDispatcher.prototype);
  33291. OrbitControls.prototype.constructor = OrbitControls; // This set of controls performs orbiting, dollying (zooming), and panning.
  33292. // Unlike TrackballControls, it maintains the "up" direction object.up (+Y by default).
  33293. // This is very similar to OrbitControls, another set of touch behavior
  33294. //
  33295. // Orbit - right mouse, or left mouse + ctrl/meta/shiftKey / touch: two-finger rotate
  33296. // Zoom - middle mouse, or mousewheel / touch: two-finger spread or squish
  33297. // Pan - left mouse, or arrow keys / touch: one-finger move
  33298. var MapControls = function (object, domElement) {
  33299. OrbitControls.call(this, object, domElement);
  33300. this.mouseButtons.LEFT = _threeModule.MOUSE.PAN;
  33301. this.mouseButtons.RIGHT = _threeModule.MOUSE.ROTATE;
  33302. this.touches.ONE = _threeModule.TOUCH.PAN;
  33303. this.touches.TWO = _threeModule.TOUCH.DOLLY_ROTATE;
  33304. };
  33305. exports.MapControls = MapControls;
  33306. MapControls.prototype = Object.create(_threeModule.EventDispatcher.prototype);
  33307. MapControls.prototype.constructor = MapControls;
  33308. },{"../../../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) {
  33309. "use strict";
  33310. Object.defineProperty(exports, "__esModule", {
  33311. value: true
  33312. });
  33313. exports.default = exports.GUI = exports.gui = exports.dom = exports.controllers = exports.color = void 0;
  33314. /**
  33315. * dat-gui JavaScript Controller Library
  33316. * http://code.google.com/p/dat-gui
  33317. *
  33318. * Copyright 2011 Data Arts Team, Google Creative Lab
  33319. *
  33320. * Licensed under the Apache License, Version 2.0 (the "License");
  33321. * you may not use this file except in compliance with the License.
  33322. * You may obtain a copy of the License at
  33323. *
  33324. * http://www.apache.org/licenses/LICENSE-2.0
  33325. */
  33326. function ___$insertStyle(css) {
  33327. if (!css) {
  33328. return;
  33329. }
  33330. if (typeof window === 'undefined') {
  33331. return;
  33332. }
  33333. var style = document.createElement('style');
  33334. style.setAttribute('type', 'text/css');
  33335. style.innerHTML = css;
  33336. document.head.appendChild(style);
  33337. return css;
  33338. }
  33339. function colorToString(color, forceCSSHex) {
  33340. var colorFormat = color.__state.conversionName.toString();
  33341. var r = Math.round(color.r);
  33342. var g = Math.round(color.g);
  33343. var b = Math.round(color.b);
  33344. var a = color.a;
  33345. var h = Math.round(color.h);
  33346. var s = color.s.toFixed(1);
  33347. var v = color.v.toFixed(1);
  33348. if (forceCSSHex || colorFormat === 'THREE_CHAR_HEX' || colorFormat === 'SIX_CHAR_HEX') {
  33349. var str = color.hex.toString(16);
  33350. while (str.length < 6) {
  33351. str = '0' + str;
  33352. }
  33353. return '#' + str;
  33354. } else if (colorFormat === 'CSS_RGB') {
  33355. return 'rgb(' + r + ',' + g + ',' + b + ')';
  33356. } else if (colorFormat === 'CSS_RGBA') {
  33357. return 'rgba(' + r + ',' + g + ',' + b + ',' + a + ')';
  33358. } else if (colorFormat === 'HEX') {
  33359. return '0x' + color.hex.toString(16);
  33360. } else if (colorFormat === 'RGB_ARRAY') {
  33361. return '[' + r + ',' + g + ',' + b + ']';
  33362. } else if (colorFormat === 'RGBA_ARRAY') {
  33363. return '[' + r + ',' + g + ',' + b + ',' + a + ']';
  33364. } else if (colorFormat === 'RGB_OBJ') {
  33365. return '{r:' + r + ',g:' + g + ',b:' + b + '}';
  33366. } else if (colorFormat === 'RGBA_OBJ') {
  33367. return '{r:' + r + ',g:' + g + ',b:' + b + ',a:' + a + '}';
  33368. } else if (colorFormat === 'HSV_OBJ') {
  33369. return '{h:' + h + ',s:' + s + ',v:' + v + '}';
  33370. } else if (colorFormat === 'HSVA_OBJ') {
  33371. return '{h:' + h + ',s:' + s + ',v:' + v + ',a:' + a + '}';
  33372. }
  33373. return 'unknown format';
  33374. }
  33375. var ARR_EACH = Array.prototype.forEach;
  33376. var ARR_SLICE = Array.prototype.slice;
  33377. var Common = {
  33378. BREAK: {},
  33379. extend: function extend(target) {
  33380. this.each(ARR_SLICE.call(arguments, 1), function (obj) {
  33381. var keys = this.isObject(obj) ? Object.keys(obj) : [];
  33382. keys.forEach(function (key) {
  33383. if (!this.isUndefined(obj[key])) {
  33384. target[key] = obj[key];
  33385. }
  33386. }.bind(this));
  33387. }, this);
  33388. return target;
  33389. },
  33390. defaults: function defaults(target) {
  33391. this.each(ARR_SLICE.call(arguments, 1), function (obj) {
  33392. var keys = this.isObject(obj) ? Object.keys(obj) : [];
  33393. keys.forEach(function (key) {
  33394. if (this.isUndefined(target[key])) {
  33395. target[key] = obj[key];
  33396. }
  33397. }.bind(this));
  33398. }, this);
  33399. return target;
  33400. },
  33401. compose: function compose() {
  33402. var toCall = ARR_SLICE.call(arguments);
  33403. return function () {
  33404. var args = ARR_SLICE.call(arguments);
  33405. for (var i = toCall.length - 1; i >= 0; i--) {
  33406. args = [toCall[i].apply(this, args)];
  33407. }
  33408. return args[0];
  33409. };
  33410. },
  33411. each: function each(obj, itr, scope) {
  33412. if (!obj) {
  33413. return;
  33414. }
  33415. if (ARR_EACH && obj.forEach && obj.forEach === ARR_EACH) {
  33416. obj.forEach(itr, scope);
  33417. } else if (obj.length === obj.length + 0) {
  33418. var key = void 0;
  33419. var l = void 0;
  33420. for (key = 0, l = obj.length; key < l; key++) {
  33421. if (key in obj && itr.call(scope, obj[key], key) === this.BREAK) {
  33422. return;
  33423. }
  33424. }
  33425. } else {
  33426. for (var _key in obj) {
  33427. if (itr.call(scope, obj[_key], _key) === this.BREAK) {
  33428. return;
  33429. }
  33430. }
  33431. }
  33432. },
  33433. defer: function defer(fnc) {
  33434. setTimeout(fnc, 0);
  33435. },
  33436. debounce: function debounce(func, threshold, callImmediately) {
  33437. var timeout = void 0;
  33438. return function () {
  33439. var obj = this;
  33440. var args = arguments;
  33441. function delayed() {
  33442. timeout = null;
  33443. if (!callImmediately) func.apply(obj, args);
  33444. }
  33445. var callNow = callImmediately || !timeout;
  33446. clearTimeout(timeout);
  33447. timeout = setTimeout(delayed, threshold);
  33448. if (callNow) {
  33449. func.apply(obj, args);
  33450. }
  33451. };
  33452. },
  33453. toArray: function toArray(obj) {
  33454. if (obj.toArray) return obj.toArray();
  33455. return ARR_SLICE.call(obj);
  33456. },
  33457. isUndefined: function isUndefined(obj) {
  33458. return obj === undefined;
  33459. },
  33460. isNull: function isNull(obj) {
  33461. return obj === null;
  33462. },
  33463. isNaN: function (_isNaN) {
  33464. function isNaN() {
  33465. return _isNaN.apply(this, arguments);
  33466. }
  33467. isNaN.toString = function () {
  33468. return _isNaN.toString();
  33469. };
  33470. return isNaN;
  33471. }(function (obj) {
  33472. return isNaN(obj);
  33473. }),
  33474. isArray: Array.isArray || function (obj) {
  33475. return obj.constructor === Array;
  33476. },
  33477. isObject: function isObject(obj) {
  33478. return obj === Object(obj);
  33479. },
  33480. isNumber: function isNumber(obj) {
  33481. return obj === obj + 0;
  33482. },
  33483. isString: function isString(obj) {
  33484. return obj === obj + '';
  33485. },
  33486. isBoolean: function isBoolean(obj) {
  33487. return obj === false || obj === true;
  33488. },
  33489. isFunction: function isFunction(obj) {
  33490. return Object.prototype.toString.call(obj) === '[object Function]';
  33491. }
  33492. };
  33493. var INTERPRETATIONS = [{
  33494. litmus: Common.isString,
  33495. conversions: {
  33496. THREE_CHAR_HEX: {
  33497. read: function read(original) {
  33498. var test = original.match(/^#([A-F0-9])([A-F0-9])([A-F0-9])$/i);
  33499. if (test === null) {
  33500. return false;
  33501. }
  33502. return {
  33503. space: 'HEX',
  33504. hex: parseInt('0x' + test[1].toString() + test[1].toString() + test[2].toString() + test[2].toString() + test[3].toString() + test[3].toString(), 0)
  33505. };
  33506. },
  33507. write: colorToString
  33508. },
  33509. SIX_CHAR_HEX: {
  33510. read: function read(original) {
  33511. var test = original.match(/^#([A-F0-9]{6})$/i);
  33512. if (test === null) {
  33513. return false;
  33514. }
  33515. return {
  33516. space: 'HEX',
  33517. hex: parseInt('0x' + test[1].toString(), 0)
  33518. };
  33519. },
  33520. write: colorToString
  33521. },
  33522. CSS_RGB: {
  33523. read: function read(original) {
  33524. var test = original.match(/^rgb\(\s*(.+)\s*,\s*(.+)\s*,\s*(.+)\s*\)/);
  33525. if (test === null) {
  33526. return false;
  33527. }
  33528. return {
  33529. space: 'RGB',
  33530. r: parseFloat(test[1]),
  33531. g: parseFloat(test[2]),
  33532. b: parseFloat(test[3])
  33533. };
  33534. },
  33535. write: colorToString
  33536. },
  33537. CSS_RGBA: {
  33538. read: function read(original) {
  33539. var test = original.match(/^rgba\(\s*(.+)\s*,\s*(.+)\s*,\s*(.+)\s*,\s*(.+)\s*\)/);
  33540. if (test === null) {
  33541. return false;
  33542. }
  33543. return {
  33544. space: 'RGB',
  33545. r: parseFloat(test[1]),
  33546. g: parseFloat(test[2]),
  33547. b: parseFloat(test[3]),
  33548. a: parseFloat(test[4])
  33549. };
  33550. },
  33551. write: colorToString
  33552. }
  33553. }
  33554. }, {
  33555. litmus: Common.isNumber,
  33556. conversions: {
  33557. HEX: {
  33558. read: function read(original) {
  33559. return {
  33560. space: 'HEX',
  33561. hex: original,
  33562. conversionName: 'HEX'
  33563. };
  33564. },
  33565. write: function write(color) {
  33566. return color.hex;
  33567. }
  33568. }
  33569. }
  33570. }, {
  33571. litmus: Common.isArray,
  33572. conversions: {
  33573. RGB_ARRAY: {
  33574. read: function read(original) {
  33575. if (original.length !== 3) {
  33576. return false;
  33577. }
  33578. return {
  33579. space: 'RGB',
  33580. r: original[0],
  33581. g: original[1],
  33582. b: original[2]
  33583. };
  33584. },
  33585. write: function write(color) {
  33586. return [color.r, color.g, color.b];
  33587. }
  33588. },
  33589. RGBA_ARRAY: {
  33590. read: function read(original) {
  33591. if (original.length !== 4) return false;
  33592. return {
  33593. space: 'RGB',
  33594. r: original[0],
  33595. g: original[1],
  33596. b: original[2],
  33597. a: original[3]
  33598. };
  33599. },
  33600. write: function write(color) {
  33601. return [color.r, color.g, color.b, color.a];
  33602. }
  33603. }
  33604. }
  33605. }, {
  33606. litmus: Common.isObject,
  33607. conversions: {
  33608. RGBA_OBJ: {
  33609. read: function read(original) {
  33610. if (Common.isNumber(original.r) && Common.isNumber(original.g) && Common.isNumber(original.b) && Common.isNumber(original.a)) {
  33611. return {
  33612. space: 'RGB',
  33613. r: original.r,
  33614. g: original.g,
  33615. b: original.b,
  33616. a: original.a
  33617. };
  33618. }
  33619. return false;
  33620. },
  33621. write: function write(color) {
  33622. return {
  33623. r: color.r,
  33624. g: color.g,
  33625. b: color.b,
  33626. a: color.a
  33627. };
  33628. }
  33629. },
  33630. RGB_OBJ: {
  33631. read: function read(original) {
  33632. if (Common.isNumber(original.r) && Common.isNumber(original.g) && Common.isNumber(original.b)) {
  33633. return {
  33634. space: 'RGB',
  33635. r: original.r,
  33636. g: original.g,
  33637. b: original.b
  33638. };
  33639. }
  33640. return false;
  33641. },
  33642. write: function write(color) {
  33643. return {
  33644. r: color.r,
  33645. g: color.g,
  33646. b: color.b
  33647. };
  33648. }
  33649. },
  33650. HSVA_OBJ: {
  33651. read: function read(original) {
  33652. if (Common.isNumber(original.h) && Common.isNumber(original.s) && Common.isNumber(original.v) && Common.isNumber(original.a)) {
  33653. return {
  33654. space: 'HSV',
  33655. h: original.h,
  33656. s: original.s,
  33657. v: original.v,
  33658. a: original.a
  33659. };
  33660. }
  33661. return false;
  33662. },
  33663. write: function write(color) {
  33664. return {
  33665. h: color.h,
  33666. s: color.s,
  33667. v: color.v,
  33668. a: color.a
  33669. };
  33670. }
  33671. },
  33672. HSV_OBJ: {
  33673. read: function read(original) {
  33674. if (Common.isNumber(original.h) && Common.isNumber(original.s) && Common.isNumber(original.v)) {
  33675. return {
  33676. space: 'HSV',
  33677. h: original.h,
  33678. s: original.s,
  33679. v: original.v
  33680. };
  33681. }
  33682. return false;
  33683. },
  33684. write: function write(color) {
  33685. return {
  33686. h: color.h,
  33687. s: color.s,
  33688. v: color.v
  33689. };
  33690. }
  33691. }
  33692. }
  33693. }];
  33694. var result = void 0;
  33695. var toReturn = void 0;
  33696. var interpret = function interpret() {
  33697. toReturn = false;
  33698. var original = arguments.length > 1 ? Common.toArray(arguments) : arguments[0];
  33699. Common.each(INTERPRETATIONS, function (family) {
  33700. if (family.litmus(original)) {
  33701. Common.each(family.conversions, function (conversion, conversionName) {
  33702. result = conversion.read(original);
  33703. if (toReturn === false && result !== false) {
  33704. toReturn = result;
  33705. result.conversionName = conversionName;
  33706. result.conversion = conversion;
  33707. return Common.BREAK;
  33708. }
  33709. });
  33710. return Common.BREAK;
  33711. }
  33712. });
  33713. return toReturn;
  33714. };
  33715. var tmpComponent = void 0;
  33716. var ColorMath = {
  33717. hsv_to_rgb: function hsv_to_rgb(h, s, v) {
  33718. var hi = Math.floor(h / 60) % 6;
  33719. var f = h / 60 - Math.floor(h / 60);
  33720. var p = v * (1.0 - s);
  33721. var q = v * (1.0 - f * s);
  33722. var t = v * (1.0 - (1.0 - f) * s);
  33723. var c = [[v, t, p], [q, v, p], [p, v, t], [p, q, v], [t, p, v], [v, p, q]][hi];
  33724. return {
  33725. r: c[0] * 255,
  33726. g: c[1] * 255,
  33727. b: c[2] * 255
  33728. };
  33729. },
  33730. rgb_to_hsv: function rgb_to_hsv(r, g, b) {
  33731. var min = Math.min(r, g, b);
  33732. var max = Math.max(r, g, b);
  33733. var delta = max - min;
  33734. var h = void 0;
  33735. var s = void 0;
  33736. if (max !== 0) {
  33737. s = delta / max;
  33738. } else {
  33739. return {
  33740. h: NaN,
  33741. s: 0,
  33742. v: 0
  33743. };
  33744. }
  33745. if (r === max) {
  33746. h = (g - b) / delta;
  33747. } else if (g === max) {
  33748. h = 2 + (b - r) / delta;
  33749. } else {
  33750. h = 4 + (r - g) / delta;
  33751. }
  33752. h /= 6;
  33753. if (h < 0) {
  33754. h += 1;
  33755. }
  33756. return {
  33757. h: h * 360,
  33758. s: s,
  33759. v: max / 255
  33760. };
  33761. },
  33762. rgb_to_hex: function rgb_to_hex(r, g, b) {
  33763. var hex = this.hex_with_component(0, 2, r);
  33764. hex = this.hex_with_component(hex, 1, g);
  33765. hex = this.hex_with_component(hex, 0, b);
  33766. return hex;
  33767. },
  33768. component_from_hex: function component_from_hex(hex, componentIndex) {
  33769. return hex >> componentIndex * 8 & 0xFF;
  33770. },
  33771. hex_with_component: function hex_with_component(hex, componentIndex, value) {
  33772. return value << (tmpComponent = componentIndex * 8) | hex & ~(0xFF << tmpComponent);
  33773. }
  33774. };
  33775. var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) {
  33776. return typeof obj;
  33777. } : function (obj) {
  33778. return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
  33779. };
  33780. var classCallCheck = function (instance, Constructor) {
  33781. if (!(instance instanceof Constructor)) {
  33782. throw new TypeError("Cannot call a class as a function");
  33783. }
  33784. };
  33785. var createClass = function () {
  33786. function defineProperties(target, props) {
  33787. for (var i = 0; i < props.length; i++) {
  33788. var descriptor = props[i];
  33789. descriptor.enumerable = descriptor.enumerable || false;
  33790. descriptor.configurable = true;
  33791. if ("value" in descriptor) descriptor.writable = true;
  33792. Object.defineProperty(target, descriptor.key, descriptor);
  33793. }
  33794. }
  33795. return function (Constructor, protoProps, staticProps) {
  33796. if (protoProps) defineProperties(Constructor.prototype, protoProps);
  33797. if (staticProps) defineProperties(Constructor, staticProps);
  33798. return Constructor;
  33799. };
  33800. }();
  33801. var get = function get(object, property, receiver) {
  33802. if (object === null) object = Function.prototype;
  33803. var desc = Object.getOwnPropertyDescriptor(object, property);
  33804. if (desc === undefined) {
  33805. var parent = Object.getPrototypeOf(object);
  33806. if (parent === null) {
  33807. return undefined;
  33808. } else {
  33809. return get(parent, property, receiver);
  33810. }
  33811. } else if ("value" in desc) {
  33812. return desc.value;
  33813. } else {
  33814. var getter = desc.get;
  33815. if (getter === undefined) {
  33816. return undefined;
  33817. }
  33818. return getter.call(receiver);
  33819. }
  33820. };
  33821. var inherits = function (subClass, superClass) {
  33822. if (typeof superClass !== "function" && superClass !== null) {
  33823. throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);
  33824. }
  33825. subClass.prototype = Object.create(superClass && superClass.prototype, {
  33826. constructor: {
  33827. value: subClass,
  33828. enumerable: false,
  33829. writable: true,
  33830. configurable: true
  33831. }
  33832. });
  33833. if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
  33834. };
  33835. var possibleConstructorReturn = function (self, call) {
  33836. if (!self) {
  33837. throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  33838. }
  33839. return call && (typeof call === "object" || typeof call === "function") ? call : self;
  33840. };
  33841. var Color = function () {
  33842. function Color() {
  33843. classCallCheck(this, Color);
  33844. this.__state = interpret.apply(this, arguments);
  33845. if (this.__state === false) {
  33846. throw new Error('Failed to interpret color arguments');
  33847. }
  33848. this.__state.a = this.__state.a || 1;
  33849. }
  33850. createClass(Color, [{
  33851. key: 'toString',
  33852. value: function toString() {
  33853. return colorToString(this);
  33854. }
  33855. }, {
  33856. key: 'toHexString',
  33857. value: function toHexString() {
  33858. return colorToString(this, true);
  33859. }
  33860. }, {
  33861. key: 'toOriginal',
  33862. value: function toOriginal() {
  33863. return this.__state.conversion.write(this);
  33864. }
  33865. }]);
  33866. return Color;
  33867. }();
  33868. function defineRGBComponent(target, component, componentHexIndex) {
  33869. Object.defineProperty(target, component, {
  33870. get: function get$$1() {
  33871. if (this.__state.space === 'RGB') {
  33872. return this.__state[component];
  33873. }
  33874. Color.recalculateRGB(this, component, componentHexIndex);
  33875. return this.__state[component];
  33876. },
  33877. set: function set$$1(v) {
  33878. if (this.__state.space !== 'RGB') {
  33879. Color.recalculateRGB(this, component, componentHexIndex);
  33880. this.__state.space = 'RGB';
  33881. }
  33882. this.__state[component] = v;
  33883. }
  33884. });
  33885. }
  33886. function defineHSVComponent(target, component) {
  33887. Object.defineProperty(target, component, {
  33888. get: function get$$1() {
  33889. if (this.__state.space === 'HSV') {
  33890. return this.__state[component];
  33891. }
  33892. Color.recalculateHSV(this);
  33893. return this.__state[component];
  33894. },
  33895. set: function set$$1(v) {
  33896. if (this.__state.space !== 'HSV') {
  33897. Color.recalculateHSV(this);
  33898. this.__state.space = 'HSV';
  33899. }
  33900. this.__state[component] = v;
  33901. }
  33902. });
  33903. }
  33904. Color.recalculateRGB = function (color, component, componentHexIndex) {
  33905. if (color.__state.space === 'HEX') {
  33906. color.__state[component] = ColorMath.component_from_hex(color.__state.hex, componentHexIndex);
  33907. } else if (color.__state.space === 'HSV') {
  33908. Common.extend(color.__state, ColorMath.hsv_to_rgb(color.__state.h, color.__state.s, color.__state.v));
  33909. } else {
  33910. throw new Error('Corrupted color state');
  33911. }
  33912. };
  33913. Color.recalculateHSV = function (color) {
  33914. var result = ColorMath.rgb_to_hsv(color.r, color.g, color.b);
  33915. Common.extend(color.__state, {
  33916. s: result.s,
  33917. v: result.v
  33918. });
  33919. if (!Common.isNaN(result.h)) {
  33920. color.__state.h = result.h;
  33921. } else if (Common.isUndefined(color.__state.h)) {
  33922. color.__state.h = 0;
  33923. }
  33924. };
  33925. Color.COMPONENTS = ['r', 'g', 'b', 'h', 's', 'v', 'hex', 'a'];
  33926. defineRGBComponent(Color.prototype, 'r', 2);
  33927. defineRGBComponent(Color.prototype, 'g', 1);
  33928. defineRGBComponent(Color.prototype, 'b', 0);
  33929. defineHSVComponent(Color.prototype, 'h');
  33930. defineHSVComponent(Color.prototype, 's');
  33931. defineHSVComponent(Color.prototype, 'v');
  33932. Object.defineProperty(Color.prototype, 'a', {
  33933. get: function get$$1() {
  33934. return this.__state.a;
  33935. },
  33936. set: function set$$1(v) {
  33937. this.__state.a = v;
  33938. }
  33939. });
  33940. Object.defineProperty(Color.prototype, 'hex', {
  33941. get: function get$$1() {
  33942. if (!this.__state.space !== 'HEX') {
  33943. this.__state.hex = ColorMath.rgb_to_hex(this.r, this.g, this.b);
  33944. }
  33945. return this.__state.hex;
  33946. },
  33947. set: function set$$1(v) {
  33948. this.__state.space = 'HEX';
  33949. this.__state.hex = v;
  33950. }
  33951. });
  33952. var Controller = function () {
  33953. function Controller(object, property) {
  33954. classCallCheck(this, Controller);
  33955. this.initialValue = object[property];
  33956. this.domElement = document.createElement('div');
  33957. this.object = object;
  33958. this.property = property;
  33959. this.__onChange = undefined;
  33960. this.__onFinishChange = undefined;
  33961. }
  33962. createClass(Controller, [{
  33963. key: 'onChange',
  33964. value: function onChange(fnc) {
  33965. this.__onChange = fnc;
  33966. return this;
  33967. }
  33968. }, {
  33969. key: 'onFinishChange',
  33970. value: function onFinishChange(fnc) {
  33971. this.__onFinishChange = fnc;
  33972. return this;
  33973. }
  33974. }, {
  33975. key: 'setValue',
  33976. value: function setValue(newValue) {
  33977. this.object[this.property] = newValue;
  33978. if (this.__onChange) {
  33979. this.__onChange.call(this, newValue);
  33980. }
  33981. this.updateDisplay();
  33982. return this;
  33983. }
  33984. }, {
  33985. key: 'getValue',
  33986. value: function getValue() {
  33987. return this.object[this.property];
  33988. }
  33989. }, {
  33990. key: 'updateDisplay',
  33991. value: function updateDisplay() {
  33992. return this;
  33993. }
  33994. }, {
  33995. key: 'isModified',
  33996. value: function isModified() {
  33997. return this.initialValue !== this.getValue();
  33998. }
  33999. }]);
  34000. return Controller;
  34001. }();
  34002. var EVENT_MAP = {
  34003. HTMLEvents: ['change'],
  34004. MouseEvents: ['click', 'mousemove', 'mousedown', 'mouseup', 'mouseover'],
  34005. KeyboardEvents: ['keydown']
  34006. };
  34007. var EVENT_MAP_INV = {};
  34008. Common.each(EVENT_MAP, function (v, k) {
  34009. Common.each(v, function (e) {
  34010. EVENT_MAP_INV[e] = k;
  34011. });
  34012. });
  34013. var CSS_VALUE_PIXELS = /(\d+(\.\d+)?)px/;
  34014. function cssValueToPixels(val) {
  34015. if (val === '0' || Common.isUndefined(val)) {
  34016. return 0;
  34017. }
  34018. var match = val.match(CSS_VALUE_PIXELS);
  34019. if (!Common.isNull(match)) {
  34020. return parseFloat(match[1]);
  34021. }
  34022. return 0;
  34023. }
  34024. var dom = {
  34025. makeSelectable: function makeSelectable(elem, selectable) {
  34026. if (elem === undefined || elem.style === undefined) return;
  34027. elem.onselectstart = selectable ? function () {
  34028. return false;
  34029. } : function () {};
  34030. elem.style.MozUserSelect = selectable ? 'auto' : 'none';
  34031. elem.style.KhtmlUserSelect = selectable ? 'auto' : 'none';
  34032. elem.unselectable = selectable ? 'on' : 'off';
  34033. },
  34034. makeFullscreen: function makeFullscreen(elem, hor, vert) {
  34035. var vertical = vert;
  34036. var horizontal = hor;
  34037. if (Common.isUndefined(horizontal)) {
  34038. horizontal = true;
  34039. }
  34040. if (Common.isUndefined(vertical)) {
  34041. vertical = true;
  34042. }
  34043. elem.style.position = 'absolute';
  34044. if (horizontal) {
  34045. elem.style.left = 0;
  34046. elem.style.right = 0;
  34047. }
  34048. if (vertical) {
  34049. elem.style.top = 0;
  34050. elem.style.bottom = 0;
  34051. }
  34052. },
  34053. fakeEvent: function fakeEvent(elem, eventType, pars, aux) {
  34054. var params = pars || {};
  34055. var className = EVENT_MAP_INV[eventType];
  34056. if (!className) {
  34057. throw new Error('Event type ' + eventType + ' not supported.');
  34058. }
  34059. var evt = document.createEvent(className);
  34060. switch (className) {
  34061. case 'MouseEvents':
  34062. {
  34063. var clientX = params.x || params.clientX || 0;
  34064. var clientY = params.y || params.clientY || 0;
  34065. evt.initMouseEvent(eventType, params.bubbles || false, params.cancelable || true, window, params.clickCount || 1, 0, 0, clientX, clientY, false, false, false, false, 0, null);
  34066. break;
  34067. }
  34068. case 'KeyboardEvents':
  34069. {
  34070. var init = evt.initKeyboardEvent || evt.initKeyEvent;
  34071. Common.defaults(params, {
  34072. cancelable: true,
  34073. ctrlKey: false,
  34074. altKey: false,
  34075. shiftKey: false,
  34076. metaKey: false,
  34077. keyCode: undefined,
  34078. charCode: undefined
  34079. });
  34080. init(eventType, params.bubbles || false, params.cancelable, window, params.ctrlKey, params.altKey, params.shiftKey, params.metaKey, params.keyCode, params.charCode);
  34081. break;
  34082. }
  34083. default:
  34084. {
  34085. evt.initEvent(eventType, params.bubbles || false, params.cancelable || true);
  34086. break;
  34087. }
  34088. }
  34089. Common.defaults(evt, aux);
  34090. elem.dispatchEvent(evt);
  34091. },
  34092. bind: function bind(elem, event, func, newBool) {
  34093. var bool = newBool || false;
  34094. if (elem.addEventListener) {
  34095. elem.addEventListener(event, func, bool);
  34096. } else if (elem.attachEvent) {
  34097. elem.attachEvent('on' + event, func);
  34098. }
  34099. return dom;
  34100. },
  34101. unbind: function unbind(elem, event, func, newBool) {
  34102. var bool = newBool || false;
  34103. if (elem.removeEventListener) {
  34104. elem.removeEventListener(event, func, bool);
  34105. } else if (elem.detachEvent) {
  34106. elem.detachEvent('on' + event, func);
  34107. }
  34108. return dom;
  34109. },
  34110. addClass: function addClass(elem, className) {
  34111. if (elem.className === undefined) {
  34112. elem.className = className;
  34113. } else if (elem.className !== className) {
  34114. var classes = elem.className.split(/ +/);
  34115. if (classes.indexOf(className) === -1) {
  34116. classes.push(className);
  34117. elem.className = classes.join(' ').replace(/^\s+/, '').replace(/\s+$/, '');
  34118. }
  34119. }
  34120. return dom;
  34121. },
  34122. removeClass: function removeClass(elem, className) {
  34123. if (className) {
  34124. if (elem.className === className) {
  34125. elem.removeAttribute('class');
  34126. } else {
  34127. var classes = elem.className.split(/ +/);
  34128. var index = classes.indexOf(className);
  34129. if (index !== -1) {
  34130. classes.splice(index, 1);
  34131. elem.className = classes.join(' ');
  34132. }
  34133. }
  34134. } else {
  34135. elem.className = undefined;
  34136. }
  34137. return dom;
  34138. },
  34139. hasClass: function hasClass(elem, className) {
  34140. return new RegExp('(?:^|\\s+)' + className + '(?:\\s+|$)').test(elem.className) || false;
  34141. },
  34142. getWidth: function getWidth(elem) {
  34143. var style = getComputedStyle(elem);
  34144. return cssValueToPixels(style['border-left-width']) + cssValueToPixels(style['border-right-width']) + cssValueToPixels(style['padding-left']) + cssValueToPixels(style['padding-right']) + cssValueToPixels(style.width);
  34145. },
  34146. getHeight: function getHeight(elem) {
  34147. var style = getComputedStyle(elem);
  34148. return cssValueToPixels(style['border-top-width']) + cssValueToPixels(style['border-bottom-width']) + cssValueToPixels(style['padding-top']) + cssValueToPixels(style['padding-bottom']) + cssValueToPixels(style.height);
  34149. },
  34150. getOffset: function getOffset(el) {
  34151. var elem = el;
  34152. var offset = {
  34153. left: 0,
  34154. top: 0
  34155. };
  34156. if (elem.offsetParent) {
  34157. do {
  34158. offset.left += elem.offsetLeft;
  34159. offset.top += elem.offsetTop;
  34160. elem = elem.offsetParent;
  34161. } while (elem);
  34162. }
  34163. return offset;
  34164. },
  34165. isActive: function isActive(elem) {
  34166. return elem === document.activeElement && (elem.type || elem.href);
  34167. }
  34168. };
  34169. var BooleanController = function (_Controller) {
  34170. inherits(BooleanController, _Controller);
  34171. function BooleanController(object, property) {
  34172. classCallCheck(this, BooleanController);
  34173. var _this2 = possibleConstructorReturn(this, (BooleanController.__proto__ || Object.getPrototypeOf(BooleanController)).call(this, object, property));
  34174. var _this = _this2;
  34175. _this2.__prev = _this2.getValue();
  34176. _this2.__checkbox = document.createElement('input');
  34177. _this2.__checkbox.setAttribute('type', 'checkbox');
  34178. function onChange() {
  34179. _this.setValue(!_this.__prev);
  34180. }
  34181. dom.bind(_this2.__checkbox, 'change', onChange, false);
  34182. _this2.domElement.appendChild(_this2.__checkbox);
  34183. _this2.updateDisplay();
  34184. return _this2;
  34185. }
  34186. createClass(BooleanController, [{
  34187. key: 'setValue',
  34188. value: function setValue(v) {
  34189. var toReturn = get(BooleanController.prototype.__proto__ || Object.getPrototypeOf(BooleanController.prototype), 'setValue', this).call(this, v);
  34190. if (this.__onFinishChange) {
  34191. this.__onFinishChange.call(this, this.getValue());
  34192. }
  34193. this.__prev = this.getValue();
  34194. return toReturn;
  34195. }
  34196. }, {
  34197. key: 'updateDisplay',
  34198. value: function updateDisplay() {
  34199. if (this.getValue() === true) {
  34200. this.__checkbox.setAttribute('checked', 'checked');
  34201. this.__checkbox.checked = true;
  34202. this.__prev = true;
  34203. } else {
  34204. this.__checkbox.checked = false;
  34205. this.__prev = false;
  34206. }
  34207. return get(BooleanController.prototype.__proto__ || Object.getPrototypeOf(BooleanController.prototype), 'updateDisplay', this).call(this);
  34208. }
  34209. }]);
  34210. return BooleanController;
  34211. }(Controller);
  34212. var OptionController = function (_Controller) {
  34213. inherits(OptionController, _Controller);
  34214. function OptionController(object, property, opts) {
  34215. classCallCheck(this, OptionController);
  34216. var _this2 = possibleConstructorReturn(this, (OptionController.__proto__ || Object.getPrototypeOf(OptionController)).call(this, object, property));
  34217. var options = opts;
  34218. var _this = _this2;
  34219. _this2.__select = document.createElement('select');
  34220. if (Common.isArray(options)) {
  34221. var map = {};
  34222. Common.each(options, function (element) {
  34223. map[element] = element;
  34224. });
  34225. options = map;
  34226. }
  34227. Common.each(options, function (value, key) {
  34228. var opt = document.createElement('option');
  34229. opt.innerHTML = key;
  34230. opt.setAttribute('value', value);
  34231. _this.__select.appendChild(opt);
  34232. });
  34233. _this2.updateDisplay();
  34234. dom.bind(_this2.__select, 'change', function () {
  34235. var desiredValue = this.options[this.selectedIndex].value;
  34236. _this.setValue(desiredValue);
  34237. });
  34238. _this2.domElement.appendChild(_this2.__select);
  34239. return _this2;
  34240. }
  34241. createClass(OptionController, [{
  34242. key: 'setValue',
  34243. value: function setValue(v) {
  34244. var toReturn = get(OptionController.prototype.__proto__ || Object.getPrototypeOf(OptionController.prototype), 'setValue', this).call(this, v);
  34245. if (this.__onFinishChange) {
  34246. this.__onFinishChange.call(this, this.getValue());
  34247. }
  34248. return toReturn;
  34249. }
  34250. }, {
  34251. key: 'updateDisplay',
  34252. value: function updateDisplay() {
  34253. if (dom.isActive(this.__select)) return this;
  34254. this.__select.value = this.getValue();
  34255. return get(OptionController.prototype.__proto__ || Object.getPrototypeOf(OptionController.prototype), 'updateDisplay', this).call(this);
  34256. }
  34257. }]);
  34258. return OptionController;
  34259. }(Controller);
  34260. var StringController = function (_Controller) {
  34261. inherits(StringController, _Controller);
  34262. function StringController(object, property) {
  34263. classCallCheck(this, StringController);
  34264. var _this2 = possibleConstructorReturn(this, (StringController.__proto__ || Object.getPrototypeOf(StringController)).call(this, object, property));
  34265. var _this = _this2;
  34266. function onChange() {
  34267. _this.setValue(_this.__input.value);
  34268. }
  34269. function onBlur() {
  34270. if (_this.__onFinishChange) {
  34271. _this.__onFinishChange.call(_this, _this.getValue());
  34272. }
  34273. }
  34274. _this2.__input = document.createElement('input');
  34275. _this2.__input.setAttribute('type', 'text');
  34276. dom.bind(_this2.__input, 'keyup', onChange);
  34277. dom.bind(_this2.__input, 'change', onChange);
  34278. dom.bind(_this2.__input, 'blur', onBlur);
  34279. dom.bind(_this2.__input, 'keydown', function (e) {
  34280. if (e.keyCode === 13) {
  34281. this.blur();
  34282. }
  34283. });
  34284. _this2.updateDisplay();
  34285. _this2.domElement.appendChild(_this2.__input);
  34286. return _this2;
  34287. }
  34288. createClass(StringController, [{
  34289. key: 'updateDisplay',
  34290. value: function updateDisplay() {
  34291. if (!dom.isActive(this.__input)) {
  34292. this.__input.value = this.getValue();
  34293. }
  34294. return get(StringController.prototype.__proto__ || Object.getPrototypeOf(StringController.prototype), 'updateDisplay', this).call(this);
  34295. }
  34296. }]);
  34297. return StringController;
  34298. }(Controller);
  34299. function numDecimals(x) {
  34300. var _x = x.toString();
  34301. if (_x.indexOf('.') > -1) {
  34302. return _x.length - _x.indexOf('.') - 1;
  34303. }
  34304. return 0;
  34305. }
  34306. var NumberController = function (_Controller) {
  34307. inherits(NumberController, _Controller);
  34308. function NumberController(object, property, params) {
  34309. classCallCheck(this, NumberController);
  34310. var _this = possibleConstructorReturn(this, (NumberController.__proto__ || Object.getPrototypeOf(NumberController)).call(this, object, property));
  34311. var _params = params || {};
  34312. _this.__min = _params.min;
  34313. _this.__max = _params.max;
  34314. _this.__step = _params.step;
  34315. if (Common.isUndefined(_this.__step)) {
  34316. if (_this.initialValue === 0) {
  34317. _this.__impliedStep = 1;
  34318. } else {
  34319. _this.__impliedStep = Math.pow(10, Math.floor(Math.log(Math.abs(_this.initialValue)) / Math.LN10)) / 10;
  34320. }
  34321. } else {
  34322. _this.__impliedStep = _this.__step;
  34323. }
  34324. _this.__precision = numDecimals(_this.__impliedStep);
  34325. return _this;
  34326. }
  34327. createClass(NumberController, [{
  34328. key: 'setValue',
  34329. value: function setValue(v) {
  34330. var _v = v;
  34331. if (this.__min !== undefined && _v < this.__min) {
  34332. _v = this.__min;
  34333. } else if (this.__max !== undefined && _v > this.__max) {
  34334. _v = this.__max;
  34335. }
  34336. if (this.__step !== undefined && _v % this.__step !== 0) {
  34337. _v = Math.round(_v / this.__step) * this.__step;
  34338. }
  34339. return get(NumberController.prototype.__proto__ || Object.getPrototypeOf(NumberController.prototype), 'setValue', this).call(this, _v);
  34340. }
  34341. }, {
  34342. key: 'min',
  34343. value: function min(minValue) {
  34344. this.__min = minValue;
  34345. return this;
  34346. }
  34347. }, {
  34348. key: 'max',
  34349. value: function max(maxValue) {
  34350. this.__max = maxValue;
  34351. return this;
  34352. }
  34353. }, {
  34354. key: 'step',
  34355. value: function step(stepValue) {
  34356. this.__step = stepValue;
  34357. this.__impliedStep = stepValue;
  34358. this.__precision = numDecimals(stepValue);
  34359. return this;
  34360. }
  34361. }]);
  34362. return NumberController;
  34363. }(Controller);
  34364. function roundToDecimal(value, decimals) {
  34365. var tenTo = Math.pow(10, decimals);
  34366. return Math.round(value * tenTo) / tenTo;
  34367. }
  34368. var NumberControllerBox = function (_NumberController) {
  34369. inherits(NumberControllerBox, _NumberController);
  34370. function NumberControllerBox(object, property, params) {
  34371. classCallCheck(this, NumberControllerBox);
  34372. var _this2 = possibleConstructorReturn(this, (NumberControllerBox.__proto__ || Object.getPrototypeOf(NumberControllerBox)).call(this, object, property, params));
  34373. _this2.__truncationSuspended = false;
  34374. var _this = _this2;
  34375. var prevY = void 0;
  34376. function onChange() {
  34377. var attempted = parseFloat(_this.__input.value);
  34378. if (!Common.isNaN(attempted)) {
  34379. _this.setValue(attempted);
  34380. }
  34381. }
  34382. function onFinish() {
  34383. if (_this.__onFinishChange) {
  34384. _this.__onFinishChange.call(_this, _this.getValue());
  34385. }
  34386. }
  34387. function onBlur() {
  34388. onFinish();
  34389. }
  34390. function onMouseDrag(e) {
  34391. var diff = prevY - e.clientY;
  34392. _this.setValue(_this.getValue() + diff * _this.__impliedStep);
  34393. prevY = e.clientY;
  34394. }
  34395. function onMouseUp() {
  34396. dom.unbind(window, 'mousemove', onMouseDrag);
  34397. dom.unbind(window, 'mouseup', onMouseUp);
  34398. onFinish();
  34399. }
  34400. function onMouseDown(e) {
  34401. dom.bind(window, 'mousemove', onMouseDrag);
  34402. dom.bind(window, 'mouseup', onMouseUp);
  34403. prevY = e.clientY;
  34404. }
  34405. _this2.__input = document.createElement('input');
  34406. _this2.__input.setAttribute('type', 'text');
  34407. dom.bind(_this2.__input, 'change', onChange);
  34408. dom.bind(_this2.__input, 'blur', onBlur);
  34409. dom.bind(_this2.__input, 'mousedown', onMouseDown);
  34410. dom.bind(_this2.__input, 'keydown', function (e) {
  34411. if (e.keyCode === 13) {
  34412. _this.__truncationSuspended = true;
  34413. this.blur();
  34414. _this.__truncationSuspended = false;
  34415. onFinish();
  34416. }
  34417. });
  34418. _this2.updateDisplay();
  34419. _this2.domElement.appendChild(_this2.__input);
  34420. return _this2;
  34421. }
  34422. createClass(NumberControllerBox, [{
  34423. key: 'updateDisplay',
  34424. value: function updateDisplay() {
  34425. this.__input.value = this.__truncationSuspended ? this.getValue() : roundToDecimal(this.getValue(), this.__precision);
  34426. return get(NumberControllerBox.prototype.__proto__ || Object.getPrototypeOf(NumberControllerBox.prototype), 'updateDisplay', this).call(this);
  34427. }
  34428. }]);
  34429. return NumberControllerBox;
  34430. }(NumberController);
  34431. function map(v, i1, i2, o1, o2) {
  34432. return o1 + (o2 - o1) * ((v - i1) / (i2 - i1));
  34433. }
  34434. var NumberControllerSlider = function (_NumberController) {
  34435. inherits(NumberControllerSlider, _NumberController);
  34436. function NumberControllerSlider(object, property, min, max, step) {
  34437. classCallCheck(this, NumberControllerSlider);
  34438. var _this2 = possibleConstructorReturn(this, (NumberControllerSlider.__proto__ || Object.getPrototypeOf(NumberControllerSlider)).call(this, object, property, {
  34439. min: min,
  34440. max: max,
  34441. step: step
  34442. }));
  34443. var _this = _this2;
  34444. _this2.__background = document.createElement('div');
  34445. _this2.__foreground = document.createElement('div');
  34446. dom.bind(_this2.__background, 'mousedown', onMouseDown);
  34447. dom.bind(_this2.__background, 'touchstart', onTouchStart);
  34448. dom.addClass(_this2.__background, 'slider');
  34449. dom.addClass(_this2.__foreground, 'slider-fg');
  34450. function onMouseDown(e) {
  34451. document.activeElement.blur();
  34452. dom.bind(window, 'mousemove', onMouseDrag);
  34453. dom.bind(window, 'mouseup', onMouseUp);
  34454. onMouseDrag(e);
  34455. }
  34456. function onMouseDrag(e) {
  34457. e.preventDefault();
  34458. var bgRect = _this.__background.getBoundingClientRect();
  34459. _this.setValue(map(e.clientX, bgRect.left, bgRect.right, _this.__min, _this.__max));
  34460. return false;
  34461. }
  34462. function onMouseUp() {
  34463. dom.unbind(window, 'mousemove', onMouseDrag);
  34464. dom.unbind(window, 'mouseup', onMouseUp);
  34465. if (_this.__onFinishChange) {
  34466. _this.__onFinishChange.call(_this, _this.getValue());
  34467. }
  34468. }
  34469. function onTouchStart(e) {
  34470. if (e.touches.length !== 1) {
  34471. return;
  34472. }
  34473. dom.bind(window, 'touchmove', onTouchMove);
  34474. dom.bind(window, 'touchend', onTouchEnd);
  34475. onTouchMove(e);
  34476. }
  34477. function onTouchMove(e) {
  34478. var clientX = e.touches[0].clientX;
  34479. var bgRect = _this.__background.getBoundingClientRect();
  34480. _this.setValue(map(clientX, bgRect.left, bgRect.right, _this.__min, _this.__max));
  34481. }
  34482. function onTouchEnd() {
  34483. dom.unbind(window, 'touchmove', onTouchMove);
  34484. dom.unbind(window, 'touchend', onTouchEnd);
  34485. if (_this.__onFinishChange) {
  34486. _this.__onFinishChange.call(_this, _this.getValue());
  34487. }
  34488. }
  34489. _this2.updateDisplay();
  34490. _this2.__background.appendChild(_this2.__foreground);
  34491. _this2.domElement.appendChild(_this2.__background);
  34492. return _this2;
  34493. }
  34494. createClass(NumberControllerSlider, [{
  34495. key: 'updateDisplay',
  34496. value: function updateDisplay() {
  34497. var pct = (this.getValue() - this.__min) / (this.__max - this.__min);
  34498. this.__foreground.style.width = pct * 100 + '%';
  34499. return get(NumberControllerSlider.prototype.__proto__ || Object.getPrototypeOf(NumberControllerSlider.prototype), 'updateDisplay', this).call(this);
  34500. }
  34501. }]);
  34502. return NumberControllerSlider;
  34503. }(NumberController);
  34504. var FunctionController = function (_Controller) {
  34505. inherits(FunctionController, _Controller);
  34506. function FunctionController(object, property, text) {
  34507. classCallCheck(this, FunctionController);
  34508. var _this2 = possibleConstructorReturn(this, (FunctionController.__proto__ || Object.getPrototypeOf(FunctionController)).call(this, object, property));
  34509. var _this = _this2;
  34510. _this2.__button = document.createElement('div');
  34511. _this2.__button.innerHTML = text === undefined ? 'Fire' : text;
  34512. dom.bind(_this2.__button, 'click', function (e) {
  34513. e.preventDefault();
  34514. _this.fire();
  34515. return false;
  34516. });
  34517. dom.addClass(_this2.__button, 'button');
  34518. _this2.domElement.appendChild(_this2.__button);
  34519. return _this2;
  34520. }
  34521. createClass(FunctionController, [{
  34522. key: 'fire',
  34523. value: function fire() {
  34524. if (this.__onChange) {
  34525. this.__onChange.call(this);
  34526. }
  34527. this.getValue().call(this.object);
  34528. if (this.__onFinishChange) {
  34529. this.__onFinishChange.call(this, this.getValue());
  34530. }
  34531. }
  34532. }]);
  34533. return FunctionController;
  34534. }(Controller);
  34535. var ColorController = function (_Controller) {
  34536. inherits(ColorController, _Controller);
  34537. function ColorController(object, property) {
  34538. classCallCheck(this, ColorController);
  34539. var _this2 = possibleConstructorReturn(this, (ColorController.__proto__ || Object.getPrototypeOf(ColorController)).call(this, object, property));
  34540. _this2.__color = new Color(_this2.getValue());
  34541. _this2.__temp = new Color(0);
  34542. var _this = _this2;
  34543. _this2.domElement = document.createElement('div');
  34544. dom.makeSelectable(_this2.domElement, false);
  34545. _this2.__selector = document.createElement('div');
  34546. _this2.__selector.className = 'selector';
  34547. _this2.__saturation_field = document.createElement('div');
  34548. _this2.__saturation_field.className = 'saturation-field';
  34549. _this2.__field_knob = document.createElement('div');
  34550. _this2.__field_knob.className = 'field-knob';
  34551. _this2.__field_knob_border = '2px solid ';
  34552. _this2.__hue_knob = document.createElement('div');
  34553. _this2.__hue_knob.className = 'hue-knob';
  34554. _this2.__hue_field = document.createElement('div');
  34555. _this2.__hue_field.className = 'hue-field';
  34556. _this2.__input = document.createElement('input');
  34557. _this2.__input.type = 'text';
  34558. _this2.__input_textShadow = '0 1px 1px ';
  34559. dom.bind(_this2.__input, 'keydown', function (e) {
  34560. if (e.keyCode === 13) {
  34561. onBlur.call(this);
  34562. }
  34563. });
  34564. dom.bind(_this2.__input, 'blur', onBlur);
  34565. dom.bind(_this2.__selector, 'mousedown', function () {
  34566. dom.addClass(this, 'drag').bind(window, 'mouseup', function () {
  34567. dom.removeClass(_this.__selector, 'drag');
  34568. });
  34569. });
  34570. dom.bind(_this2.__selector, 'touchstart', function () {
  34571. dom.addClass(this, 'drag').bind(window, 'touchend', function () {
  34572. dom.removeClass(_this.__selector, 'drag');
  34573. });
  34574. });
  34575. var valueField = document.createElement('div');
  34576. Common.extend(_this2.__selector.style, {
  34577. width: '122px',
  34578. height: '102px',
  34579. padding: '3px',
  34580. backgroundColor: '#222',
  34581. boxShadow: '0px 1px 3px rgba(0,0,0,0.3)'
  34582. });
  34583. Common.extend(_this2.__field_knob.style, {
  34584. position: 'absolute',
  34585. width: '12px',
  34586. height: '12px',
  34587. border: _this2.__field_knob_border + (_this2.__color.v < 0.5 ? '#fff' : '#000'),
  34588. boxShadow: '0px 1px 3px rgba(0,0,0,0.5)',
  34589. borderRadius: '12px',
  34590. zIndex: 1
  34591. });
  34592. Common.extend(_this2.__hue_knob.style, {
  34593. position: 'absolute',
  34594. width: '15px',
  34595. height: '2px',
  34596. borderRight: '4px solid #fff',
  34597. zIndex: 1
  34598. });
  34599. Common.extend(_this2.__saturation_field.style, {
  34600. width: '100px',
  34601. height: '100px',
  34602. border: '1px solid #555',
  34603. marginRight: '3px',
  34604. display: 'inline-block',
  34605. cursor: 'pointer'
  34606. });
  34607. Common.extend(valueField.style, {
  34608. width: '100%',
  34609. height: '100%',
  34610. background: 'none'
  34611. });
  34612. linearGradient(valueField, 'top', 'rgba(0,0,0,0)', '#000');
  34613. Common.extend(_this2.__hue_field.style, {
  34614. width: '15px',
  34615. height: '100px',
  34616. border: '1px solid #555',
  34617. cursor: 'ns-resize',
  34618. position: 'absolute',
  34619. top: '3px',
  34620. right: '3px'
  34621. });
  34622. hueGradient(_this2.__hue_field);
  34623. Common.extend(_this2.__input.style, {
  34624. outline: 'none',
  34625. textAlign: 'center',
  34626. color: '#fff',
  34627. border: 0,
  34628. fontWeight: 'bold',
  34629. textShadow: _this2.__input_textShadow + 'rgba(0,0,0,0.7)'
  34630. });
  34631. dom.bind(_this2.__saturation_field, 'mousedown', fieldDown);
  34632. dom.bind(_this2.__saturation_field, 'touchstart', fieldDown);
  34633. dom.bind(_this2.__field_knob, 'mousedown', fieldDown);
  34634. dom.bind(_this2.__field_knob, 'touchstart', fieldDown);
  34635. dom.bind(_this2.__hue_field, 'mousedown', fieldDownH);
  34636. dom.bind(_this2.__hue_field, 'touchstart', fieldDownH);
  34637. function fieldDown(e) {
  34638. setSV(e);
  34639. dom.bind(window, 'mousemove', setSV);
  34640. dom.bind(window, 'touchmove', setSV);
  34641. dom.bind(window, 'mouseup', fieldUpSV);
  34642. dom.bind(window, 'touchend', fieldUpSV);
  34643. }
  34644. function fieldDownH(e) {
  34645. setH(e);
  34646. dom.bind(window, 'mousemove', setH);
  34647. dom.bind(window, 'touchmove', setH);
  34648. dom.bind(window, 'mouseup', fieldUpH);
  34649. dom.bind(window, 'touchend', fieldUpH);
  34650. }
  34651. function fieldUpSV() {
  34652. dom.unbind(window, 'mousemove', setSV);
  34653. dom.unbind(window, 'touchmove', setSV);
  34654. dom.unbind(window, 'mouseup', fieldUpSV);
  34655. dom.unbind(window, 'touchend', fieldUpSV);
  34656. onFinish();
  34657. }
  34658. function fieldUpH() {
  34659. dom.unbind(window, 'mousemove', setH);
  34660. dom.unbind(window, 'touchmove', setH);
  34661. dom.unbind(window, 'mouseup', fieldUpH);
  34662. dom.unbind(window, 'touchend', fieldUpH);
  34663. onFinish();
  34664. }
  34665. function onBlur() {
  34666. var i = interpret(this.value);
  34667. if (i !== false) {
  34668. _this.__color.__state = i;
  34669. _this.setValue(_this.__color.toOriginal());
  34670. } else {
  34671. this.value = _this.__color.toString();
  34672. }
  34673. }
  34674. function onFinish() {
  34675. if (_this.__onFinishChange) {
  34676. _this.__onFinishChange.call(_this, _this.__color.toOriginal());
  34677. }
  34678. }
  34679. _this2.__saturation_field.appendChild(valueField);
  34680. _this2.__selector.appendChild(_this2.__field_knob);
  34681. _this2.__selector.appendChild(_this2.__saturation_field);
  34682. _this2.__selector.appendChild(_this2.__hue_field);
  34683. _this2.__hue_field.appendChild(_this2.__hue_knob);
  34684. _this2.domElement.appendChild(_this2.__input);
  34685. _this2.domElement.appendChild(_this2.__selector);
  34686. _this2.updateDisplay();
  34687. function setSV(e) {
  34688. if (e.type.indexOf('touch') === -1) {
  34689. e.preventDefault();
  34690. }
  34691. var fieldRect = _this.__saturation_field.getBoundingClientRect();
  34692. var _ref = e.touches && e.touches[0] || e,
  34693. clientX = _ref.clientX,
  34694. clientY = _ref.clientY;
  34695. var s = (clientX - fieldRect.left) / (fieldRect.right - fieldRect.left);
  34696. var v = 1 - (clientY - fieldRect.top) / (fieldRect.bottom - fieldRect.top);
  34697. if (v > 1) {
  34698. v = 1;
  34699. } else if (v < 0) {
  34700. v = 0;
  34701. }
  34702. if (s > 1) {
  34703. s = 1;
  34704. } else if (s < 0) {
  34705. s = 0;
  34706. }
  34707. _this.__color.v = v;
  34708. _this.__color.s = s;
  34709. _this.setValue(_this.__color.toOriginal());
  34710. return false;
  34711. }
  34712. function setH(e) {
  34713. if (e.type.indexOf('touch') === -1) {
  34714. e.preventDefault();
  34715. }
  34716. var fieldRect = _this.__hue_field.getBoundingClientRect();
  34717. var _ref2 = e.touches && e.touches[0] || e,
  34718. clientY = _ref2.clientY;
  34719. var h = 1 - (clientY - fieldRect.top) / (fieldRect.bottom - fieldRect.top);
  34720. if (h > 1) {
  34721. h = 1;
  34722. } else if (h < 0) {
  34723. h = 0;
  34724. }
  34725. _this.__color.h = h * 360;
  34726. _this.setValue(_this.__color.toOriginal());
  34727. return false;
  34728. }
  34729. return _this2;
  34730. }
  34731. createClass(ColorController, [{
  34732. key: 'updateDisplay',
  34733. value: function updateDisplay() {
  34734. var i = interpret(this.getValue());
  34735. if (i !== false) {
  34736. var mismatch = false;
  34737. Common.each(Color.COMPONENTS, function (component) {
  34738. if (!Common.isUndefined(i[component]) && !Common.isUndefined(this.__color.__state[component]) && i[component] !== this.__color.__state[component]) {
  34739. mismatch = true;
  34740. return {};
  34741. }
  34742. }, this);
  34743. if (mismatch) {
  34744. Common.extend(this.__color.__state, i);
  34745. }
  34746. }
  34747. Common.extend(this.__temp.__state, this.__color.__state);
  34748. this.__temp.a = 1;
  34749. var flip = this.__color.v < 0.5 || this.__color.s > 0.5 ? 255 : 0;
  34750. var _flip = 255 - flip;
  34751. Common.extend(this.__field_knob.style, {
  34752. marginLeft: 100 * this.__color.s - 7 + 'px',
  34753. marginTop: 100 * (1 - this.__color.v) - 7 + 'px',
  34754. backgroundColor: this.__temp.toHexString(),
  34755. border: this.__field_knob_border + 'rgb(' + flip + ',' + flip + ',' + flip + ')'
  34756. });
  34757. this.__hue_knob.style.marginTop = (1 - this.__color.h / 360) * 100 + 'px';
  34758. this.__temp.s = 1;
  34759. this.__temp.v = 1;
  34760. linearGradient(this.__saturation_field, 'left', '#fff', this.__temp.toHexString());
  34761. this.__input.value = this.__color.toString();
  34762. Common.extend(this.__input.style, {
  34763. backgroundColor: this.__color.toHexString(),
  34764. color: 'rgb(' + flip + ',' + flip + ',' + flip + ')',
  34765. textShadow: this.__input_textShadow + 'rgba(' + _flip + ',' + _flip + ',' + _flip + ',.7)'
  34766. });
  34767. }
  34768. }]);
  34769. return ColorController;
  34770. }(Controller);
  34771. var vendors = ['-moz-', '-o-', '-webkit-', '-ms-', ''];
  34772. function linearGradient(elem, x, a, b) {
  34773. elem.style.background = '';
  34774. Common.each(vendors, function (vendor) {
  34775. elem.style.cssText += 'background: ' + vendor + 'linear-gradient(' + x + ', ' + a + ' 0%, ' + b + ' 100%); ';
  34776. });
  34777. }
  34778. function hueGradient(elem) {
  34779. elem.style.background = '';
  34780. elem.style.cssText += 'background: -moz-linear-gradient(top, #ff0000 0%, #ff00ff 17%, #0000ff 34%, #00ffff 50%, #00ff00 67%, #ffff00 84%, #ff0000 100%);';
  34781. elem.style.cssText += 'background: -webkit-linear-gradient(top, #ff0000 0%,#ff00ff 17%,#0000ff 34%,#00ffff 50%,#00ff00 67%,#ffff00 84%,#ff0000 100%);';
  34782. elem.style.cssText += 'background: -o-linear-gradient(top, #ff0000 0%,#ff00ff 17%,#0000ff 34%,#00ffff 50%,#00ff00 67%,#ffff00 84%,#ff0000 100%);';
  34783. elem.style.cssText += 'background: -ms-linear-gradient(top, #ff0000 0%,#ff00ff 17%,#0000ff 34%,#00ffff 50%,#00ff00 67%,#ffff00 84%,#ff0000 100%);';
  34784. elem.style.cssText += 'background: linear-gradient(top, #ff0000 0%,#ff00ff 17%,#0000ff 34%,#00ffff 50%,#00ff00 67%,#ffff00 84%,#ff0000 100%);';
  34785. }
  34786. var css = {
  34787. load: function load(url, indoc) {
  34788. var doc = indoc || document;
  34789. var link = doc.createElement('link');
  34790. link.type = 'text/css';
  34791. link.rel = 'stylesheet';
  34792. link.href = url;
  34793. doc.getElementsByTagName('head')[0].appendChild(link);
  34794. },
  34795. inject: function inject(cssContent, indoc) {
  34796. var doc = indoc || document;
  34797. var injected = document.createElement('style');
  34798. injected.type = 'text/css';
  34799. injected.innerHTML = cssContent;
  34800. var head = doc.getElementsByTagName('head')[0];
  34801. try {
  34802. head.appendChild(injected);
  34803. } catch (e) {}
  34804. }
  34805. };
  34806. 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>";
  34807. var ControllerFactory = function ControllerFactory(object, property) {
  34808. var initialValue = object[property];
  34809. if (Common.isArray(arguments[2]) || Common.isObject(arguments[2])) {
  34810. return new OptionController(object, property, arguments[2]);
  34811. }
  34812. if (Common.isNumber(initialValue)) {
  34813. if (Common.isNumber(arguments[2]) && Common.isNumber(arguments[3])) {
  34814. if (Common.isNumber(arguments[4])) {
  34815. return new NumberControllerSlider(object, property, arguments[2], arguments[3], arguments[4]);
  34816. }
  34817. return new NumberControllerSlider(object, property, arguments[2], arguments[3]);
  34818. }
  34819. if (Common.isNumber(arguments[4])) {
  34820. return new NumberControllerBox(object, property, {
  34821. min: arguments[2],
  34822. max: arguments[3],
  34823. step: arguments[4]
  34824. });
  34825. }
  34826. return new NumberControllerBox(object, property, {
  34827. min: arguments[2],
  34828. max: arguments[3]
  34829. });
  34830. }
  34831. if (Common.isString(initialValue)) {
  34832. return new StringController(object, property);
  34833. }
  34834. if (Common.isFunction(initialValue)) {
  34835. return new FunctionController(object, property, '');
  34836. }
  34837. if (Common.isBoolean(initialValue)) {
  34838. return new BooleanController(object, property);
  34839. }
  34840. return null;
  34841. };
  34842. function requestAnimationFrame(callback) {
  34843. setTimeout(callback, 1000 / 60);
  34844. }
  34845. var requestAnimationFrame$1 = window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || requestAnimationFrame;
  34846. var CenteredDiv = function () {
  34847. function CenteredDiv() {
  34848. classCallCheck(this, CenteredDiv);
  34849. this.backgroundElement = document.createElement('div');
  34850. Common.extend(this.backgroundElement.style, {
  34851. backgroundColor: 'rgba(0,0,0,0.8)',
  34852. top: 0,
  34853. left: 0,
  34854. display: 'none',
  34855. zIndex: '1000',
  34856. opacity: 0,
  34857. WebkitTransition: 'opacity 0.2s linear',
  34858. transition: 'opacity 0.2s linear'
  34859. });
  34860. dom.makeFullscreen(this.backgroundElement);
  34861. this.backgroundElement.style.position = 'fixed';
  34862. this.domElement = document.createElement('div');
  34863. Common.extend(this.domElement.style, {
  34864. position: 'fixed',
  34865. display: 'none',
  34866. zIndex: '1001',
  34867. opacity: 0,
  34868. WebkitTransition: '-webkit-transform 0.2s ease-out, opacity 0.2s linear',
  34869. transition: 'transform 0.2s ease-out, opacity 0.2s linear'
  34870. });
  34871. document.body.appendChild(this.backgroundElement);
  34872. document.body.appendChild(this.domElement);
  34873. var _this = this;
  34874. dom.bind(this.backgroundElement, 'click', function () {
  34875. _this.hide();
  34876. });
  34877. }
  34878. createClass(CenteredDiv, [{
  34879. key: 'show',
  34880. value: function show() {
  34881. var _this = this;
  34882. this.backgroundElement.style.display = 'block';
  34883. this.domElement.style.display = 'block';
  34884. this.domElement.style.opacity = 0;
  34885. this.domElement.style.webkitTransform = 'scale(1.1)';
  34886. this.layout();
  34887. Common.defer(function () {
  34888. _this.backgroundElement.style.opacity = 1;
  34889. _this.domElement.style.opacity = 1;
  34890. _this.domElement.style.webkitTransform = 'scale(1)';
  34891. });
  34892. }
  34893. }, {
  34894. key: 'hide',
  34895. value: function hide() {
  34896. var _this = this;
  34897. var hide = function hide() {
  34898. _this.domElement.style.display = 'none';
  34899. _this.backgroundElement.style.display = 'none';
  34900. dom.unbind(_this.domElement, 'webkitTransitionEnd', hide);
  34901. dom.unbind(_this.domElement, 'transitionend', hide);
  34902. dom.unbind(_this.domElement, 'oTransitionEnd', hide);
  34903. };
  34904. dom.bind(this.domElement, 'webkitTransitionEnd', hide);
  34905. dom.bind(this.domElement, 'transitionend', hide);
  34906. dom.bind(this.domElement, 'oTransitionEnd', hide);
  34907. this.backgroundElement.style.opacity = 0;
  34908. this.domElement.style.opacity = 0;
  34909. this.domElement.style.webkitTransform = 'scale(1.1)';
  34910. }
  34911. }, {
  34912. key: 'layout',
  34913. value: function layout() {
  34914. this.domElement.style.left = window.innerWidth / 2 - dom.getWidth(this.domElement) / 2 + 'px';
  34915. this.domElement.style.top = window.innerHeight / 2 - dom.getHeight(this.domElement) / 2 + 'px';
  34916. }
  34917. }]);
  34918. return CenteredDiv;
  34919. }();
  34920. 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");
  34921. css.inject(styleSheet);
  34922. var CSS_NAMESPACE = 'dg';
  34923. var HIDE_KEY_CODE = 72;
  34924. var CLOSE_BUTTON_HEIGHT = 20;
  34925. var DEFAULT_DEFAULT_PRESET_NAME = 'Default';
  34926. var SUPPORTS_LOCAL_STORAGE = function () {
  34927. try {
  34928. return !!window.localStorage;
  34929. } catch (e) {
  34930. return false;
  34931. }
  34932. }();
  34933. var SAVE_DIALOGUE = void 0;
  34934. var autoPlaceVirgin = true;
  34935. var autoPlaceContainer = void 0;
  34936. var hide = false;
  34937. var hideableGuis = [];
  34938. var GUI = function GUI(pars) {
  34939. var _this = this;
  34940. var params = pars || {};
  34941. this.domElement = document.createElement('div');
  34942. this.__ul = document.createElement('ul');
  34943. this.domElement.appendChild(this.__ul);
  34944. dom.addClass(this.domElement, CSS_NAMESPACE);
  34945. this.__folders = {};
  34946. this.__controllers = [];
  34947. this.__rememberedObjects = [];
  34948. this.__rememberedObjectIndecesToControllers = [];
  34949. this.__listening = [];
  34950. params = Common.defaults(params, {
  34951. closeOnTop: false,
  34952. autoPlace: true,
  34953. width: GUI.DEFAULT_WIDTH
  34954. });
  34955. params = Common.defaults(params, {
  34956. resizable: params.autoPlace,
  34957. hideable: params.autoPlace
  34958. });
  34959. if (!Common.isUndefined(params.load)) {
  34960. if (params.preset) {
  34961. params.load.preset = params.preset;
  34962. }
  34963. } else {
  34964. params.load = {
  34965. preset: DEFAULT_DEFAULT_PRESET_NAME
  34966. };
  34967. }
  34968. if (Common.isUndefined(params.parent) && params.hideable) {
  34969. hideableGuis.push(this);
  34970. }
  34971. params.resizable = Common.isUndefined(params.parent) && params.resizable;
  34972. if (params.autoPlace && Common.isUndefined(params.scrollable)) {
  34973. params.scrollable = true;
  34974. }
  34975. var useLocalStorage = SUPPORTS_LOCAL_STORAGE && localStorage.getItem(getLocalStorageHash(this, 'isLocal')) === 'true';
  34976. var saveToLocalStorage = void 0;
  34977. var titleRow = void 0;
  34978. Object.defineProperties(this, {
  34979. parent: {
  34980. get: function get$$1() {
  34981. return params.parent;
  34982. }
  34983. },
  34984. scrollable: {
  34985. get: function get$$1() {
  34986. return params.scrollable;
  34987. }
  34988. },
  34989. autoPlace: {
  34990. get: function get$$1() {
  34991. return params.autoPlace;
  34992. }
  34993. },
  34994. closeOnTop: {
  34995. get: function get$$1() {
  34996. return params.closeOnTop;
  34997. }
  34998. },
  34999. preset: {
  35000. get: function get$$1() {
  35001. if (_this.parent) {
  35002. return _this.getRoot().preset;
  35003. }
  35004. return params.load.preset;
  35005. },
  35006. set: function set$$1(v) {
  35007. if (_this.parent) {
  35008. _this.getRoot().preset = v;
  35009. } else {
  35010. params.load.preset = v;
  35011. }
  35012. setPresetSelectIndex(this);
  35013. _this.revert();
  35014. }
  35015. },
  35016. width: {
  35017. get: function get$$1() {
  35018. return params.width;
  35019. },
  35020. set: function set$$1(v) {
  35021. params.width = v;
  35022. setWidth(_this, v);
  35023. }
  35024. },
  35025. name: {
  35026. get: function get$$1() {
  35027. return params.name;
  35028. },
  35029. set: function set$$1(v) {
  35030. params.name = v;
  35031. if (titleRow) {
  35032. titleRow.innerHTML = params.name;
  35033. }
  35034. }
  35035. },
  35036. closed: {
  35037. get: function get$$1() {
  35038. return params.closed;
  35039. },
  35040. set: function set$$1(v) {
  35041. params.closed = v;
  35042. if (params.closed) {
  35043. dom.addClass(_this.__ul, GUI.CLASS_CLOSED);
  35044. } else {
  35045. dom.removeClass(_this.__ul, GUI.CLASS_CLOSED);
  35046. }
  35047. this.onResize();
  35048. if (_this.__closeButton) {
  35049. _this.__closeButton.innerHTML = v ? GUI.TEXT_OPEN : GUI.TEXT_CLOSED;
  35050. }
  35051. }
  35052. },
  35053. load: {
  35054. get: function get$$1() {
  35055. return params.load;
  35056. }
  35057. },
  35058. useLocalStorage: {
  35059. get: function get$$1() {
  35060. return useLocalStorage;
  35061. },
  35062. set: function set$$1(bool) {
  35063. if (SUPPORTS_LOCAL_STORAGE) {
  35064. useLocalStorage = bool;
  35065. if (bool) {
  35066. dom.bind(window, 'unload', saveToLocalStorage);
  35067. } else {
  35068. dom.unbind(window, 'unload', saveToLocalStorage);
  35069. }
  35070. localStorage.setItem(getLocalStorageHash(_this, 'isLocal'), bool);
  35071. }
  35072. }
  35073. }
  35074. });
  35075. if (Common.isUndefined(params.parent)) {
  35076. this.closed = params.closed || false;
  35077. dom.addClass(this.domElement, GUI.CLASS_MAIN);
  35078. dom.makeSelectable(this.domElement, false);
  35079. if (SUPPORTS_LOCAL_STORAGE) {
  35080. if (useLocalStorage) {
  35081. _this.useLocalStorage = true;
  35082. var savedGui = localStorage.getItem(getLocalStorageHash(this, 'gui'));
  35083. if (savedGui) {
  35084. params.load = JSON.parse(savedGui);
  35085. }
  35086. }
  35087. }
  35088. this.__closeButton = document.createElement('div');
  35089. this.__closeButton.innerHTML = GUI.TEXT_CLOSED;
  35090. dom.addClass(this.__closeButton, GUI.CLASS_CLOSE_BUTTON);
  35091. if (params.closeOnTop) {
  35092. dom.addClass(this.__closeButton, GUI.CLASS_CLOSE_TOP);
  35093. this.domElement.insertBefore(this.__closeButton, this.domElement.childNodes[0]);
  35094. } else {
  35095. dom.addClass(this.__closeButton, GUI.CLASS_CLOSE_BOTTOM);
  35096. this.domElement.appendChild(this.__closeButton);
  35097. }
  35098. dom.bind(this.__closeButton, 'click', function () {
  35099. _this.closed = !_this.closed;
  35100. });
  35101. } else {
  35102. if (params.closed === undefined) {
  35103. params.closed = true;
  35104. }
  35105. var titleRowName = document.createTextNode(params.name);
  35106. dom.addClass(titleRowName, 'controller-name');
  35107. titleRow = addRow(_this, titleRowName);
  35108. var onClickTitle = function onClickTitle(e) {
  35109. e.preventDefault();
  35110. _this.closed = !_this.closed;
  35111. return false;
  35112. };
  35113. dom.addClass(this.__ul, GUI.CLASS_CLOSED);
  35114. dom.addClass(titleRow, 'title');
  35115. dom.bind(titleRow, 'click', onClickTitle);
  35116. if (!params.closed) {
  35117. this.closed = false;
  35118. }
  35119. }
  35120. if (params.autoPlace) {
  35121. if (Common.isUndefined(params.parent)) {
  35122. if (autoPlaceVirgin) {
  35123. autoPlaceContainer = document.createElement('div');
  35124. dom.addClass(autoPlaceContainer, CSS_NAMESPACE);
  35125. dom.addClass(autoPlaceContainer, GUI.CLASS_AUTO_PLACE_CONTAINER);
  35126. document.body.appendChild(autoPlaceContainer);
  35127. autoPlaceVirgin = false;
  35128. }
  35129. autoPlaceContainer.appendChild(this.domElement);
  35130. dom.addClass(this.domElement, GUI.CLASS_AUTO_PLACE);
  35131. }
  35132. if (!this.parent) {
  35133. setWidth(_this, params.width);
  35134. }
  35135. }
  35136. this.__resizeHandler = function () {
  35137. _this.onResizeDebounced();
  35138. };
  35139. dom.bind(window, 'resize', this.__resizeHandler);
  35140. dom.bind(this.__ul, 'webkitTransitionEnd', this.__resizeHandler);
  35141. dom.bind(this.__ul, 'transitionend', this.__resizeHandler);
  35142. dom.bind(this.__ul, 'oTransitionEnd', this.__resizeHandler);
  35143. this.onResize();
  35144. if (params.resizable) {
  35145. addResizeHandle(this);
  35146. }
  35147. saveToLocalStorage = function saveToLocalStorage() {
  35148. if (SUPPORTS_LOCAL_STORAGE && localStorage.getItem(getLocalStorageHash(_this, 'isLocal')) === 'true') {
  35149. localStorage.setItem(getLocalStorageHash(_this, 'gui'), JSON.stringify(_this.getSaveObject()));
  35150. }
  35151. };
  35152. this.saveToLocalStorageIfPossible = saveToLocalStorage;
  35153. function resetWidth() {
  35154. var root = _this.getRoot();
  35155. root.width += 1;
  35156. Common.defer(function () {
  35157. root.width -= 1;
  35158. });
  35159. }
  35160. if (!params.parent) {
  35161. resetWidth();
  35162. }
  35163. };
  35164. GUI.toggleHide = function () {
  35165. hide = !hide;
  35166. Common.each(hideableGuis, function (gui) {
  35167. gui.domElement.style.display = hide ? 'none' : '';
  35168. });
  35169. };
  35170. GUI.CLASS_AUTO_PLACE = 'a';
  35171. GUI.CLASS_AUTO_PLACE_CONTAINER = 'ac';
  35172. GUI.CLASS_MAIN = 'main';
  35173. GUI.CLASS_CONTROLLER_ROW = 'cr';
  35174. GUI.CLASS_TOO_TALL = 'taller-than-window';
  35175. GUI.CLASS_CLOSED = 'closed';
  35176. GUI.CLASS_CLOSE_BUTTON = 'close-button';
  35177. GUI.CLASS_CLOSE_TOP = 'close-top';
  35178. GUI.CLASS_CLOSE_BOTTOM = 'close-bottom';
  35179. GUI.CLASS_DRAG = 'drag';
  35180. GUI.DEFAULT_WIDTH = 245;
  35181. GUI.TEXT_CLOSED = 'Close Controls';
  35182. GUI.TEXT_OPEN = 'Open Controls';
  35183. GUI._keydownHandler = function (e) {
  35184. if (document.activeElement.type !== 'text' && (e.which === HIDE_KEY_CODE || e.keyCode === HIDE_KEY_CODE)) {
  35185. GUI.toggleHide();
  35186. }
  35187. };
  35188. dom.bind(window, 'keydown', GUI._keydownHandler, false);
  35189. Common.extend(GUI.prototype, {
  35190. add: function add(object, property) {
  35191. return _add(this, object, property, {
  35192. factoryArgs: Array.prototype.slice.call(arguments, 2)
  35193. });
  35194. },
  35195. addColor: function addColor(object, property) {
  35196. return _add(this, object, property, {
  35197. color: true
  35198. });
  35199. },
  35200. remove: function remove(controller) {
  35201. this.__ul.removeChild(controller.__li);
  35202. this.__controllers.splice(this.__controllers.indexOf(controller), 1);
  35203. var _this = this;
  35204. Common.defer(function () {
  35205. _this.onResize();
  35206. });
  35207. },
  35208. destroy: function destroy() {
  35209. if (this.parent) {
  35210. throw new Error('Only the root GUI should be removed with .destroy(). ' + 'For subfolders, use gui.removeFolder(folder) instead.');
  35211. }
  35212. if (this.autoPlace) {
  35213. autoPlaceContainer.removeChild(this.domElement);
  35214. }
  35215. var _this = this;
  35216. Common.each(this.__folders, function (subfolder) {
  35217. _this.removeFolder(subfolder);
  35218. });
  35219. dom.unbind(window, 'keydown', GUI._keydownHandler, false);
  35220. removeListeners(this);
  35221. },
  35222. addFolder: function addFolder(name) {
  35223. if (this.__folders[name] !== undefined) {
  35224. throw new Error('You already have a folder in this GUI by the' + ' name "' + name + '"');
  35225. }
  35226. var newGuiParams = {
  35227. name: name,
  35228. parent: this
  35229. };
  35230. newGuiParams.autoPlace = this.autoPlace;
  35231. if (this.load && this.load.folders && this.load.folders[name]) {
  35232. newGuiParams.closed = this.load.folders[name].closed;
  35233. newGuiParams.load = this.load.folders[name];
  35234. }
  35235. var gui = new GUI(newGuiParams);
  35236. this.__folders[name] = gui;
  35237. var li = addRow(this, gui.domElement);
  35238. dom.addClass(li, 'folder');
  35239. return gui;
  35240. },
  35241. removeFolder: function removeFolder(folder) {
  35242. this.__ul.removeChild(folder.domElement.parentElement);
  35243. delete this.__folders[folder.name];
  35244. if (this.load && this.load.folders && this.load.folders[folder.name]) {
  35245. delete this.load.folders[folder.name];
  35246. }
  35247. removeListeners(folder);
  35248. var _this = this;
  35249. Common.each(folder.__folders, function (subfolder) {
  35250. folder.removeFolder(subfolder);
  35251. });
  35252. Common.defer(function () {
  35253. _this.onResize();
  35254. });
  35255. },
  35256. open: function open() {
  35257. this.closed = false;
  35258. },
  35259. close: function close() {
  35260. this.closed = true;
  35261. },
  35262. hide: function hide() {
  35263. this.domElement.style.display = 'none';
  35264. },
  35265. show: function show() {
  35266. this.domElement.style.display = '';
  35267. },
  35268. onResize: function onResize() {
  35269. var root = this.getRoot();
  35270. if (root.scrollable) {
  35271. var top = dom.getOffset(root.__ul).top;
  35272. var h = 0;
  35273. Common.each(root.__ul.childNodes, function (node) {
  35274. if (!(root.autoPlace && node === root.__save_row)) {
  35275. h += dom.getHeight(node);
  35276. }
  35277. });
  35278. if (window.innerHeight - top - CLOSE_BUTTON_HEIGHT < h) {
  35279. dom.addClass(root.domElement, GUI.CLASS_TOO_TALL);
  35280. root.__ul.style.height = window.innerHeight - top - CLOSE_BUTTON_HEIGHT + 'px';
  35281. } else {
  35282. dom.removeClass(root.domElement, GUI.CLASS_TOO_TALL);
  35283. root.__ul.style.height = 'auto';
  35284. }
  35285. }
  35286. if (root.__resize_handle) {
  35287. Common.defer(function () {
  35288. root.__resize_handle.style.height = root.__ul.offsetHeight + 'px';
  35289. });
  35290. }
  35291. if (root.__closeButton) {
  35292. root.__closeButton.style.width = root.width + 'px';
  35293. }
  35294. },
  35295. onResizeDebounced: Common.debounce(function () {
  35296. this.onResize();
  35297. }, 50),
  35298. remember: function remember() {
  35299. if (Common.isUndefined(SAVE_DIALOGUE)) {
  35300. SAVE_DIALOGUE = new CenteredDiv();
  35301. SAVE_DIALOGUE.domElement.innerHTML = saveDialogContents;
  35302. }
  35303. if (this.parent) {
  35304. throw new Error('You can only call remember on a top level GUI.');
  35305. }
  35306. var _this = this;
  35307. Common.each(Array.prototype.slice.call(arguments), function (object) {
  35308. if (_this.__rememberedObjects.length === 0) {
  35309. addSaveMenu(_this);
  35310. }
  35311. if (_this.__rememberedObjects.indexOf(object) === -1) {
  35312. _this.__rememberedObjects.push(object);
  35313. }
  35314. });
  35315. if (this.autoPlace) {
  35316. setWidth(this, this.width);
  35317. }
  35318. },
  35319. getRoot: function getRoot() {
  35320. var gui = this;
  35321. while (gui.parent) {
  35322. gui = gui.parent;
  35323. }
  35324. return gui;
  35325. },
  35326. getSaveObject: function getSaveObject() {
  35327. var toReturn = this.load;
  35328. toReturn.closed = this.closed;
  35329. if (this.__rememberedObjects.length > 0) {
  35330. toReturn.preset = this.preset;
  35331. if (!toReturn.remembered) {
  35332. toReturn.remembered = {};
  35333. }
  35334. toReturn.remembered[this.preset] = getCurrentPreset(this);
  35335. }
  35336. toReturn.folders = {};
  35337. Common.each(this.__folders, function (element, key) {
  35338. toReturn.folders[key] = element.getSaveObject();
  35339. });
  35340. return toReturn;
  35341. },
  35342. save: function save() {
  35343. if (!this.load.remembered) {
  35344. this.load.remembered = {};
  35345. }
  35346. this.load.remembered[this.preset] = getCurrentPreset(this);
  35347. markPresetModified(this, false);
  35348. this.saveToLocalStorageIfPossible();
  35349. },
  35350. saveAs: function saveAs(presetName) {
  35351. if (!this.load.remembered) {
  35352. this.load.remembered = {};
  35353. this.load.remembered[DEFAULT_DEFAULT_PRESET_NAME] = getCurrentPreset(this, true);
  35354. }
  35355. this.load.remembered[presetName] = getCurrentPreset(this);
  35356. this.preset = presetName;
  35357. addPresetOption(this, presetName, true);
  35358. this.saveToLocalStorageIfPossible();
  35359. },
  35360. revert: function revert(gui) {
  35361. Common.each(this.__controllers, function (controller) {
  35362. if (!this.getRoot().load.remembered) {
  35363. controller.setValue(controller.initialValue);
  35364. } else {
  35365. recallSavedValue(gui || this.getRoot(), controller);
  35366. }
  35367. if (controller.__onFinishChange) {
  35368. controller.__onFinishChange.call(controller, controller.getValue());
  35369. }
  35370. }, this);
  35371. Common.each(this.__folders, function (folder) {
  35372. folder.revert(folder);
  35373. });
  35374. if (!gui) {
  35375. markPresetModified(this.getRoot(), false);
  35376. }
  35377. },
  35378. listen: function listen(controller) {
  35379. var init = this.__listening.length === 0;
  35380. this.__listening.push(controller);
  35381. if (init) {
  35382. updateDisplays(this.__listening);
  35383. }
  35384. },
  35385. updateDisplay: function updateDisplay() {
  35386. Common.each(this.__controllers, function (controller) {
  35387. controller.updateDisplay();
  35388. });
  35389. Common.each(this.__folders, function (folder) {
  35390. folder.updateDisplay();
  35391. });
  35392. }
  35393. });
  35394. function addRow(gui, newDom, liBefore) {
  35395. var li = document.createElement('li');
  35396. if (newDom) {
  35397. li.appendChild(newDom);
  35398. }
  35399. if (liBefore) {
  35400. gui.__ul.insertBefore(li, liBefore);
  35401. } else {
  35402. gui.__ul.appendChild(li);
  35403. }
  35404. gui.onResize();
  35405. return li;
  35406. }
  35407. function removeListeners(gui) {
  35408. dom.unbind(window, 'resize', gui.__resizeHandler);
  35409. if (gui.saveToLocalStorageIfPossible) {
  35410. dom.unbind(window, 'unload', gui.saveToLocalStorageIfPossible);
  35411. }
  35412. }
  35413. function markPresetModified(gui, modified) {
  35414. var opt = gui.__preset_select[gui.__preset_select.selectedIndex];
  35415. if (modified) {
  35416. opt.innerHTML = opt.value + '*';
  35417. } else {
  35418. opt.innerHTML = opt.value;
  35419. }
  35420. }
  35421. function augmentController(gui, li, controller) {
  35422. controller.__li = li;
  35423. controller.__gui = gui;
  35424. Common.extend(controller, {
  35425. options: function options(_options) {
  35426. if (arguments.length > 1) {
  35427. var nextSibling = controller.__li.nextElementSibling;
  35428. controller.remove();
  35429. return _add(gui, controller.object, controller.property, {
  35430. before: nextSibling,
  35431. factoryArgs: [Common.toArray(arguments)]
  35432. });
  35433. }
  35434. if (Common.isArray(_options) || Common.isObject(_options)) {
  35435. var _nextSibling = controller.__li.nextElementSibling;
  35436. controller.remove();
  35437. return _add(gui, controller.object, controller.property, {
  35438. before: _nextSibling,
  35439. factoryArgs: [_options]
  35440. });
  35441. }
  35442. },
  35443. name: function name(_name) {
  35444. controller.__li.firstElementChild.firstElementChild.innerHTML = _name;
  35445. return controller;
  35446. },
  35447. listen: function listen() {
  35448. controller.__gui.listen(controller);
  35449. return controller;
  35450. },
  35451. remove: function remove() {
  35452. controller.__gui.remove(controller);
  35453. return controller;
  35454. }
  35455. });
  35456. if (controller instanceof NumberControllerSlider) {
  35457. var box = new NumberControllerBox(controller.object, controller.property, {
  35458. min: controller.__min,
  35459. max: controller.__max,
  35460. step: controller.__step
  35461. });
  35462. Common.each(['updateDisplay', 'onChange', 'onFinishChange', 'step', 'min', 'max'], function (method) {
  35463. var pc = controller[method];
  35464. var pb = box[method];
  35465. controller[method] = box[method] = function () {
  35466. var args = Array.prototype.slice.call(arguments);
  35467. pb.apply(box, args);
  35468. return pc.apply(controller, args);
  35469. };
  35470. });
  35471. dom.addClass(li, 'has-slider');
  35472. controller.domElement.insertBefore(box.domElement, controller.domElement.firstElementChild);
  35473. } else if (controller instanceof NumberControllerBox) {
  35474. var r = function r(returned) {
  35475. if (Common.isNumber(controller.__min) && Common.isNumber(controller.__max)) {
  35476. var oldName = controller.__li.firstElementChild.firstElementChild.innerHTML;
  35477. var wasListening = controller.__gui.__listening.indexOf(controller) > -1;
  35478. controller.remove();
  35479. var newController = _add(gui, controller.object, controller.property, {
  35480. before: controller.__li.nextElementSibling,
  35481. factoryArgs: [controller.__min, controller.__max, controller.__step]
  35482. });
  35483. newController.name(oldName);
  35484. if (wasListening) newController.listen();
  35485. return newController;
  35486. }
  35487. return returned;
  35488. };
  35489. controller.min = Common.compose(r, controller.min);
  35490. controller.max = Common.compose(r, controller.max);
  35491. } else if (controller instanceof BooleanController) {
  35492. dom.bind(li, 'click', function () {
  35493. dom.fakeEvent(controller.__checkbox, 'click');
  35494. });
  35495. dom.bind(controller.__checkbox, 'click', function (e) {
  35496. e.stopPropagation();
  35497. });
  35498. } else if (controller instanceof FunctionController) {
  35499. dom.bind(li, 'click', function () {
  35500. dom.fakeEvent(controller.__button, 'click');
  35501. });
  35502. dom.bind(li, 'mouseover', function () {
  35503. dom.addClass(controller.__button, 'hover');
  35504. });
  35505. dom.bind(li, 'mouseout', function () {
  35506. dom.removeClass(controller.__button, 'hover');
  35507. });
  35508. } else if (controller instanceof ColorController) {
  35509. dom.addClass(li, 'color');
  35510. controller.updateDisplay = Common.compose(function (val) {
  35511. li.style.borderLeftColor = controller.__color.toString();
  35512. return val;
  35513. }, controller.updateDisplay);
  35514. controller.updateDisplay();
  35515. }
  35516. controller.setValue = Common.compose(function (val) {
  35517. if (gui.getRoot().__preset_select && controller.isModified()) {
  35518. markPresetModified(gui.getRoot(), true);
  35519. }
  35520. return val;
  35521. }, controller.setValue);
  35522. }
  35523. function recallSavedValue(gui, controller) {
  35524. var root = gui.getRoot();
  35525. var matchedIndex = root.__rememberedObjects.indexOf(controller.object);
  35526. if (matchedIndex !== -1) {
  35527. var controllerMap = root.__rememberedObjectIndecesToControllers[matchedIndex];
  35528. if (controllerMap === undefined) {
  35529. controllerMap = {};
  35530. root.__rememberedObjectIndecesToControllers[matchedIndex] = controllerMap;
  35531. }
  35532. controllerMap[controller.property] = controller;
  35533. if (root.load && root.load.remembered) {
  35534. var presetMap = root.load.remembered;
  35535. var preset = void 0;
  35536. if (presetMap[gui.preset]) {
  35537. preset = presetMap[gui.preset];
  35538. } else if (presetMap[DEFAULT_DEFAULT_PRESET_NAME]) {
  35539. preset = presetMap[DEFAULT_DEFAULT_PRESET_NAME];
  35540. } else {
  35541. return;
  35542. }
  35543. if (preset[matchedIndex] && preset[matchedIndex][controller.property] !== undefined) {
  35544. var value = preset[matchedIndex][controller.property];
  35545. controller.initialValue = value;
  35546. controller.setValue(value);
  35547. }
  35548. }
  35549. }
  35550. }
  35551. function _add(gui, object, property, params) {
  35552. if (object[property] === undefined) {
  35553. throw new Error('Object "' + object + '" has no property "' + property + '"');
  35554. }
  35555. var controller = void 0;
  35556. if (params.color) {
  35557. controller = new ColorController(object, property);
  35558. } else {
  35559. var factoryArgs = [object, property].concat(params.factoryArgs);
  35560. controller = ControllerFactory.apply(gui, factoryArgs);
  35561. }
  35562. if (params.before instanceof Controller) {
  35563. params.before = params.before.__li;
  35564. }
  35565. recallSavedValue(gui, controller);
  35566. dom.addClass(controller.domElement, 'c');
  35567. var name = document.createElement('span');
  35568. dom.addClass(name, 'property-name');
  35569. name.innerHTML = controller.property;
  35570. var container = document.createElement('div');
  35571. container.appendChild(name);
  35572. container.appendChild(controller.domElement);
  35573. var li = addRow(gui, container, params.before);
  35574. dom.addClass(li, GUI.CLASS_CONTROLLER_ROW);
  35575. if (controller instanceof ColorController) {
  35576. dom.addClass(li, 'color');
  35577. } else {
  35578. dom.addClass(li, _typeof(controller.getValue()));
  35579. }
  35580. augmentController(gui, li, controller);
  35581. gui.__controllers.push(controller);
  35582. return controller;
  35583. }
  35584. function getLocalStorageHash(gui, key) {
  35585. return document.location.href + '.' + key;
  35586. }
  35587. function addPresetOption(gui, name, setSelected) {
  35588. var opt = document.createElement('option');
  35589. opt.innerHTML = name;
  35590. opt.value = name;
  35591. gui.__preset_select.appendChild(opt);
  35592. if (setSelected) {
  35593. gui.__preset_select.selectedIndex = gui.__preset_select.length - 1;
  35594. }
  35595. }
  35596. function showHideExplain(gui, explain) {
  35597. explain.style.display = gui.useLocalStorage ? 'block' : 'none';
  35598. }
  35599. function addSaveMenu(gui) {
  35600. var div = gui.__save_row = document.createElement('li');
  35601. dom.addClass(gui.domElement, 'has-save');
  35602. gui.__ul.insertBefore(div, gui.__ul.firstChild);
  35603. dom.addClass(div, 'save-row');
  35604. var gears = document.createElement('span');
  35605. gears.innerHTML = '&nbsp;';
  35606. dom.addClass(gears, 'button gears');
  35607. var button = document.createElement('span');
  35608. button.innerHTML = 'Save';
  35609. dom.addClass(button, 'button');
  35610. dom.addClass(button, 'save');
  35611. var button2 = document.createElement('span');
  35612. button2.innerHTML = 'New';
  35613. dom.addClass(button2, 'button');
  35614. dom.addClass(button2, 'save-as');
  35615. var button3 = document.createElement('span');
  35616. button3.innerHTML = 'Revert';
  35617. dom.addClass(button3, 'button');
  35618. dom.addClass(button3, 'revert');
  35619. var select = gui.__preset_select = document.createElement('select');
  35620. if (gui.load && gui.load.remembered) {
  35621. Common.each(gui.load.remembered, function (value, key) {
  35622. addPresetOption(gui, key, key === gui.preset);
  35623. });
  35624. } else {
  35625. addPresetOption(gui, DEFAULT_DEFAULT_PRESET_NAME, false);
  35626. }
  35627. dom.bind(select, 'change', function () {
  35628. for (var index = 0; index < gui.__preset_select.length; index++) {
  35629. gui.__preset_select[index].innerHTML = gui.__preset_select[index].value;
  35630. }
  35631. gui.preset = this.value;
  35632. });
  35633. div.appendChild(select);
  35634. div.appendChild(gears);
  35635. div.appendChild(button);
  35636. div.appendChild(button2);
  35637. div.appendChild(button3);
  35638. if (SUPPORTS_LOCAL_STORAGE) {
  35639. var explain = document.getElementById('dg-local-explain');
  35640. var localStorageCheckBox = document.getElementById('dg-local-storage');
  35641. var saveLocally = document.getElementById('dg-save-locally');
  35642. saveLocally.style.display = 'block';
  35643. if (localStorage.getItem(getLocalStorageHash(gui, 'isLocal')) === 'true') {
  35644. localStorageCheckBox.setAttribute('checked', 'checked');
  35645. }
  35646. showHideExplain(gui, explain);
  35647. dom.bind(localStorageCheckBox, 'change', function () {
  35648. gui.useLocalStorage = !gui.useLocalStorage;
  35649. showHideExplain(gui, explain);
  35650. });
  35651. }
  35652. var newConstructorTextArea = document.getElementById('dg-new-constructor');
  35653. dom.bind(newConstructorTextArea, 'keydown', function (e) {
  35654. if (e.metaKey && (e.which === 67 || e.keyCode === 67)) {
  35655. SAVE_DIALOGUE.hide();
  35656. }
  35657. });
  35658. dom.bind(gears, 'click', function () {
  35659. newConstructorTextArea.innerHTML = JSON.stringify(gui.getSaveObject(), undefined, 2);
  35660. SAVE_DIALOGUE.show();
  35661. newConstructorTextArea.focus();
  35662. newConstructorTextArea.select();
  35663. });
  35664. dom.bind(button, 'click', function () {
  35665. gui.save();
  35666. });
  35667. dom.bind(button2, 'click', function () {
  35668. var presetName = prompt('Enter a new preset name.');
  35669. if (presetName) {
  35670. gui.saveAs(presetName);
  35671. }
  35672. });
  35673. dom.bind(button3, 'click', function () {
  35674. gui.revert();
  35675. });
  35676. }
  35677. function addResizeHandle(gui) {
  35678. var pmouseX = void 0;
  35679. gui.__resize_handle = document.createElement('div');
  35680. Common.extend(gui.__resize_handle.style, {
  35681. width: '6px',
  35682. marginLeft: '-3px',
  35683. height: '200px',
  35684. cursor: 'ew-resize',
  35685. position: 'absolute'
  35686. });
  35687. function drag(e) {
  35688. e.preventDefault();
  35689. gui.width += pmouseX - e.clientX;
  35690. gui.onResize();
  35691. pmouseX = e.clientX;
  35692. return false;
  35693. }
  35694. function dragStop() {
  35695. dom.removeClass(gui.__closeButton, GUI.CLASS_DRAG);
  35696. dom.unbind(window, 'mousemove', drag);
  35697. dom.unbind(window, 'mouseup', dragStop);
  35698. }
  35699. function dragStart(e) {
  35700. e.preventDefault();
  35701. pmouseX = e.clientX;
  35702. dom.addClass(gui.__closeButton, GUI.CLASS_DRAG);
  35703. dom.bind(window, 'mousemove', drag);
  35704. dom.bind(window, 'mouseup', dragStop);
  35705. return false;
  35706. }
  35707. dom.bind(gui.__resize_handle, 'mousedown', dragStart);
  35708. dom.bind(gui.__closeButton, 'mousedown', dragStart);
  35709. gui.domElement.insertBefore(gui.__resize_handle, gui.domElement.firstElementChild);
  35710. }
  35711. function setWidth(gui, w) {
  35712. gui.domElement.style.width = w + 'px';
  35713. if (gui.__save_row && gui.autoPlace) {
  35714. gui.__save_row.style.width = w + 'px';
  35715. }
  35716. if (gui.__closeButton) {
  35717. gui.__closeButton.style.width = w + 'px';
  35718. }
  35719. }
  35720. function getCurrentPreset(gui, useInitialValues) {
  35721. var toReturn = {};
  35722. Common.each(gui.__rememberedObjects, function (val, index) {
  35723. var savedValues = {};
  35724. var controllerMap = gui.__rememberedObjectIndecesToControllers[index];
  35725. Common.each(controllerMap, function (controller, property) {
  35726. savedValues[property] = useInitialValues ? controller.initialValue : controller.getValue();
  35727. });
  35728. toReturn[index] = savedValues;
  35729. });
  35730. return toReturn;
  35731. }
  35732. function setPresetSelectIndex(gui) {
  35733. for (var index = 0; index < gui.__preset_select.length; index++) {
  35734. if (gui.__preset_select[index].value === gui.preset) {
  35735. gui.__preset_select.selectedIndex = index;
  35736. }
  35737. }
  35738. }
  35739. function updateDisplays(controllerArray) {
  35740. if (controllerArray.length !== 0) {
  35741. requestAnimationFrame$1.call(window, function () {
  35742. updateDisplays(controllerArray);
  35743. });
  35744. }
  35745. Common.each(controllerArray, function (c) {
  35746. c.updateDisplay();
  35747. });
  35748. }
  35749. var color = {
  35750. Color: Color,
  35751. math: ColorMath,
  35752. interpret: interpret
  35753. };
  35754. exports.color = color;
  35755. var controllers = {
  35756. Controller: Controller,
  35757. BooleanController: BooleanController,
  35758. OptionController: OptionController,
  35759. StringController: StringController,
  35760. NumberController: NumberController,
  35761. NumberControllerBox: NumberControllerBox,
  35762. NumberControllerSlider: NumberControllerSlider,
  35763. FunctionController: FunctionController,
  35764. ColorController: ColorController
  35765. };
  35766. exports.controllers = controllers;
  35767. var dom$1 = {
  35768. dom: dom
  35769. };
  35770. exports.dom = dom$1;
  35771. var gui = {
  35772. GUI: GUI
  35773. };
  35774. exports.gui = gui;
  35775. var GUI$1 = GUI;
  35776. exports.GUI = GUI$1;
  35777. var index = {
  35778. color: color,
  35779. controllers: controllers,
  35780. dom: dom$1,
  35781. gui: gui,
  35782. GUI: GUI$1
  35783. };
  35784. var _default = index;
  35785. exports.default = _default;
  35786. },{}],"../node_modules/three/examples/jsm/libs/stats.module.js":[function(require,module,exports) {
  35787. "use strict";
  35788. Object.defineProperty(exports, "__esModule", {
  35789. value: true
  35790. });
  35791. exports.default = void 0;
  35792. /**
  35793. * @author mrdoob / http://mrdoob.com/
  35794. */
  35795. var Stats = function () {
  35796. var mode = 0;
  35797. var container = document.createElement('div');
  35798. container.style.cssText = 'position:fixed;top:0;left:0;cursor:pointer;opacity:0.9;z-index:10000';
  35799. container.addEventListener('click', function (event) {
  35800. event.preventDefault();
  35801. showPanel(++mode % container.children.length);
  35802. }, false); //
  35803. function addPanel(panel) {
  35804. container.appendChild(panel.dom);
  35805. return panel;
  35806. }
  35807. function showPanel(id) {
  35808. for (var i = 0; i < container.children.length; i++) {
  35809. container.children[i].style.display = i === id ? 'block' : 'none';
  35810. }
  35811. mode = id;
  35812. } //
  35813. var beginTime = (performance || Date).now(),
  35814. prevTime = beginTime,
  35815. frames = 0;
  35816. var fpsPanel = addPanel(new Stats.Panel('FPS', '#0ff', '#002'));
  35817. var msPanel = addPanel(new Stats.Panel('MS', '#0f0', '#020'));
  35818. if (self.performance && self.performance.memory) {
  35819. var memPanel = addPanel(new Stats.Panel('MB', '#f08', '#201'));
  35820. }
  35821. showPanel(0);
  35822. return {
  35823. REVISION: 16,
  35824. dom: container,
  35825. addPanel: addPanel,
  35826. showPanel: showPanel,
  35827. begin: function () {
  35828. beginTime = (performance || Date).now();
  35829. },
  35830. end: function () {
  35831. frames++;
  35832. var time = (performance || Date).now();
  35833. msPanel.update(time - beginTime, 200);
  35834. if (time >= prevTime + 1000) {
  35835. fpsPanel.update(frames * 1000 / (time - prevTime), 100);
  35836. prevTime = time;
  35837. frames = 0;
  35838. if (memPanel) {
  35839. var memory = performance.memory;
  35840. memPanel.update(memory.usedJSHeapSize / 1048576, memory.jsHeapSizeLimit / 1048576);
  35841. }
  35842. }
  35843. return time;
  35844. },
  35845. update: function () {
  35846. beginTime = this.end();
  35847. },
  35848. // Backwards Compatibility
  35849. domElement: container,
  35850. setMode: showPanel
  35851. };
  35852. };
  35853. Stats.Panel = function (name, fg, bg) {
  35854. var min = Infinity,
  35855. max = 0,
  35856. round = Math.round;
  35857. var PR = round(window.devicePixelRatio || 1);
  35858. var WIDTH = 80 * PR,
  35859. HEIGHT = 48 * PR,
  35860. TEXT_X = 3 * PR,
  35861. TEXT_Y = 2 * PR,
  35862. GRAPH_X = 3 * PR,
  35863. GRAPH_Y = 15 * PR,
  35864. GRAPH_WIDTH = 74 * PR,
  35865. GRAPH_HEIGHT = 30 * PR;
  35866. var canvas = document.createElement('canvas');
  35867. canvas.width = WIDTH;
  35868. canvas.height = HEIGHT;
  35869. canvas.style.cssText = 'width:80px;height:48px';
  35870. var context = canvas.getContext('2d');
  35871. context.font = 'bold ' + 9 * PR + 'px Helvetica,Arial,sans-serif';
  35872. context.textBaseline = 'top';
  35873. context.fillStyle = bg;
  35874. context.fillRect(0, 0, WIDTH, HEIGHT);
  35875. context.fillStyle = fg;
  35876. context.fillText(name, TEXT_X, TEXT_Y);
  35877. context.fillRect(GRAPH_X, GRAPH_Y, GRAPH_WIDTH, GRAPH_HEIGHT);
  35878. context.fillStyle = bg;
  35879. context.globalAlpha = 0.9;
  35880. context.fillRect(GRAPH_X, GRAPH_Y, GRAPH_WIDTH, GRAPH_HEIGHT);
  35881. return {
  35882. dom: canvas,
  35883. update: function (value, maxValue) {
  35884. min = Math.min(min, value);
  35885. max = Math.max(max, value);
  35886. context.fillStyle = bg;
  35887. context.globalAlpha = 1;
  35888. context.fillRect(0, 0, WIDTH, GRAPH_Y);
  35889. context.fillStyle = fg;
  35890. context.fillText(round(value) + ' ' + name + ' (' + round(min) + '-' + round(max) + ')', TEXT_X, TEXT_Y);
  35891. context.drawImage(canvas, GRAPH_X + PR, GRAPH_Y, GRAPH_WIDTH - PR, GRAPH_HEIGHT, GRAPH_X, GRAPH_Y, GRAPH_WIDTH - PR, GRAPH_HEIGHT);
  35892. context.fillRect(GRAPH_X + GRAPH_WIDTH - PR, GRAPH_Y, PR, GRAPH_HEIGHT);
  35893. context.fillStyle = bg;
  35894. context.globalAlpha = 0.9;
  35895. context.fillRect(GRAPH_X + GRAPH_WIDTH - PR, GRAPH_Y, PR, round((1 - value / maxValue) * GRAPH_HEIGHT));
  35896. }
  35897. };
  35898. };
  35899. var _default = Stats;
  35900. exports.default = _default;
  35901. },{}],"index.js":[function(require,module,exports) {
  35902. "use strict";
  35903. var _index = require("../src/index.js");
  35904. var _three = require("three");
  35905. var _OrbitControls = require("three/examples/jsm/controls/OrbitControls.js");
  35906. var dat = _interopRequireWildcard(require("three/examples/jsm/libs/dat.gui.module.js"));
  35907. var _statsModule = _interopRequireDefault(require("three/examples/jsm/libs/stats.module.js"));
  35908. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  35909. function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; }
  35910. 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; }
  35911. let camera, controls, scene, renderer, tiles, cameraHelper;
  35912. let thirdPersonCamera, thirdPersonRenderer, thirdPersonControls;
  35913. let box;
  35914. let raycaster, mouse, rayIntersect;
  35915. let offsetParent;
  35916. let statsContainer, stats;
  35917. let params = {
  35918. 'errorTarget': 6,
  35919. 'errorThreshold': 60,
  35920. 'maxDepth': 15,
  35921. 'loadSiblings': true,
  35922. 'up': '+Y',
  35923. 'displayBounds': false,
  35924. 'showThirdPerson': true,
  35925. 'reload': reinstantiateTiles
  35926. };
  35927. init();
  35928. animate();
  35929. function reinstantiateTiles() {
  35930. const url = window.location.hash.replace(/^#/, '') || './SampleTileset/tileset.json';
  35931. if (tiles) {
  35932. offsetParent.remove(tiles.group);
  35933. }
  35934. tiles = new _index.ThreeTilesRenderer(url, camera, renderer);
  35935. offsetParent.add(tiles.group);
  35936. }
  35937. function init() {
  35938. // Third person camera view
  35939. thirdPersonCamera = new _three.PerspectiveCamera(60, window.innerWidth / window.innerHeight, 1, 3000);
  35940. thirdPersonCamera.position.set(50, 40, 40);
  35941. thirdPersonCamera.lookAt(0, 0, 0);
  35942. thirdPersonRenderer = new _three.WebGLRenderer({
  35943. antialias: true
  35944. });
  35945. thirdPersonRenderer.setPixelRatio(window.devicePixelRatio);
  35946. thirdPersonRenderer.setSize(window.innerWidth, window.innerHeight);
  35947. thirdPersonRenderer.setClearColor(0x0f1416);
  35948. document.body.appendChild(thirdPersonRenderer.domElement);
  35949. thirdPersonRenderer.domElement.style.position = 'fixed';
  35950. thirdPersonRenderer.domElement.style.left = '5px';
  35951. thirdPersonRenderer.domElement.style.bottom = '5px';
  35952. thirdPersonControls = new _OrbitControls.OrbitControls(thirdPersonCamera, thirdPersonRenderer.domElement);
  35953. thirdPersonControls.screenSpacePanning = false;
  35954. thirdPersonControls.minDistance = 1;
  35955. thirdPersonControls.maxDistance = 2000; // primary camera view
  35956. scene = new _three.Scene();
  35957. renderer = new _three.WebGLRenderer({
  35958. antialias: true
  35959. });
  35960. renderer.setPixelRatio(window.devicePixelRatio);
  35961. renderer.setSize(window.innerWidth, window.innerHeight);
  35962. renderer.setClearColor(0x151c1f);
  35963. renderer.gammaInput = true;
  35964. renderer.gameOutput = true;
  35965. document.body.appendChild(renderer.domElement);
  35966. camera = new _three.PerspectiveCamera(60, window.innerWidth / window.innerHeight, 1, 2000);
  35967. camera.position.set(100, 100, 100);
  35968. cameraHelper = new _three.CameraHelper(camera);
  35969. scene.add(cameraHelper); // controls
  35970. controls = new _OrbitControls.OrbitControls(camera, renderer.domElement);
  35971. controls.screenSpacePanning = false;
  35972. controls.minDistance = 1;
  35973. controls.maxDistance = 2000; // lights
  35974. var dirLight = new _three.DirectionalLight(0xffffff);
  35975. dirLight.position.set(1, 1, 1);
  35976. scene.add(dirLight);
  35977. var ambLight = new _three.AmbientLight(0x222222);
  35978. scene.add(ambLight);
  35979. box = new _three.Box3();
  35980. offsetParent = new _three.Group();
  35981. scene.add(offsetParent); // Raycasting init
  35982. raycaster = new _three.Raycaster();
  35983. mouse = new _three.Vector2();
  35984. rayIntersect = new _three.Group();
  35985. const rayIntersectMat = new _three.MeshBasicMaterial({
  35986. color: 0xe91e63
  35987. });
  35988. const rayMesh = new _three.Mesh(new _three.CylinderBufferGeometry(0.25, 0.25, 10), rayIntersectMat);
  35989. rayMesh.rotation.x = Math.PI / 2;
  35990. rayMesh.position.z += 5;
  35991. rayIntersect.add(rayMesh);
  35992. const rayRing = new _three.Mesh(new _three.TorusBufferGeometry(1.5, 0.2, 16, 100), rayIntersectMat);
  35993. rayIntersect.add(rayRing);
  35994. scene.add(rayIntersect);
  35995. rayIntersect.visible = false;
  35996. reinstantiateTiles();
  35997. onWindowResize();
  35998. window.addEventListener('resize', onWindowResize, false);
  35999. window.addEventListener('mousemove', onMouseMove, false); // GUI
  36000. const gui = new dat.GUI();
  36001. const tiles = gui.addFolder('Tiles Options');
  36002. tiles.add(params, 'loadSiblings');
  36003. tiles.add(params, 'errorTarget').min(0).max(50);
  36004. tiles.add(params, 'errorThreshold').min(0).max(1000);
  36005. tiles.add(params, 'maxDepth').min(1).max(100);
  36006. tiles.add(params, 'up', ['+Y', '-Z']);
  36007. tiles.open();
  36008. gui.add(params, 'displayBounds');
  36009. gui.add(params, 'showThirdPerson');
  36010. gui.add(params, 'reload');
  36011. gui.open();
  36012. statsContainer = document.createElement('div');
  36013. statsContainer.style.position = 'absolute';
  36014. statsContainer.style.top = 0;
  36015. statsContainer.style.left = 0;
  36016. statsContainer.style.color = 'white';
  36017. statsContainer.style.width = '100%';
  36018. statsContainer.style.textAlign = 'center';
  36019. statsContainer.style.padding = '10px';
  36020. document.body.appendChild(statsContainer); // Stats
  36021. stats = new _statsModule.default();
  36022. stats.showPanel(0);
  36023. document.body.appendChild(stats.dom);
  36024. }
  36025. function onWindowResize() {
  36026. thirdPersonCamera.aspect = window.innerWidth / window.innerHeight;
  36027. thirdPersonCamera.updateProjectionMatrix();
  36028. thirdPersonRenderer.setSize(Math.floor(window.innerWidth / 3), Math.floor(window.innerHeight / 3));
  36029. camera.aspect = window.innerWidth / window.innerHeight;
  36030. camera.updateProjectionMatrix();
  36031. renderer.setSize(window.innerWidth, window.innerHeight);
  36032. }
  36033. function onMouseMove(e) {
  36034. mouse.x = e.clientX / window.innerWidth * 2 - 1;
  36035. mouse.y = -(e.clientY / window.innerHeight) * 2 + 1;
  36036. }
  36037. function animate() {
  36038. // update options
  36039. tiles.errorTarget = params.errorTarget;
  36040. tiles.errorThreshold = params.errorThreshold;
  36041. tiles.loadSiblings = params.loadSiblings;
  36042. tiles.maxDepth = params.maxDepth;
  36043. tiles.displayBounds = params.displayBounds; // update tiles
  36044. tiles.update();
  36045. window.tiles = tiles;
  36046. offsetParent.rotation.set(0, 0, 0);
  36047. if (params.up === '-Z') {
  36048. offsetParent.rotation.x = Math.PI / 2;
  36049. } // update tiles center
  36050. if (tiles.getBounds(box)) {
  36051. box.getCenter(tiles.group.position);
  36052. tiles.group.position.multiplyScalar(-1);
  36053. }
  36054. raycaster.setFromCamera(mouse, camera);
  36055. const results = raycaster.intersectObject(tiles.group, true);
  36056. if (results.length) {
  36057. const closestHit = results[0];
  36058. const point = closestHit.point;
  36059. rayIntersect.position.copy(point); // If the display bounds are visible they get intersected
  36060. if (closestHit.face) {
  36061. const normal = closestHit.face.normal;
  36062. rayIntersect.lookAt(point.x + normal.x, point.y + normal.y, point.z + normal.z);
  36063. }
  36064. rayIntersect.visible = true;
  36065. } else {
  36066. rayIntersect.visible = false;
  36067. }
  36068. stats.begin();
  36069. render();
  36070. stats.end();
  36071. requestAnimationFrame(animate);
  36072. }
  36073. function render() {
  36074. // render primary view
  36075. cameraHelper.visible = false;
  36076. renderer.render(scene, camera); // render third person view
  36077. thirdPersonRenderer.domElement.style.visibility = params.showThirdPerson ? 'visible' : 'hidden';
  36078. if (params.showThirdPerson) {
  36079. cameraHelper.visible = true;
  36080. thirdPersonRenderer.render(scene, thirdPersonCamera);
  36081. }
  36082. statsContainer.innerText = `Downloading: ${tiles.stats.downloading} Parsing: ${tiles.stats.parsing} Visible: ${tiles.group.children.length}`;
  36083. }
  36084. },{"../src/index.js":"../src/index.js","three":"../node_modules/three/build/three.module.js","three/examples/jsm/controls/OrbitControls.js":"../node_modules/three/examples/jsm/controls/OrbitControls.js","three/examples/jsm/libs/dat.gui.module.js":"../node_modules/three/examples/jsm/libs/dat.gui.module.js","three/examples/jsm/libs/stats.module.js":"../node_modules/three/examples/jsm/libs/stats.module.js"}],"../node_modules/parcel-bundler/src/builtins/hmr-runtime.js":[function(require,module,exports) {
  36085. var global = arguments[3];
  36086. var OVERLAY_ID = '__parcel__error__overlay__';
  36087. var OldModule = module.bundle.Module;
  36088. function Module(moduleName) {
  36089. OldModule.call(this, moduleName);
  36090. this.hot = {
  36091. data: module.bundle.hotData,
  36092. _acceptCallbacks: [],
  36093. _disposeCallbacks: [],
  36094. accept: function (fn) {
  36095. this._acceptCallbacks.push(fn || function () {});
  36096. },
  36097. dispose: function (fn) {
  36098. this._disposeCallbacks.push(fn);
  36099. }
  36100. };
  36101. module.bundle.hotData = null;
  36102. }
  36103. module.bundle.Module = Module;
  36104. var checkedAssets, assetsToAccept;
  36105. var parent = module.bundle.parent;
  36106. if ((!parent || !parent.isParcelRequire) && typeof WebSocket !== 'undefined') {
  36107. var hostname = "" || location.hostname;
  36108. var protocol = location.protocol === 'https:' ? 'wss' : 'ws';
  36109. var ws = new WebSocket(protocol + '://' + hostname + ':' + "52787" + '/');
  36110. ws.onmessage = function (event) {
  36111. checkedAssets = {};
  36112. assetsToAccept = [];
  36113. var data = JSON.parse(event.data);
  36114. if (data.type === 'update') {
  36115. var handled = false;
  36116. data.assets.forEach(function (asset) {
  36117. if (!asset.isNew) {
  36118. var didAccept = hmrAcceptCheck(global.parcelRequire, asset.id);
  36119. if (didAccept) {
  36120. handled = true;
  36121. }
  36122. }
  36123. }); // Enable HMR for CSS by default.
  36124. handled = handled || data.assets.every(function (asset) {
  36125. return asset.type === 'css' && asset.generated.js;
  36126. });
  36127. if (handled) {
  36128. console.clear();
  36129. data.assets.forEach(function (asset) {
  36130. hmrApply(global.parcelRequire, asset);
  36131. });
  36132. assetsToAccept.forEach(function (v) {
  36133. hmrAcceptRun(v[0], v[1]);
  36134. });
  36135. } else if (location.reload) {
  36136. // `location` global exists in a web worker context but lacks `.reload()` function.
  36137. location.reload();
  36138. }
  36139. }
  36140. if (data.type === 'reload') {
  36141. ws.close();
  36142. ws.onclose = function () {
  36143. location.reload();
  36144. };
  36145. }
  36146. if (data.type === 'error-resolved') {
  36147. console.log('[parcel] ✨ Error resolved');
  36148. removeErrorOverlay();
  36149. }
  36150. if (data.type === 'error') {
  36151. console.error('[parcel] 🚨 ' + data.error.message + '\n' + data.error.stack);
  36152. removeErrorOverlay();
  36153. var overlay = createErrorOverlay(data);
  36154. document.body.appendChild(overlay);
  36155. }
  36156. };
  36157. }
  36158. function removeErrorOverlay() {
  36159. var overlay = document.getElementById(OVERLAY_ID);
  36160. if (overlay) {
  36161. overlay.remove();
  36162. }
  36163. }
  36164. function createErrorOverlay(data) {
  36165. var overlay = document.createElement('div');
  36166. overlay.id = OVERLAY_ID; // html encode message and stack trace
  36167. var message = document.createElement('div');
  36168. var stackTrace = document.createElement('pre');
  36169. message.innerText = data.error.message;
  36170. stackTrace.innerText = data.error.stack;
  36171. 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>';
  36172. return overlay;
  36173. }
  36174. function getParents(bundle, id) {
  36175. var modules = bundle.modules;
  36176. if (!modules) {
  36177. return [];
  36178. }
  36179. var parents = [];
  36180. var k, d, dep;
  36181. for (k in modules) {
  36182. for (d in modules[k][1]) {
  36183. dep = modules[k][1][d];
  36184. if (dep === id || Array.isArray(dep) && dep[dep.length - 1] === id) {
  36185. parents.push(k);
  36186. }
  36187. }
  36188. }
  36189. if (bundle.parent) {
  36190. parents = parents.concat(getParents(bundle.parent, id));
  36191. }
  36192. return parents;
  36193. }
  36194. function hmrApply(bundle, asset) {
  36195. var modules = bundle.modules;
  36196. if (!modules) {
  36197. return;
  36198. }
  36199. if (modules[asset.id] || !bundle.parent) {
  36200. var fn = new Function('require', 'module', 'exports', asset.generated.js);
  36201. asset.isNew = !modules[asset.id];
  36202. modules[asset.id] = [fn, asset.deps];
  36203. } else if (bundle.parent) {
  36204. hmrApply(bundle.parent, asset);
  36205. }
  36206. }
  36207. function hmrAcceptCheck(bundle, id) {
  36208. var modules = bundle.modules;
  36209. if (!modules) {
  36210. return;
  36211. }
  36212. if (!modules[id] && bundle.parent) {
  36213. return hmrAcceptCheck(bundle.parent, id);
  36214. }
  36215. if (checkedAssets[id]) {
  36216. return;
  36217. }
  36218. checkedAssets[id] = true;
  36219. var cached = bundle.cache[id];
  36220. assetsToAccept.push([bundle, id]);
  36221. if (cached && cached.hot && cached.hot._acceptCallbacks.length) {
  36222. return true;
  36223. }
  36224. return getParents(global.parcelRequire, id).some(function (id) {
  36225. return hmrAcceptCheck(global.parcelRequire, id);
  36226. });
  36227. }
  36228. function hmrAcceptRun(bundle, id) {
  36229. var cached = bundle.cache[id];
  36230. bundle.hotData = {};
  36231. if (cached) {
  36232. cached.hot.data = bundle.hotData;
  36233. }
  36234. if (cached && cached.hot && cached.hot._disposeCallbacks.length) {
  36235. cached.hot._disposeCallbacks.forEach(function (cb) {
  36236. cb(bundle.hotData);
  36237. });
  36238. }
  36239. delete bundle.cache[id];
  36240. bundle(id);
  36241. cached = bundle.cache[id];
  36242. if (cached && cached.hot && cached.hot._acceptCallbacks.length) {
  36243. cached.hot._acceptCallbacks.forEach(function (cb) {
  36244. cb();
  36245. });
  36246. return true;
  36247. }
  36248. }
  36249. },{}]},{},["../node_modules/parcel-bundler/src/builtins/hmr-runtime.js","index.js"], null)
  36250. //# sourceMappingURL=example.e31bb0bc.js.map