example.e31bb0bc.js 1.4 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447374483744937450374513745237453374543745537456374573745837459374603746137462374633746437465374663746737468374693747037471374723747337474374753747637477374783747937480374813748237483374843748537486374873748837489374903749137492374933749437495374963749737498374993750037501375023750337504375053750637507375083750937510375113751237513375143751537516375173751837519375203752137522375233752437525375263752737528375293753037531375323753337534375353753637537375383753937540375413754237543375443754537546375473754837549375503755137552375533755437555375563755737558375593756037561375623756337564375653756637567375683756937570375713757237573375743757537576375773757837579375803758137582375833758437585375863758737588375893759037591375923759337594375953759637597375983759937600376013760237603376043760537606376073760837609376103761137612376133761437615376163761737618376193762037621376223762337624376253762637627376283762937630376313763237633376343763537636376373763837639376403764137642376433764437645376463764737648376493765037651376523765337654376553765637657376583765937660376613766237663376643766537666376673766837669376703767137672376733767437675376763767737678376793768037681376823768337684376853768637687376883768937690376913769237693376943769537696376973769837699377003770137702377033770437705377063770737708377093771037711377123771337714377153771637717377183771937720377213772237723377243772537726377273772837729377303773137732377333773437735377363773737738377393774037741377423774337744377453774637747377483774937750377513775237753377543775537756377573775837759377603776137762377633776437765377663776737768377693777037771377723777337774377753777637777377783777937780377813778237783377843778537786377873778837789377903779137792377933779437795377963779737798377993780037801378023780337804378053780637807378083780937810378113781237813378143781537816378173781837819378203782137822378233782437825378263782737828378293783037831378323783337834378353783637837378383783937840378413784237843378443784537846378473784837849378503785137852378533785437855378563785737858378593786037861378623786337864378653786637867378683786937870378713787237873378743787537876378773787837879378803788137882378833788437885378863788737888378893789037891378923789337894378953789637897378983789937900379013790237903379043790537906379073790837909379103791137912379133791437915379163791737918379193792037921379223792337924379253792637927379283792937930379313793237933379343793537936379373793837939379403794137942379433794437945379463794737948379493795037951379523795337954379553795637957379583795937960379613796237963379643796537966379673796837969379703797137972379733797437975379763797737978379793798037981379823798337984379853798637987379883798937990379913799237993379943799537996379973799837999380003800138002380033800438005380063800738008380093801038011380123801338014380153801638017380183801938020380213802238023380243802538026380273802838029380303803138032380333803438035380363803738038380393804038041380423804338044380453804638047380483804938050380513805238053380543805538056380573805838059380603806138062380633806438065380663806738068380693807038071380723807338074380753807638077380783807938080380813808238083380843808538086380873808838089380903809138092380933809438095380963809738098380993810038101381023810338104381053810638107381083810938110381113811238113381143811538116381173811838119381203812138122381233812438125381263812738128381293813038131381323813338134381353813638137381383813938140381413814238143381443814538146381473814838149381503815138152381533815438155381563815738158381593816038161381623816338164381653816638167381683816938170381713817238173381743817538176381773817838179381803818138182381833818438185381863818738188381893819038191381923819338194381953819638197381983819938200382013820238203382043820538206382073820838209382103821138212382133821438215382163821738218382193822038221382223822338224382253822638227382283822938230382313823238233382343823538236382373823838239382403824138242382433824438245382463824738248382493825038251382523825338254382553825638257382583825938260382613826238263382643826538266382673826838269382703827138272382733827438275382763827738278382793828038281382823828338284382853828638287382883828938290382913829238293382943829538296382973829838299383003830138302383033830438305383063830738308383093831038311383123831338314383153831638317383183831938320383213832238323383243832538326383273832838329383303833138332383333833438335383363833738338383393834038341383423834338344383453834638347383483834938350383513835238353383543835538356383573835838359383603836138362383633836438365383663836738368383693837038371383723837338374383753837638377383783837938380383813838238383383843838538386383873838838389383903839138392383933839438395383963839738398383993840038401384023840338404384053840638407384083840938410384113841238413384143841538416384173841838419384203842138422384233842438425384263842738428384293843038431384323843338434384353843638437384383843938440384413844238443384443844538446384473844838449384503845138452384533845438455384563845738458384593846038461384623846338464384653846638467384683846938470384713847238473384743847538476384773847838479384803848138482384833848438485384863848738488384893849038491384923849338494384953849638497384983849938500385013850238503385043850538506385073850838509385103851138512385133851438515385163851738518385193852038521385223852338524385253852638527385283852938530385313853238533385343853538536385373853838539385403854138542385433854438545385463854738548385493855038551385523855338554385553855638557385583855938560385613856238563385643856538566385673856838569385703857138572385733857438575385763857738578385793858038581385823858338584385853858638587385883858938590385913859238593385943859538596385973859838599386003860138602386033860438605386063860738608386093861038611386123861338614386153861638617386183861938620386213862238623386243862538626386273862838629386303863138632386333863438635386363863738638386393864038641386423864338644386453864638647386483864938650386513865238653386543865538656386573865838659386603866138662386633866438665386663866738668386693867038671386723867338674386753867638677386783867938680386813868238683386843868538686386873868838689386903869138692386933869438695386963869738698386993870038701387023870338704387053870638707387083870938710387113871238713387143871538716387173871838719387203872138722387233872438725387263872738728387293873038731387323873338734387353873638737387383873938740387413874238743387443874538746387473874838749387503875138752387533875438755387563875738758387593876038761387623876338764387653876638767387683876938770387713877238773387743877538776387773877838779387803878138782387833878438785387863878738788387893879038791387923879338794387953879638797387983879938800388013880238803388043880538806388073880838809388103881138812388133881438815388163881738818388193882038821388223882338824388253882638827388283882938830388313883238833388343883538836388373883838839388403884138842388433884438845388463884738848388493885038851388523885338854388553885638857388583885938860388613886238863388643886538866388673886838869388703887138872388733887438875388763887738878388793888038881388823888338884388853888638887388883888938890388913889238893388943889538896388973889838899389003890138902389033890438905389063890738908389093891038911389123891338914389153891638917389183891938920389213892238923389243892538926389273892838929389303893138932389333893438935389363893738938389393894038941389423894338944389453894638947389483894938950389513895238953389543895538956389573895838959389603896138962389633896438965389663896738968389693897038971389723897338974389753897638977389783897938980389813898238983389843898538986389873898838989389903899138992389933899438995389963899738998389993900039001390023900339004390053900639007390083900939010390113901239013390143901539016390173901839019390203902139022390233902439025390263902739028390293903039031390323903339034390353903639037390383903939040390413904239043390443904539046390473904839049390503905139052390533905439055390563905739058390593906039061390623906339064390653906639067390683906939070390713907239073390743907539076390773907839079390803908139082390833908439085390863908739088390893909039091390923909339094390953909639097390983909939100391013910239103391043910539106391073910839109391103911139112391133911439115391163911739118391193912039121391223912339124391253912639127391283912939130391313913239133391343913539136391373913839139391403914139142391433914439145391463914739148391493915039151391523915339154391553915639157391583915939160391613916239163391643916539166391673916839169391703917139172391733917439175391763917739178391793918039181391823918339184391853918639187391883918939190391913919239193391943919539196391973919839199392003920139202392033920439205392063920739208392093921039211392123921339214392153921639217392183921939220392213922239223392243922539226392273922839229392303923139232392333923439235392363923739238392393924039241392423924339244392453924639247392483924939250392513925239253392543925539256392573925839259392603926139262392633926439265392663926739268392693927039271392723927339274392753927639277392783927939280392813928239283392843928539286392873928839289392903929139292392933929439295392963929739298392993930039301393023930339304393053930639307393083930939310393113931239313393143931539316393173931839319393203932139322393233932439325393263932739328393293933039331393323933339334393353933639337393383933939340393413934239343393443934539346393473934839349393503935139352393533935439355393563935739358393593936039361393623936339364393653936639367393683936939370393713937239373393743937539376393773937839379393803938139382393833938439385393863938739388393893939039391393923939339394393953939639397393983939939400394013940239403394043940539406394073940839409394103941139412394133941439415394163941739418394193942039421394223942339424394253942639427394283942939430394313943239433394343943539436394373943839439394403944139442394433944439445394463944739448394493945039451394523945339454394553945639457394583945939460394613946239463394643946539466394673946839469394703947139472394733947439475394763947739478394793948039481394823948339484394853948639487394883948939490394913949239493394943949539496394973949839499395003950139502395033950439505395063950739508395093951039511395123951339514395153951639517395183951939520395213952239523395243952539526395273952839529395303953139532395333953439535395363953739538395393954039541395423954339544395453954639547395483954939550395513955239553395543955539556395573955839559395603956139562395633956439565395663956739568395693957039571395723957339574395753957639577395783957939580395813958239583395843958539586395873958839589395903959139592395933959439595395963959739598395993960039601396023960339604396053960639607396083960939610396113961239613396143961539616396173961839619396203962139622396233962439625396263962739628396293963039631396323963339634396353963639637396383963939640396413964239643396443964539646396473964839649396503965139652396533965439655396563965739658396593966039661396623966339664396653966639667396683966939670396713967239673396743967539676396773967839679396803968139682396833968439685396863968739688396893969039691396923969339694396953969639697396983969939700397013970239703397043970539706397073970839709397103971139712397133971439715397163971739718397193972039721397223972339724397253972639727397283972939730397313973239733397343973539736397373973839739397403974139742397433974439745397463974739748397493975039751397523975339754397553975639757397583975939760397613976239763397643976539766397673976839769397703977139772397733977439775397763977739778397793978039781397823978339784397853978639787397883978939790397913979239793397943979539796397973979839799398003980139802398033980439805398063980739808398093981039811398123981339814398153981639817398183981939820398213982239823398243982539826398273982839829398303983139832398333983439835398363983739838398393984039841398423984339844398453984639847398483984939850398513985239853398543985539856398573985839859398603986139862398633986439865398663986739868398693987039871398723987339874398753987639877398783987939880398813988239883398843988539886398873988839889398903989139892398933989439895398963989739898398993990039901399023990339904399053990639907399083990939910399113991239913399143991539916399173991839919399203992139922399233992439925399263992739928399293993039931399323993339934399353993639937399383993939940399413994239943399443994539946399473994839949399503995139952399533995439955399563995739958399593996039961399623996339964399653996639967399683996939970399713997239973399743997539976399773997839979399803998139982399833998439985399863998739988399893999039991399923999339994399953999639997399983999940000400014000240003400044000540006400074000840009400104001140012400134001440015400164001740018400194002040021400224002340024400254002640027400284002940030400314003240033400344003540036400374003840039400404004140042400434004440045400464004740048400494005040051400524005340054400554005640057400584005940060400614006240063400644006540066400674006840069400704007140072400734007440075400764007740078400794008040081400824008340084400854008640087400884008940090400914009240093400944009540096400974009840099401004010140102401034010440105401064010740108401094011040111401124011340114401154011640117401184011940120401214012240123401244012540126401274012840129401304013140132401334013440135401364013740138401394014040141401424014340144401454014640147401484014940150401514015240153401544015540156401574015840159401604016140162401634016440165401664016740168401694017040171401724017340174401754017640177401784017940180401814018240183401844018540186401874018840189401904019140192401934019440195401964019740198401994020040201402024020340204402054020640207402084020940210402114021240213402144021540216402174021840219402204022140222402234022440225402264022740228402294023040231402324023340234402354023640237402384023940240402414024240243402444024540246402474024840249402504025140252402534025440255402564025740258402594026040261402624026340264402654026640267402684026940270402714027240273402744027540276402774027840279402804028140282402834028440285402864028740288402894029040291402924029340294402954029640297402984029940300403014030240303403044030540306403074030840309403104031140312403134031440315403164031740318403194032040321403224032340324403254032640327403284032940330403314033240333403344033540336403374033840339403404034140342403434034440345403464034740348403494035040351403524035340354403554035640357403584035940360403614036240363403644036540366403674036840369403704037140372403734037440375403764037740378403794038040381403824038340384403854038640387403884038940390403914039240393403944039540396403974039840399404004040140402404034040440405404064040740408404094041040411404124041340414404154041640417404184041940420404214042240423404244042540426404274042840429404304043140432404334043440435404364043740438404394044040441404424044340444404454044640447404484044940450404514045240453404544045540456404574045840459404604046140462404634046440465404664046740468404694047040471404724047340474404754047640477404784047940480404814048240483404844048540486404874048840489404904049140492404934049440495404964049740498404994050040501405024050340504405054050640507405084050940510405114051240513405144051540516405174051840519405204052140522405234052440525405264052740528405294053040531405324053340534405354053640537405384053940540405414054240543405444054540546405474054840549405504055140552405534055440555405564055740558405594056040561405624056340564405654056640567405684056940570405714057240573405744057540576405774057840579405804058140582405834058440585405864058740588405894059040591405924059340594405954059640597405984059940600406014060240603406044060540606406074060840609406104061140612406134061440615406164061740618406194062040621406224062340624406254062640627406284062940630406314063240633406344063540636406374063840639406404064140642406434064440645406464064740648406494065040651406524065340654406554065640657406584065940660406614066240663406644066540666406674066840669406704067140672406734067440675406764067740678406794068040681406824068340684406854068640687406884068940690406914069240693406944069540696406974069840699407004070140702407034070440705407064070740708407094071040711407124071340714407154071640717407184071940720407214072240723407244072540726407274072840729407304073140732407334073440735407364073740738407394074040741407424074340744407454074640747407484074940750407514075240753407544075540756407574075840759407604076140762407634076440765407664076740768407694077040771407724077340774407754077640777407784077940780407814078240783407844078540786407874078840789407904079140792407934079440795407964079740798407994080040801408024080340804408054080640807408084080940810408114081240813408144081540816408174081840819408204082140822408234082440825408264082740828408294083040831408324083340834408354083640837408384083940840408414084240843408444084540846408474084840849408504085140852408534085440855408564085740858408594086040861408624086340864408654086640867408684086940870408714087240873408744087540876408774087840879408804088140882408834088440885408864088740888408894089040891408924089340894408954089640897408984089940900409014090240903409044090540906409074090840909409104091140912409134091440915409164091740918409194092040921409224092340924409254092640927409284092940930409314093240933409344093540936409374093840939409404094140942409434094440945409464094740948409494095040951409524095340954409554095640957409584095940960409614096240963409644096540966409674096840969409704097140972409734097440975409764097740978409794098040981409824098340984409854098640987409884098940990409914099240993409944099540996409974099840999410004100141002410034100441005410064100741008410094101041011410124101341014410154101641017410184101941020410214102241023410244102541026410274102841029410304103141032410334103441035410364103741038410394104041041410424104341044410454104641047410484104941050410514105241053410544105541056410574105841059410604106141062410634106441065410664106741068410694107041071410724107341074410754107641077410784107941080410814108241083410844108541086410874108841089410904109141092410934109441095410964109741098410994110041101411024110341104411054110641107411084110941110411114111241113411144111541116411174111841119411204112141122411234112441125411264112741128411294113041131411324113341134411354113641137411384113941140411414114241143411444114541146411474114841149411504115141152411534115441155411564115741158411594116041161411624116341164411654116641167411684116941170411714117241173411744117541176411774117841179411804118141182411834118441185411864118741188411894119041191411924119341194411954119641197411984119941200412014120241203412044120541206412074120841209412104121141212412134121441215412164121741218412194122041221412224122341224412254122641227412284122941230412314123241233412344123541236412374123841239412404124141242412434124441245412464124741248412494125041251412524125341254412554125641257412584125941260412614126241263412644126541266412674126841269412704127141272412734127441275412764127741278412794128041281412824128341284412854128641287412884128941290412914129241293412944129541296412974129841299413004130141302413034130441305413064130741308413094131041311413124131341314413154131641317413184131941320413214132241323413244132541326413274132841329413304133141332413334133441335413364133741338413394134041341413424134341344413454134641347413484134941350413514135241353413544135541356413574135841359413604136141362413634136441365413664136741368413694137041371413724137341374413754137641377413784137941380413814138241383413844138541386413874138841389413904139141392413934139441395413964139741398413994140041401414024140341404414054140641407414084140941410414114141241413414144141541416414174141841419414204142141422414234142441425414264142741428414294143041431414324143341434414354143641437414384143941440414414144241443414444144541446414474144841449414504145141452414534145441455414564145741458414594146041461414624146341464414654146641467414684146941470414714147241473414744147541476414774147841479414804148141482414834148441485414864148741488414894149041491414924149341494414954149641497414984149941500415014150241503415044150541506415074150841509415104151141512415134151441515415164151741518415194152041521415224152341524415254152641527415284152941530415314153241533415344153541536415374153841539415404154141542415434154441545415464154741548415494155041551415524155341554415554155641557415584155941560415614156241563415644156541566415674156841569415704157141572415734157441575415764157741578415794158041581415824158341584415854158641587415884158941590415914159241593415944159541596415974159841599416004160141602416034160441605416064160741608416094161041611416124161341614416154161641617416184161941620416214162241623416244162541626416274162841629416304163141632416334163441635416364163741638416394164041641416424164341644416454164641647416484164941650416514165241653416544165541656416574165841659416604166141662416634166441665416664166741668416694167041671416724167341674416754167641677416784167941680416814168241683416844168541686416874168841689416904169141692416934169441695416964169741698416994170041701417024170341704417054170641707417084170941710417114171241713417144171541716417174171841719417204172141722417234172441725417264172741728417294173041731417324173341734417354173641737417384173941740417414174241743417444174541746417474174841749417504175141752417534175441755417564175741758417594176041761417624176341764417654176641767417684176941770417714177241773417744177541776417774177841779417804178141782417834178441785417864178741788417894179041791417924179341794417954179641797417984179941800418014180241803418044180541806418074180841809418104181141812418134181441815418164181741818418194182041821418224182341824418254182641827418284182941830418314183241833418344183541836418374183841839418404184141842418434184441845418464184741848418494185041851418524185341854418554185641857418584185941860418614186241863418644186541866418674186841869418704187141872418734187441875418764187741878418794188041881418824188341884418854188641887418884188941890418914189241893418944189541896418974189841899419004190141902419034190441905419064190741908419094191041911419124191341914419154191641917419184191941920419214192241923419244192541926419274192841929419304193141932419334193441935419364193741938419394194041941419424194341944419454194641947419484194941950419514195241953419544195541956419574195841959419604196141962419634196441965419664196741968419694197041971419724197341974419754197641977419784197941980419814198241983419844198541986419874198841989419904199141992419934199441995419964199741998419994200042001420024200342004420054200642007420084200942010420114201242013420144201542016420174201842019420204202142022420234202442025420264202742028420294203042031420324203342034420354203642037420384203942040420414204242043420444204542046420474204842049420504205142052420534205442055420564205742058420594206042061420624206342064420654206642067420684206942070420714207242073420744207542076420774207842079420804208142082420834208442085420864208742088420894209042091420924209342094420954209642097420984209942100421014210242103421044210542106421074210842109421104211142112421134211442115421164211742118421194212042121421224212342124421254212642127421284212942130421314213242133421344213542136421374213842139421404214142142421434214442145421464214742148421494215042151421524215342154421554215642157421584215942160421614216242163421644216542166421674216842169421704217142172421734217442175421764217742178421794218042181421824218342184421854218642187421884218942190421914219242193421944219542196421974219842199422004220142202422034220442205422064220742208422094221042211422124221342214422154221642217422184221942220422214222242223422244222542226422274222842229422304223142232422334223442235422364223742238422394224042241422424224342244422454224642247422484224942250422514225242253422544225542256422574225842259422604226142262422634226442265422664226742268422694227042271422724227342274422754227642277422784227942280422814228242283422844228542286422874228842289422904229142292422934229442295422964229742298422994230042301423024230342304423054230642307423084230942310423114231242313423144231542316423174231842319423204232142322423234232442325423264232742328423294233042331423324233342334423354233642337423384233942340423414234242343423444234542346423474234842349423504235142352423534235442355423564235742358423594236042361423624236342364423654236642367423684236942370423714237242373423744237542376423774237842379423804238142382423834238442385423864238742388423894239042391423924239342394423954239642397423984239942400424014240242403424044240542406424074240842409424104241142412424134241442415424164241742418424194242042421424224242342424424254242642427424284242942430424314243242433424344243542436424374243842439424404244142442424434244442445424464244742448424494245042451424524245342454424554245642457424584245942460424614246242463424644246542466424674246842469424704247142472424734247442475424764247742478424794248042481424824248342484424854248642487424884248942490424914249242493424944249542496424974249842499425004250142502425034250442505425064250742508425094251042511425124251342514425154251642517425184251942520425214252242523425244252542526425274252842529425304253142532425334253442535425364253742538425394254042541425424254342544425454254642547425484254942550425514255242553425544255542556425574255842559425604256142562425634256442565425664256742568425694257042571425724257342574425754257642577425784257942580425814258242583425844258542586425874258842589425904259142592425934259442595425964259742598425994260042601426024260342604426054260642607426084260942610426114261242613426144261542616426174261842619426204262142622426234262442625426264262742628426294263042631426324263342634426354263642637426384263942640426414264242643426444264542646426474264842649426504265142652426534265442655426564265742658426594266042661426624266342664426654266642667426684266942670426714267242673426744267542676426774267842679426804268142682426834268442685426864268742688426894269042691426924269342694426954269642697426984269942700427014270242703427044270542706427074270842709427104271142712427134271442715427164271742718427194272042721427224272342724427254272642727427284272942730427314273242733427344273542736427374273842739427404274142742427434274442745427464274742748427494275042751427524275342754427554275642757427584275942760427614276242763427644276542766427674276842769427704277142772427734277442775427764277742778427794278042781427824278342784427854278642787427884278942790427914279242793427944279542796427974279842799428004280142802428034280442805428064280742808428094281042811428124281342814428154281642817428184281942820428214282242823428244282542826428274282842829428304283142832428334283442835428364283742838428394284042841428424284342844428454284642847428484284942850428514285242853428544285542856428574285842859428604286142862428634286442865428664286742868428694287042871428724287342874428754287642877428784287942880428814288242883428844288542886428874288842889428904289142892428934289442895428964289742898428994290042901429024290342904429054290642907429084290942910429114291242913429144291542916429174291842919429204292142922429234292442925429264292742928429294293042931429324293342934429354293642937429384293942940429414294242943429444294542946429474294842949429504295142952429534295442955429564295742958429594296042961429624296342964429654296642967429684296942970429714297242973429744297542976429774297842979429804298142982429834298442985429864298742988429894299042991429924299342994429954299642997429984299943000430014300243003430044300543006430074300843009430104301143012430134301443015430164301743018430194302043021430224302343024430254302643027430284302943030430314303243033430344303543036430374303843039430404304143042430434304443045430464304743048430494305043051430524305343054430554305643057430584305943060430614306243063430644306543066430674306843069430704307143072430734307443075430764307743078430794308043081430824308343084430854308643087430884308943090430914309243093430944309543096430974309843099431004310143102431034310443105431064310743108431094311043111431124311343114431154311643117431184311943120431214312243123431244312543126431274312843129431304313143132431334313443135431364313743138431394314043141431424314343144431454314643147431484314943150431514315243153431544315543156431574315843159431604316143162431634316443165431664316743168431694317043171431724317343174431754317643177431784317943180431814318243183431844318543186431874318843189431904319143192431934319443195431964319743198431994320043201432024320343204432054320643207432084320943210432114321243213432144321543216432174321843219432204322143222432234322443225432264322743228432294323043231432324323343234432354323643237432384323943240432414324243243432444324543246432474324843249432504325143252432534325443255432564325743258432594326043261432624326343264432654326643267432684326943270432714327243273432744327543276432774327843279432804328143282432834328443285432864328743288432894329043291432924329343294432954329643297432984329943300433014330243303433044330543306433074330843309433104331143312433134331443315433164331743318433194332043321433224332343324433254332643327433284332943330433314333243333433344333543336433374333843339433404334143342433434334443345433464334743348433494335043351433524335343354433554335643357433584335943360433614336243363433644336543366433674336843369433704337143372433734337443375433764337743378433794338043381433824338343384433854338643387433884338943390433914339243393433944339543396433974339843399434004340143402434034340443405434064340743408434094341043411434124341343414434154341643417434184341943420434214342243423434244342543426434274342843429434304343143432434334343443435434364343743438434394344043441434424344343444434454344643447434484344943450434514345243453434544345543456434574345843459434604346143462434634346443465434664346743468434694347043471434724347343474434754347643477434784347943480434814348243483434844348543486434874348843489434904349143492434934349443495434964349743498434994350043501435024350343504435054350643507435084350943510435114351243513435144351543516435174351843519435204352143522435234352443525435264352743528435294353043531435324353343534435354353643537435384353943540435414354243543435444354543546435474354843549435504355143552435534355443555435564355743558435594356043561435624356343564435654356643567435684356943570435714357243573435744357543576435774357843579435804358143582435834358443585435864358743588435894359043591435924359343594435954359643597435984359943600436014360243603436044360543606436074360843609436104361143612436134361443615436164361743618436194362043621436224362343624436254362643627436284362943630436314363243633436344363543636436374363843639436404364143642436434364443645436464364743648436494365043651436524365343654436554365643657436584365943660436614366243663436644366543666436674366843669436704367143672436734367443675436764367743678436794368043681436824368343684436854368643687436884368943690436914369243693436944369543696436974369843699437004370143702437034370443705437064370743708437094371043711437124371343714437154371643717437184371943720437214372243723437244372543726437274372843729437304373143732437334373443735437364373743738437394374043741437424374343744437454374643747437484374943750437514375243753437544375543756437574375843759437604376143762437634376443765437664376743768437694377043771437724377343774437754377643777437784377943780437814378243783437844378543786437874378843789437904379143792437934379443795437964379743798437994380043801438024380343804438054380643807438084380943810438114381243813438144381543816438174381843819438204382143822438234382443825438264382743828438294383043831438324383343834438354383643837438384383943840438414384243843438444384543846438474384843849438504385143852438534385443855438564385743858438594386043861438624386343864438654386643867438684386943870438714387243873438744387543876438774387843879438804388143882438834388443885438864388743888438894389043891438924389343894438954389643897438984389943900439014390243903439044390543906439074390843909439104391143912439134391443915439164391743918439194392043921439224392343924439254392643927439284392943930439314393243933439344393543936439374393843939439404394143942439434394443945439464394743948439494395043951439524395343954439554395643957439584395943960439614396243963439644396543966439674396843969439704397143972439734397443975439764397743978439794398043981439824398343984439854398643987439884398943990439914399243993439944399543996439974399843999440004400144002440034400444005440064400744008440094401044011440124401344014440154401644017440184401944020440214402244023440244402544026440274402844029440304403144032440334403444035440364403744038440394404044041440424404344044440454404644047440484404944050
  1. // modules are defined as an array
  2. // [ module function, map of requires ]
  3. //
  4. // map of requires is short require name -> numeric require
  5. //
  6. // anything defined in a previous bundle is accessed via the
  7. // orig method which is the require for previous bundles
  8. parcelRequire = (function (modules, cache, entry, globalName) {
  9. // Save the require from previous bundle to this closure if any
  10. var previousRequire = typeof parcelRequire === 'function' && parcelRequire;
  11. var nodeRequire = typeof require === 'function' && require;
  12. function newRequire(name, jumped) {
  13. if (!cache[name]) {
  14. if (!modules[name]) {
  15. // if we cannot find the module within our internal map or
  16. // cache jump to the current global require ie. the last bundle
  17. // that was added to the page.
  18. var currentRequire = typeof parcelRequire === 'function' && parcelRequire;
  19. if (!jumped && currentRequire) {
  20. return currentRequire(name, true);
  21. }
  22. // If there are other bundles on this page the require from the
  23. // previous one is saved to 'previousRequire'. Repeat this as
  24. // many times as there are bundles until the module is found or
  25. // we exhaust the require chain.
  26. if (previousRequire) {
  27. return previousRequire(name, true);
  28. }
  29. // Try the node require function if it exists.
  30. if (nodeRequire && typeof name === 'string') {
  31. return nodeRequire(name);
  32. }
  33. var err = new Error('Cannot find module \'' + name + '\'');
  34. err.code = 'MODULE_NOT_FOUND';
  35. throw err;
  36. }
  37. localRequire.resolve = resolve;
  38. localRequire.cache = {};
  39. var module = cache[name] = new newRequire.Module(name);
  40. modules[name][0].call(module.exports, localRequire, module, module.exports, this);
  41. }
  42. return cache[name].exports;
  43. function localRequire(x){
  44. return newRequire(localRequire.resolve(x));
  45. }
  46. function resolve(x){
  47. return modules[name][1][x] || x;
  48. }
  49. }
  50. function Module(moduleName) {
  51. this.id = moduleName;
  52. this.bundle = newRequire;
  53. this.exports = {};
  54. }
  55. newRequire.isParcelRequire = true;
  56. newRequire.Module = Module;
  57. newRequire.modules = modules;
  58. newRequire.cache = cache;
  59. newRequire.parent = previousRequire;
  60. newRequire.register = function (id, exports) {
  61. modules[id] = [function (require, module) {
  62. module.exports = exports;
  63. }, {}];
  64. };
  65. var error;
  66. for (var i = 0; i < entry.length; i++) {
  67. try {
  68. newRequire(entry[i]);
  69. } catch (e) {
  70. // Save first error but execute all entries
  71. if (!error) {
  72. error = e;
  73. }
  74. }
  75. }
  76. if (entry.length) {
  77. // Expose entry point to Node, AMD or browser globals
  78. // Based on https://github.com/ForbesLindesay/umd/blob/master/template.js
  79. var mainExports = newRequire(entry[entry.length - 1]);
  80. // CommonJS
  81. if (typeof exports === "object" && typeof module !== "undefined") {
  82. module.exports = mainExports;
  83. // RequireJS
  84. } else if (typeof define === "function" && define.amd) {
  85. define(function () {
  86. return mainExports;
  87. });
  88. // <script>
  89. } else if (globalName) {
  90. this[globalName] = mainExports;
  91. }
  92. }
  93. // Override the current require with this new one
  94. parcelRequire = newRequire;
  95. if (error) {
  96. // throw error from earlier, _after updating parcelRequire_
  97. throw error;
  98. }
  99. return newRequire;
  100. })({"../node_modules/three/build/three.module.js":[function(require,module,exports) {
  101. "use strict";
  102. Object.defineProperty(exports, "__esModule", {
  103. value: true
  104. });
  105. exports.AmbientLight = AmbientLight;
  106. exports.AmbientLightProbe = AmbientLightProbe;
  107. exports.AnimationClip = AnimationClip;
  108. exports.AnimationLoader = AnimationLoader;
  109. exports.AnimationMixer = AnimationMixer;
  110. exports.AnimationObjectGroup = AnimationObjectGroup;
  111. exports.ArcCurve = ArcCurve;
  112. exports.ArrayCamera = ArrayCamera;
  113. exports.ArrowHelper = ArrowHelper;
  114. exports.Audio = Audio;
  115. exports.AudioAnalyser = AudioAnalyser;
  116. exports.AudioListener = AudioListener;
  117. exports.AudioLoader = AudioLoader;
  118. exports.AxesHelper = AxesHelper;
  119. exports.AxisHelper = AxisHelper;
  120. exports.BinaryTextureLoader = BinaryTextureLoader;
  121. exports.Bone = Bone;
  122. exports.BooleanKeyframeTrack = BooleanKeyframeTrack;
  123. exports.BoundingBoxHelper = BoundingBoxHelper;
  124. exports.Box2 = Box2;
  125. exports.Box3 = Box3;
  126. exports.Box3Helper = Box3Helper;
  127. exports.BoxHelper = BoxHelper;
  128. exports.BufferAttribute = BufferAttribute;
  129. exports.BufferGeometry = BufferGeometry;
  130. exports.BufferGeometryLoader = BufferGeometryLoader;
  131. exports.Camera = Camera;
  132. exports.CameraHelper = CameraHelper;
  133. exports.CanvasRenderer = CanvasRenderer;
  134. exports.CanvasTexture = CanvasTexture;
  135. exports.CatmullRomCurve3 = CatmullRomCurve3;
  136. exports.CircleBufferGeometry = CircleBufferGeometry;
  137. exports.CircleGeometry = CircleGeometry;
  138. exports.Clock = Clock;
  139. exports.ClosedSplineCurve3 = ClosedSplineCurve3;
  140. exports.Color = Color;
  141. exports.ColorKeyframeTrack = ColorKeyframeTrack;
  142. exports.CompressedTexture = CompressedTexture;
  143. exports.CompressedTextureLoader = CompressedTextureLoader;
  144. exports.ConeBufferGeometry = ConeBufferGeometry;
  145. exports.ConeGeometry = ConeGeometry;
  146. exports.CubeCamera = CubeCamera;
  147. exports.CubeTexture = CubeTexture;
  148. exports.CubeTextureLoader = CubeTextureLoader;
  149. exports.CubicBezierCurve = CubicBezierCurve;
  150. exports.CubicBezierCurve3 = CubicBezierCurve3;
  151. exports.CubicInterpolant = CubicInterpolant;
  152. exports.Curve = Curve;
  153. exports.CurvePath = CurvePath;
  154. exports.CylinderBufferGeometry = CylinderBufferGeometry;
  155. exports.CylinderGeometry = CylinderGeometry;
  156. exports.Cylindrical = Cylindrical;
  157. exports.DataTexture = DataTexture;
  158. exports.DataTexture2DArray = DataTexture2DArray;
  159. exports.DataTexture3D = DataTexture3D;
  160. exports.DataTextureLoader = DataTextureLoader;
  161. exports.DepthTexture = DepthTexture;
  162. exports.DirectionalLight = DirectionalLight;
  163. exports.DirectionalLightHelper = DirectionalLightHelper;
  164. exports.DirectionalLightShadow = DirectionalLightShadow;
  165. exports.DiscreteInterpolant = DiscreteInterpolant;
  166. exports.DodecahedronBufferGeometry = DodecahedronBufferGeometry;
  167. exports.DodecahedronGeometry = DodecahedronGeometry;
  168. exports.DynamicBufferAttribute = DynamicBufferAttribute;
  169. exports.EdgesGeometry = EdgesGeometry;
  170. exports.EdgesHelper = EdgesHelper;
  171. exports.EllipseCurve = EllipseCurve;
  172. exports.Euler = Euler;
  173. exports.EventDispatcher = EventDispatcher;
  174. exports.ExtrudeBufferGeometry = ExtrudeBufferGeometry;
  175. exports.ExtrudeGeometry = ExtrudeGeometry;
  176. exports.Face3 = Face3;
  177. exports.Face4 = Face4;
  178. exports.FaceNormalsHelper = FaceNormalsHelper;
  179. exports.FileLoader = FileLoader;
  180. exports.Float32Attribute = Float32Attribute;
  181. exports.Float32BufferAttribute = Float32BufferAttribute;
  182. exports.Float64Attribute = Float64Attribute;
  183. exports.Float64BufferAttribute = Float64BufferAttribute;
  184. exports.Fog = Fog;
  185. exports.FogExp2 = FogExp2;
  186. exports.Font = Font;
  187. exports.FontLoader = FontLoader;
  188. exports.Frustum = Frustum;
  189. exports.Geometry = Geometry;
  190. exports.GridHelper = GridHelper;
  191. exports.Group = Group;
  192. exports.HemisphereLight = HemisphereLight;
  193. exports.HemisphereLightHelper = HemisphereLightHelper;
  194. exports.HemisphereLightProbe = HemisphereLightProbe;
  195. exports.IcosahedronBufferGeometry = IcosahedronBufferGeometry;
  196. exports.IcosahedronGeometry = IcosahedronGeometry;
  197. exports.ImageBitmapLoader = ImageBitmapLoader;
  198. exports.ImageLoader = ImageLoader;
  199. exports.ImmediateRenderObject = ImmediateRenderObject;
  200. exports.InstancedBufferAttribute = InstancedBufferAttribute;
  201. exports.InstancedBufferGeometry = InstancedBufferGeometry;
  202. exports.InstancedInterleavedBuffer = InstancedInterleavedBuffer;
  203. exports.InstancedMesh = InstancedMesh;
  204. exports.Int16Attribute = Int16Attribute;
  205. exports.Int16BufferAttribute = Int16BufferAttribute;
  206. exports.Int32Attribute = Int32Attribute;
  207. exports.Int32BufferAttribute = Int32BufferAttribute;
  208. exports.Int8Attribute = Int8Attribute;
  209. exports.Int8BufferAttribute = Int8BufferAttribute;
  210. exports.InterleavedBuffer = InterleavedBuffer;
  211. exports.InterleavedBufferAttribute = InterleavedBufferAttribute;
  212. exports.Interpolant = Interpolant;
  213. exports.JSONLoader = JSONLoader;
  214. exports.KeyframeTrack = KeyframeTrack;
  215. exports.LOD = LOD;
  216. exports.LatheBufferGeometry = LatheBufferGeometry;
  217. exports.LatheGeometry = LatheGeometry;
  218. exports.Layers = Layers;
  219. exports.LensFlare = LensFlare;
  220. exports.Light = Light;
  221. exports.LightProbe = LightProbe;
  222. exports.LightProbeHelper = LightProbeHelper;
  223. exports.LightShadow = LightShadow;
  224. exports.Line = Line;
  225. exports.Line3 = Line3;
  226. exports.LineBasicMaterial = LineBasicMaterial;
  227. exports.LineCurve = LineCurve;
  228. exports.LineCurve3 = LineCurve3;
  229. exports.LineDashedMaterial = LineDashedMaterial;
  230. exports.LineLoop = LineLoop;
  231. exports.LineSegments = LineSegments;
  232. exports.LinearInterpolant = LinearInterpolant;
  233. exports.Loader = Loader;
  234. exports.LoadingManager = LoadingManager;
  235. exports.Material = Material;
  236. exports.MaterialLoader = MaterialLoader;
  237. exports.Matrix3 = Matrix3;
  238. exports.Matrix4 = Matrix4;
  239. exports.Mesh = Mesh;
  240. exports.MeshBasicMaterial = MeshBasicMaterial;
  241. exports.MeshDepthMaterial = MeshDepthMaterial;
  242. exports.MeshDistanceMaterial = MeshDistanceMaterial;
  243. exports.MeshFaceMaterial = MeshFaceMaterial;
  244. exports.MeshLambertMaterial = MeshLambertMaterial;
  245. exports.MeshMatcapMaterial = MeshMatcapMaterial;
  246. exports.MeshNormalMaterial = MeshNormalMaterial;
  247. exports.MeshPhongMaterial = MeshPhongMaterial;
  248. exports.MeshPhysicalMaterial = MeshPhysicalMaterial;
  249. exports.MeshStandardMaterial = MeshStandardMaterial;
  250. exports.MeshToonMaterial = MeshToonMaterial;
  251. exports.MultiMaterial = MultiMaterial;
  252. exports.NumberKeyframeTrack = NumberKeyframeTrack;
  253. exports.Object3D = Object3D;
  254. exports.ObjectLoader = ObjectLoader;
  255. exports.OctahedronBufferGeometry = OctahedronBufferGeometry;
  256. exports.OctahedronGeometry = OctahedronGeometry;
  257. exports.OrthographicCamera = OrthographicCamera;
  258. exports.ParametricBufferGeometry = ParametricBufferGeometry;
  259. exports.ParametricGeometry = ParametricGeometry;
  260. exports.Particle = Particle;
  261. exports.ParticleBasicMaterial = ParticleBasicMaterial;
  262. exports.ParticleSystem = ParticleSystem;
  263. exports.ParticleSystemMaterial = ParticleSystemMaterial;
  264. exports.Path = Path;
  265. exports.PerspectiveCamera = PerspectiveCamera;
  266. exports.Plane = Plane;
  267. exports.PlaneBufferGeometry = PlaneBufferGeometry;
  268. exports.PlaneGeometry = PlaneGeometry;
  269. exports.PlaneHelper = PlaneHelper;
  270. exports.PointCloud = PointCloud;
  271. exports.PointCloudMaterial = PointCloudMaterial;
  272. exports.PointLight = PointLight;
  273. exports.PointLightHelper = PointLightHelper;
  274. exports.Points = Points;
  275. exports.PointsMaterial = PointsMaterial;
  276. exports.PolarGridHelper = PolarGridHelper;
  277. exports.PolyhedronBufferGeometry = PolyhedronBufferGeometry;
  278. exports.PolyhedronGeometry = PolyhedronGeometry;
  279. exports.PositionalAudio = PositionalAudio;
  280. exports.PositionalAudioHelper = PositionalAudioHelper;
  281. exports.PropertyBinding = PropertyBinding;
  282. exports.PropertyMixer = PropertyMixer;
  283. exports.QuadraticBezierCurve = QuadraticBezierCurve;
  284. exports.QuadraticBezierCurve3 = QuadraticBezierCurve3;
  285. exports.Quaternion = Quaternion;
  286. exports.QuaternionKeyframeTrack = QuaternionKeyframeTrack;
  287. exports.QuaternionLinearInterpolant = QuaternionLinearInterpolant;
  288. exports.RawShaderMaterial = RawShaderMaterial;
  289. exports.Ray = Ray;
  290. exports.Raycaster = Raycaster;
  291. exports.RectAreaLight = RectAreaLight;
  292. exports.RectAreaLightHelper = RectAreaLightHelper;
  293. exports.RingBufferGeometry = RingBufferGeometry;
  294. exports.RingGeometry = RingGeometry;
  295. exports.Scene = Scene;
  296. exports.ShaderMaterial = ShaderMaterial;
  297. exports.ShadowMaterial = ShadowMaterial;
  298. exports.Shape = Shape;
  299. exports.ShapeBufferGeometry = ShapeBufferGeometry;
  300. exports.ShapeGeometry = ShapeGeometry;
  301. exports.ShapePath = ShapePath;
  302. exports.Skeleton = Skeleton;
  303. exports.SkeletonHelper = SkeletonHelper;
  304. exports.SkinnedMesh = SkinnedMesh;
  305. exports.Sphere = Sphere;
  306. exports.SphereBufferGeometry = SphereBufferGeometry;
  307. exports.SphereGeometry = SphereGeometry;
  308. exports.Spherical = Spherical;
  309. exports.SphericalHarmonics3 = SphericalHarmonics3;
  310. exports.Spline = Spline;
  311. exports.SplineCurve = SplineCurve;
  312. exports.SplineCurve3 = SplineCurve3;
  313. exports.SpotLight = SpotLight;
  314. exports.SpotLightHelper = SpotLightHelper;
  315. exports.SpotLightShadow = SpotLightShadow;
  316. exports.Sprite = Sprite;
  317. exports.SpriteMaterial = SpriteMaterial;
  318. exports.StereoCamera = StereoCamera;
  319. exports.StringKeyframeTrack = StringKeyframeTrack;
  320. exports.TetrahedronBufferGeometry = TetrahedronBufferGeometry;
  321. exports.TetrahedronGeometry = TetrahedronGeometry;
  322. exports.TextBufferGeometry = TextBufferGeometry;
  323. exports.TextGeometry = TextGeometry;
  324. exports.Texture = Texture;
  325. exports.TextureLoader = TextureLoader;
  326. exports.TorusBufferGeometry = TorusBufferGeometry;
  327. exports.TorusGeometry = TorusGeometry;
  328. exports.TorusKnotBufferGeometry = TorusKnotBufferGeometry;
  329. exports.TorusKnotGeometry = TorusKnotGeometry;
  330. exports.Triangle = Triangle;
  331. exports.TubeBufferGeometry = TubeBufferGeometry;
  332. exports.TubeGeometry = TubeGeometry;
  333. exports.Uint16Attribute = Uint16Attribute;
  334. exports.Uint16BufferAttribute = Uint16BufferAttribute;
  335. exports.Uint32Attribute = Uint32Attribute;
  336. exports.Uint32BufferAttribute = Uint32BufferAttribute;
  337. exports.Uint8Attribute = Uint8Attribute;
  338. exports.Uint8BufferAttribute = Uint8BufferAttribute;
  339. exports.Uint8ClampedAttribute = Uint8ClampedAttribute;
  340. exports.Uint8ClampedBufferAttribute = Uint8ClampedBufferAttribute;
  341. exports.Uniform = Uniform;
  342. exports.Vector2 = Vector2;
  343. exports.Vector3 = Vector3;
  344. exports.Vector4 = Vector4;
  345. exports.VectorKeyframeTrack = VectorKeyframeTrack;
  346. exports.Vertex = Vertex;
  347. exports.VertexNormalsHelper = VertexNormalsHelper;
  348. exports.VideoTexture = VideoTexture;
  349. exports.WebGLMultisampleRenderTarget = WebGLMultisampleRenderTarget;
  350. exports.WebGLRenderTarget = WebGLRenderTarget;
  351. exports.WebGLRenderTargetCube = WebGLRenderTargetCube;
  352. exports.WebGLRenderer = WebGLRenderer;
  353. exports.WebGLUtils = WebGLUtils;
  354. exports.WireframeGeometry = WireframeGeometry;
  355. exports.WireframeHelper = WireframeHelper;
  356. exports.XHRLoader = XHRLoader;
  357. 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;
  358. 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;
  359. // Polyfills
  360. if (Number.EPSILON === undefined) {
  361. Number.EPSILON = Math.pow(2, -52);
  362. }
  363. if (Number.isInteger === undefined) {
  364. // Missing in IE
  365. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isInteger
  366. Number.isInteger = function (value) {
  367. return typeof value === 'number' && isFinite(value) && Math.floor(value) === value;
  368. };
  369. } //
  370. if (Math.sign === undefined) {
  371. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sign
  372. Math.sign = function (x) {
  373. return x < 0 ? -1 : x > 0 ? 1 : +x;
  374. };
  375. }
  376. if ('name' in Function.prototype === false) {
  377. // Missing in IE
  378. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name
  379. Object.defineProperty(Function.prototype, 'name', {
  380. get: function () {
  381. return this.toString().match(/^\s*function\s*([^\(\s]*)/)[1];
  382. }
  383. });
  384. }
  385. if (Object.assign === undefined) {
  386. // Missing in IE
  387. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign
  388. Object.assign = function (target) {
  389. if (target === undefined || target === null) {
  390. throw new TypeError('Cannot convert undefined or null to object');
  391. }
  392. var output = Object(target);
  393. for (var index = 1; index < arguments.length; index++) {
  394. var source = arguments[index];
  395. if (source !== undefined && source !== null) {
  396. for (var nextKey in source) {
  397. if (Object.prototype.hasOwnProperty.call(source, nextKey)) {
  398. output[nextKey] = source[nextKey];
  399. }
  400. }
  401. }
  402. }
  403. return output;
  404. };
  405. }
  406. var REVISION = '109';
  407. exports.REVISION = REVISION;
  408. var MOUSE = {
  409. LEFT: 0,
  410. MIDDLE: 1,
  411. RIGHT: 2,
  412. ROTATE: 0,
  413. DOLLY: 1,
  414. PAN: 2
  415. };
  416. exports.MOUSE = MOUSE;
  417. var TOUCH = {
  418. ROTATE: 0,
  419. PAN: 1,
  420. DOLLY_PAN: 2,
  421. DOLLY_ROTATE: 3
  422. };
  423. exports.TOUCH = TOUCH;
  424. var CullFaceNone = 0;
  425. exports.CullFaceNone = CullFaceNone;
  426. var CullFaceBack = 1;
  427. exports.CullFaceBack = CullFaceBack;
  428. var CullFaceFront = 2;
  429. exports.CullFaceFront = CullFaceFront;
  430. var CullFaceFrontBack = 3;
  431. exports.CullFaceFrontBack = CullFaceFrontBack;
  432. var FrontFaceDirectionCW = 0;
  433. exports.FrontFaceDirectionCW = FrontFaceDirectionCW;
  434. var FrontFaceDirectionCCW = 1;
  435. exports.FrontFaceDirectionCCW = FrontFaceDirectionCCW;
  436. var BasicShadowMap = 0;
  437. exports.BasicShadowMap = BasicShadowMap;
  438. var PCFShadowMap = 1;
  439. exports.PCFShadowMap = PCFShadowMap;
  440. var PCFSoftShadowMap = 2;
  441. exports.PCFSoftShadowMap = PCFSoftShadowMap;
  442. var VSMShadowMap = 3;
  443. exports.VSMShadowMap = VSMShadowMap;
  444. var FrontSide = 0;
  445. exports.FrontSide = FrontSide;
  446. var BackSide = 1;
  447. exports.BackSide = BackSide;
  448. var DoubleSide = 2;
  449. exports.DoubleSide = DoubleSide;
  450. var FlatShading = 1;
  451. exports.FlatShading = FlatShading;
  452. var SmoothShading = 2;
  453. exports.SmoothShading = SmoothShading;
  454. var NoColors = 0;
  455. exports.NoColors = NoColors;
  456. var FaceColors = 1;
  457. exports.FaceColors = FaceColors;
  458. var VertexColors = 2;
  459. exports.VertexColors = VertexColors;
  460. var NoBlending = 0;
  461. exports.NoBlending = NoBlending;
  462. var NormalBlending = 1;
  463. exports.NormalBlending = NormalBlending;
  464. var AdditiveBlending = 2;
  465. exports.AdditiveBlending = AdditiveBlending;
  466. var SubtractiveBlending = 3;
  467. exports.SubtractiveBlending = SubtractiveBlending;
  468. var MultiplyBlending = 4;
  469. exports.MultiplyBlending = MultiplyBlending;
  470. var CustomBlending = 5;
  471. exports.CustomBlending = CustomBlending;
  472. var AddEquation = 100;
  473. exports.AddEquation = AddEquation;
  474. var SubtractEquation = 101;
  475. exports.SubtractEquation = SubtractEquation;
  476. var ReverseSubtractEquation = 102;
  477. exports.ReverseSubtractEquation = ReverseSubtractEquation;
  478. var MinEquation = 103;
  479. exports.MinEquation = MinEquation;
  480. var MaxEquation = 104;
  481. exports.MaxEquation = MaxEquation;
  482. var ZeroFactor = 200;
  483. exports.ZeroFactor = ZeroFactor;
  484. var OneFactor = 201;
  485. exports.OneFactor = OneFactor;
  486. var SrcColorFactor = 202;
  487. exports.SrcColorFactor = SrcColorFactor;
  488. var OneMinusSrcColorFactor = 203;
  489. exports.OneMinusSrcColorFactor = OneMinusSrcColorFactor;
  490. var SrcAlphaFactor = 204;
  491. exports.SrcAlphaFactor = SrcAlphaFactor;
  492. var OneMinusSrcAlphaFactor = 205;
  493. exports.OneMinusSrcAlphaFactor = OneMinusSrcAlphaFactor;
  494. var DstAlphaFactor = 206;
  495. exports.DstAlphaFactor = DstAlphaFactor;
  496. var OneMinusDstAlphaFactor = 207;
  497. exports.OneMinusDstAlphaFactor = OneMinusDstAlphaFactor;
  498. var DstColorFactor = 208;
  499. exports.DstColorFactor = DstColorFactor;
  500. var OneMinusDstColorFactor = 209;
  501. exports.OneMinusDstColorFactor = OneMinusDstColorFactor;
  502. var SrcAlphaSaturateFactor = 210;
  503. exports.SrcAlphaSaturateFactor = SrcAlphaSaturateFactor;
  504. var NeverDepth = 0;
  505. exports.NeverDepth = NeverDepth;
  506. var AlwaysDepth = 1;
  507. exports.AlwaysDepth = AlwaysDepth;
  508. var LessDepth = 2;
  509. exports.LessDepth = LessDepth;
  510. var LessEqualDepth = 3;
  511. exports.LessEqualDepth = LessEqualDepth;
  512. var EqualDepth = 4;
  513. exports.EqualDepth = EqualDepth;
  514. var GreaterEqualDepth = 5;
  515. exports.GreaterEqualDepth = GreaterEqualDepth;
  516. var GreaterDepth = 6;
  517. exports.GreaterDepth = GreaterDepth;
  518. var NotEqualDepth = 7;
  519. exports.NotEqualDepth = NotEqualDepth;
  520. var MultiplyOperation = 0;
  521. exports.MultiplyOperation = MultiplyOperation;
  522. var MixOperation = 1;
  523. exports.MixOperation = MixOperation;
  524. var AddOperation = 2;
  525. exports.AddOperation = AddOperation;
  526. var NoToneMapping = 0;
  527. exports.NoToneMapping = NoToneMapping;
  528. var LinearToneMapping = 1;
  529. exports.LinearToneMapping = LinearToneMapping;
  530. var ReinhardToneMapping = 2;
  531. exports.ReinhardToneMapping = ReinhardToneMapping;
  532. var Uncharted2ToneMapping = 3;
  533. exports.Uncharted2ToneMapping = Uncharted2ToneMapping;
  534. var CineonToneMapping = 4;
  535. exports.CineonToneMapping = CineonToneMapping;
  536. var ACESFilmicToneMapping = 5;
  537. exports.ACESFilmicToneMapping = ACESFilmicToneMapping;
  538. var UVMapping = 300;
  539. exports.UVMapping = UVMapping;
  540. var CubeReflectionMapping = 301;
  541. exports.CubeReflectionMapping = CubeReflectionMapping;
  542. var CubeRefractionMapping = 302;
  543. exports.CubeRefractionMapping = CubeRefractionMapping;
  544. var EquirectangularReflectionMapping = 303;
  545. exports.EquirectangularReflectionMapping = EquirectangularReflectionMapping;
  546. var EquirectangularRefractionMapping = 304;
  547. exports.EquirectangularRefractionMapping = EquirectangularRefractionMapping;
  548. var SphericalReflectionMapping = 305;
  549. exports.SphericalReflectionMapping = SphericalReflectionMapping;
  550. var CubeUVReflectionMapping = 306;
  551. exports.CubeUVReflectionMapping = CubeUVReflectionMapping;
  552. var CubeUVRefractionMapping = 307;
  553. exports.CubeUVRefractionMapping = CubeUVRefractionMapping;
  554. var RepeatWrapping = 1000;
  555. exports.RepeatWrapping = RepeatWrapping;
  556. var ClampToEdgeWrapping = 1001;
  557. exports.ClampToEdgeWrapping = ClampToEdgeWrapping;
  558. var MirroredRepeatWrapping = 1002;
  559. exports.MirroredRepeatWrapping = MirroredRepeatWrapping;
  560. var NearestFilter = 1003;
  561. exports.NearestFilter = NearestFilter;
  562. var NearestMipmapNearestFilter = 1004;
  563. exports.NearestMipmapNearestFilter = NearestMipmapNearestFilter;
  564. var NearestMipMapNearestFilter = 1004;
  565. exports.NearestMipMapNearestFilter = NearestMipMapNearestFilter;
  566. var NearestMipmapLinearFilter = 1005;
  567. exports.NearestMipmapLinearFilter = NearestMipmapLinearFilter;
  568. var NearestMipMapLinearFilter = 1005;
  569. exports.NearestMipMapLinearFilter = NearestMipMapLinearFilter;
  570. var LinearFilter = 1006;
  571. exports.LinearFilter = LinearFilter;
  572. var LinearMipmapNearestFilter = 1007;
  573. exports.LinearMipmapNearestFilter = LinearMipmapNearestFilter;
  574. var LinearMipMapNearestFilter = 1007;
  575. exports.LinearMipMapNearestFilter = LinearMipMapNearestFilter;
  576. var LinearMipmapLinearFilter = 1008;
  577. exports.LinearMipmapLinearFilter = LinearMipmapLinearFilter;
  578. var LinearMipMapLinearFilter = 1008;
  579. exports.LinearMipMapLinearFilter = LinearMipMapLinearFilter;
  580. var UnsignedByteType = 1009;
  581. exports.UnsignedByteType = UnsignedByteType;
  582. var ByteType = 1010;
  583. exports.ByteType = ByteType;
  584. var ShortType = 1011;
  585. exports.ShortType = ShortType;
  586. var UnsignedShortType = 1012;
  587. exports.UnsignedShortType = UnsignedShortType;
  588. var IntType = 1013;
  589. exports.IntType = IntType;
  590. var UnsignedIntType = 1014;
  591. exports.UnsignedIntType = UnsignedIntType;
  592. var FloatType = 1015;
  593. exports.FloatType = FloatType;
  594. var HalfFloatType = 1016;
  595. exports.HalfFloatType = HalfFloatType;
  596. var UnsignedShort4444Type = 1017;
  597. exports.UnsignedShort4444Type = UnsignedShort4444Type;
  598. var UnsignedShort5551Type = 1018;
  599. exports.UnsignedShort5551Type = UnsignedShort5551Type;
  600. var UnsignedShort565Type = 1019;
  601. exports.UnsignedShort565Type = UnsignedShort565Type;
  602. var UnsignedInt248Type = 1020;
  603. exports.UnsignedInt248Type = UnsignedInt248Type;
  604. var AlphaFormat = 1021;
  605. exports.AlphaFormat = AlphaFormat;
  606. var RGBFormat = 1022;
  607. exports.RGBFormat = RGBFormat;
  608. var RGBAFormat = 1023;
  609. exports.RGBAFormat = RGBAFormat;
  610. var LuminanceFormat = 1024;
  611. exports.LuminanceFormat = LuminanceFormat;
  612. var LuminanceAlphaFormat = 1025;
  613. exports.LuminanceAlphaFormat = LuminanceAlphaFormat;
  614. var RGBEFormat = RGBAFormat;
  615. exports.RGBEFormat = RGBEFormat;
  616. var DepthFormat = 1026;
  617. exports.DepthFormat = DepthFormat;
  618. var DepthStencilFormat = 1027;
  619. exports.DepthStencilFormat = DepthStencilFormat;
  620. var RedFormat = 1028;
  621. exports.RedFormat = RedFormat;
  622. var RGB_S3TC_DXT1_Format = 33776;
  623. exports.RGB_S3TC_DXT1_Format = RGB_S3TC_DXT1_Format;
  624. var RGBA_S3TC_DXT1_Format = 33777;
  625. exports.RGBA_S3TC_DXT1_Format = RGBA_S3TC_DXT1_Format;
  626. var RGBA_S3TC_DXT3_Format = 33778;
  627. exports.RGBA_S3TC_DXT3_Format = RGBA_S3TC_DXT3_Format;
  628. var RGBA_S3TC_DXT5_Format = 33779;
  629. exports.RGBA_S3TC_DXT5_Format = RGBA_S3TC_DXT5_Format;
  630. var RGB_PVRTC_4BPPV1_Format = 35840;
  631. exports.RGB_PVRTC_4BPPV1_Format = RGB_PVRTC_4BPPV1_Format;
  632. var RGB_PVRTC_2BPPV1_Format = 35841;
  633. exports.RGB_PVRTC_2BPPV1_Format = RGB_PVRTC_2BPPV1_Format;
  634. var RGBA_PVRTC_4BPPV1_Format = 35842;
  635. exports.RGBA_PVRTC_4BPPV1_Format = RGBA_PVRTC_4BPPV1_Format;
  636. var RGBA_PVRTC_2BPPV1_Format = 35843;
  637. exports.RGBA_PVRTC_2BPPV1_Format = RGBA_PVRTC_2BPPV1_Format;
  638. var RGB_ETC1_Format = 36196;
  639. exports.RGB_ETC1_Format = RGB_ETC1_Format;
  640. var RGBA_ASTC_4x4_Format = 37808;
  641. exports.RGBA_ASTC_4x4_Format = RGBA_ASTC_4x4_Format;
  642. var RGBA_ASTC_5x4_Format = 37809;
  643. exports.RGBA_ASTC_5x4_Format = RGBA_ASTC_5x4_Format;
  644. var RGBA_ASTC_5x5_Format = 37810;
  645. exports.RGBA_ASTC_5x5_Format = RGBA_ASTC_5x5_Format;
  646. var RGBA_ASTC_6x5_Format = 37811;
  647. exports.RGBA_ASTC_6x5_Format = RGBA_ASTC_6x5_Format;
  648. var RGBA_ASTC_6x6_Format = 37812;
  649. exports.RGBA_ASTC_6x6_Format = RGBA_ASTC_6x6_Format;
  650. var RGBA_ASTC_8x5_Format = 37813;
  651. exports.RGBA_ASTC_8x5_Format = RGBA_ASTC_8x5_Format;
  652. var RGBA_ASTC_8x6_Format = 37814;
  653. exports.RGBA_ASTC_8x6_Format = RGBA_ASTC_8x6_Format;
  654. var RGBA_ASTC_8x8_Format = 37815;
  655. exports.RGBA_ASTC_8x8_Format = RGBA_ASTC_8x8_Format;
  656. var RGBA_ASTC_10x5_Format = 37816;
  657. exports.RGBA_ASTC_10x5_Format = RGBA_ASTC_10x5_Format;
  658. var RGBA_ASTC_10x6_Format = 37817;
  659. exports.RGBA_ASTC_10x6_Format = RGBA_ASTC_10x6_Format;
  660. var RGBA_ASTC_10x8_Format = 37818;
  661. exports.RGBA_ASTC_10x8_Format = RGBA_ASTC_10x8_Format;
  662. var RGBA_ASTC_10x10_Format = 37819;
  663. exports.RGBA_ASTC_10x10_Format = RGBA_ASTC_10x10_Format;
  664. var RGBA_ASTC_12x10_Format = 37820;
  665. exports.RGBA_ASTC_12x10_Format = RGBA_ASTC_12x10_Format;
  666. var RGBA_ASTC_12x12_Format = 37821;
  667. exports.RGBA_ASTC_12x12_Format = RGBA_ASTC_12x12_Format;
  668. var LoopOnce = 2200;
  669. exports.LoopOnce = LoopOnce;
  670. var LoopRepeat = 2201;
  671. exports.LoopRepeat = LoopRepeat;
  672. var LoopPingPong = 2202;
  673. exports.LoopPingPong = LoopPingPong;
  674. var InterpolateDiscrete = 2300;
  675. exports.InterpolateDiscrete = InterpolateDiscrete;
  676. var InterpolateLinear = 2301;
  677. exports.InterpolateLinear = InterpolateLinear;
  678. var InterpolateSmooth = 2302;
  679. exports.InterpolateSmooth = InterpolateSmooth;
  680. var ZeroCurvatureEnding = 2400;
  681. exports.ZeroCurvatureEnding = ZeroCurvatureEnding;
  682. var ZeroSlopeEnding = 2401;
  683. exports.ZeroSlopeEnding = ZeroSlopeEnding;
  684. var WrapAroundEnding = 2402;
  685. exports.WrapAroundEnding = WrapAroundEnding;
  686. var TrianglesDrawMode = 0;
  687. exports.TrianglesDrawMode = TrianglesDrawMode;
  688. var TriangleStripDrawMode = 1;
  689. exports.TriangleStripDrawMode = TriangleStripDrawMode;
  690. var TriangleFanDrawMode = 2;
  691. exports.TriangleFanDrawMode = TriangleFanDrawMode;
  692. var LinearEncoding = 3000;
  693. exports.LinearEncoding = LinearEncoding;
  694. var sRGBEncoding = 3001;
  695. exports.sRGBEncoding = sRGBEncoding;
  696. var GammaEncoding = 3007;
  697. exports.GammaEncoding = GammaEncoding;
  698. var RGBEEncoding = 3002;
  699. exports.RGBEEncoding = RGBEEncoding;
  700. var LogLuvEncoding = 3003;
  701. exports.LogLuvEncoding = LogLuvEncoding;
  702. var RGBM7Encoding = 3004;
  703. exports.RGBM7Encoding = RGBM7Encoding;
  704. var RGBM16Encoding = 3005;
  705. exports.RGBM16Encoding = RGBM16Encoding;
  706. var RGBDEncoding = 3006;
  707. exports.RGBDEncoding = RGBDEncoding;
  708. var BasicDepthPacking = 3200;
  709. exports.BasicDepthPacking = BasicDepthPacking;
  710. var RGBADepthPacking = 3201;
  711. exports.RGBADepthPacking = RGBADepthPacking;
  712. var TangentSpaceNormalMap = 0;
  713. exports.TangentSpaceNormalMap = TangentSpaceNormalMap;
  714. var ObjectSpaceNormalMap = 1;
  715. exports.ObjectSpaceNormalMap = ObjectSpaceNormalMap;
  716. var ZeroStencilOp = 0;
  717. exports.ZeroStencilOp = ZeroStencilOp;
  718. var KeepStencilOp = 7680;
  719. exports.KeepStencilOp = KeepStencilOp;
  720. var ReplaceStencilOp = 7681;
  721. exports.ReplaceStencilOp = ReplaceStencilOp;
  722. var IncrementStencilOp = 7682;
  723. exports.IncrementStencilOp = IncrementStencilOp;
  724. var DecrementStencilOp = 7683;
  725. exports.DecrementStencilOp = DecrementStencilOp;
  726. var IncrementWrapStencilOp = 34055;
  727. exports.IncrementWrapStencilOp = IncrementWrapStencilOp;
  728. var DecrementWrapStencilOp = 34056;
  729. exports.DecrementWrapStencilOp = DecrementWrapStencilOp;
  730. var InvertStencilOp = 5386;
  731. exports.InvertStencilOp = InvertStencilOp;
  732. var NeverStencilFunc = 512;
  733. exports.NeverStencilFunc = NeverStencilFunc;
  734. var LessStencilFunc = 513;
  735. exports.LessStencilFunc = LessStencilFunc;
  736. var EqualStencilFunc = 514;
  737. exports.EqualStencilFunc = EqualStencilFunc;
  738. var LessEqualStencilFunc = 515;
  739. exports.LessEqualStencilFunc = LessEqualStencilFunc;
  740. var GreaterStencilFunc = 516;
  741. exports.GreaterStencilFunc = GreaterStencilFunc;
  742. var NotEqualStencilFunc = 517;
  743. exports.NotEqualStencilFunc = NotEqualStencilFunc;
  744. var GreaterEqualStencilFunc = 518;
  745. exports.GreaterEqualStencilFunc = GreaterEqualStencilFunc;
  746. var AlwaysStencilFunc = 519;
  747. /**
  748. * https://github.com/mrdoob/eventdispatcher.js/
  749. */
  750. exports.AlwaysStencilFunc = AlwaysStencilFunc;
  751. function EventDispatcher() {}
  752. Object.assign(EventDispatcher.prototype, {
  753. addEventListener: function (type, listener) {
  754. if (this._listeners === undefined) this._listeners = {};
  755. var listeners = this._listeners;
  756. if (listeners[type] === undefined) {
  757. listeners[type] = [];
  758. }
  759. if (listeners[type].indexOf(listener) === -1) {
  760. listeners[type].push(listener);
  761. }
  762. },
  763. hasEventListener: function (type, listener) {
  764. if (this._listeners === undefined) return false;
  765. var listeners = this._listeners;
  766. return listeners[type] !== undefined && listeners[type].indexOf(listener) !== -1;
  767. },
  768. removeEventListener: function (type, listener) {
  769. if (this._listeners === undefined) return;
  770. var listeners = this._listeners;
  771. var listenerArray = listeners[type];
  772. if (listenerArray !== undefined) {
  773. var index = listenerArray.indexOf(listener);
  774. if (index !== -1) {
  775. listenerArray.splice(index, 1);
  776. }
  777. }
  778. },
  779. dispatchEvent: function (event) {
  780. if (this._listeners === undefined) return;
  781. var listeners = this._listeners;
  782. var listenerArray = listeners[event.type];
  783. if (listenerArray !== undefined) {
  784. event.target = this;
  785. var array = listenerArray.slice(0);
  786. for (var i = 0, l = array.length; i < l; i++) {
  787. array[i].call(this, event);
  788. }
  789. }
  790. }
  791. });
  792. /**
  793. * @author alteredq / http://alteredqualia.com/
  794. * @author mrdoob / http://mrdoob.com/
  795. */
  796. var _lut = [];
  797. for (var i = 0; i < 256; i++) {
  798. _lut[i] = (i < 16 ? '0' : '') + i.toString(16);
  799. }
  800. var _Math = {
  801. DEG2RAD: Math.PI / 180,
  802. RAD2DEG: 180 / Math.PI,
  803. generateUUID: function () {
  804. // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/21963136#21963136
  805. var d0 = Math.random() * 0xffffffff | 0;
  806. var d1 = Math.random() * 0xffffffff | 0;
  807. var d2 = Math.random() * 0xffffffff | 0;
  808. var d3 = Math.random() * 0xffffffff | 0;
  809. 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.
  810. return uuid.toUpperCase();
  811. },
  812. clamp: function (value, min, max) {
  813. return Math.max(min, Math.min(max, value));
  814. },
  815. // compute euclidian modulo of m % n
  816. // https://en.wikipedia.org/wiki/Modulo_operation
  817. euclideanModulo: function (n, m) {
  818. return (n % m + m) % m;
  819. },
  820. // Linear mapping from range <a1, a2> to range <b1, b2>
  821. mapLinear: function (x, a1, a2, b1, b2) {
  822. return b1 + (x - a1) * (b2 - b1) / (a2 - a1);
  823. },
  824. // https://en.wikipedia.org/wiki/Linear_interpolation
  825. lerp: function (x, y, t) {
  826. return (1 - t) * x + t * y;
  827. },
  828. // http://en.wikipedia.org/wiki/Smoothstep
  829. smoothstep: function (x, min, max) {
  830. if (x <= min) return 0;
  831. if (x >= max) return 1;
  832. x = (x - min) / (max - min);
  833. return x * x * (3 - 2 * x);
  834. },
  835. smootherstep: function (x, min, max) {
  836. if (x <= min) return 0;
  837. if (x >= max) return 1;
  838. x = (x - min) / (max - min);
  839. return x * x * x * (x * (x * 6 - 15) + 10);
  840. },
  841. // Random integer from <low, high> interval
  842. randInt: function (low, high) {
  843. return low + Math.floor(Math.random() * (high - low + 1));
  844. },
  845. // Random float from <low, high> interval
  846. randFloat: function (low, high) {
  847. return low + Math.random() * (high - low);
  848. },
  849. // Random float from <-range/2, range/2> interval
  850. randFloatSpread: function (range) {
  851. return range * (0.5 - Math.random());
  852. },
  853. degToRad: function (degrees) {
  854. return degrees * _Math.DEG2RAD;
  855. },
  856. radToDeg: function (radians) {
  857. return radians * _Math.RAD2DEG;
  858. },
  859. isPowerOfTwo: function (value) {
  860. return (value & value - 1) === 0 && value !== 0;
  861. },
  862. ceilPowerOfTwo: function (value) {
  863. return Math.pow(2, Math.ceil(Math.log(value) / Math.LN2));
  864. },
  865. floorPowerOfTwo: function (value) {
  866. return Math.pow(2, Math.floor(Math.log(value) / Math.LN2));
  867. }
  868. };
  869. /**
  870. * @author mrdoob / http://mrdoob.com/
  871. * @author philogb / http://blog.thejit.org/
  872. * @author egraether / http://egraether.com/
  873. * @author zz85 / http://www.lab4games.net/zz85/blog
  874. */
  875. exports.Math = _Math;
  876. function Vector2(x, y) {
  877. this.x = x || 0;
  878. this.y = y || 0;
  879. }
  880. Object.defineProperties(Vector2.prototype, {
  881. "width": {
  882. get: function () {
  883. return this.x;
  884. },
  885. set: function (value) {
  886. this.x = value;
  887. }
  888. },
  889. "height": {
  890. get: function () {
  891. return this.y;
  892. },
  893. set: function (value) {
  894. this.y = value;
  895. }
  896. }
  897. });
  898. Object.assign(Vector2.prototype, {
  899. isVector2: true,
  900. set: function (x, y) {
  901. this.x = x;
  902. this.y = y;
  903. return this;
  904. },
  905. setScalar: function (scalar) {
  906. this.x = scalar;
  907. this.y = scalar;
  908. return this;
  909. },
  910. setX: function (x) {
  911. this.x = x;
  912. return this;
  913. },
  914. setY: function (y) {
  915. this.y = y;
  916. return this;
  917. },
  918. setComponent: function (index, value) {
  919. switch (index) {
  920. case 0:
  921. this.x = value;
  922. break;
  923. case 1:
  924. this.y = value;
  925. break;
  926. default:
  927. throw new Error('index is out of range: ' + index);
  928. }
  929. return this;
  930. },
  931. getComponent: function (index) {
  932. switch (index) {
  933. case 0:
  934. return this.x;
  935. case 1:
  936. return this.y;
  937. default:
  938. throw new Error('index is out of range: ' + index);
  939. }
  940. },
  941. clone: function () {
  942. return new this.constructor(this.x, this.y);
  943. },
  944. copy: function (v) {
  945. this.x = v.x;
  946. this.y = v.y;
  947. return this;
  948. },
  949. add: function (v, w) {
  950. if (w !== undefined) {
  951. console.warn('THREE.Vector2: .add() now only accepts one argument. Use .addVectors( a, b ) instead.');
  952. return this.addVectors(v, w);
  953. }
  954. this.x += v.x;
  955. this.y += v.y;
  956. return this;
  957. },
  958. addScalar: function (s) {
  959. this.x += s;
  960. this.y += s;
  961. return this;
  962. },
  963. addVectors: function (a, b) {
  964. this.x = a.x + b.x;
  965. this.y = a.y + b.y;
  966. return this;
  967. },
  968. addScaledVector: function (v, s) {
  969. this.x += v.x * s;
  970. this.y += v.y * s;
  971. return this;
  972. },
  973. sub: function (v, w) {
  974. if (w !== undefined) {
  975. console.warn('THREE.Vector2: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.');
  976. return this.subVectors(v, w);
  977. }
  978. this.x -= v.x;
  979. this.y -= v.y;
  980. return this;
  981. },
  982. subScalar: function (s) {
  983. this.x -= s;
  984. this.y -= s;
  985. return this;
  986. },
  987. subVectors: function (a, b) {
  988. this.x = a.x - b.x;
  989. this.y = a.y - b.y;
  990. return this;
  991. },
  992. multiply: function (v) {
  993. this.x *= v.x;
  994. this.y *= v.y;
  995. return this;
  996. },
  997. multiplyScalar: function (scalar) {
  998. this.x *= scalar;
  999. this.y *= scalar;
  1000. return this;
  1001. },
  1002. divide: function (v) {
  1003. this.x /= v.x;
  1004. this.y /= v.y;
  1005. return this;
  1006. },
  1007. divideScalar: function (scalar) {
  1008. return this.multiplyScalar(1 / scalar);
  1009. },
  1010. applyMatrix3: function (m) {
  1011. var x = this.x,
  1012. y = this.y;
  1013. var e = m.elements;
  1014. this.x = e[0] * x + e[3] * y + e[6];
  1015. this.y = e[1] * x + e[4] * y + e[7];
  1016. return this;
  1017. },
  1018. min: function (v) {
  1019. this.x = Math.min(this.x, v.x);
  1020. this.y = Math.min(this.y, v.y);
  1021. return this;
  1022. },
  1023. max: function (v) {
  1024. this.x = Math.max(this.x, v.x);
  1025. this.y = Math.max(this.y, v.y);
  1026. return this;
  1027. },
  1028. clamp: function (min, max) {
  1029. // assumes min < max, componentwise
  1030. this.x = Math.max(min.x, Math.min(max.x, this.x));
  1031. this.y = Math.max(min.y, Math.min(max.y, this.y));
  1032. return this;
  1033. },
  1034. clampScalar: function (minVal, maxVal) {
  1035. this.x = Math.max(minVal, Math.min(maxVal, this.x));
  1036. this.y = Math.max(minVal, Math.min(maxVal, this.y));
  1037. return this;
  1038. },
  1039. clampLength: function (min, max) {
  1040. var length = this.length();
  1041. return this.divideScalar(length || 1).multiplyScalar(Math.max(min, Math.min(max, length)));
  1042. },
  1043. floor: function () {
  1044. this.x = Math.floor(this.x);
  1045. this.y = Math.floor(this.y);
  1046. return this;
  1047. },
  1048. ceil: function () {
  1049. this.x = Math.ceil(this.x);
  1050. this.y = Math.ceil(this.y);
  1051. return this;
  1052. },
  1053. round: function () {
  1054. this.x = Math.round(this.x);
  1055. this.y = Math.round(this.y);
  1056. return this;
  1057. },
  1058. roundToZero: function () {
  1059. this.x = this.x < 0 ? Math.ceil(this.x) : Math.floor(this.x);
  1060. this.y = this.y < 0 ? Math.ceil(this.y) : Math.floor(this.y);
  1061. return this;
  1062. },
  1063. negate: function () {
  1064. this.x = -this.x;
  1065. this.y = -this.y;
  1066. return this;
  1067. },
  1068. dot: function (v) {
  1069. return this.x * v.x + this.y * v.y;
  1070. },
  1071. cross: function (v) {
  1072. return this.x * v.y - this.y * v.x;
  1073. },
  1074. lengthSq: function () {
  1075. return this.x * this.x + this.y * this.y;
  1076. },
  1077. length: function () {
  1078. return Math.sqrt(this.x * this.x + this.y * this.y);
  1079. },
  1080. manhattanLength: function () {
  1081. return Math.abs(this.x) + Math.abs(this.y);
  1082. },
  1083. normalize: function () {
  1084. return this.divideScalar(this.length() || 1);
  1085. },
  1086. angle: function () {
  1087. // computes the angle in radians with respect to the positive x-axis
  1088. var angle = Math.atan2(this.y, this.x);
  1089. if (angle < 0) angle += 2 * Math.PI;
  1090. return angle;
  1091. },
  1092. distanceTo: function (v) {
  1093. return Math.sqrt(this.distanceToSquared(v));
  1094. },
  1095. distanceToSquared: function (v) {
  1096. var dx = this.x - v.x,
  1097. dy = this.y - v.y;
  1098. return dx * dx + dy * dy;
  1099. },
  1100. manhattanDistanceTo: function (v) {
  1101. return Math.abs(this.x - v.x) + Math.abs(this.y - v.y);
  1102. },
  1103. setLength: function (length) {
  1104. return this.normalize().multiplyScalar(length);
  1105. },
  1106. lerp: function (v, alpha) {
  1107. this.x += (v.x - this.x) * alpha;
  1108. this.y += (v.y - this.y) * alpha;
  1109. return this;
  1110. },
  1111. lerpVectors: function (v1, v2, alpha) {
  1112. return this.subVectors(v2, v1).multiplyScalar(alpha).add(v1);
  1113. },
  1114. equals: function (v) {
  1115. return v.x === this.x && v.y === this.y;
  1116. },
  1117. fromArray: function (array, offset) {
  1118. if (offset === undefined) offset = 0;
  1119. this.x = array[offset];
  1120. this.y = array[offset + 1];
  1121. return this;
  1122. },
  1123. toArray: function (array, offset) {
  1124. if (array === undefined) array = [];
  1125. if (offset === undefined) offset = 0;
  1126. array[offset] = this.x;
  1127. array[offset + 1] = this.y;
  1128. return array;
  1129. },
  1130. fromBufferAttribute: function (attribute, index, offset) {
  1131. if (offset !== undefined) {
  1132. console.warn('THREE.Vector2: offset has been removed from .fromBufferAttribute().');
  1133. }
  1134. this.x = attribute.getX(index);
  1135. this.y = attribute.getY(index);
  1136. return this;
  1137. },
  1138. rotateAround: function (center, angle) {
  1139. var c = Math.cos(angle),
  1140. s = Math.sin(angle);
  1141. var x = this.x - center.x;
  1142. var y = this.y - center.y;
  1143. this.x = x * c - y * s + center.x;
  1144. this.y = x * s + y * c + center.y;
  1145. return this;
  1146. }
  1147. });
  1148. /**
  1149. * @author mikael emtinger / http://gomo.se/
  1150. * @author alteredq / http://alteredqualia.com/
  1151. * @author WestLangley / http://github.com/WestLangley
  1152. * @author bhouston / http://clara.io
  1153. */
  1154. function Quaternion(x, y, z, w) {
  1155. this._x = x || 0;
  1156. this._y = y || 0;
  1157. this._z = z || 0;
  1158. this._w = w !== undefined ? w : 1;
  1159. }
  1160. Object.assign(Quaternion, {
  1161. slerp: function (qa, qb, qm, t) {
  1162. return qm.copy(qa).slerp(qb, t);
  1163. },
  1164. slerpFlat: function (dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t) {
  1165. // fuzz-free, array-based Quaternion SLERP operation
  1166. var x0 = src0[srcOffset0 + 0],
  1167. y0 = src0[srcOffset0 + 1],
  1168. z0 = src0[srcOffset0 + 2],
  1169. w0 = src0[srcOffset0 + 3],
  1170. x1 = src1[srcOffset1 + 0],
  1171. y1 = src1[srcOffset1 + 1],
  1172. z1 = src1[srcOffset1 + 2],
  1173. w1 = src1[srcOffset1 + 3];
  1174. if (w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1) {
  1175. var s = 1 - t,
  1176. cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1,
  1177. dir = cos >= 0 ? 1 : -1,
  1178. sqrSin = 1 - cos * cos; // Skip the Slerp for tiny steps to avoid numeric problems:
  1179. if (sqrSin > Number.EPSILON) {
  1180. var sin = Math.sqrt(sqrSin),
  1181. len = Math.atan2(sin, cos * dir);
  1182. s = Math.sin(s * len) / sin;
  1183. t = Math.sin(t * len) / sin;
  1184. }
  1185. var tDir = t * dir;
  1186. x0 = x0 * s + x1 * tDir;
  1187. y0 = y0 * s + y1 * tDir;
  1188. z0 = z0 * s + z1 * tDir;
  1189. w0 = w0 * s + w1 * tDir; // Normalize in case we just did a lerp:
  1190. if (s === 1 - t) {
  1191. var f = 1 / Math.sqrt(x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0);
  1192. x0 *= f;
  1193. y0 *= f;
  1194. z0 *= f;
  1195. w0 *= f;
  1196. }
  1197. }
  1198. dst[dstOffset] = x0;
  1199. dst[dstOffset + 1] = y0;
  1200. dst[dstOffset + 2] = z0;
  1201. dst[dstOffset + 3] = w0;
  1202. }
  1203. });
  1204. Object.defineProperties(Quaternion.prototype, {
  1205. x: {
  1206. get: function () {
  1207. return this._x;
  1208. },
  1209. set: function (value) {
  1210. this._x = value;
  1211. this._onChangeCallback();
  1212. }
  1213. },
  1214. y: {
  1215. get: function () {
  1216. return this._y;
  1217. },
  1218. set: function (value) {
  1219. this._y = value;
  1220. this._onChangeCallback();
  1221. }
  1222. },
  1223. z: {
  1224. get: function () {
  1225. return this._z;
  1226. },
  1227. set: function (value) {
  1228. this._z = value;
  1229. this._onChangeCallback();
  1230. }
  1231. },
  1232. w: {
  1233. get: function () {
  1234. return this._w;
  1235. },
  1236. set: function (value) {
  1237. this._w = value;
  1238. this._onChangeCallback();
  1239. }
  1240. }
  1241. });
  1242. Object.assign(Quaternion.prototype, {
  1243. isQuaternion: true,
  1244. set: function (x, y, z, w) {
  1245. this._x = x;
  1246. this._y = y;
  1247. this._z = z;
  1248. this._w = w;
  1249. this._onChangeCallback();
  1250. return this;
  1251. },
  1252. clone: function () {
  1253. return new this.constructor(this._x, this._y, this._z, this._w);
  1254. },
  1255. copy: function (quaternion) {
  1256. this._x = quaternion.x;
  1257. this._y = quaternion.y;
  1258. this._z = quaternion.z;
  1259. this._w = quaternion.w;
  1260. this._onChangeCallback();
  1261. return this;
  1262. },
  1263. setFromEuler: function (euler, update) {
  1264. if (!(euler && euler.isEuler)) {
  1265. throw new Error('THREE.Quaternion: .setFromEuler() now expects an Euler rotation rather than a Vector3 and order.');
  1266. }
  1267. var x = euler._x,
  1268. y = euler._y,
  1269. z = euler._z,
  1270. order = euler.order; // http://www.mathworks.com/matlabcentral/fileexchange/
  1271. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  1272. // content/SpinCalc.m
  1273. var cos = Math.cos;
  1274. var sin = Math.sin;
  1275. var c1 = cos(x / 2);
  1276. var c2 = cos(y / 2);
  1277. var c3 = cos(z / 2);
  1278. var s1 = sin(x / 2);
  1279. var s2 = sin(y / 2);
  1280. var s3 = sin(z / 2);
  1281. if (order === 'XYZ') {
  1282. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  1283. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  1284. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  1285. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  1286. } else if (order === 'YXZ') {
  1287. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  1288. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  1289. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  1290. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  1291. } else if (order === 'ZXY') {
  1292. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  1293. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  1294. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  1295. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  1296. } else if (order === 'ZYX') {
  1297. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  1298. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  1299. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  1300. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  1301. } else if (order === 'YZX') {
  1302. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  1303. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  1304. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  1305. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  1306. } else if (order === 'XZY') {
  1307. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  1308. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  1309. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  1310. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  1311. }
  1312. if (update !== false) this._onChangeCallback();
  1313. return this;
  1314. },
  1315. setFromAxisAngle: function (axis, angle) {
  1316. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  1317. // assumes axis is normalized
  1318. var halfAngle = angle / 2,
  1319. s = Math.sin(halfAngle);
  1320. this._x = axis.x * s;
  1321. this._y = axis.y * s;
  1322. this._z = axis.z * s;
  1323. this._w = Math.cos(halfAngle);
  1324. this._onChangeCallback();
  1325. return this;
  1326. },
  1327. setFromRotationMatrix: function (m) {
  1328. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  1329. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1330. var te = m.elements,
  1331. m11 = te[0],
  1332. m12 = te[4],
  1333. m13 = te[8],
  1334. m21 = te[1],
  1335. m22 = te[5],
  1336. m23 = te[9],
  1337. m31 = te[2],
  1338. m32 = te[6],
  1339. m33 = te[10],
  1340. trace = m11 + m22 + m33,
  1341. s;
  1342. if (trace > 0) {
  1343. s = 0.5 / Math.sqrt(trace + 1.0);
  1344. this._w = 0.25 / s;
  1345. this._x = (m32 - m23) * s;
  1346. this._y = (m13 - m31) * s;
  1347. this._z = (m21 - m12) * s;
  1348. } else if (m11 > m22 && m11 > m33) {
  1349. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  1350. this._w = (m32 - m23) / s;
  1351. this._x = 0.25 * s;
  1352. this._y = (m12 + m21) / s;
  1353. this._z = (m13 + m31) / s;
  1354. } else if (m22 > m33) {
  1355. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  1356. this._w = (m13 - m31) / s;
  1357. this._x = (m12 + m21) / s;
  1358. this._y = 0.25 * s;
  1359. this._z = (m23 + m32) / s;
  1360. } else {
  1361. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  1362. this._w = (m21 - m12) / s;
  1363. this._x = (m13 + m31) / s;
  1364. this._y = (m23 + m32) / s;
  1365. this._z = 0.25 * s;
  1366. }
  1367. this._onChangeCallback();
  1368. return this;
  1369. },
  1370. setFromUnitVectors: function (vFrom, vTo) {
  1371. // assumes direction vectors vFrom and vTo are normalized
  1372. var EPS = 0.000001;
  1373. var r = vFrom.dot(vTo) + 1;
  1374. if (r < EPS) {
  1375. r = 0;
  1376. if (Math.abs(vFrom.x) > Math.abs(vFrom.z)) {
  1377. this._x = -vFrom.y;
  1378. this._y = vFrom.x;
  1379. this._z = 0;
  1380. this._w = r;
  1381. } else {
  1382. this._x = 0;
  1383. this._y = -vFrom.z;
  1384. this._z = vFrom.y;
  1385. this._w = r;
  1386. }
  1387. } else {
  1388. // crossVectors( vFrom, vTo ); // inlined to avoid cyclic dependency on Vector3
  1389. this._x = vFrom.y * vTo.z - vFrom.z * vTo.y;
  1390. this._y = vFrom.z * vTo.x - vFrom.x * vTo.z;
  1391. this._z = vFrom.x * vTo.y - vFrom.y * vTo.x;
  1392. this._w = r;
  1393. }
  1394. return this.normalize();
  1395. },
  1396. angleTo: function (q) {
  1397. return 2 * Math.acos(Math.abs(_Math.clamp(this.dot(q), -1, 1)));
  1398. },
  1399. rotateTowards: function (q, step) {
  1400. var angle = this.angleTo(q);
  1401. if (angle === 0) return this;
  1402. var t = Math.min(1, step / angle);
  1403. this.slerp(q, t);
  1404. return this;
  1405. },
  1406. inverse: function () {
  1407. // quaternion is assumed to have unit length
  1408. return this.conjugate();
  1409. },
  1410. conjugate: function () {
  1411. this._x *= -1;
  1412. this._y *= -1;
  1413. this._z *= -1;
  1414. this._onChangeCallback();
  1415. return this;
  1416. },
  1417. dot: function (v) {
  1418. return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w;
  1419. },
  1420. lengthSq: function () {
  1421. return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  1422. },
  1423. length: function () {
  1424. return Math.sqrt(this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w);
  1425. },
  1426. normalize: function () {
  1427. var l = this.length();
  1428. if (l === 0) {
  1429. this._x = 0;
  1430. this._y = 0;
  1431. this._z = 0;
  1432. this._w = 1;
  1433. } else {
  1434. l = 1 / l;
  1435. this._x = this._x * l;
  1436. this._y = this._y * l;
  1437. this._z = this._z * l;
  1438. this._w = this._w * l;
  1439. }
  1440. this._onChangeCallback();
  1441. return this;
  1442. },
  1443. multiply: function (q, p) {
  1444. if (p !== undefined) {
  1445. console.warn('THREE.Quaternion: .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead.');
  1446. return this.multiplyQuaternions(q, p);
  1447. }
  1448. return this.multiplyQuaternions(this, q);
  1449. },
  1450. premultiply: function (q) {
  1451. return this.multiplyQuaternions(q, this);
  1452. },
  1453. multiplyQuaternions: function (a, b) {
  1454. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  1455. var qax = a._x,
  1456. qay = a._y,
  1457. qaz = a._z,
  1458. qaw = a._w;
  1459. var qbx = b._x,
  1460. qby = b._y,
  1461. qbz = b._z,
  1462. qbw = b._w;
  1463. this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  1464. this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  1465. this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  1466. this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  1467. this._onChangeCallback();
  1468. return this;
  1469. },
  1470. slerp: function (qb, t) {
  1471. if (t === 0) return this;
  1472. if (t === 1) return this.copy(qb);
  1473. var x = this._x,
  1474. y = this._y,
  1475. z = this._z,
  1476. w = this._w; // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  1477. var cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z;
  1478. if (cosHalfTheta < 0) {
  1479. this._w = -qb._w;
  1480. this._x = -qb._x;
  1481. this._y = -qb._y;
  1482. this._z = -qb._z;
  1483. cosHalfTheta = -cosHalfTheta;
  1484. } else {
  1485. this.copy(qb);
  1486. }
  1487. if (cosHalfTheta >= 1.0) {
  1488. this._w = w;
  1489. this._x = x;
  1490. this._y = y;
  1491. this._z = z;
  1492. return this;
  1493. }
  1494. var sqrSinHalfTheta = 1.0 - cosHalfTheta * cosHalfTheta;
  1495. if (sqrSinHalfTheta <= Number.EPSILON) {
  1496. var s = 1 - t;
  1497. this._w = s * w + t * this._w;
  1498. this._x = s * x + t * this._x;
  1499. this._y = s * y + t * this._y;
  1500. this._z = s * z + t * this._z;
  1501. this.normalize();
  1502. this._onChangeCallback();
  1503. return this;
  1504. }
  1505. var sinHalfTheta = Math.sqrt(sqrSinHalfTheta);
  1506. var halfTheta = Math.atan2(sinHalfTheta, cosHalfTheta);
  1507. var ratioA = Math.sin((1 - t) * halfTheta) / sinHalfTheta,
  1508. ratioB = Math.sin(t * halfTheta) / sinHalfTheta;
  1509. this._w = w * ratioA + this._w * ratioB;
  1510. this._x = x * ratioA + this._x * ratioB;
  1511. this._y = y * ratioA + this._y * ratioB;
  1512. this._z = z * ratioA + this._z * ratioB;
  1513. this._onChangeCallback();
  1514. return this;
  1515. },
  1516. equals: function (quaternion) {
  1517. return quaternion._x === this._x && quaternion._y === this._y && quaternion._z === this._z && quaternion._w === this._w;
  1518. },
  1519. fromArray: function (array, offset) {
  1520. if (offset === undefined) offset = 0;
  1521. this._x = array[offset];
  1522. this._y = array[offset + 1];
  1523. this._z = array[offset + 2];
  1524. this._w = array[offset + 3];
  1525. this._onChangeCallback();
  1526. return this;
  1527. },
  1528. toArray: function (array, offset) {
  1529. if (array === undefined) array = [];
  1530. if (offset === undefined) offset = 0;
  1531. array[offset] = this._x;
  1532. array[offset + 1] = this._y;
  1533. array[offset + 2] = this._z;
  1534. array[offset + 3] = this._w;
  1535. return array;
  1536. },
  1537. _onChange: function (callback) {
  1538. this._onChangeCallback = callback;
  1539. return this;
  1540. },
  1541. _onChangeCallback: function () {}
  1542. });
  1543. /**
  1544. * @author mrdoob / http://mrdoob.com/
  1545. * @author kile / http://kile.stravaganza.org/
  1546. * @author philogb / http://blog.thejit.org/
  1547. * @author mikael emtinger / http://gomo.se/
  1548. * @author egraether / http://egraether.com/
  1549. * @author WestLangley / http://github.com/WestLangley
  1550. */
  1551. var _vector = new Vector3();
  1552. var _quaternion = new Quaternion();
  1553. function Vector3(x, y, z) {
  1554. this.x = x || 0;
  1555. this.y = y || 0;
  1556. this.z = z || 0;
  1557. }
  1558. Object.assign(Vector3.prototype, {
  1559. isVector3: true,
  1560. set: function (x, y, z) {
  1561. this.x = x;
  1562. this.y = y;
  1563. this.z = z;
  1564. return this;
  1565. },
  1566. setScalar: function (scalar) {
  1567. this.x = scalar;
  1568. this.y = scalar;
  1569. this.z = scalar;
  1570. return this;
  1571. },
  1572. setX: function (x) {
  1573. this.x = x;
  1574. return this;
  1575. },
  1576. setY: function (y) {
  1577. this.y = y;
  1578. return this;
  1579. },
  1580. setZ: function (z) {
  1581. this.z = z;
  1582. return this;
  1583. },
  1584. setComponent: function (index, value) {
  1585. switch (index) {
  1586. case 0:
  1587. this.x = value;
  1588. break;
  1589. case 1:
  1590. this.y = value;
  1591. break;
  1592. case 2:
  1593. this.z = value;
  1594. break;
  1595. default:
  1596. throw new Error('index is out of range: ' + index);
  1597. }
  1598. return this;
  1599. },
  1600. getComponent: function (index) {
  1601. switch (index) {
  1602. case 0:
  1603. return this.x;
  1604. case 1:
  1605. return this.y;
  1606. case 2:
  1607. return this.z;
  1608. default:
  1609. throw new Error('index is out of range: ' + index);
  1610. }
  1611. },
  1612. clone: function () {
  1613. return new this.constructor(this.x, this.y, this.z);
  1614. },
  1615. copy: function (v) {
  1616. this.x = v.x;
  1617. this.y = v.y;
  1618. this.z = v.z;
  1619. return this;
  1620. },
  1621. add: function (v, w) {
  1622. if (w !== undefined) {
  1623. console.warn('THREE.Vector3: .add() now only accepts one argument. Use .addVectors( a, b ) instead.');
  1624. return this.addVectors(v, w);
  1625. }
  1626. this.x += v.x;
  1627. this.y += v.y;
  1628. this.z += v.z;
  1629. return this;
  1630. },
  1631. addScalar: function (s) {
  1632. this.x += s;
  1633. this.y += s;
  1634. this.z += s;
  1635. return this;
  1636. },
  1637. addVectors: function (a, b) {
  1638. this.x = a.x + b.x;
  1639. this.y = a.y + b.y;
  1640. this.z = a.z + b.z;
  1641. return this;
  1642. },
  1643. addScaledVector: function (v, s) {
  1644. this.x += v.x * s;
  1645. this.y += v.y * s;
  1646. this.z += v.z * s;
  1647. return this;
  1648. },
  1649. sub: function (v, w) {
  1650. if (w !== undefined) {
  1651. console.warn('THREE.Vector3: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.');
  1652. return this.subVectors(v, w);
  1653. }
  1654. this.x -= v.x;
  1655. this.y -= v.y;
  1656. this.z -= v.z;
  1657. return this;
  1658. },
  1659. subScalar: function (s) {
  1660. this.x -= s;
  1661. this.y -= s;
  1662. this.z -= s;
  1663. return this;
  1664. },
  1665. subVectors: function (a, b) {
  1666. this.x = a.x - b.x;
  1667. this.y = a.y - b.y;
  1668. this.z = a.z - b.z;
  1669. return this;
  1670. },
  1671. multiply: function (v, w) {
  1672. if (w !== undefined) {
  1673. console.warn('THREE.Vector3: .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead.');
  1674. return this.multiplyVectors(v, w);
  1675. }
  1676. this.x *= v.x;
  1677. this.y *= v.y;
  1678. this.z *= v.z;
  1679. return this;
  1680. },
  1681. multiplyScalar: function (scalar) {
  1682. this.x *= scalar;
  1683. this.y *= scalar;
  1684. this.z *= scalar;
  1685. return this;
  1686. },
  1687. multiplyVectors: function (a, b) {
  1688. this.x = a.x * b.x;
  1689. this.y = a.y * b.y;
  1690. this.z = a.z * b.z;
  1691. return this;
  1692. },
  1693. applyEuler: function (euler) {
  1694. if (!(euler && euler.isEuler)) {
  1695. console.error('THREE.Vector3: .applyEuler() now expects an Euler rotation rather than a Vector3 and order.');
  1696. }
  1697. return this.applyQuaternion(_quaternion.setFromEuler(euler));
  1698. },
  1699. applyAxisAngle: function (axis, angle) {
  1700. return this.applyQuaternion(_quaternion.setFromAxisAngle(axis, angle));
  1701. },
  1702. applyMatrix3: function (m) {
  1703. var x = this.x,
  1704. y = this.y,
  1705. z = this.z;
  1706. var e = m.elements;
  1707. this.x = e[0] * x + e[3] * y + e[6] * z;
  1708. this.y = e[1] * x + e[4] * y + e[7] * z;
  1709. this.z = e[2] * x + e[5] * y + e[8] * z;
  1710. return this;
  1711. },
  1712. applyMatrix4: function (m) {
  1713. var x = this.x,
  1714. y = this.y,
  1715. z = this.z;
  1716. var e = m.elements;
  1717. var w = 1 / (e[3] * x + e[7] * y + e[11] * z + e[15]);
  1718. this.x = (e[0] * x + e[4] * y + e[8] * z + e[12]) * w;
  1719. this.y = (e[1] * x + e[5] * y + e[9] * z + e[13]) * w;
  1720. this.z = (e[2] * x + e[6] * y + e[10] * z + e[14]) * w;
  1721. return this;
  1722. },
  1723. applyQuaternion: function (q) {
  1724. var x = this.x,
  1725. y = this.y,
  1726. z = this.z;
  1727. var qx = q.x,
  1728. qy = q.y,
  1729. qz = q.z,
  1730. qw = q.w; // calculate quat * vector
  1731. var ix = qw * x + qy * z - qz * y;
  1732. var iy = qw * y + qz * x - qx * z;
  1733. var iz = qw * z + qx * y - qy * x;
  1734. var iw = -qx * x - qy * y - qz * z; // calculate result * inverse quat
  1735. this.x = ix * qw + iw * -qx + iy * -qz - iz * -qy;
  1736. this.y = iy * qw + iw * -qy + iz * -qx - ix * -qz;
  1737. this.z = iz * qw + iw * -qz + ix * -qy - iy * -qx;
  1738. return this;
  1739. },
  1740. project: function (camera) {
  1741. return this.applyMatrix4(camera.matrixWorldInverse).applyMatrix4(camera.projectionMatrix);
  1742. },
  1743. unproject: function (camera) {
  1744. return this.applyMatrix4(camera.projectionMatrixInverse).applyMatrix4(camera.matrixWorld);
  1745. },
  1746. transformDirection: function (m) {
  1747. // input: THREE.Matrix4 affine matrix
  1748. // vector interpreted as a direction
  1749. var x = this.x,
  1750. y = this.y,
  1751. z = this.z;
  1752. var e = m.elements;
  1753. this.x = e[0] * x + e[4] * y + e[8] * z;
  1754. this.y = e[1] * x + e[5] * y + e[9] * z;
  1755. this.z = e[2] * x + e[6] * y + e[10] * z;
  1756. return this.normalize();
  1757. },
  1758. divide: function (v) {
  1759. this.x /= v.x;
  1760. this.y /= v.y;
  1761. this.z /= v.z;
  1762. return this;
  1763. },
  1764. divideScalar: function (scalar) {
  1765. return this.multiplyScalar(1 / scalar);
  1766. },
  1767. min: function (v) {
  1768. this.x = Math.min(this.x, v.x);
  1769. this.y = Math.min(this.y, v.y);
  1770. this.z = Math.min(this.z, v.z);
  1771. return this;
  1772. },
  1773. max: function (v) {
  1774. this.x = Math.max(this.x, v.x);
  1775. this.y = Math.max(this.y, v.y);
  1776. this.z = Math.max(this.z, v.z);
  1777. return this;
  1778. },
  1779. clamp: function (min, max) {
  1780. // assumes min < max, componentwise
  1781. this.x = Math.max(min.x, Math.min(max.x, this.x));
  1782. this.y = Math.max(min.y, Math.min(max.y, this.y));
  1783. this.z = Math.max(min.z, Math.min(max.z, this.z));
  1784. return this;
  1785. },
  1786. clampScalar: function (minVal, maxVal) {
  1787. this.x = Math.max(minVal, Math.min(maxVal, this.x));
  1788. this.y = Math.max(minVal, Math.min(maxVal, this.y));
  1789. this.z = Math.max(minVal, Math.min(maxVal, this.z));
  1790. return this;
  1791. },
  1792. clampLength: function (min, max) {
  1793. var length = this.length();
  1794. return this.divideScalar(length || 1).multiplyScalar(Math.max(min, Math.min(max, length)));
  1795. },
  1796. floor: function () {
  1797. this.x = Math.floor(this.x);
  1798. this.y = Math.floor(this.y);
  1799. this.z = Math.floor(this.z);
  1800. return this;
  1801. },
  1802. ceil: function () {
  1803. this.x = Math.ceil(this.x);
  1804. this.y = Math.ceil(this.y);
  1805. this.z = Math.ceil(this.z);
  1806. return this;
  1807. },
  1808. round: function () {
  1809. this.x = Math.round(this.x);
  1810. this.y = Math.round(this.y);
  1811. this.z = Math.round(this.z);
  1812. return this;
  1813. },
  1814. roundToZero: function () {
  1815. this.x = this.x < 0 ? Math.ceil(this.x) : Math.floor(this.x);
  1816. this.y = this.y < 0 ? Math.ceil(this.y) : Math.floor(this.y);
  1817. this.z = this.z < 0 ? Math.ceil(this.z) : Math.floor(this.z);
  1818. return this;
  1819. },
  1820. negate: function () {
  1821. this.x = -this.x;
  1822. this.y = -this.y;
  1823. this.z = -this.z;
  1824. return this;
  1825. },
  1826. dot: function (v) {
  1827. return this.x * v.x + this.y * v.y + this.z * v.z;
  1828. },
  1829. // TODO lengthSquared?
  1830. lengthSq: function () {
  1831. return this.x * this.x + this.y * this.y + this.z * this.z;
  1832. },
  1833. length: function () {
  1834. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  1835. },
  1836. manhattanLength: function () {
  1837. return Math.abs(this.x) + Math.abs(this.y) + Math.abs(this.z);
  1838. },
  1839. normalize: function () {
  1840. return this.divideScalar(this.length() || 1);
  1841. },
  1842. setLength: function (length) {
  1843. return this.normalize().multiplyScalar(length);
  1844. },
  1845. lerp: function (v, alpha) {
  1846. this.x += (v.x - this.x) * alpha;
  1847. this.y += (v.y - this.y) * alpha;
  1848. this.z += (v.z - this.z) * alpha;
  1849. return this;
  1850. },
  1851. lerpVectors: function (v1, v2, alpha) {
  1852. return this.subVectors(v2, v1).multiplyScalar(alpha).add(v1);
  1853. },
  1854. cross: function (v, w) {
  1855. if (w !== undefined) {
  1856. console.warn('THREE.Vector3: .cross() now only accepts one argument. Use .crossVectors( a, b ) instead.');
  1857. return this.crossVectors(v, w);
  1858. }
  1859. return this.crossVectors(this, v);
  1860. },
  1861. crossVectors: function (a, b) {
  1862. var ax = a.x,
  1863. ay = a.y,
  1864. az = a.z;
  1865. var bx = b.x,
  1866. by = b.y,
  1867. bz = b.z;
  1868. this.x = ay * bz - az * by;
  1869. this.y = az * bx - ax * bz;
  1870. this.z = ax * by - ay * bx;
  1871. return this;
  1872. },
  1873. projectOnVector: function (v) {
  1874. // v cannot be the zero v
  1875. var scalar = v.dot(this) / v.lengthSq();
  1876. return this.copy(v).multiplyScalar(scalar);
  1877. },
  1878. projectOnPlane: function (planeNormal) {
  1879. _vector.copy(this).projectOnVector(planeNormal);
  1880. return this.sub(_vector);
  1881. },
  1882. reflect: function (normal) {
  1883. // reflect incident vector off plane orthogonal to normal
  1884. // normal is assumed to have unit length
  1885. return this.sub(_vector.copy(normal).multiplyScalar(2 * this.dot(normal)));
  1886. },
  1887. angleTo: function (v) {
  1888. var denominator = Math.sqrt(this.lengthSq() * v.lengthSq());
  1889. if (denominator === 0) console.error('THREE.Vector3: angleTo() can\'t handle zero length vectors.');
  1890. var theta = this.dot(v) / denominator; // clamp, to handle numerical problems
  1891. return Math.acos(_Math.clamp(theta, -1, 1));
  1892. },
  1893. distanceTo: function (v) {
  1894. return Math.sqrt(this.distanceToSquared(v));
  1895. },
  1896. distanceToSquared: function (v) {
  1897. var dx = this.x - v.x,
  1898. dy = this.y - v.y,
  1899. dz = this.z - v.z;
  1900. return dx * dx + dy * dy + dz * dz;
  1901. },
  1902. manhattanDistanceTo: function (v) {
  1903. return Math.abs(this.x - v.x) + Math.abs(this.y - v.y) + Math.abs(this.z - v.z);
  1904. },
  1905. setFromSpherical: function (s) {
  1906. return this.setFromSphericalCoords(s.radius, s.phi, s.theta);
  1907. },
  1908. setFromSphericalCoords: function (radius, phi, theta) {
  1909. var sinPhiRadius = Math.sin(phi) * radius;
  1910. this.x = sinPhiRadius * Math.sin(theta);
  1911. this.y = Math.cos(phi) * radius;
  1912. this.z = sinPhiRadius * Math.cos(theta);
  1913. return this;
  1914. },
  1915. setFromCylindrical: function (c) {
  1916. return this.setFromCylindricalCoords(c.radius, c.theta, c.y);
  1917. },
  1918. setFromCylindricalCoords: function (radius, theta, y) {
  1919. this.x = radius * Math.sin(theta);
  1920. this.y = y;
  1921. this.z = radius * Math.cos(theta);
  1922. return this;
  1923. },
  1924. setFromMatrixPosition: function (m) {
  1925. var e = m.elements;
  1926. this.x = e[12];
  1927. this.y = e[13];
  1928. this.z = e[14];
  1929. return this;
  1930. },
  1931. setFromMatrixScale: function (m) {
  1932. var sx = this.setFromMatrixColumn(m, 0).length();
  1933. var sy = this.setFromMatrixColumn(m, 1).length();
  1934. var sz = this.setFromMatrixColumn(m, 2).length();
  1935. this.x = sx;
  1936. this.y = sy;
  1937. this.z = sz;
  1938. return this;
  1939. },
  1940. setFromMatrixColumn: function (m, index) {
  1941. return this.fromArray(m.elements, index * 4);
  1942. },
  1943. equals: function (v) {
  1944. return v.x === this.x && v.y === this.y && v.z === this.z;
  1945. },
  1946. fromArray: function (array, offset) {
  1947. if (offset === undefined) offset = 0;
  1948. this.x = array[offset];
  1949. this.y = array[offset + 1];
  1950. this.z = array[offset + 2];
  1951. return this;
  1952. },
  1953. toArray: function (array, offset) {
  1954. if (array === undefined) array = [];
  1955. if (offset === undefined) offset = 0;
  1956. array[offset] = this.x;
  1957. array[offset + 1] = this.y;
  1958. array[offset + 2] = this.z;
  1959. return array;
  1960. },
  1961. fromBufferAttribute: function (attribute, index, offset) {
  1962. if (offset !== undefined) {
  1963. console.warn('THREE.Vector3: offset has been removed from .fromBufferAttribute().');
  1964. }
  1965. this.x = attribute.getX(index);
  1966. this.y = attribute.getY(index);
  1967. this.z = attribute.getZ(index);
  1968. return this;
  1969. }
  1970. });
  1971. /**
  1972. * @author alteredq / http://alteredqualia.com/
  1973. * @author WestLangley / http://github.com/WestLangley
  1974. * @author bhouston / http://clara.io
  1975. * @author tschw
  1976. */
  1977. var _vector$1 = new Vector3();
  1978. function Matrix3() {
  1979. this.elements = [1, 0, 0, 0, 1, 0, 0, 0, 1];
  1980. if (arguments.length > 0) {
  1981. console.error('THREE.Matrix3: the constructor no longer reads arguments. use .set() instead.');
  1982. }
  1983. }
  1984. Object.assign(Matrix3.prototype, {
  1985. isMatrix3: true,
  1986. set: function (n11, n12, n13, n21, n22, n23, n31, n32, n33) {
  1987. var te = this.elements;
  1988. te[0] = n11;
  1989. te[1] = n21;
  1990. te[2] = n31;
  1991. te[3] = n12;
  1992. te[4] = n22;
  1993. te[5] = n32;
  1994. te[6] = n13;
  1995. te[7] = n23;
  1996. te[8] = n33;
  1997. return this;
  1998. },
  1999. identity: function () {
  2000. this.set(1, 0, 0, 0, 1, 0, 0, 0, 1);
  2001. return this;
  2002. },
  2003. clone: function () {
  2004. return new this.constructor().fromArray(this.elements);
  2005. },
  2006. copy: function (m) {
  2007. var te = this.elements;
  2008. var me = m.elements;
  2009. te[0] = me[0];
  2010. te[1] = me[1];
  2011. te[2] = me[2];
  2012. te[3] = me[3];
  2013. te[4] = me[4];
  2014. te[5] = me[5];
  2015. te[6] = me[6];
  2016. te[7] = me[7];
  2017. te[8] = me[8];
  2018. return this;
  2019. },
  2020. setFromMatrix4: function (m) {
  2021. var me = m.elements;
  2022. this.set(me[0], me[4], me[8], me[1], me[5], me[9], me[2], me[6], me[10]);
  2023. return this;
  2024. },
  2025. applyToBufferAttribute: function (attribute) {
  2026. for (var i = 0, l = attribute.count; i < l; i++) {
  2027. _vector$1.x = attribute.getX(i);
  2028. _vector$1.y = attribute.getY(i);
  2029. _vector$1.z = attribute.getZ(i);
  2030. _vector$1.applyMatrix3(this);
  2031. attribute.setXYZ(i, _vector$1.x, _vector$1.y, _vector$1.z);
  2032. }
  2033. return attribute;
  2034. },
  2035. multiply: function (m) {
  2036. return this.multiplyMatrices(this, m);
  2037. },
  2038. premultiply: function (m) {
  2039. return this.multiplyMatrices(m, this);
  2040. },
  2041. multiplyMatrices: function (a, b) {
  2042. var ae = a.elements;
  2043. var be = b.elements;
  2044. var te = this.elements;
  2045. var a11 = ae[0],
  2046. a12 = ae[3],
  2047. a13 = ae[6];
  2048. var a21 = ae[1],
  2049. a22 = ae[4],
  2050. a23 = ae[7];
  2051. var a31 = ae[2],
  2052. a32 = ae[5],
  2053. a33 = ae[8];
  2054. var b11 = be[0],
  2055. b12 = be[3],
  2056. b13 = be[6];
  2057. var b21 = be[1],
  2058. b22 = be[4],
  2059. b23 = be[7];
  2060. var b31 = be[2],
  2061. b32 = be[5],
  2062. b33 = be[8];
  2063. te[0] = a11 * b11 + a12 * b21 + a13 * b31;
  2064. te[3] = a11 * b12 + a12 * b22 + a13 * b32;
  2065. te[6] = a11 * b13 + a12 * b23 + a13 * b33;
  2066. te[1] = a21 * b11 + a22 * b21 + a23 * b31;
  2067. te[4] = a21 * b12 + a22 * b22 + a23 * b32;
  2068. te[7] = a21 * b13 + a22 * b23 + a23 * b33;
  2069. te[2] = a31 * b11 + a32 * b21 + a33 * b31;
  2070. te[5] = a31 * b12 + a32 * b22 + a33 * b32;
  2071. te[8] = a31 * b13 + a32 * b23 + a33 * b33;
  2072. return this;
  2073. },
  2074. multiplyScalar: function (s) {
  2075. var te = this.elements;
  2076. te[0] *= s;
  2077. te[3] *= s;
  2078. te[6] *= s;
  2079. te[1] *= s;
  2080. te[4] *= s;
  2081. te[7] *= s;
  2082. te[2] *= s;
  2083. te[5] *= s;
  2084. te[8] *= s;
  2085. return this;
  2086. },
  2087. determinant: function () {
  2088. var te = this.elements;
  2089. var a = te[0],
  2090. b = te[1],
  2091. c = te[2],
  2092. d = te[3],
  2093. e = te[4],
  2094. f = te[5],
  2095. g = te[6],
  2096. h = te[7],
  2097. i = te[8];
  2098. return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g;
  2099. },
  2100. getInverse: function (matrix, throwOnDegenerate) {
  2101. if (matrix && matrix.isMatrix4) {
  2102. console.error("THREE.Matrix3: .getInverse() no longer takes a Matrix4 argument.");
  2103. }
  2104. var me = matrix.elements,
  2105. te = this.elements,
  2106. n11 = me[0],
  2107. n21 = me[1],
  2108. n31 = me[2],
  2109. n12 = me[3],
  2110. n22 = me[4],
  2111. n32 = me[5],
  2112. n13 = me[6],
  2113. n23 = me[7],
  2114. n33 = me[8],
  2115. t11 = n33 * n22 - n32 * n23,
  2116. t12 = n32 * n13 - n33 * n12,
  2117. t13 = n23 * n12 - n22 * n13,
  2118. det = n11 * t11 + n21 * t12 + n31 * t13;
  2119. if (det === 0) {
  2120. var msg = "THREE.Matrix3: .getInverse() can't invert matrix, determinant is 0";
  2121. if (throwOnDegenerate === true) {
  2122. throw new Error(msg);
  2123. } else {
  2124. console.warn(msg);
  2125. }
  2126. return this.identity();
  2127. }
  2128. var detInv = 1 / det;
  2129. te[0] = t11 * detInv;
  2130. te[1] = (n31 * n23 - n33 * n21) * detInv;
  2131. te[2] = (n32 * n21 - n31 * n22) * detInv;
  2132. te[3] = t12 * detInv;
  2133. te[4] = (n33 * n11 - n31 * n13) * detInv;
  2134. te[5] = (n31 * n12 - n32 * n11) * detInv;
  2135. te[6] = t13 * detInv;
  2136. te[7] = (n21 * n13 - n23 * n11) * detInv;
  2137. te[8] = (n22 * n11 - n21 * n12) * detInv;
  2138. return this;
  2139. },
  2140. transpose: function () {
  2141. var tmp,
  2142. m = this.elements;
  2143. tmp = m[1];
  2144. m[1] = m[3];
  2145. m[3] = tmp;
  2146. tmp = m[2];
  2147. m[2] = m[6];
  2148. m[6] = tmp;
  2149. tmp = m[5];
  2150. m[5] = m[7];
  2151. m[7] = tmp;
  2152. return this;
  2153. },
  2154. getNormalMatrix: function (matrix4) {
  2155. return this.setFromMatrix4(matrix4).getInverse(this).transpose();
  2156. },
  2157. transposeIntoArray: function (r) {
  2158. var m = this.elements;
  2159. r[0] = m[0];
  2160. r[1] = m[3];
  2161. r[2] = m[6];
  2162. r[3] = m[1];
  2163. r[4] = m[4];
  2164. r[5] = m[7];
  2165. r[6] = m[2];
  2166. r[7] = m[5];
  2167. r[8] = m[8];
  2168. return this;
  2169. },
  2170. setUvTransform: function (tx, ty, sx, sy, rotation, cx, cy) {
  2171. var c = Math.cos(rotation);
  2172. var s = Math.sin(rotation);
  2173. 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);
  2174. },
  2175. scale: function (sx, sy) {
  2176. var te = this.elements;
  2177. te[0] *= sx;
  2178. te[3] *= sx;
  2179. te[6] *= sx;
  2180. te[1] *= sy;
  2181. te[4] *= sy;
  2182. te[7] *= sy;
  2183. return this;
  2184. },
  2185. rotate: function (theta) {
  2186. var c = Math.cos(theta);
  2187. var s = Math.sin(theta);
  2188. var te = this.elements;
  2189. var a11 = te[0],
  2190. a12 = te[3],
  2191. a13 = te[6];
  2192. var a21 = te[1],
  2193. a22 = te[4],
  2194. a23 = te[7];
  2195. te[0] = c * a11 + s * a21;
  2196. te[3] = c * a12 + s * a22;
  2197. te[6] = c * a13 + s * a23;
  2198. te[1] = -s * a11 + c * a21;
  2199. te[4] = -s * a12 + c * a22;
  2200. te[7] = -s * a13 + c * a23;
  2201. return this;
  2202. },
  2203. translate: function (tx, ty) {
  2204. var te = this.elements;
  2205. te[0] += tx * te[2];
  2206. te[3] += tx * te[5];
  2207. te[6] += tx * te[8];
  2208. te[1] += ty * te[2];
  2209. te[4] += ty * te[5];
  2210. te[7] += ty * te[8];
  2211. return this;
  2212. },
  2213. equals: function (matrix) {
  2214. var te = this.elements;
  2215. var me = matrix.elements;
  2216. for (var i = 0; i < 9; i++) {
  2217. if (te[i] !== me[i]) return false;
  2218. }
  2219. return true;
  2220. },
  2221. fromArray: function (array, offset) {
  2222. if (offset === undefined) offset = 0;
  2223. for (var i = 0; i < 9; i++) {
  2224. this.elements[i] = array[i + offset];
  2225. }
  2226. return this;
  2227. },
  2228. toArray: function (array, offset) {
  2229. if (array === undefined) array = [];
  2230. if (offset === undefined) offset = 0;
  2231. var te = this.elements;
  2232. array[offset] = te[0];
  2233. array[offset + 1] = te[1];
  2234. array[offset + 2] = te[2];
  2235. array[offset + 3] = te[3];
  2236. array[offset + 4] = te[4];
  2237. array[offset + 5] = te[5];
  2238. array[offset + 6] = te[6];
  2239. array[offset + 7] = te[7];
  2240. array[offset + 8] = te[8];
  2241. return array;
  2242. }
  2243. });
  2244. /**
  2245. * @author mrdoob / http://mrdoob.com/
  2246. * @author alteredq / http://alteredqualia.com/
  2247. * @author szimek / https://github.com/szimek/
  2248. */
  2249. var _canvas;
  2250. var ImageUtils = {
  2251. getDataURL: function (image) {
  2252. var canvas;
  2253. if (typeof HTMLCanvasElement == 'undefined') {
  2254. return image.src;
  2255. } else if (image instanceof HTMLCanvasElement) {
  2256. canvas = image;
  2257. } else {
  2258. if (_canvas === undefined) _canvas = document.createElementNS('http://www.w3.org/1999/xhtml', 'canvas');
  2259. _canvas.width = image.width;
  2260. _canvas.height = image.height;
  2261. var context = _canvas.getContext('2d');
  2262. if (image instanceof ImageData) {
  2263. context.putImageData(image, 0, 0);
  2264. } else {
  2265. context.drawImage(image, 0, 0, image.width, image.height);
  2266. }
  2267. canvas = _canvas;
  2268. }
  2269. if (canvas.width > 2048 || canvas.height > 2048) {
  2270. return canvas.toDataURL('image/jpeg', 0.6);
  2271. } else {
  2272. return canvas.toDataURL('image/png');
  2273. }
  2274. }
  2275. };
  2276. /**
  2277. * @author mrdoob / http://mrdoob.com/
  2278. * @author alteredq / http://alteredqualia.com/
  2279. * @author szimek / https://github.com/szimek/
  2280. */
  2281. exports.ImageUtils = ImageUtils;
  2282. var textureId = 0;
  2283. function Texture(image, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding) {
  2284. Object.defineProperty(this, 'id', {
  2285. value: textureId++
  2286. });
  2287. this.uuid = _Math.generateUUID();
  2288. this.name = '';
  2289. this.image = image !== undefined ? image : Texture.DEFAULT_IMAGE;
  2290. this.mipmaps = [];
  2291. this.mapping = mapping !== undefined ? mapping : Texture.DEFAULT_MAPPING;
  2292. this.wrapS = wrapS !== undefined ? wrapS : ClampToEdgeWrapping;
  2293. this.wrapT = wrapT !== undefined ? wrapT : ClampToEdgeWrapping;
  2294. this.magFilter = magFilter !== undefined ? magFilter : LinearFilter;
  2295. this.minFilter = minFilter !== undefined ? minFilter : LinearMipmapLinearFilter;
  2296. this.anisotropy = anisotropy !== undefined ? anisotropy : 1;
  2297. this.format = format !== undefined ? format : RGBAFormat;
  2298. this.type = type !== undefined ? type : UnsignedByteType;
  2299. this.offset = new Vector2(0, 0);
  2300. this.repeat = new Vector2(1, 1);
  2301. this.center = new Vector2(0, 0);
  2302. this.rotation = 0;
  2303. this.matrixAutoUpdate = true;
  2304. this.matrix = new Matrix3();
  2305. this.generateMipmaps = true;
  2306. this.premultiplyAlpha = false;
  2307. this.flipY = true;
  2308. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  2309. // Values of encoding !== THREE.LinearEncoding only supported on map, envMap and emissiveMap.
  2310. //
  2311. // Also changing the encoding after already used by a Material will not automatically make the Material
  2312. // update. You need to explicitly call Material.needsUpdate to trigger it to recompile.
  2313. this.encoding = encoding !== undefined ? encoding : LinearEncoding;
  2314. this.version = 0;
  2315. this.onUpdate = null;
  2316. }
  2317. Texture.DEFAULT_IMAGE = undefined;
  2318. Texture.DEFAULT_MAPPING = UVMapping;
  2319. Texture.prototype = Object.assign(Object.create(EventDispatcher.prototype), {
  2320. constructor: Texture,
  2321. isTexture: true,
  2322. updateMatrix: function () {
  2323. this.matrix.setUvTransform(this.offset.x, this.offset.y, this.repeat.x, this.repeat.y, this.rotation, this.center.x, this.center.y);
  2324. },
  2325. clone: function () {
  2326. return new this.constructor().copy(this);
  2327. },
  2328. copy: function (source) {
  2329. this.name = source.name;
  2330. this.image = source.image;
  2331. this.mipmaps = source.mipmaps.slice(0);
  2332. this.mapping = source.mapping;
  2333. this.wrapS = source.wrapS;
  2334. this.wrapT = source.wrapT;
  2335. this.magFilter = source.magFilter;
  2336. this.minFilter = source.minFilter;
  2337. this.anisotropy = source.anisotropy;
  2338. this.format = source.format;
  2339. this.type = source.type;
  2340. this.offset.copy(source.offset);
  2341. this.repeat.copy(source.repeat);
  2342. this.center.copy(source.center);
  2343. this.rotation = source.rotation;
  2344. this.matrixAutoUpdate = source.matrixAutoUpdate;
  2345. this.matrix.copy(source.matrix);
  2346. this.generateMipmaps = source.generateMipmaps;
  2347. this.premultiplyAlpha = source.premultiplyAlpha;
  2348. this.flipY = source.flipY;
  2349. this.unpackAlignment = source.unpackAlignment;
  2350. this.encoding = source.encoding;
  2351. return this;
  2352. },
  2353. toJSON: function (meta) {
  2354. var isRootObject = meta === undefined || typeof meta === 'string';
  2355. if (!isRootObject && meta.textures[this.uuid] !== undefined) {
  2356. return meta.textures[this.uuid];
  2357. }
  2358. var output = {
  2359. metadata: {
  2360. version: 4.5,
  2361. type: 'Texture',
  2362. generator: 'Texture.toJSON'
  2363. },
  2364. uuid: this.uuid,
  2365. name: this.name,
  2366. mapping: this.mapping,
  2367. repeat: [this.repeat.x, this.repeat.y],
  2368. offset: [this.offset.x, this.offset.y],
  2369. center: [this.center.x, this.center.y],
  2370. rotation: this.rotation,
  2371. wrap: [this.wrapS, this.wrapT],
  2372. format: this.format,
  2373. type: this.type,
  2374. encoding: this.encoding,
  2375. minFilter: this.minFilter,
  2376. magFilter: this.magFilter,
  2377. anisotropy: this.anisotropy,
  2378. flipY: this.flipY,
  2379. premultiplyAlpha: this.premultiplyAlpha,
  2380. unpackAlignment: this.unpackAlignment
  2381. };
  2382. if (this.image !== undefined) {
  2383. // TODO: Move to THREE.Image
  2384. var image = this.image;
  2385. if (image.uuid === undefined) {
  2386. image.uuid = _Math.generateUUID(); // UGH
  2387. }
  2388. if (!isRootObject && meta.images[image.uuid] === undefined) {
  2389. var url;
  2390. if (Array.isArray(image)) {
  2391. // process array of images e.g. CubeTexture
  2392. url = [];
  2393. for (var i = 0, l = image.length; i < l; i++) {
  2394. url.push(ImageUtils.getDataURL(image[i]));
  2395. }
  2396. } else {
  2397. // process single image
  2398. url = ImageUtils.getDataURL(image);
  2399. }
  2400. meta.images[image.uuid] = {
  2401. uuid: image.uuid,
  2402. url: url
  2403. };
  2404. }
  2405. output.image = image.uuid;
  2406. }
  2407. if (!isRootObject) {
  2408. meta.textures[this.uuid] = output;
  2409. }
  2410. return output;
  2411. },
  2412. dispose: function () {
  2413. this.dispatchEvent({
  2414. type: 'dispose'
  2415. });
  2416. },
  2417. transformUv: function (uv) {
  2418. if (this.mapping !== UVMapping) return uv;
  2419. uv.applyMatrix3(this.matrix);
  2420. if (uv.x < 0 || uv.x > 1) {
  2421. switch (this.wrapS) {
  2422. case RepeatWrapping:
  2423. uv.x = uv.x - Math.floor(uv.x);
  2424. break;
  2425. case ClampToEdgeWrapping:
  2426. uv.x = uv.x < 0 ? 0 : 1;
  2427. break;
  2428. case MirroredRepeatWrapping:
  2429. if (Math.abs(Math.floor(uv.x) % 2) === 1) {
  2430. uv.x = Math.ceil(uv.x) - uv.x;
  2431. } else {
  2432. uv.x = uv.x - Math.floor(uv.x);
  2433. }
  2434. break;
  2435. }
  2436. }
  2437. if (uv.y < 0 || uv.y > 1) {
  2438. switch (this.wrapT) {
  2439. case RepeatWrapping:
  2440. uv.y = uv.y - Math.floor(uv.y);
  2441. break;
  2442. case ClampToEdgeWrapping:
  2443. uv.y = uv.y < 0 ? 0 : 1;
  2444. break;
  2445. case MirroredRepeatWrapping:
  2446. if (Math.abs(Math.floor(uv.y) % 2) === 1) {
  2447. uv.y = Math.ceil(uv.y) - uv.y;
  2448. } else {
  2449. uv.y = uv.y - Math.floor(uv.y);
  2450. }
  2451. break;
  2452. }
  2453. }
  2454. if (this.flipY) {
  2455. uv.y = 1 - uv.y;
  2456. }
  2457. return uv;
  2458. }
  2459. });
  2460. Object.defineProperty(Texture.prototype, "needsUpdate", {
  2461. set: function (value) {
  2462. if (value === true) this.version++;
  2463. }
  2464. });
  2465. /**
  2466. * @author supereggbert / http://www.paulbrunt.co.uk/
  2467. * @author philogb / http://blog.thejit.org/
  2468. * @author mikael emtinger / http://gomo.se/
  2469. * @author egraether / http://egraether.com/
  2470. * @author WestLangley / http://github.com/WestLangley
  2471. */
  2472. function Vector4(x, y, z, w) {
  2473. this.x = x || 0;
  2474. this.y = y || 0;
  2475. this.z = z || 0;
  2476. this.w = w !== undefined ? w : 1;
  2477. }
  2478. Object.defineProperties(Vector4.prototype, {
  2479. "width": {
  2480. get: function () {
  2481. return this.z;
  2482. },
  2483. set: function (value) {
  2484. this.z = value;
  2485. }
  2486. },
  2487. "height": {
  2488. get: function () {
  2489. return this.w;
  2490. },
  2491. set: function (value) {
  2492. this.w = value;
  2493. }
  2494. }
  2495. });
  2496. Object.assign(Vector4.prototype, {
  2497. isVector4: true,
  2498. set: function (x, y, z, w) {
  2499. this.x = x;
  2500. this.y = y;
  2501. this.z = z;
  2502. this.w = w;
  2503. return this;
  2504. },
  2505. setScalar: function (scalar) {
  2506. this.x = scalar;
  2507. this.y = scalar;
  2508. this.z = scalar;
  2509. this.w = scalar;
  2510. return this;
  2511. },
  2512. setX: function (x) {
  2513. this.x = x;
  2514. return this;
  2515. },
  2516. setY: function (y) {
  2517. this.y = y;
  2518. return this;
  2519. },
  2520. setZ: function (z) {
  2521. this.z = z;
  2522. return this;
  2523. },
  2524. setW: function (w) {
  2525. this.w = w;
  2526. return this;
  2527. },
  2528. setComponent: function (index, value) {
  2529. switch (index) {
  2530. case 0:
  2531. this.x = value;
  2532. break;
  2533. case 1:
  2534. this.y = value;
  2535. break;
  2536. case 2:
  2537. this.z = value;
  2538. break;
  2539. case 3:
  2540. this.w = value;
  2541. break;
  2542. default:
  2543. throw new Error('index is out of range: ' + index);
  2544. }
  2545. return this;
  2546. },
  2547. getComponent: function (index) {
  2548. switch (index) {
  2549. case 0:
  2550. return this.x;
  2551. case 1:
  2552. return this.y;
  2553. case 2:
  2554. return this.z;
  2555. case 3:
  2556. return this.w;
  2557. default:
  2558. throw new Error('index is out of range: ' + index);
  2559. }
  2560. },
  2561. clone: function () {
  2562. return new this.constructor(this.x, this.y, this.z, this.w);
  2563. },
  2564. copy: function (v) {
  2565. this.x = v.x;
  2566. this.y = v.y;
  2567. this.z = v.z;
  2568. this.w = v.w !== undefined ? v.w : 1;
  2569. return this;
  2570. },
  2571. add: function (v, w) {
  2572. if (w !== undefined) {
  2573. console.warn('THREE.Vector4: .add() now only accepts one argument. Use .addVectors( a, b ) instead.');
  2574. return this.addVectors(v, w);
  2575. }
  2576. this.x += v.x;
  2577. this.y += v.y;
  2578. this.z += v.z;
  2579. this.w += v.w;
  2580. return this;
  2581. },
  2582. addScalar: function (s) {
  2583. this.x += s;
  2584. this.y += s;
  2585. this.z += s;
  2586. this.w += s;
  2587. return this;
  2588. },
  2589. addVectors: function (a, b) {
  2590. this.x = a.x + b.x;
  2591. this.y = a.y + b.y;
  2592. this.z = a.z + b.z;
  2593. this.w = a.w + b.w;
  2594. return this;
  2595. },
  2596. addScaledVector: function (v, s) {
  2597. this.x += v.x * s;
  2598. this.y += v.y * s;
  2599. this.z += v.z * s;
  2600. this.w += v.w * s;
  2601. return this;
  2602. },
  2603. sub: function (v, w) {
  2604. if (w !== undefined) {
  2605. console.warn('THREE.Vector4: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.');
  2606. return this.subVectors(v, w);
  2607. }
  2608. this.x -= v.x;
  2609. this.y -= v.y;
  2610. this.z -= v.z;
  2611. this.w -= v.w;
  2612. return this;
  2613. },
  2614. subScalar: function (s) {
  2615. this.x -= s;
  2616. this.y -= s;
  2617. this.z -= s;
  2618. this.w -= s;
  2619. return this;
  2620. },
  2621. subVectors: function (a, b) {
  2622. this.x = a.x - b.x;
  2623. this.y = a.y - b.y;
  2624. this.z = a.z - b.z;
  2625. this.w = a.w - b.w;
  2626. return this;
  2627. },
  2628. multiplyScalar: function (scalar) {
  2629. this.x *= scalar;
  2630. this.y *= scalar;
  2631. this.z *= scalar;
  2632. this.w *= scalar;
  2633. return this;
  2634. },
  2635. applyMatrix4: function (m) {
  2636. var x = this.x,
  2637. y = this.y,
  2638. z = this.z,
  2639. w = this.w;
  2640. var e = m.elements;
  2641. this.x = e[0] * x + e[4] * y + e[8] * z + e[12] * w;
  2642. this.y = e[1] * x + e[5] * y + e[9] * z + e[13] * w;
  2643. this.z = e[2] * x + e[6] * y + e[10] * z + e[14] * w;
  2644. this.w = e[3] * x + e[7] * y + e[11] * z + e[15] * w;
  2645. return this;
  2646. },
  2647. divideScalar: function (scalar) {
  2648. return this.multiplyScalar(1 / scalar);
  2649. },
  2650. setAxisAngleFromQuaternion: function (q) {
  2651. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  2652. // q is assumed to be normalized
  2653. this.w = 2 * Math.acos(q.w);
  2654. var s = Math.sqrt(1 - q.w * q.w);
  2655. if (s < 0.0001) {
  2656. this.x = 1;
  2657. this.y = 0;
  2658. this.z = 0;
  2659. } else {
  2660. this.x = q.x / s;
  2661. this.y = q.y / s;
  2662. this.z = q.z / s;
  2663. }
  2664. return this;
  2665. },
  2666. setAxisAngleFromRotationMatrix: function (m) {
  2667. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  2668. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  2669. var angle,
  2670. x,
  2671. y,
  2672. z,
  2673. // variables for result
  2674. epsilon = 0.01,
  2675. // margin to allow for rounding errors
  2676. epsilon2 = 0.1,
  2677. // margin to distinguish between 0 and 180 degrees
  2678. te = m.elements,
  2679. m11 = te[0],
  2680. m12 = te[4],
  2681. m13 = te[8],
  2682. m21 = te[1],
  2683. m22 = te[5],
  2684. m23 = te[9],
  2685. m31 = te[2],
  2686. m32 = te[6],
  2687. m33 = te[10];
  2688. if (Math.abs(m12 - m21) < epsilon && Math.abs(m13 - m31) < epsilon && Math.abs(m23 - m32) < epsilon) {
  2689. // singularity found
  2690. // first check for identity matrix which must have +1 for all terms
  2691. // in leading diagonal and zero in other terms
  2692. if (Math.abs(m12 + m21) < epsilon2 && Math.abs(m13 + m31) < epsilon2 && Math.abs(m23 + m32) < epsilon2 && Math.abs(m11 + m22 + m33 - 3) < epsilon2) {
  2693. // this singularity is identity matrix so angle = 0
  2694. this.set(1, 0, 0, 0);
  2695. return this; // zero angle, arbitrary axis
  2696. } // otherwise this singularity is angle = 180
  2697. angle = Math.PI;
  2698. var xx = (m11 + 1) / 2;
  2699. var yy = (m22 + 1) / 2;
  2700. var zz = (m33 + 1) / 2;
  2701. var xy = (m12 + m21) / 4;
  2702. var xz = (m13 + m31) / 4;
  2703. var yz = (m23 + m32) / 4;
  2704. if (xx > yy && xx > zz) {
  2705. // m11 is the largest diagonal term
  2706. if (xx < epsilon) {
  2707. x = 0;
  2708. y = 0.707106781;
  2709. z = 0.707106781;
  2710. } else {
  2711. x = Math.sqrt(xx);
  2712. y = xy / x;
  2713. z = xz / x;
  2714. }
  2715. } else if (yy > zz) {
  2716. // m22 is the largest diagonal term
  2717. if (yy < epsilon) {
  2718. x = 0.707106781;
  2719. y = 0;
  2720. z = 0.707106781;
  2721. } else {
  2722. y = Math.sqrt(yy);
  2723. x = xy / y;
  2724. z = yz / y;
  2725. }
  2726. } else {
  2727. // m33 is the largest diagonal term so base result on this
  2728. if (zz < epsilon) {
  2729. x = 0.707106781;
  2730. y = 0.707106781;
  2731. z = 0;
  2732. } else {
  2733. z = Math.sqrt(zz);
  2734. x = xz / z;
  2735. y = yz / z;
  2736. }
  2737. }
  2738. this.set(x, y, z, angle);
  2739. return this; // return 180 deg rotation
  2740. } // as we have reached here there are no singularities so we can handle normally
  2741. var s = Math.sqrt((m32 - m23) * (m32 - m23) + (m13 - m31) * (m13 - m31) + (m21 - m12) * (m21 - m12)); // used to normalize
  2742. if (Math.abs(s) < 0.001) s = 1; // prevent divide by zero, should not happen if matrix is orthogonal and should be
  2743. // caught by singularity test above, but I've left it in just in case
  2744. this.x = (m32 - m23) / s;
  2745. this.y = (m13 - m31) / s;
  2746. this.z = (m21 - m12) / s;
  2747. this.w = Math.acos((m11 + m22 + m33 - 1) / 2);
  2748. return this;
  2749. },
  2750. min: function (v) {
  2751. this.x = Math.min(this.x, v.x);
  2752. this.y = Math.min(this.y, v.y);
  2753. this.z = Math.min(this.z, v.z);
  2754. this.w = Math.min(this.w, v.w);
  2755. return this;
  2756. },
  2757. max: function (v) {
  2758. this.x = Math.max(this.x, v.x);
  2759. this.y = Math.max(this.y, v.y);
  2760. this.z = Math.max(this.z, v.z);
  2761. this.w = Math.max(this.w, v.w);
  2762. return this;
  2763. },
  2764. clamp: function (min, max) {
  2765. // assumes min < max, componentwise
  2766. this.x = Math.max(min.x, Math.min(max.x, this.x));
  2767. this.y = Math.max(min.y, Math.min(max.y, this.y));
  2768. this.z = Math.max(min.z, Math.min(max.z, this.z));
  2769. this.w = Math.max(min.w, Math.min(max.w, this.w));
  2770. return this;
  2771. },
  2772. clampScalar: function (minVal, maxVal) {
  2773. this.x = Math.max(minVal, Math.min(maxVal, this.x));
  2774. this.y = Math.max(minVal, Math.min(maxVal, this.y));
  2775. this.z = Math.max(minVal, Math.min(maxVal, this.z));
  2776. this.w = Math.max(minVal, Math.min(maxVal, this.w));
  2777. return this;
  2778. },
  2779. clampLength: function (min, max) {
  2780. var length = this.length();
  2781. return this.divideScalar(length || 1).multiplyScalar(Math.max(min, Math.min(max, length)));
  2782. },
  2783. floor: function () {
  2784. this.x = Math.floor(this.x);
  2785. this.y = Math.floor(this.y);
  2786. this.z = Math.floor(this.z);
  2787. this.w = Math.floor(this.w);
  2788. return this;
  2789. },
  2790. ceil: function () {
  2791. this.x = Math.ceil(this.x);
  2792. this.y = Math.ceil(this.y);
  2793. this.z = Math.ceil(this.z);
  2794. this.w = Math.ceil(this.w);
  2795. return this;
  2796. },
  2797. round: function () {
  2798. this.x = Math.round(this.x);
  2799. this.y = Math.round(this.y);
  2800. this.z = Math.round(this.z);
  2801. this.w = Math.round(this.w);
  2802. return this;
  2803. },
  2804. roundToZero: function () {
  2805. this.x = this.x < 0 ? Math.ceil(this.x) : Math.floor(this.x);
  2806. this.y = this.y < 0 ? Math.ceil(this.y) : Math.floor(this.y);
  2807. this.z = this.z < 0 ? Math.ceil(this.z) : Math.floor(this.z);
  2808. this.w = this.w < 0 ? Math.ceil(this.w) : Math.floor(this.w);
  2809. return this;
  2810. },
  2811. negate: function () {
  2812. this.x = -this.x;
  2813. this.y = -this.y;
  2814. this.z = -this.z;
  2815. this.w = -this.w;
  2816. return this;
  2817. },
  2818. dot: function (v) {
  2819. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  2820. },
  2821. lengthSq: function () {
  2822. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  2823. },
  2824. length: function () {
  2825. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  2826. },
  2827. manhattanLength: function () {
  2828. return Math.abs(this.x) + Math.abs(this.y) + Math.abs(this.z) + Math.abs(this.w);
  2829. },
  2830. normalize: function () {
  2831. return this.divideScalar(this.length() || 1);
  2832. },
  2833. setLength: function (length) {
  2834. return this.normalize().multiplyScalar(length);
  2835. },
  2836. lerp: function (v, alpha) {
  2837. this.x += (v.x - this.x) * alpha;
  2838. this.y += (v.y - this.y) * alpha;
  2839. this.z += (v.z - this.z) * alpha;
  2840. this.w += (v.w - this.w) * alpha;
  2841. return this;
  2842. },
  2843. lerpVectors: function (v1, v2, alpha) {
  2844. return this.subVectors(v2, v1).multiplyScalar(alpha).add(v1);
  2845. },
  2846. equals: function (v) {
  2847. return v.x === this.x && v.y === this.y && v.z === this.z && v.w === this.w;
  2848. },
  2849. fromArray: function (array, offset) {
  2850. if (offset === undefined) offset = 0;
  2851. this.x = array[offset];
  2852. this.y = array[offset + 1];
  2853. this.z = array[offset + 2];
  2854. this.w = array[offset + 3];
  2855. return this;
  2856. },
  2857. toArray: function (array, offset) {
  2858. if (array === undefined) array = [];
  2859. if (offset === undefined) offset = 0;
  2860. array[offset] = this.x;
  2861. array[offset + 1] = this.y;
  2862. array[offset + 2] = this.z;
  2863. array[offset + 3] = this.w;
  2864. return array;
  2865. },
  2866. fromBufferAttribute: function (attribute, index, offset) {
  2867. if (offset !== undefined) {
  2868. console.warn('THREE.Vector4: offset has been removed from .fromBufferAttribute().');
  2869. }
  2870. this.x = attribute.getX(index);
  2871. this.y = attribute.getY(index);
  2872. this.z = attribute.getZ(index);
  2873. this.w = attribute.getW(index);
  2874. return this;
  2875. }
  2876. });
  2877. /**
  2878. * @author szimek / https://github.com/szimek/
  2879. * @author alteredq / http://alteredqualia.com/
  2880. * @author Marius Kintel / https://github.com/kintel
  2881. */
  2882. /*
  2883. In options, we can specify:
  2884. * Texture parameters for an auto-generated target texture
  2885. * depthBuffer/stencilBuffer: Booleans to indicate if we should generate these buffers
  2886. */
  2887. function WebGLRenderTarget(width, height, options) {
  2888. this.width = width;
  2889. this.height = height;
  2890. this.scissor = new Vector4(0, 0, width, height);
  2891. this.scissorTest = false;
  2892. this.viewport = new Vector4(0, 0, width, height);
  2893. options = options || {};
  2894. this.texture = new Texture(undefined, undefined, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding);
  2895. this.texture.image = {};
  2896. this.texture.image.width = width;
  2897. this.texture.image.height = height;
  2898. this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false;
  2899. this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter;
  2900. this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
  2901. this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : true;
  2902. this.depthTexture = options.depthTexture !== undefined ? options.depthTexture : null;
  2903. }
  2904. WebGLRenderTarget.prototype = Object.assign(Object.create(EventDispatcher.prototype), {
  2905. constructor: WebGLRenderTarget,
  2906. isWebGLRenderTarget: true,
  2907. setSize: function (width, height) {
  2908. if (this.width !== width || this.height !== height) {
  2909. this.width = width;
  2910. this.height = height;
  2911. this.texture.image.width = width;
  2912. this.texture.image.height = height;
  2913. this.dispose();
  2914. }
  2915. this.viewport.set(0, 0, width, height);
  2916. this.scissor.set(0, 0, width, height);
  2917. },
  2918. clone: function () {
  2919. return new this.constructor().copy(this);
  2920. },
  2921. copy: function (source) {
  2922. this.width = source.width;
  2923. this.height = source.height;
  2924. this.viewport.copy(source.viewport);
  2925. this.texture = source.texture.clone();
  2926. this.depthBuffer = source.depthBuffer;
  2927. this.stencilBuffer = source.stencilBuffer;
  2928. this.depthTexture = source.depthTexture;
  2929. return this;
  2930. },
  2931. dispose: function () {
  2932. this.dispatchEvent({
  2933. type: 'dispose'
  2934. });
  2935. }
  2936. });
  2937. /**
  2938. * @author Mugen87 / https://github.com/Mugen87
  2939. * @author Matt DesLauriers / @mattdesl
  2940. */
  2941. function WebGLMultisampleRenderTarget(width, height, options) {
  2942. WebGLRenderTarget.call(this, width, height, options);
  2943. this.samples = 4;
  2944. }
  2945. WebGLMultisampleRenderTarget.prototype = Object.assign(Object.create(WebGLRenderTarget.prototype), {
  2946. constructor: WebGLMultisampleRenderTarget,
  2947. isWebGLMultisampleRenderTarget: true,
  2948. copy: function (source) {
  2949. WebGLRenderTarget.prototype.copy.call(this, source);
  2950. this.samples = source.samples;
  2951. return this;
  2952. }
  2953. });
  2954. var _v1 = new Vector3();
  2955. var _m1 = new Matrix4();
  2956. var _zero = new Vector3(0, 0, 0);
  2957. var _one = new Vector3(1, 1, 1);
  2958. var _x = new Vector3();
  2959. var _y = new Vector3();
  2960. var _z = new Vector3();
  2961. /**
  2962. * @author mrdoob / http://mrdoob.com/
  2963. * @author supereggbert / http://www.paulbrunt.co.uk/
  2964. * @author philogb / http://blog.thejit.org/
  2965. * @author jordi_ros / http://plattsoft.com
  2966. * @author D1plo1d / http://github.com/D1plo1d
  2967. * @author alteredq / http://alteredqualia.com/
  2968. * @author mikael emtinger / http://gomo.se/
  2969. * @author timknip / http://www.floorplanner.com/
  2970. * @author bhouston / http://clara.io
  2971. * @author WestLangley / http://github.com/WestLangley
  2972. */
  2973. function Matrix4() {
  2974. this.elements = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];
  2975. if (arguments.length > 0) {
  2976. console.error('THREE.Matrix4: the constructor no longer reads arguments. use .set() instead.');
  2977. }
  2978. }
  2979. Object.assign(Matrix4.prototype, {
  2980. isMatrix4: true,
  2981. set: function (n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44) {
  2982. var te = this.elements;
  2983. te[0] = n11;
  2984. te[4] = n12;
  2985. te[8] = n13;
  2986. te[12] = n14;
  2987. te[1] = n21;
  2988. te[5] = n22;
  2989. te[9] = n23;
  2990. te[13] = n24;
  2991. te[2] = n31;
  2992. te[6] = n32;
  2993. te[10] = n33;
  2994. te[14] = n34;
  2995. te[3] = n41;
  2996. te[7] = n42;
  2997. te[11] = n43;
  2998. te[15] = n44;
  2999. return this;
  3000. },
  3001. identity: function () {
  3002. this.set(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1);
  3003. return this;
  3004. },
  3005. clone: function () {
  3006. return new Matrix4().fromArray(this.elements);
  3007. },
  3008. copy: function (m) {
  3009. var te = this.elements;
  3010. var me = m.elements;
  3011. te[0] = me[0];
  3012. te[1] = me[1];
  3013. te[2] = me[2];
  3014. te[3] = me[3];
  3015. te[4] = me[4];
  3016. te[5] = me[5];
  3017. te[6] = me[6];
  3018. te[7] = me[7];
  3019. te[8] = me[8];
  3020. te[9] = me[9];
  3021. te[10] = me[10];
  3022. te[11] = me[11];
  3023. te[12] = me[12];
  3024. te[13] = me[13];
  3025. te[14] = me[14];
  3026. te[15] = me[15];
  3027. return this;
  3028. },
  3029. copyPosition: function (m) {
  3030. var te = this.elements,
  3031. me = m.elements;
  3032. te[12] = me[12];
  3033. te[13] = me[13];
  3034. te[14] = me[14];
  3035. return this;
  3036. },
  3037. extractBasis: function (xAxis, yAxis, zAxis) {
  3038. xAxis.setFromMatrixColumn(this, 0);
  3039. yAxis.setFromMatrixColumn(this, 1);
  3040. zAxis.setFromMatrixColumn(this, 2);
  3041. return this;
  3042. },
  3043. makeBasis: function (xAxis, yAxis, zAxis) {
  3044. 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);
  3045. return this;
  3046. },
  3047. extractRotation: function (m) {
  3048. // this method does not support reflection matrices
  3049. var te = this.elements;
  3050. var me = m.elements;
  3051. var scaleX = 1 / _v1.setFromMatrixColumn(m, 0).length();
  3052. var scaleY = 1 / _v1.setFromMatrixColumn(m, 1).length();
  3053. var scaleZ = 1 / _v1.setFromMatrixColumn(m, 2).length();
  3054. te[0] = me[0] * scaleX;
  3055. te[1] = me[1] * scaleX;
  3056. te[2] = me[2] * scaleX;
  3057. te[3] = 0;
  3058. te[4] = me[4] * scaleY;
  3059. te[5] = me[5] * scaleY;
  3060. te[6] = me[6] * scaleY;
  3061. te[7] = 0;
  3062. te[8] = me[8] * scaleZ;
  3063. te[9] = me[9] * scaleZ;
  3064. te[10] = me[10] * scaleZ;
  3065. te[11] = 0;
  3066. te[12] = 0;
  3067. te[13] = 0;
  3068. te[14] = 0;
  3069. te[15] = 1;
  3070. return this;
  3071. },
  3072. makeRotationFromEuler: function (euler) {
  3073. if (!(euler && euler.isEuler)) {
  3074. console.error('THREE.Matrix4: .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order.');
  3075. }
  3076. var te = this.elements;
  3077. var x = euler.x,
  3078. y = euler.y,
  3079. z = euler.z;
  3080. var a = Math.cos(x),
  3081. b = Math.sin(x);
  3082. var c = Math.cos(y),
  3083. d = Math.sin(y);
  3084. var e = Math.cos(z),
  3085. f = Math.sin(z);
  3086. if (euler.order === 'XYZ') {
  3087. var ae = a * e,
  3088. af = a * f,
  3089. be = b * e,
  3090. bf = b * f;
  3091. te[0] = c * e;
  3092. te[4] = -c * f;
  3093. te[8] = d;
  3094. te[1] = af + be * d;
  3095. te[5] = ae - bf * d;
  3096. te[9] = -b * c;
  3097. te[2] = bf - ae * d;
  3098. te[6] = be + af * d;
  3099. te[10] = a * c;
  3100. } else if (euler.order === 'YXZ') {
  3101. var ce = c * e,
  3102. cf = c * f,
  3103. de = d * e,
  3104. df = d * f;
  3105. te[0] = ce + df * b;
  3106. te[4] = de * b - cf;
  3107. te[8] = a * d;
  3108. te[1] = a * f;
  3109. te[5] = a * e;
  3110. te[9] = -b;
  3111. te[2] = cf * b - de;
  3112. te[6] = df + ce * b;
  3113. te[10] = a * c;
  3114. } else if (euler.order === 'ZXY') {
  3115. var ce = c * e,
  3116. cf = c * f,
  3117. de = d * e,
  3118. df = d * f;
  3119. te[0] = ce - df * b;
  3120. te[4] = -a * f;
  3121. te[8] = de + cf * b;
  3122. te[1] = cf + de * b;
  3123. te[5] = a * e;
  3124. te[9] = df - ce * b;
  3125. te[2] = -a * d;
  3126. te[6] = b;
  3127. te[10] = a * c;
  3128. } else if (euler.order === 'ZYX') {
  3129. var ae = a * e,
  3130. af = a * f,
  3131. be = b * e,
  3132. bf = b * f;
  3133. te[0] = c * e;
  3134. te[4] = be * d - af;
  3135. te[8] = ae * d + bf;
  3136. te[1] = c * f;
  3137. te[5] = bf * d + ae;
  3138. te[9] = af * d - be;
  3139. te[2] = -d;
  3140. te[6] = b * c;
  3141. te[10] = a * c;
  3142. } else if (euler.order === 'YZX') {
  3143. var ac = a * c,
  3144. ad = a * d,
  3145. bc = b * c,
  3146. bd = b * d;
  3147. te[0] = c * e;
  3148. te[4] = bd - ac * f;
  3149. te[8] = bc * f + ad;
  3150. te[1] = f;
  3151. te[5] = a * e;
  3152. te[9] = -b * e;
  3153. te[2] = -d * e;
  3154. te[6] = ad * f + bc;
  3155. te[10] = ac - bd * f;
  3156. } else if (euler.order === 'XZY') {
  3157. var ac = a * c,
  3158. ad = a * d,
  3159. bc = b * c,
  3160. bd = b * d;
  3161. te[0] = c * e;
  3162. te[4] = -f;
  3163. te[8] = d * e;
  3164. te[1] = ac * f + bd;
  3165. te[5] = a * e;
  3166. te[9] = ad * f - bc;
  3167. te[2] = bc * f - ad;
  3168. te[6] = b * e;
  3169. te[10] = bd * f + ac;
  3170. } // bottom row
  3171. te[3] = 0;
  3172. te[7] = 0;
  3173. te[11] = 0; // last column
  3174. te[12] = 0;
  3175. te[13] = 0;
  3176. te[14] = 0;
  3177. te[15] = 1;
  3178. return this;
  3179. },
  3180. makeRotationFromQuaternion: function (q) {
  3181. return this.compose(_zero, q, _one);
  3182. },
  3183. lookAt: function (eye, target, up) {
  3184. var te = this.elements;
  3185. _z.subVectors(eye, target);
  3186. if (_z.lengthSq() === 0) {
  3187. // eye and target are in the same position
  3188. _z.z = 1;
  3189. }
  3190. _z.normalize();
  3191. _x.crossVectors(up, _z);
  3192. if (_x.lengthSq() === 0) {
  3193. // up and z are parallel
  3194. if (Math.abs(up.z) === 1) {
  3195. _z.x += 0.0001;
  3196. } else {
  3197. _z.z += 0.0001;
  3198. }
  3199. _z.normalize();
  3200. _x.crossVectors(up, _z);
  3201. }
  3202. _x.normalize();
  3203. _y.crossVectors(_z, _x);
  3204. te[0] = _x.x;
  3205. te[4] = _y.x;
  3206. te[8] = _z.x;
  3207. te[1] = _x.y;
  3208. te[5] = _y.y;
  3209. te[9] = _z.y;
  3210. te[2] = _x.z;
  3211. te[6] = _y.z;
  3212. te[10] = _z.z;
  3213. return this;
  3214. },
  3215. multiply: function (m, n) {
  3216. if (n !== undefined) {
  3217. console.warn('THREE.Matrix4: .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead.');
  3218. return this.multiplyMatrices(m, n);
  3219. }
  3220. return this.multiplyMatrices(this, m);
  3221. },
  3222. premultiply: function (m) {
  3223. return this.multiplyMatrices(m, this);
  3224. },
  3225. multiplyMatrices: function (a, b) {
  3226. var ae = a.elements;
  3227. var be = b.elements;
  3228. var te = this.elements;
  3229. var a11 = ae[0],
  3230. a12 = ae[4],
  3231. a13 = ae[8],
  3232. a14 = ae[12];
  3233. var a21 = ae[1],
  3234. a22 = ae[5],
  3235. a23 = ae[9],
  3236. a24 = ae[13];
  3237. var a31 = ae[2],
  3238. a32 = ae[6],
  3239. a33 = ae[10],
  3240. a34 = ae[14];
  3241. var a41 = ae[3],
  3242. a42 = ae[7],
  3243. a43 = ae[11],
  3244. a44 = ae[15];
  3245. var b11 = be[0],
  3246. b12 = be[4],
  3247. b13 = be[8],
  3248. b14 = be[12];
  3249. var b21 = be[1],
  3250. b22 = be[5],
  3251. b23 = be[9],
  3252. b24 = be[13];
  3253. var b31 = be[2],
  3254. b32 = be[6],
  3255. b33 = be[10],
  3256. b34 = be[14];
  3257. var b41 = be[3],
  3258. b42 = be[7],
  3259. b43 = be[11],
  3260. b44 = be[15];
  3261. te[0] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  3262. te[4] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  3263. te[8] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  3264. te[12] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  3265. te[1] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  3266. te[5] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  3267. te[9] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  3268. te[13] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  3269. te[2] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  3270. te[6] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  3271. te[10] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  3272. te[14] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  3273. te[3] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  3274. te[7] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  3275. te[11] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  3276. te[15] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  3277. return this;
  3278. },
  3279. multiplyScalar: function (s) {
  3280. var te = this.elements;
  3281. te[0] *= s;
  3282. te[4] *= s;
  3283. te[8] *= s;
  3284. te[12] *= s;
  3285. te[1] *= s;
  3286. te[5] *= s;
  3287. te[9] *= s;
  3288. te[13] *= s;
  3289. te[2] *= s;
  3290. te[6] *= s;
  3291. te[10] *= s;
  3292. te[14] *= s;
  3293. te[3] *= s;
  3294. te[7] *= s;
  3295. te[11] *= s;
  3296. te[15] *= s;
  3297. return this;
  3298. },
  3299. applyToBufferAttribute: function (attribute) {
  3300. for (var i = 0, l = attribute.count; i < l; i++) {
  3301. _v1.x = attribute.getX(i);
  3302. _v1.y = attribute.getY(i);
  3303. _v1.z = attribute.getZ(i);
  3304. _v1.applyMatrix4(this);
  3305. attribute.setXYZ(i, _v1.x, _v1.y, _v1.z);
  3306. }
  3307. return attribute;
  3308. },
  3309. determinant: function () {
  3310. var te = this.elements;
  3311. var n11 = te[0],
  3312. n12 = te[4],
  3313. n13 = te[8],
  3314. n14 = te[12];
  3315. var n21 = te[1],
  3316. n22 = te[5],
  3317. n23 = te[9],
  3318. n24 = te[13];
  3319. var n31 = te[2],
  3320. n32 = te[6],
  3321. n33 = te[10],
  3322. n34 = te[14];
  3323. var n41 = te[3],
  3324. n42 = te[7],
  3325. n43 = te[11],
  3326. n44 = te[15]; //TODO: make this more efficient
  3327. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  3328. 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);
  3329. },
  3330. transpose: function () {
  3331. var te = this.elements;
  3332. var tmp;
  3333. tmp = te[1];
  3334. te[1] = te[4];
  3335. te[4] = tmp;
  3336. tmp = te[2];
  3337. te[2] = te[8];
  3338. te[8] = tmp;
  3339. tmp = te[6];
  3340. te[6] = te[9];
  3341. te[9] = tmp;
  3342. tmp = te[3];
  3343. te[3] = te[12];
  3344. te[12] = tmp;
  3345. tmp = te[7];
  3346. te[7] = te[13];
  3347. te[13] = tmp;
  3348. tmp = te[11];
  3349. te[11] = te[14];
  3350. te[14] = tmp;
  3351. return this;
  3352. },
  3353. setPosition: function (x, y, z) {
  3354. var te = this.elements;
  3355. if (x.isVector3) {
  3356. te[12] = x.x;
  3357. te[13] = x.y;
  3358. te[14] = x.z;
  3359. } else {
  3360. te[12] = x;
  3361. te[13] = y;
  3362. te[14] = z;
  3363. }
  3364. return this;
  3365. },
  3366. getInverse: function (m, throwOnDegenerate) {
  3367. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  3368. var te = this.elements,
  3369. me = m.elements,
  3370. n11 = me[0],
  3371. n21 = me[1],
  3372. n31 = me[2],
  3373. n41 = me[3],
  3374. n12 = me[4],
  3375. n22 = me[5],
  3376. n32 = me[6],
  3377. n42 = me[7],
  3378. n13 = me[8],
  3379. n23 = me[9],
  3380. n33 = me[10],
  3381. n43 = me[11],
  3382. n14 = me[12],
  3383. n24 = me[13],
  3384. n34 = me[14],
  3385. n44 = me[15],
  3386. t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44,
  3387. t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44,
  3388. t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44,
  3389. t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34;
  3390. var det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14;
  3391. if (det === 0) {
  3392. var msg = "THREE.Matrix4: .getInverse() can't invert matrix, determinant is 0";
  3393. if (throwOnDegenerate === true) {
  3394. throw new Error(msg);
  3395. } else {
  3396. console.warn(msg);
  3397. }
  3398. return this.identity();
  3399. }
  3400. var detInv = 1 / det;
  3401. te[0] = t11 * detInv;
  3402. te[1] = (n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44) * detInv;
  3403. te[2] = (n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44) * detInv;
  3404. te[3] = (n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43) * detInv;
  3405. te[4] = t12 * detInv;
  3406. te[5] = (n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44) * detInv;
  3407. te[6] = (n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44) * detInv;
  3408. te[7] = (n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43) * detInv;
  3409. te[8] = t13 * detInv;
  3410. te[9] = (n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44) * detInv;
  3411. te[10] = (n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44) * detInv;
  3412. te[11] = (n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43) * detInv;
  3413. te[12] = t14 * detInv;
  3414. te[13] = (n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34) * detInv;
  3415. te[14] = (n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34) * detInv;
  3416. te[15] = (n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33) * detInv;
  3417. return this;
  3418. },
  3419. scale: function (v) {
  3420. var te = this.elements;
  3421. var x = v.x,
  3422. y = v.y,
  3423. z = v.z;
  3424. te[0] *= x;
  3425. te[4] *= y;
  3426. te[8] *= z;
  3427. te[1] *= x;
  3428. te[5] *= y;
  3429. te[9] *= z;
  3430. te[2] *= x;
  3431. te[6] *= y;
  3432. te[10] *= z;
  3433. te[3] *= x;
  3434. te[7] *= y;
  3435. te[11] *= z;
  3436. return this;
  3437. },
  3438. getMaxScaleOnAxis: function () {
  3439. var te = this.elements;
  3440. var scaleXSq = te[0] * te[0] + te[1] * te[1] + te[2] * te[2];
  3441. var scaleYSq = te[4] * te[4] + te[5] * te[5] + te[6] * te[6];
  3442. var scaleZSq = te[8] * te[8] + te[9] * te[9] + te[10] * te[10];
  3443. return Math.sqrt(Math.max(scaleXSq, scaleYSq, scaleZSq));
  3444. },
  3445. makeTranslation: function (x, y, z) {
  3446. this.set(1, 0, 0, x, 0, 1, 0, y, 0, 0, 1, z, 0, 0, 0, 1);
  3447. return this;
  3448. },
  3449. makeRotationX: function (theta) {
  3450. var c = Math.cos(theta),
  3451. s = Math.sin(theta);
  3452. this.set(1, 0, 0, 0, 0, c, -s, 0, 0, s, c, 0, 0, 0, 0, 1);
  3453. return this;
  3454. },
  3455. makeRotationY: function (theta) {
  3456. var c = Math.cos(theta),
  3457. s = Math.sin(theta);
  3458. this.set(c, 0, s, 0, 0, 1, 0, 0, -s, 0, c, 0, 0, 0, 0, 1);
  3459. return this;
  3460. },
  3461. makeRotationZ: function (theta) {
  3462. var c = Math.cos(theta),
  3463. s = Math.sin(theta);
  3464. this.set(c, -s, 0, 0, s, c, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1);
  3465. return this;
  3466. },
  3467. makeRotationAxis: function (axis, angle) {
  3468. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  3469. var c = Math.cos(angle);
  3470. var s = Math.sin(angle);
  3471. var t = 1 - c;
  3472. var x = axis.x,
  3473. y = axis.y,
  3474. z = axis.z;
  3475. var tx = t * x,
  3476. ty = t * y;
  3477. 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);
  3478. return this;
  3479. },
  3480. makeScale: function (x, y, z) {
  3481. this.set(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1);
  3482. return this;
  3483. },
  3484. makeShear: function (x, y, z) {
  3485. this.set(1, y, z, 0, x, 1, z, 0, x, y, 1, 0, 0, 0, 0, 1);
  3486. return this;
  3487. },
  3488. compose: function (position, quaternion, scale) {
  3489. var te = this.elements;
  3490. var x = quaternion._x,
  3491. y = quaternion._y,
  3492. z = quaternion._z,
  3493. w = quaternion._w;
  3494. var x2 = x + x,
  3495. y2 = y + y,
  3496. z2 = z + z;
  3497. var xx = x * x2,
  3498. xy = x * y2,
  3499. xz = x * z2;
  3500. var yy = y * y2,
  3501. yz = y * z2,
  3502. zz = z * z2;
  3503. var wx = w * x2,
  3504. wy = w * y2,
  3505. wz = w * z2;
  3506. var sx = scale.x,
  3507. sy = scale.y,
  3508. sz = scale.z;
  3509. te[0] = (1 - (yy + zz)) * sx;
  3510. te[1] = (xy + wz) * sx;
  3511. te[2] = (xz - wy) * sx;
  3512. te[3] = 0;
  3513. te[4] = (xy - wz) * sy;
  3514. te[5] = (1 - (xx + zz)) * sy;
  3515. te[6] = (yz + wx) * sy;
  3516. te[7] = 0;
  3517. te[8] = (xz + wy) * sz;
  3518. te[9] = (yz - wx) * sz;
  3519. te[10] = (1 - (xx + yy)) * sz;
  3520. te[11] = 0;
  3521. te[12] = position.x;
  3522. te[13] = position.y;
  3523. te[14] = position.z;
  3524. te[15] = 1;
  3525. return this;
  3526. },
  3527. decompose: function (position, quaternion, scale) {
  3528. var te = this.elements;
  3529. var sx = _v1.set(te[0], te[1], te[2]).length();
  3530. var sy = _v1.set(te[4], te[5], te[6]).length();
  3531. var sz = _v1.set(te[8], te[9], te[10]).length(); // if determine is negative, we need to invert one scale
  3532. var det = this.determinant();
  3533. if (det < 0) sx = -sx;
  3534. position.x = te[12];
  3535. position.y = te[13];
  3536. position.z = te[14]; // scale the rotation part
  3537. _m1.copy(this);
  3538. var invSX = 1 / sx;
  3539. var invSY = 1 / sy;
  3540. var invSZ = 1 / sz;
  3541. _m1.elements[0] *= invSX;
  3542. _m1.elements[1] *= invSX;
  3543. _m1.elements[2] *= invSX;
  3544. _m1.elements[4] *= invSY;
  3545. _m1.elements[5] *= invSY;
  3546. _m1.elements[6] *= invSY;
  3547. _m1.elements[8] *= invSZ;
  3548. _m1.elements[9] *= invSZ;
  3549. _m1.elements[10] *= invSZ;
  3550. quaternion.setFromRotationMatrix(_m1);
  3551. scale.x = sx;
  3552. scale.y = sy;
  3553. scale.z = sz;
  3554. return this;
  3555. },
  3556. makePerspective: function (left, right, top, bottom, near, far) {
  3557. if (far === undefined) {
  3558. console.warn('THREE.Matrix4: .makePerspective() has been redefined and has a new signature. Please check the docs.');
  3559. }
  3560. var te = this.elements;
  3561. var x = 2 * near / (right - left);
  3562. var y = 2 * near / (top - bottom);
  3563. var a = (right + left) / (right - left);
  3564. var b = (top + bottom) / (top - bottom);
  3565. var c = -(far + near) / (far - near);
  3566. var d = -2 * far * near / (far - near);
  3567. te[0] = x;
  3568. te[4] = 0;
  3569. te[8] = a;
  3570. te[12] = 0;
  3571. te[1] = 0;
  3572. te[5] = y;
  3573. te[9] = b;
  3574. te[13] = 0;
  3575. te[2] = 0;
  3576. te[6] = 0;
  3577. te[10] = c;
  3578. te[14] = d;
  3579. te[3] = 0;
  3580. te[7] = 0;
  3581. te[11] = -1;
  3582. te[15] = 0;
  3583. return this;
  3584. },
  3585. makeOrthographic: function (left, right, top, bottom, near, far) {
  3586. var te = this.elements;
  3587. var w = 1.0 / (right - left);
  3588. var h = 1.0 / (top - bottom);
  3589. var p = 1.0 / (far - near);
  3590. var x = (right + left) * w;
  3591. var y = (top + bottom) * h;
  3592. var z = (far + near) * p;
  3593. te[0] = 2 * w;
  3594. te[4] = 0;
  3595. te[8] = 0;
  3596. te[12] = -x;
  3597. te[1] = 0;
  3598. te[5] = 2 * h;
  3599. te[9] = 0;
  3600. te[13] = -y;
  3601. te[2] = 0;
  3602. te[6] = 0;
  3603. te[10] = -2 * p;
  3604. te[14] = -z;
  3605. te[3] = 0;
  3606. te[7] = 0;
  3607. te[11] = 0;
  3608. te[15] = 1;
  3609. return this;
  3610. },
  3611. equals: function (matrix) {
  3612. var te = this.elements;
  3613. var me = matrix.elements;
  3614. for (var i = 0; i < 16; i++) {
  3615. if (te[i] !== me[i]) return false;
  3616. }
  3617. return true;
  3618. },
  3619. fromArray: function (array, offset) {
  3620. if (offset === undefined) offset = 0;
  3621. for (var i = 0; i < 16; i++) {
  3622. this.elements[i] = array[i + offset];
  3623. }
  3624. return this;
  3625. },
  3626. toArray: function (array, offset) {
  3627. if (array === undefined) array = [];
  3628. if (offset === undefined) offset = 0;
  3629. var te = this.elements;
  3630. array[offset] = te[0];
  3631. array[offset + 1] = te[1];
  3632. array[offset + 2] = te[2];
  3633. array[offset + 3] = te[3];
  3634. array[offset + 4] = te[4];
  3635. array[offset + 5] = te[5];
  3636. array[offset + 6] = te[6];
  3637. array[offset + 7] = te[7];
  3638. array[offset + 8] = te[8];
  3639. array[offset + 9] = te[9];
  3640. array[offset + 10] = te[10];
  3641. array[offset + 11] = te[11];
  3642. array[offset + 12] = te[12];
  3643. array[offset + 13] = te[13];
  3644. array[offset + 14] = te[14];
  3645. array[offset + 15] = te[15];
  3646. return array;
  3647. }
  3648. });
  3649. /**
  3650. * @author mrdoob / http://mrdoob.com/
  3651. * @author WestLangley / http://github.com/WestLangley
  3652. * @author bhouston / http://clara.io
  3653. */
  3654. var _matrix = new Matrix4();
  3655. var _quaternion$1 = new Quaternion();
  3656. function Euler(x, y, z, order) {
  3657. this._x = x || 0;
  3658. this._y = y || 0;
  3659. this._z = z || 0;
  3660. this._order = order || Euler.DefaultOrder;
  3661. }
  3662. Euler.RotationOrders = ['XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX'];
  3663. Euler.DefaultOrder = 'XYZ';
  3664. Object.defineProperties(Euler.prototype, {
  3665. x: {
  3666. get: function () {
  3667. return this._x;
  3668. },
  3669. set: function (value) {
  3670. this._x = value;
  3671. this._onChangeCallback();
  3672. }
  3673. },
  3674. y: {
  3675. get: function () {
  3676. return this._y;
  3677. },
  3678. set: function (value) {
  3679. this._y = value;
  3680. this._onChangeCallback();
  3681. }
  3682. },
  3683. z: {
  3684. get: function () {
  3685. return this._z;
  3686. },
  3687. set: function (value) {
  3688. this._z = value;
  3689. this._onChangeCallback();
  3690. }
  3691. },
  3692. order: {
  3693. get: function () {
  3694. return this._order;
  3695. },
  3696. set: function (value) {
  3697. this._order = value;
  3698. this._onChangeCallback();
  3699. }
  3700. }
  3701. });
  3702. Object.assign(Euler.prototype, {
  3703. isEuler: true,
  3704. set: function (x, y, z, order) {
  3705. this._x = x;
  3706. this._y = y;
  3707. this._z = z;
  3708. this._order = order || this._order;
  3709. this._onChangeCallback();
  3710. return this;
  3711. },
  3712. clone: function () {
  3713. return new this.constructor(this._x, this._y, this._z, this._order);
  3714. },
  3715. copy: function (euler) {
  3716. this._x = euler._x;
  3717. this._y = euler._y;
  3718. this._z = euler._z;
  3719. this._order = euler._order;
  3720. this._onChangeCallback();
  3721. return this;
  3722. },
  3723. setFromRotationMatrix: function (m, order, update) {
  3724. var clamp = _Math.clamp; // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  3725. var te = m.elements;
  3726. var m11 = te[0],
  3727. m12 = te[4],
  3728. m13 = te[8];
  3729. var m21 = te[1],
  3730. m22 = te[5],
  3731. m23 = te[9];
  3732. var m31 = te[2],
  3733. m32 = te[6],
  3734. m33 = te[10];
  3735. order = order || this._order;
  3736. if (order === 'XYZ') {
  3737. this._y = Math.asin(clamp(m13, -1, 1));
  3738. if (Math.abs(m13) < 0.9999999) {
  3739. this._x = Math.atan2(-m23, m33);
  3740. this._z = Math.atan2(-m12, m11);
  3741. } else {
  3742. this._x = Math.atan2(m32, m22);
  3743. this._z = 0;
  3744. }
  3745. } else if (order === 'YXZ') {
  3746. this._x = Math.asin(-clamp(m23, -1, 1));
  3747. if (Math.abs(m23) < 0.9999999) {
  3748. this._y = Math.atan2(m13, m33);
  3749. this._z = Math.atan2(m21, m22);
  3750. } else {
  3751. this._y = Math.atan2(-m31, m11);
  3752. this._z = 0;
  3753. }
  3754. } else if (order === 'ZXY') {
  3755. this._x = Math.asin(clamp(m32, -1, 1));
  3756. if (Math.abs(m32) < 0.9999999) {
  3757. this._y = Math.atan2(-m31, m33);
  3758. this._z = Math.atan2(-m12, m22);
  3759. } else {
  3760. this._y = 0;
  3761. this._z = Math.atan2(m21, m11);
  3762. }
  3763. } else if (order === 'ZYX') {
  3764. this._y = Math.asin(-clamp(m31, -1, 1));
  3765. if (Math.abs(m31) < 0.9999999) {
  3766. this._x = Math.atan2(m32, m33);
  3767. this._z = Math.atan2(m21, m11);
  3768. } else {
  3769. this._x = 0;
  3770. this._z = Math.atan2(-m12, m22);
  3771. }
  3772. } else if (order === 'YZX') {
  3773. this._z = Math.asin(clamp(m21, -1, 1));
  3774. if (Math.abs(m21) < 0.9999999) {
  3775. this._x = Math.atan2(-m23, m22);
  3776. this._y = Math.atan2(-m31, m11);
  3777. } else {
  3778. this._x = 0;
  3779. this._y = Math.atan2(m13, m33);
  3780. }
  3781. } else if (order === 'XZY') {
  3782. this._z = Math.asin(-clamp(m12, -1, 1));
  3783. if (Math.abs(m12) < 0.9999999) {
  3784. this._x = Math.atan2(m32, m22);
  3785. this._y = Math.atan2(m13, m11);
  3786. } else {
  3787. this._x = Math.atan2(-m23, m33);
  3788. this._y = 0;
  3789. }
  3790. } else {
  3791. console.warn('THREE.Euler: .setFromRotationMatrix() given unsupported order: ' + order);
  3792. }
  3793. this._order = order;
  3794. if (update !== false) this._onChangeCallback();
  3795. return this;
  3796. },
  3797. setFromQuaternion: function (q, order, update) {
  3798. _matrix.makeRotationFromQuaternion(q);
  3799. return this.setFromRotationMatrix(_matrix, order, update);
  3800. },
  3801. setFromVector3: function (v, order) {
  3802. return this.set(v.x, v.y, v.z, order || this._order);
  3803. },
  3804. reorder: function (newOrder) {
  3805. // WARNING: this discards revolution information -bhouston
  3806. _quaternion$1.setFromEuler(this);
  3807. return this.setFromQuaternion(_quaternion$1, newOrder);
  3808. },
  3809. equals: function (euler) {
  3810. return euler._x === this._x && euler._y === this._y && euler._z === this._z && euler._order === this._order;
  3811. },
  3812. fromArray: function (array) {
  3813. this._x = array[0];
  3814. this._y = array[1];
  3815. this._z = array[2];
  3816. if (array[3] !== undefined) this._order = array[3];
  3817. this._onChangeCallback();
  3818. return this;
  3819. },
  3820. toArray: function (array, offset) {
  3821. if (array === undefined) array = [];
  3822. if (offset === undefined) offset = 0;
  3823. array[offset] = this._x;
  3824. array[offset + 1] = this._y;
  3825. array[offset + 2] = this._z;
  3826. array[offset + 3] = this._order;
  3827. return array;
  3828. },
  3829. toVector3: function (optionalResult) {
  3830. if (optionalResult) {
  3831. return optionalResult.set(this._x, this._y, this._z);
  3832. } else {
  3833. return new Vector3(this._x, this._y, this._z);
  3834. }
  3835. },
  3836. _onChange: function (callback) {
  3837. this._onChangeCallback = callback;
  3838. return this;
  3839. },
  3840. _onChangeCallback: function () {}
  3841. });
  3842. /**
  3843. * @author mrdoob / http://mrdoob.com/
  3844. */
  3845. function Layers() {
  3846. this.mask = 1 | 0;
  3847. }
  3848. Object.assign(Layers.prototype, {
  3849. set: function (channel) {
  3850. this.mask = 1 << channel | 0;
  3851. },
  3852. enable: function (channel) {
  3853. this.mask |= 1 << channel | 0;
  3854. },
  3855. enableAll: function () {
  3856. this.mask = 0xffffffff | 0;
  3857. },
  3858. toggle: function (channel) {
  3859. this.mask ^= 1 << channel | 0;
  3860. },
  3861. disable: function (channel) {
  3862. this.mask &= ~(1 << channel | 0);
  3863. },
  3864. disableAll: function () {
  3865. this.mask = 0;
  3866. },
  3867. test: function (layers) {
  3868. return (this.mask & layers.mask) !== 0;
  3869. }
  3870. });
  3871. var _object3DId = 0;
  3872. var _v1$1 = new Vector3();
  3873. var _q1 = new Quaternion();
  3874. var _m1$1 = new Matrix4();
  3875. var _target = new Vector3();
  3876. var _position = new Vector3();
  3877. var _scale = new Vector3();
  3878. var _quaternion$2 = new Quaternion();
  3879. var _xAxis = new Vector3(1, 0, 0);
  3880. var _yAxis = new Vector3(0, 1, 0);
  3881. var _zAxis = new Vector3(0, 0, 1);
  3882. var _addedEvent = {
  3883. type: 'added'
  3884. };
  3885. var _removedEvent = {
  3886. type: 'removed'
  3887. };
  3888. /**
  3889. * @author mrdoob / http://mrdoob.com/
  3890. * @author mikael emtinger / http://gomo.se/
  3891. * @author alteredq / http://alteredqualia.com/
  3892. * @author WestLangley / http://github.com/WestLangley
  3893. * @author elephantatwork / www.elephantatwork.ch
  3894. */
  3895. function Object3D() {
  3896. Object.defineProperty(this, 'id', {
  3897. value: _object3DId++
  3898. });
  3899. this.uuid = _Math.generateUUID();
  3900. this.name = '';
  3901. this.type = 'Object3D';
  3902. this.parent = null;
  3903. this.children = [];
  3904. this.up = Object3D.DefaultUp.clone();
  3905. var position = new Vector3();
  3906. var rotation = new Euler();
  3907. var quaternion = new Quaternion();
  3908. var scale = new Vector3(1, 1, 1);
  3909. function onRotationChange() {
  3910. quaternion.setFromEuler(rotation, false);
  3911. }
  3912. function onQuaternionChange() {
  3913. rotation.setFromQuaternion(quaternion, undefined, false);
  3914. }
  3915. rotation._onChange(onRotationChange);
  3916. quaternion._onChange(onQuaternionChange);
  3917. Object.defineProperties(this, {
  3918. position: {
  3919. configurable: true,
  3920. enumerable: true,
  3921. value: position
  3922. },
  3923. rotation: {
  3924. configurable: true,
  3925. enumerable: true,
  3926. value: rotation
  3927. },
  3928. quaternion: {
  3929. configurable: true,
  3930. enumerable: true,
  3931. value: quaternion
  3932. },
  3933. scale: {
  3934. configurable: true,
  3935. enumerable: true,
  3936. value: scale
  3937. },
  3938. modelViewMatrix: {
  3939. value: new Matrix4()
  3940. },
  3941. normalMatrix: {
  3942. value: new Matrix3()
  3943. }
  3944. });
  3945. this.matrix = new Matrix4();
  3946. this.matrixWorld = new Matrix4();
  3947. this.matrixAutoUpdate = Object3D.DefaultMatrixAutoUpdate;
  3948. this.matrixWorldNeedsUpdate = false;
  3949. this.layers = new Layers();
  3950. this.visible = true;
  3951. this.castShadow = false;
  3952. this.receiveShadow = false;
  3953. this.frustumCulled = true;
  3954. this.renderOrder = 0;
  3955. this.userData = {};
  3956. }
  3957. Object3D.DefaultUp = new Vector3(0, 1, 0);
  3958. Object3D.DefaultMatrixAutoUpdate = true;
  3959. Object3D.prototype = Object.assign(Object.create(EventDispatcher.prototype), {
  3960. constructor: Object3D,
  3961. isObject3D: true,
  3962. onBeforeRender: function () {},
  3963. onAfterRender: function () {},
  3964. applyMatrix: function (matrix) {
  3965. if (this.matrixAutoUpdate) this.updateMatrix();
  3966. this.matrix.premultiply(matrix);
  3967. this.matrix.decompose(this.position, this.quaternion, this.scale);
  3968. },
  3969. applyQuaternion: function (q) {
  3970. this.quaternion.premultiply(q);
  3971. return this;
  3972. },
  3973. setRotationFromAxisAngle: function (axis, angle) {
  3974. // assumes axis is normalized
  3975. this.quaternion.setFromAxisAngle(axis, angle);
  3976. },
  3977. setRotationFromEuler: function (euler) {
  3978. this.quaternion.setFromEuler(euler, true);
  3979. },
  3980. setRotationFromMatrix: function (m) {
  3981. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  3982. this.quaternion.setFromRotationMatrix(m);
  3983. },
  3984. setRotationFromQuaternion: function (q) {
  3985. // assumes q is normalized
  3986. this.quaternion.copy(q);
  3987. },
  3988. rotateOnAxis: function (axis, angle) {
  3989. // rotate object on axis in object space
  3990. // axis is assumed to be normalized
  3991. _q1.setFromAxisAngle(axis, angle);
  3992. this.quaternion.multiply(_q1);
  3993. return this;
  3994. },
  3995. rotateOnWorldAxis: function (axis, angle) {
  3996. // rotate object on axis in world space
  3997. // axis is assumed to be normalized
  3998. // method assumes no rotated parent
  3999. _q1.setFromAxisAngle(axis, angle);
  4000. this.quaternion.premultiply(_q1);
  4001. return this;
  4002. },
  4003. rotateX: function (angle) {
  4004. return this.rotateOnAxis(_xAxis, angle);
  4005. },
  4006. rotateY: function (angle) {
  4007. return this.rotateOnAxis(_yAxis, angle);
  4008. },
  4009. rotateZ: function (angle) {
  4010. return this.rotateOnAxis(_zAxis, angle);
  4011. },
  4012. translateOnAxis: function (axis, distance) {
  4013. // translate object by distance along axis in object space
  4014. // axis is assumed to be normalized
  4015. _v1$1.copy(axis).applyQuaternion(this.quaternion);
  4016. this.position.add(_v1$1.multiplyScalar(distance));
  4017. return this;
  4018. },
  4019. translateX: function (distance) {
  4020. return this.translateOnAxis(_xAxis, distance);
  4021. },
  4022. translateY: function (distance) {
  4023. return this.translateOnAxis(_yAxis, distance);
  4024. },
  4025. translateZ: function (distance) {
  4026. return this.translateOnAxis(_zAxis, distance);
  4027. },
  4028. localToWorld: function (vector) {
  4029. return vector.applyMatrix4(this.matrixWorld);
  4030. },
  4031. worldToLocal: function (vector) {
  4032. return vector.applyMatrix4(_m1$1.getInverse(this.matrixWorld));
  4033. },
  4034. lookAt: function (x, y, z) {
  4035. // This method does not support objects having non-uniformly-scaled parent(s)
  4036. if (x.isVector3) {
  4037. _target.copy(x);
  4038. } else {
  4039. _target.set(x, y, z);
  4040. }
  4041. var parent = this.parent;
  4042. this.updateWorldMatrix(true, false);
  4043. _position.setFromMatrixPosition(this.matrixWorld);
  4044. if (this.isCamera || this.isLight) {
  4045. _m1$1.lookAt(_position, _target, this.up);
  4046. } else {
  4047. _m1$1.lookAt(_target, _position, this.up);
  4048. }
  4049. this.quaternion.setFromRotationMatrix(_m1$1);
  4050. if (parent) {
  4051. _m1$1.extractRotation(parent.matrixWorld);
  4052. _q1.setFromRotationMatrix(_m1$1);
  4053. this.quaternion.premultiply(_q1.inverse());
  4054. }
  4055. },
  4056. add: function (object) {
  4057. if (arguments.length > 1) {
  4058. for (var i = 0; i < arguments.length; i++) {
  4059. this.add(arguments[i]);
  4060. }
  4061. return this;
  4062. }
  4063. if (object === this) {
  4064. console.error("THREE.Object3D.add: object can't be added as a child of itself.", object);
  4065. return this;
  4066. }
  4067. if (object && object.isObject3D) {
  4068. if (object.parent !== null) {
  4069. object.parent.remove(object);
  4070. }
  4071. object.parent = this;
  4072. this.children.push(object);
  4073. object.dispatchEvent(_addedEvent);
  4074. } else {
  4075. console.error("THREE.Object3D.add: object not an instance of THREE.Object3D.", object);
  4076. }
  4077. return this;
  4078. },
  4079. remove: function (object) {
  4080. if (arguments.length > 1) {
  4081. for (var i = 0; i < arguments.length; i++) {
  4082. this.remove(arguments[i]);
  4083. }
  4084. return this;
  4085. }
  4086. var index = this.children.indexOf(object);
  4087. if (index !== -1) {
  4088. object.parent = null;
  4089. this.children.splice(index, 1);
  4090. object.dispatchEvent(_removedEvent);
  4091. }
  4092. return this;
  4093. },
  4094. attach: function (object) {
  4095. // adds object as a child of this, while maintaining the object's world transform
  4096. this.updateWorldMatrix(true, false);
  4097. _m1$1.getInverse(this.matrixWorld);
  4098. if (object.parent !== null) {
  4099. object.parent.updateWorldMatrix(true, false);
  4100. _m1$1.multiply(object.parent.matrixWorld);
  4101. }
  4102. object.applyMatrix(_m1$1);
  4103. object.updateWorldMatrix(false, false);
  4104. this.add(object);
  4105. return this;
  4106. },
  4107. getObjectById: function (id) {
  4108. return this.getObjectByProperty('id', id);
  4109. },
  4110. getObjectByName: function (name) {
  4111. return this.getObjectByProperty('name', name);
  4112. },
  4113. getObjectByProperty: function (name, value) {
  4114. if (this[name] === value) return this;
  4115. for (var i = 0, l = this.children.length; i < l; i++) {
  4116. var child = this.children[i];
  4117. var object = child.getObjectByProperty(name, value);
  4118. if (object !== undefined) {
  4119. return object;
  4120. }
  4121. }
  4122. return undefined;
  4123. },
  4124. getWorldPosition: function (target) {
  4125. if (target === undefined) {
  4126. console.warn('THREE.Object3D: .getWorldPosition() target is now required');
  4127. target = new Vector3();
  4128. }
  4129. this.updateMatrixWorld(true);
  4130. return target.setFromMatrixPosition(this.matrixWorld);
  4131. },
  4132. getWorldQuaternion: function (target) {
  4133. if (target === undefined) {
  4134. console.warn('THREE.Object3D: .getWorldQuaternion() target is now required');
  4135. target = new Quaternion();
  4136. }
  4137. this.updateMatrixWorld(true);
  4138. this.matrixWorld.decompose(_position, target, _scale);
  4139. return target;
  4140. },
  4141. getWorldScale: function (target) {
  4142. if (target === undefined) {
  4143. console.warn('THREE.Object3D: .getWorldScale() target is now required');
  4144. target = new Vector3();
  4145. }
  4146. this.updateMatrixWorld(true);
  4147. this.matrixWorld.decompose(_position, _quaternion$2, target);
  4148. return target;
  4149. },
  4150. getWorldDirection: function (target) {
  4151. if (target === undefined) {
  4152. console.warn('THREE.Object3D: .getWorldDirection() target is now required');
  4153. target = new Vector3();
  4154. }
  4155. this.updateMatrixWorld(true);
  4156. var e = this.matrixWorld.elements;
  4157. return target.set(e[8], e[9], e[10]).normalize();
  4158. },
  4159. raycast: function () {},
  4160. traverse: function (callback) {
  4161. callback(this);
  4162. var children = this.children;
  4163. for (var i = 0, l = children.length; i < l; i++) {
  4164. children[i].traverse(callback);
  4165. }
  4166. },
  4167. traverseVisible: function (callback) {
  4168. if (this.visible === false) return;
  4169. callback(this);
  4170. var children = this.children;
  4171. for (var i = 0, l = children.length; i < l; i++) {
  4172. children[i].traverseVisible(callback);
  4173. }
  4174. },
  4175. traverseAncestors: function (callback) {
  4176. var parent = this.parent;
  4177. if (parent !== null) {
  4178. callback(parent);
  4179. parent.traverseAncestors(callback);
  4180. }
  4181. },
  4182. updateMatrix: function () {
  4183. this.matrix.compose(this.position, this.quaternion, this.scale);
  4184. this.matrixWorldNeedsUpdate = true;
  4185. },
  4186. updateMatrixWorld: function (force) {
  4187. if (this.matrixAutoUpdate) this.updateMatrix();
  4188. if (this.matrixWorldNeedsUpdate || force) {
  4189. if (this.parent === null) {
  4190. this.matrixWorld.copy(this.matrix);
  4191. } else {
  4192. this.matrixWorld.multiplyMatrices(this.parent.matrixWorld, this.matrix);
  4193. }
  4194. this.matrixWorldNeedsUpdate = false;
  4195. force = true;
  4196. } // update children
  4197. var children = this.children;
  4198. for (var i = 0, l = children.length; i < l; i++) {
  4199. children[i].updateMatrixWorld(force);
  4200. }
  4201. },
  4202. updateWorldMatrix: function (updateParents, updateChildren) {
  4203. var parent = this.parent;
  4204. if (updateParents === true && parent !== null) {
  4205. parent.updateWorldMatrix(true, false);
  4206. }
  4207. if (this.matrixAutoUpdate) this.updateMatrix();
  4208. if (this.parent === null) {
  4209. this.matrixWorld.copy(this.matrix);
  4210. } else {
  4211. this.matrixWorld.multiplyMatrices(this.parent.matrixWorld, this.matrix);
  4212. } // update children
  4213. if (updateChildren === true) {
  4214. var children = this.children;
  4215. for (var i = 0, l = children.length; i < l; i++) {
  4216. children[i].updateWorldMatrix(false, true);
  4217. }
  4218. }
  4219. },
  4220. toJSON: function (meta) {
  4221. // meta is a string when called from JSON.stringify
  4222. var isRootObject = meta === undefined || typeof meta === 'string';
  4223. var output = {}; // meta is a hash used to collect geometries, materials.
  4224. // not providing it implies that this is the root object
  4225. // being serialized.
  4226. if (isRootObject) {
  4227. // initialize meta obj
  4228. meta = {
  4229. geometries: {},
  4230. materials: {},
  4231. textures: {},
  4232. images: {},
  4233. shapes: {}
  4234. };
  4235. output.metadata = {
  4236. version: 4.5,
  4237. type: 'Object',
  4238. generator: 'Object3D.toJSON'
  4239. };
  4240. } // standard Object3D serialization
  4241. var object = {};
  4242. object.uuid = this.uuid;
  4243. object.type = this.type;
  4244. if (this.name !== '') object.name = this.name;
  4245. if (this.castShadow === true) object.castShadow = true;
  4246. if (this.receiveShadow === true) object.receiveShadow = true;
  4247. if (this.visible === false) object.visible = false;
  4248. if (this.frustumCulled === false) object.frustumCulled = false;
  4249. if (this.renderOrder !== 0) object.renderOrder = this.renderOrder;
  4250. if (JSON.stringify(this.userData) !== '{}') object.userData = this.userData;
  4251. object.layers = this.layers.mask;
  4252. object.matrix = this.matrix.toArray();
  4253. if (this.matrixAutoUpdate === false) object.matrixAutoUpdate = false; // object specific properties
  4254. if (this.isMesh && this.drawMode !== TrianglesDrawMode) object.drawMode = this.drawMode; //
  4255. function serialize(library, element) {
  4256. if (library[element.uuid] === undefined) {
  4257. library[element.uuid] = element.toJSON(meta);
  4258. }
  4259. return element.uuid;
  4260. }
  4261. if (this.isMesh || this.isLine || this.isPoints) {
  4262. object.geometry = serialize(meta.geometries, this.geometry);
  4263. var parameters = this.geometry.parameters;
  4264. if (parameters !== undefined && parameters.shapes !== undefined) {
  4265. var shapes = parameters.shapes;
  4266. if (Array.isArray(shapes)) {
  4267. for (var i = 0, l = shapes.length; i < l; i++) {
  4268. var shape = shapes[i];
  4269. serialize(meta.shapes, shape);
  4270. }
  4271. } else {
  4272. serialize(meta.shapes, shapes);
  4273. }
  4274. }
  4275. }
  4276. if (this.material !== undefined) {
  4277. if (Array.isArray(this.material)) {
  4278. var uuids = [];
  4279. for (var i = 0, l = this.material.length; i < l; i++) {
  4280. uuids.push(serialize(meta.materials, this.material[i]));
  4281. }
  4282. object.material = uuids;
  4283. } else {
  4284. object.material = serialize(meta.materials, this.material);
  4285. }
  4286. } //
  4287. if (this.children.length > 0) {
  4288. object.children = [];
  4289. for (var i = 0; i < this.children.length; i++) {
  4290. object.children.push(this.children[i].toJSON(meta).object);
  4291. }
  4292. }
  4293. if (isRootObject) {
  4294. var geometries = extractFromCache(meta.geometries);
  4295. var materials = extractFromCache(meta.materials);
  4296. var textures = extractFromCache(meta.textures);
  4297. var images = extractFromCache(meta.images);
  4298. var shapes = extractFromCache(meta.shapes);
  4299. if (geometries.length > 0) output.geometries = geometries;
  4300. if (materials.length > 0) output.materials = materials;
  4301. if (textures.length > 0) output.textures = textures;
  4302. if (images.length > 0) output.images = images;
  4303. if (shapes.length > 0) output.shapes = shapes;
  4304. }
  4305. output.object = object;
  4306. return output; // extract data from the cache hash
  4307. // remove metadata on each item
  4308. // and return as array
  4309. function extractFromCache(cache) {
  4310. var values = [];
  4311. for (var key in cache) {
  4312. var data = cache[key];
  4313. delete data.metadata;
  4314. values.push(data);
  4315. }
  4316. return values;
  4317. }
  4318. },
  4319. clone: function (recursive) {
  4320. return new this.constructor().copy(this, recursive);
  4321. },
  4322. copy: function (source, recursive) {
  4323. if (recursive === undefined) recursive = true;
  4324. this.name = source.name;
  4325. this.up.copy(source.up);
  4326. this.position.copy(source.position);
  4327. this.quaternion.copy(source.quaternion);
  4328. this.scale.copy(source.scale);
  4329. this.matrix.copy(source.matrix);
  4330. this.matrixWorld.copy(source.matrixWorld);
  4331. this.matrixAutoUpdate = source.matrixAutoUpdate;
  4332. this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;
  4333. this.layers.mask = source.layers.mask;
  4334. this.visible = source.visible;
  4335. this.castShadow = source.castShadow;
  4336. this.receiveShadow = source.receiveShadow;
  4337. this.frustumCulled = source.frustumCulled;
  4338. this.renderOrder = source.renderOrder;
  4339. this.userData = JSON.parse(JSON.stringify(source.userData));
  4340. if (recursive === true) {
  4341. for (var i = 0; i < source.children.length; i++) {
  4342. var child = source.children[i];
  4343. this.add(child.clone());
  4344. }
  4345. }
  4346. return this;
  4347. }
  4348. });
  4349. /**
  4350. * @author mrdoob / http://mrdoob.com/
  4351. */
  4352. function Scene() {
  4353. Object3D.call(this);
  4354. this.type = 'Scene';
  4355. this.background = null;
  4356. this.fog = null;
  4357. this.overrideMaterial = null;
  4358. this.autoUpdate = true; // checked by the renderer
  4359. if (typeof __THREE_DEVTOOLS__ !== 'undefined') {
  4360. __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent('observe', {
  4361. detail: this
  4362. })); // eslint-disable-line no-undef
  4363. }
  4364. }
  4365. Scene.prototype = Object.assign(Object.create(Object3D.prototype), {
  4366. constructor: Scene,
  4367. isScene: true,
  4368. copy: function (source, recursive) {
  4369. Object3D.prototype.copy.call(this, source, recursive);
  4370. if (source.background !== null) this.background = source.background.clone();
  4371. if (source.fog !== null) this.fog = source.fog.clone();
  4372. if (source.overrideMaterial !== null) this.overrideMaterial = source.overrideMaterial.clone();
  4373. this.autoUpdate = source.autoUpdate;
  4374. this.matrixAutoUpdate = source.matrixAutoUpdate;
  4375. return this;
  4376. },
  4377. toJSON: function (meta) {
  4378. var data = Object3D.prototype.toJSON.call(this, meta);
  4379. if (this.background !== null) data.object.background = this.background.toJSON(meta);
  4380. if (this.fog !== null) data.object.fog = this.fog.toJSON();
  4381. return data;
  4382. },
  4383. dispose: function () {
  4384. this.dispatchEvent({
  4385. type: 'dispose'
  4386. });
  4387. }
  4388. });
  4389. var _points = [new Vector3(), new Vector3(), new Vector3(), new Vector3(), new Vector3(), new Vector3(), new Vector3(), new Vector3()];
  4390. var _vector$2 = new Vector3(); // triangle centered vertices
  4391. var _v0 = new Vector3();
  4392. var _v1$2 = new Vector3();
  4393. var _v2 = new Vector3(); // triangle edge vectors
  4394. var _f0 = new Vector3();
  4395. var _f1 = new Vector3();
  4396. var _f2 = new Vector3();
  4397. var _center = new Vector3();
  4398. var _extents = new Vector3();
  4399. var _triangleNormal = new Vector3();
  4400. var _testAxis = new Vector3();
  4401. /**
  4402. * @author bhouston / http://clara.io
  4403. * @author WestLangley / http://github.com/WestLangley
  4404. */
  4405. function Box3(min, max) {
  4406. this.min = min !== undefined ? min : new Vector3(+Infinity, +Infinity, +Infinity);
  4407. this.max = max !== undefined ? max : new Vector3(-Infinity, -Infinity, -Infinity);
  4408. }
  4409. Object.assign(Box3.prototype, {
  4410. isBox3: true,
  4411. set: function (min, max) {
  4412. this.min.copy(min);
  4413. this.max.copy(max);
  4414. return this;
  4415. },
  4416. setFromArray: function (array) {
  4417. var minX = +Infinity;
  4418. var minY = +Infinity;
  4419. var minZ = +Infinity;
  4420. var maxX = -Infinity;
  4421. var maxY = -Infinity;
  4422. var maxZ = -Infinity;
  4423. for (var i = 0, l = array.length; i < l; i += 3) {
  4424. var x = array[i];
  4425. var y = array[i + 1];
  4426. var z = array[i + 2];
  4427. if (x < minX) minX = x;
  4428. if (y < minY) minY = y;
  4429. if (z < minZ) minZ = z;
  4430. if (x > maxX) maxX = x;
  4431. if (y > maxY) maxY = y;
  4432. if (z > maxZ) maxZ = z;
  4433. }
  4434. this.min.set(minX, minY, minZ);
  4435. this.max.set(maxX, maxY, maxZ);
  4436. return this;
  4437. },
  4438. setFromBufferAttribute: function (attribute) {
  4439. var minX = +Infinity;
  4440. var minY = +Infinity;
  4441. var minZ = +Infinity;
  4442. var maxX = -Infinity;
  4443. var maxY = -Infinity;
  4444. var maxZ = -Infinity;
  4445. for (var i = 0, l = attribute.count; i < l; i++) {
  4446. var x = attribute.getX(i);
  4447. var y = attribute.getY(i);
  4448. var z = attribute.getZ(i);
  4449. if (x < minX) minX = x;
  4450. if (y < minY) minY = y;
  4451. if (z < minZ) minZ = z;
  4452. if (x > maxX) maxX = x;
  4453. if (y > maxY) maxY = y;
  4454. if (z > maxZ) maxZ = z;
  4455. }
  4456. this.min.set(minX, minY, minZ);
  4457. this.max.set(maxX, maxY, maxZ);
  4458. return this;
  4459. },
  4460. setFromPoints: function (points) {
  4461. this.makeEmpty();
  4462. for (var i = 0, il = points.length; i < il; i++) {
  4463. this.expandByPoint(points[i]);
  4464. }
  4465. return this;
  4466. },
  4467. setFromCenterAndSize: function (center, size) {
  4468. var halfSize = _vector$2.copy(size).multiplyScalar(0.5);
  4469. this.min.copy(center).sub(halfSize);
  4470. this.max.copy(center).add(halfSize);
  4471. return this;
  4472. },
  4473. setFromObject: function (object) {
  4474. this.makeEmpty();
  4475. return this.expandByObject(object);
  4476. },
  4477. clone: function () {
  4478. return new this.constructor().copy(this);
  4479. },
  4480. copy: function (box) {
  4481. this.min.copy(box.min);
  4482. this.max.copy(box.max);
  4483. return this;
  4484. },
  4485. makeEmpty: function () {
  4486. this.min.x = this.min.y = this.min.z = +Infinity;
  4487. this.max.x = this.max.y = this.max.z = -Infinity;
  4488. return this;
  4489. },
  4490. isEmpty: function () {
  4491. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  4492. return this.max.x < this.min.x || this.max.y < this.min.y || this.max.z < this.min.z;
  4493. },
  4494. getCenter: function (target) {
  4495. if (target === undefined) {
  4496. console.warn('THREE.Box3: .getCenter() target is now required');
  4497. target = new Vector3();
  4498. }
  4499. return this.isEmpty() ? target.set(0, 0, 0) : target.addVectors(this.min, this.max).multiplyScalar(0.5);
  4500. },
  4501. getSize: function (target) {
  4502. if (target === undefined) {
  4503. console.warn('THREE.Box3: .getSize() target is now required');
  4504. target = new Vector3();
  4505. }
  4506. return this.isEmpty() ? target.set(0, 0, 0) : target.subVectors(this.max, this.min);
  4507. },
  4508. expandByPoint: function (point) {
  4509. this.min.min(point);
  4510. this.max.max(point);
  4511. return this;
  4512. },
  4513. expandByVector: function (vector) {
  4514. this.min.sub(vector);
  4515. this.max.add(vector);
  4516. return this;
  4517. },
  4518. expandByScalar: function (scalar) {
  4519. this.min.addScalar(-scalar);
  4520. this.max.addScalar(scalar);
  4521. return this;
  4522. },
  4523. expandByObject: function (object) {
  4524. var i, l; // Computes the world-axis-aligned bounding box of an object (including its children),
  4525. // accounting for both the object's, and children's, world transforms
  4526. object.updateWorldMatrix(false, false);
  4527. var geometry = object.geometry;
  4528. if (geometry !== undefined) {
  4529. if (geometry.isGeometry) {
  4530. var vertices = geometry.vertices;
  4531. for (i = 0, l = vertices.length; i < l; i++) {
  4532. _vector$2.copy(vertices[i]);
  4533. _vector$2.applyMatrix4(object.matrixWorld);
  4534. this.expandByPoint(_vector$2);
  4535. }
  4536. } else if (geometry.isBufferGeometry) {
  4537. var attribute = geometry.attributes.position;
  4538. if (attribute !== undefined) {
  4539. for (i = 0, l = attribute.count; i < l; i++) {
  4540. _vector$2.fromBufferAttribute(attribute, i).applyMatrix4(object.matrixWorld);
  4541. this.expandByPoint(_vector$2);
  4542. }
  4543. }
  4544. }
  4545. } //
  4546. var children = object.children;
  4547. for (i = 0, l = children.length; i < l; i++) {
  4548. this.expandByObject(children[i]);
  4549. }
  4550. return this;
  4551. },
  4552. containsPoint: function (point) {
  4553. 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;
  4554. },
  4555. containsBox: function (box) {
  4556. 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;
  4557. },
  4558. getParameter: function (point, target) {
  4559. // This can potentially have a divide by zero if the box
  4560. // has a size dimension of 0.
  4561. if (target === undefined) {
  4562. console.warn('THREE.Box3: .getParameter() target is now required');
  4563. target = new Vector3();
  4564. }
  4565. 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));
  4566. },
  4567. intersectsBox: function (box) {
  4568. // using 6 splitting planes to rule out intersections.
  4569. 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;
  4570. },
  4571. intersectsSphere: function (sphere) {
  4572. // Find the point on the AABB closest to the sphere center.
  4573. this.clampPoint(sphere.center, _vector$2); // If that point is inside the sphere, the AABB and sphere intersect.
  4574. return _vector$2.distanceToSquared(sphere.center) <= sphere.radius * sphere.radius;
  4575. },
  4576. intersectsPlane: function (plane) {
  4577. // We compute the minimum and maximum dot product values. If those values
  4578. // are on the same side (back or front) of the plane, then there is no intersection.
  4579. var min, max;
  4580. if (plane.normal.x > 0) {
  4581. min = plane.normal.x * this.min.x;
  4582. max = plane.normal.x * this.max.x;
  4583. } else {
  4584. min = plane.normal.x * this.max.x;
  4585. max = plane.normal.x * this.min.x;
  4586. }
  4587. if (plane.normal.y > 0) {
  4588. min += plane.normal.y * this.min.y;
  4589. max += plane.normal.y * this.max.y;
  4590. } else {
  4591. min += plane.normal.y * this.max.y;
  4592. max += plane.normal.y * this.min.y;
  4593. }
  4594. if (plane.normal.z > 0) {
  4595. min += plane.normal.z * this.min.z;
  4596. max += plane.normal.z * this.max.z;
  4597. } else {
  4598. min += plane.normal.z * this.max.z;
  4599. max += plane.normal.z * this.min.z;
  4600. }
  4601. return min <= -plane.constant && max >= -plane.constant;
  4602. },
  4603. intersectsTriangle: function (triangle) {
  4604. if (this.isEmpty()) {
  4605. return false;
  4606. } // compute box center and extents
  4607. this.getCenter(_center);
  4608. _extents.subVectors(this.max, _center); // translate triangle to aabb origin
  4609. _v0.subVectors(triangle.a, _center);
  4610. _v1$2.subVectors(triangle.b, _center);
  4611. _v2.subVectors(triangle.c, _center); // compute edge vectors for triangle
  4612. _f0.subVectors(_v1$2, _v0);
  4613. _f1.subVectors(_v2, _v1$2);
  4614. _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
  4615. // 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
  4616. // axis_ij = u_i x f_j (u0, u1, u2 = face normals of aabb = x,y,z axes vectors since aabb is axis aligned)
  4617. 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];
  4618. if (!satForAxes(axes, _v0, _v1$2, _v2, _extents)) {
  4619. return false;
  4620. } // test 3 face normals from the aabb
  4621. axes = [1, 0, 0, 0, 1, 0, 0, 0, 1];
  4622. if (!satForAxes(axes, _v0, _v1$2, _v2, _extents)) {
  4623. return false;
  4624. } // finally testing the face normal of the triangle
  4625. // use already existing triangle edge vectors here
  4626. _triangleNormal.crossVectors(_f0, _f1);
  4627. axes = [_triangleNormal.x, _triangleNormal.y, _triangleNormal.z];
  4628. return satForAxes(axes, _v0, _v1$2, _v2, _extents);
  4629. },
  4630. clampPoint: function (point, target) {
  4631. if (target === undefined) {
  4632. console.warn('THREE.Box3: .clampPoint() target is now required');
  4633. target = new Vector3();
  4634. }
  4635. return target.copy(point).clamp(this.min, this.max);
  4636. },
  4637. distanceToPoint: function (point) {
  4638. var clampedPoint = _vector$2.copy(point).clamp(this.min, this.max);
  4639. return clampedPoint.sub(point).length();
  4640. },
  4641. getBoundingSphere: function (target) {
  4642. if (target === undefined) {
  4643. console.error('THREE.Box3: .getBoundingSphere() target is now required'); //target = new Sphere(); // removed to avoid cyclic dependency
  4644. }
  4645. this.getCenter(target.center);
  4646. target.radius = this.getSize(_vector$2).length() * 0.5;
  4647. return target;
  4648. },
  4649. intersect: function (box) {
  4650. this.min.max(box.min);
  4651. 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.
  4652. if (this.isEmpty()) this.makeEmpty();
  4653. return this;
  4654. },
  4655. union: function (box) {
  4656. this.min.min(box.min);
  4657. this.max.max(box.max);
  4658. return this;
  4659. },
  4660. applyMatrix4: function (matrix) {
  4661. // transform of empty box is an empty box.
  4662. if (this.isEmpty()) return this; // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  4663. _points[0].set(this.min.x, this.min.y, this.min.z).applyMatrix4(matrix); // 000
  4664. _points[1].set(this.min.x, this.min.y, this.max.z).applyMatrix4(matrix); // 001
  4665. _points[2].set(this.min.x, this.max.y, this.min.z).applyMatrix4(matrix); // 010
  4666. _points[3].set(this.min.x, this.max.y, this.max.z).applyMatrix4(matrix); // 011
  4667. _points[4].set(this.max.x, this.min.y, this.min.z).applyMatrix4(matrix); // 100
  4668. _points[5].set(this.max.x, this.min.y, this.max.z).applyMatrix4(matrix); // 101
  4669. _points[6].set(this.max.x, this.max.y, this.min.z).applyMatrix4(matrix); // 110
  4670. _points[7].set(this.max.x, this.max.y, this.max.z).applyMatrix4(matrix); // 111
  4671. this.setFromPoints(_points);
  4672. return this;
  4673. },
  4674. translate: function (offset) {
  4675. this.min.add(offset);
  4676. this.max.add(offset);
  4677. return this;
  4678. },
  4679. equals: function (box) {
  4680. return box.min.equals(this.min) && box.max.equals(this.max);
  4681. }
  4682. });
  4683. function satForAxes(axes, v0, v1, v2, extents) {
  4684. var i, j;
  4685. for (i = 0, j = axes.length - 3; i <= j; i += 3) {
  4686. _testAxis.fromArray(axes, i); // project the aabb onto the seperating axis
  4687. 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
  4688. var p0 = v0.dot(_testAxis);
  4689. var p1 = v1.dot(_testAxis);
  4690. var p2 = v2.dot(_testAxis); // actual test, basically see if either of the most extreme of the triangle points intersects r
  4691. if (Math.max(-Math.max(p0, p1, p2), Math.min(p0, p1, p2)) > r) {
  4692. // points of the projected triangle are outside the projected half-length of the aabb
  4693. // the axis is seperating and we can exit
  4694. return false;
  4695. }
  4696. }
  4697. return true;
  4698. }
  4699. var _box = new Box3();
  4700. /**
  4701. * @author bhouston / http://clara.io
  4702. * @author mrdoob / http://mrdoob.com/
  4703. */
  4704. function Sphere(center, radius) {
  4705. this.center = center !== undefined ? center : new Vector3();
  4706. this.radius = radius !== undefined ? radius : 0;
  4707. }
  4708. Object.assign(Sphere.prototype, {
  4709. set: function (center, radius) {
  4710. this.center.copy(center);
  4711. this.radius = radius;
  4712. return this;
  4713. },
  4714. setFromPoints: function (points, optionalCenter) {
  4715. var center = this.center;
  4716. if (optionalCenter !== undefined) {
  4717. center.copy(optionalCenter);
  4718. } else {
  4719. _box.setFromPoints(points).getCenter(center);
  4720. }
  4721. var maxRadiusSq = 0;
  4722. for (var i = 0, il = points.length; i < il; i++) {
  4723. maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(points[i]));
  4724. }
  4725. this.radius = Math.sqrt(maxRadiusSq);
  4726. return this;
  4727. },
  4728. clone: function () {
  4729. return new this.constructor().copy(this);
  4730. },
  4731. copy: function (sphere) {
  4732. this.center.copy(sphere.center);
  4733. this.radius = sphere.radius;
  4734. return this;
  4735. },
  4736. empty: function () {
  4737. return this.radius <= 0;
  4738. },
  4739. containsPoint: function (point) {
  4740. return point.distanceToSquared(this.center) <= this.radius * this.radius;
  4741. },
  4742. distanceToPoint: function (point) {
  4743. return point.distanceTo(this.center) - this.radius;
  4744. },
  4745. intersectsSphere: function (sphere) {
  4746. var radiusSum = this.radius + sphere.radius;
  4747. return sphere.center.distanceToSquared(this.center) <= radiusSum * radiusSum;
  4748. },
  4749. intersectsBox: function (box) {
  4750. return box.intersectsSphere(this);
  4751. },
  4752. intersectsPlane: function (plane) {
  4753. return Math.abs(plane.distanceToPoint(this.center)) <= this.radius;
  4754. },
  4755. clampPoint: function (point, target) {
  4756. var deltaLengthSq = this.center.distanceToSquared(point);
  4757. if (target === undefined) {
  4758. console.warn('THREE.Sphere: .clampPoint() target is now required');
  4759. target = new Vector3();
  4760. }
  4761. target.copy(point);
  4762. if (deltaLengthSq > this.radius * this.radius) {
  4763. target.sub(this.center).normalize();
  4764. target.multiplyScalar(this.radius).add(this.center);
  4765. }
  4766. return target;
  4767. },
  4768. getBoundingBox: function (target) {
  4769. if (target === undefined) {
  4770. console.warn('THREE.Sphere: .getBoundingBox() target is now required');
  4771. target = new Box3();
  4772. }
  4773. target.set(this.center, this.center);
  4774. target.expandByScalar(this.radius);
  4775. return target;
  4776. },
  4777. applyMatrix4: function (matrix) {
  4778. this.center.applyMatrix4(matrix);
  4779. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  4780. return this;
  4781. },
  4782. translate: function (offset) {
  4783. this.center.add(offset);
  4784. return this;
  4785. },
  4786. equals: function (sphere) {
  4787. return sphere.center.equals(this.center) && sphere.radius === this.radius;
  4788. }
  4789. });
  4790. var _vector$3 = new Vector3();
  4791. var _segCenter = new Vector3();
  4792. var _segDir = new Vector3();
  4793. var _diff = new Vector3();
  4794. var _edge1 = new Vector3();
  4795. var _edge2 = new Vector3();
  4796. var _normal = new Vector3();
  4797. /**
  4798. * @author bhouston / http://clara.io
  4799. */
  4800. function Ray(origin, direction) {
  4801. this.origin = origin !== undefined ? origin : new Vector3();
  4802. this.direction = direction !== undefined ? direction : new Vector3();
  4803. }
  4804. Object.assign(Ray.prototype, {
  4805. set: function (origin, direction) {
  4806. this.origin.copy(origin);
  4807. this.direction.copy(direction);
  4808. return this;
  4809. },
  4810. clone: function () {
  4811. return new this.constructor().copy(this);
  4812. },
  4813. copy: function (ray) {
  4814. this.origin.copy(ray.origin);
  4815. this.direction.copy(ray.direction);
  4816. return this;
  4817. },
  4818. at: function (t, target) {
  4819. if (target === undefined) {
  4820. console.warn('THREE.Ray: .at() target is now required');
  4821. target = new Vector3();
  4822. }
  4823. return target.copy(this.direction).multiplyScalar(t).add(this.origin);
  4824. },
  4825. lookAt: function (v) {
  4826. this.direction.copy(v).sub(this.origin).normalize();
  4827. return this;
  4828. },
  4829. recast: function (t) {
  4830. this.origin.copy(this.at(t, _vector$3));
  4831. return this;
  4832. },
  4833. closestPointToPoint: function (point, target) {
  4834. if (target === undefined) {
  4835. console.warn('THREE.Ray: .closestPointToPoint() target is now required');
  4836. target = new Vector3();
  4837. }
  4838. target.subVectors(point, this.origin);
  4839. var directionDistance = target.dot(this.direction);
  4840. if (directionDistance < 0) {
  4841. return target.copy(this.origin);
  4842. }
  4843. return target.copy(this.direction).multiplyScalar(directionDistance).add(this.origin);
  4844. },
  4845. distanceToPoint: function (point) {
  4846. return Math.sqrt(this.distanceSqToPoint(point));
  4847. },
  4848. distanceSqToPoint: function (point) {
  4849. var directionDistance = _vector$3.subVectors(point, this.origin).dot(this.direction); // point behind the ray
  4850. if (directionDistance < 0) {
  4851. return this.origin.distanceToSquared(point);
  4852. }
  4853. _vector$3.copy(this.direction).multiplyScalar(directionDistance).add(this.origin);
  4854. return _vector$3.distanceToSquared(point);
  4855. },
  4856. distanceSqToSegment: function (v0, v1, optionalPointOnRay, optionalPointOnSegment) {
  4857. // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteDistRaySegment.h
  4858. // It returns the min distance between the ray and the segment
  4859. // defined by v0 and v1
  4860. // It can also set two optional targets :
  4861. // - The closest point on the ray
  4862. // - The closest point on the segment
  4863. _segCenter.copy(v0).add(v1).multiplyScalar(0.5);
  4864. _segDir.copy(v1).sub(v0).normalize();
  4865. _diff.copy(this.origin).sub(_segCenter);
  4866. var segExtent = v0.distanceTo(v1) * 0.5;
  4867. var a01 = -this.direction.dot(_segDir);
  4868. var b0 = _diff.dot(this.direction);
  4869. var b1 = -_diff.dot(_segDir);
  4870. var c = _diff.lengthSq();
  4871. var det = Math.abs(1 - a01 * a01);
  4872. var s0, s1, sqrDist, extDet;
  4873. if (det > 0) {
  4874. // The ray and segment are not parallel.
  4875. s0 = a01 * b1 - b0;
  4876. s1 = a01 * b0 - b1;
  4877. extDet = segExtent * det;
  4878. if (s0 >= 0) {
  4879. if (s1 >= -extDet) {
  4880. if (s1 <= extDet) {
  4881. // region 0
  4882. // Minimum at interior points of ray and segment.
  4883. var invDet = 1 / det;
  4884. s0 *= invDet;
  4885. s1 *= invDet;
  4886. sqrDist = s0 * (s0 + a01 * s1 + 2 * b0) + s1 * (a01 * s0 + s1 + 2 * b1) + c;
  4887. } else {
  4888. // region 1
  4889. s1 = segExtent;
  4890. s0 = Math.max(0, -(a01 * s1 + b0));
  4891. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  4892. }
  4893. } else {
  4894. // region 5
  4895. s1 = -segExtent;
  4896. s0 = Math.max(0, -(a01 * s1 + b0));
  4897. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  4898. }
  4899. } else {
  4900. if (s1 <= -extDet) {
  4901. // region 4
  4902. s0 = Math.max(0, -(-a01 * segExtent + b0));
  4903. s1 = s0 > 0 ? -segExtent : Math.min(Math.max(-segExtent, -b1), segExtent);
  4904. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  4905. } else if (s1 <= extDet) {
  4906. // region 3
  4907. s0 = 0;
  4908. s1 = Math.min(Math.max(-segExtent, -b1), segExtent);
  4909. sqrDist = s1 * (s1 + 2 * b1) + c;
  4910. } else {
  4911. // region 2
  4912. s0 = Math.max(0, -(a01 * segExtent + b0));
  4913. s1 = s0 > 0 ? segExtent : Math.min(Math.max(-segExtent, -b1), segExtent);
  4914. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  4915. }
  4916. }
  4917. } else {
  4918. // Ray and segment are parallel.
  4919. s1 = a01 > 0 ? -segExtent : segExtent;
  4920. s0 = Math.max(0, -(a01 * s1 + b0));
  4921. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  4922. }
  4923. if (optionalPointOnRay) {
  4924. optionalPointOnRay.copy(this.direction).multiplyScalar(s0).add(this.origin);
  4925. }
  4926. if (optionalPointOnSegment) {
  4927. optionalPointOnSegment.copy(_segDir).multiplyScalar(s1).add(_segCenter);
  4928. }
  4929. return sqrDist;
  4930. },
  4931. intersectSphere: function (sphere, target) {
  4932. _vector$3.subVectors(sphere.center, this.origin);
  4933. var tca = _vector$3.dot(this.direction);
  4934. var d2 = _vector$3.dot(_vector$3) - tca * tca;
  4935. var radius2 = sphere.radius * sphere.radius;
  4936. if (d2 > radius2) return null;
  4937. var thc = Math.sqrt(radius2 - d2); // t0 = first intersect point - entrance on front of sphere
  4938. var t0 = tca - thc; // t1 = second intersect point - exit point on back of sphere
  4939. var t1 = tca + thc; // test to see if both t0 and t1 are behind the ray - if so, return null
  4940. if (t0 < 0 && t1 < 0) return null; // test to see if t0 is behind the ray:
  4941. // if it is, the ray is inside the sphere, so return the second exit point scaled by t1,
  4942. // in order to always return an intersect point that is in front of the ray.
  4943. 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
  4944. return this.at(t0, target);
  4945. },
  4946. intersectsSphere: function (sphere) {
  4947. return this.distanceSqToPoint(sphere.center) <= sphere.radius * sphere.radius;
  4948. },
  4949. distanceToPlane: function (plane) {
  4950. var denominator = plane.normal.dot(this.direction);
  4951. if (denominator === 0) {
  4952. // line is coplanar, return origin
  4953. if (plane.distanceToPoint(this.origin) === 0) {
  4954. return 0;
  4955. } // Null is preferable to undefined since undefined means.... it is undefined
  4956. return null;
  4957. }
  4958. var t = -(this.origin.dot(plane.normal) + plane.constant) / denominator; // Return if the ray never intersects the plane
  4959. return t >= 0 ? t : null;
  4960. },
  4961. intersectPlane: function (plane, target) {
  4962. var t = this.distanceToPlane(plane);
  4963. if (t === null) {
  4964. return null;
  4965. }
  4966. return this.at(t, target);
  4967. },
  4968. intersectsPlane: function (plane) {
  4969. // check if the ray lies on the plane first
  4970. var distToPoint = plane.distanceToPoint(this.origin);
  4971. if (distToPoint === 0) {
  4972. return true;
  4973. }
  4974. var denominator = plane.normal.dot(this.direction);
  4975. if (denominator * distToPoint < 0) {
  4976. return true;
  4977. } // ray origin is behind the plane (and is pointing behind it)
  4978. return false;
  4979. },
  4980. intersectBox: function (box, target) {
  4981. var tmin, tmax, tymin, tymax, tzmin, tzmax;
  4982. var invdirx = 1 / this.direction.x,
  4983. invdiry = 1 / this.direction.y,
  4984. invdirz = 1 / this.direction.z;
  4985. var origin = this.origin;
  4986. if (invdirx >= 0) {
  4987. tmin = (box.min.x - origin.x) * invdirx;
  4988. tmax = (box.max.x - origin.x) * invdirx;
  4989. } else {
  4990. tmin = (box.max.x - origin.x) * invdirx;
  4991. tmax = (box.min.x - origin.x) * invdirx;
  4992. }
  4993. if (invdiry >= 0) {
  4994. tymin = (box.min.y - origin.y) * invdiry;
  4995. tymax = (box.max.y - origin.y) * invdiry;
  4996. } else {
  4997. tymin = (box.max.y - origin.y) * invdiry;
  4998. tymax = (box.min.y - origin.y) * invdiry;
  4999. }
  5000. if (tmin > tymax || tymin > tmax) return null; // These lines also handle the case where tmin or tmax is NaN
  5001. // (result of 0 * Infinity). x !== x returns true if x is NaN
  5002. if (tymin > tmin || tmin !== tmin) tmin = tymin;
  5003. if (tymax < tmax || tmax !== tmax) tmax = tymax;
  5004. if (invdirz >= 0) {
  5005. tzmin = (box.min.z - origin.z) * invdirz;
  5006. tzmax = (box.max.z - origin.z) * invdirz;
  5007. } else {
  5008. tzmin = (box.max.z - origin.z) * invdirz;
  5009. tzmax = (box.min.z - origin.z) * invdirz;
  5010. }
  5011. if (tmin > tzmax || tzmin > tmax) return null;
  5012. if (tzmin > tmin || tmin !== tmin) tmin = tzmin;
  5013. if (tzmax < tmax || tmax !== tmax) tmax = tzmax; //return point closest to the ray (positive side)
  5014. if (tmax < 0) return null;
  5015. return this.at(tmin >= 0 ? tmin : tmax, target);
  5016. },
  5017. intersectsBox: function (box) {
  5018. return this.intersectBox(box, _vector$3) !== null;
  5019. },
  5020. intersectTriangle: function (a, b, c, backfaceCulling, target) {
  5021. // Compute the offset origin, edges, and normal.
  5022. // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h
  5023. _edge1.subVectors(b, a);
  5024. _edge2.subVectors(c, a);
  5025. _normal.crossVectors(_edge1, _edge2); // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  5026. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  5027. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  5028. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  5029. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  5030. var DdN = this.direction.dot(_normal);
  5031. var sign;
  5032. if (DdN > 0) {
  5033. if (backfaceCulling) return null;
  5034. sign = 1;
  5035. } else if (DdN < 0) {
  5036. sign = -1;
  5037. DdN = -DdN;
  5038. } else {
  5039. return null;
  5040. }
  5041. _diff.subVectors(this.origin, a);
  5042. var DdQxE2 = sign * this.direction.dot(_edge2.crossVectors(_diff, _edge2)); // b1 < 0, no intersection
  5043. if (DdQxE2 < 0) {
  5044. return null;
  5045. }
  5046. var DdE1xQ = sign * this.direction.dot(_edge1.cross(_diff)); // b2 < 0, no intersection
  5047. if (DdE1xQ < 0) {
  5048. return null;
  5049. } // b1+b2 > 1, no intersection
  5050. if (DdQxE2 + DdE1xQ > DdN) {
  5051. return null;
  5052. } // Line intersects triangle, check if ray does.
  5053. var QdN = -sign * _diff.dot(_normal); // t < 0, no intersection
  5054. if (QdN < 0) {
  5055. return null;
  5056. } // Ray intersects triangle.
  5057. return this.at(QdN / DdN, target);
  5058. },
  5059. applyMatrix4: function (matrix4) {
  5060. this.origin.applyMatrix4(matrix4);
  5061. this.direction.transformDirection(matrix4);
  5062. return this;
  5063. },
  5064. equals: function (ray) {
  5065. return ray.origin.equals(this.origin) && ray.direction.equals(this.direction);
  5066. }
  5067. });
  5068. /**
  5069. * @author bhouston / http://clara.io
  5070. * @author mrdoob / http://mrdoob.com/
  5071. */
  5072. var _v0$1 = new Vector3();
  5073. var _v1$3 = new Vector3();
  5074. var _v2$1 = new Vector3();
  5075. var _v3 = new Vector3();
  5076. var _vab = new Vector3();
  5077. var _vac = new Vector3();
  5078. var _vbc = new Vector3();
  5079. var _vap = new Vector3();
  5080. var _vbp = new Vector3();
  5081. var _vcp = new Vector3();
  5082. function Triangle(a, b, c) {
  5083. this.a = a !== undefined ? a : new Vector3();
  5084. this.b = b !== undefined ? b : new Vector3();
  5085. this.c = c !== undefined ? c : new Vector3();
  5086. }
  5087. Object.assign(Triangle, {
  5088. getNormal: function (a, b, c, target) {
  5089. if (target === undefined) {
  5090. console.warn('THREE.Triangle: .getNormal() target is now required');
  5091. target = new Vector3();
  5092. }
  5093. target.subVectors(c, b);
  5094. _v0$1.subVectors(a, b);
  5095. target.cross(_v0$1);
  5096. var targetLengthSq = target.lengthSq();
  5097. if (targetLengthSq > 0) {
  5098. return target.multiplyScalar(1 / Math.sqrt(targetLengthSq));
  5099. }
  5100. return target.set(0, 0, 0);
  5101. },
  5102. // static/instance method to calculate barycentric coordinates
  5103. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  5104. getBarycoord: function (point, a, b, c, target) {
  5105. _v0$1.subVectors(c, a);
  5106. _v1$3.subVectors(b, a);
  5107. _v2$1.subVectors(point, a);
  5108. var dot00 = _v0$1.dot(_v0$1);
  5109. var dot01 = _v0$1.dot(_v1$3);
  5110. var dot02 = _v0$1.dot(_v2$1);
  5111. var dot11 = _v1$3.dot(_v1$3);
  5112. var dot12 = _v1$3.dot(_v2$1);
  5113. var denom = dot00 * dot11 - dot01 * dot01;
  5114. if (target === undefined) {
  5115. console.warn('THREE.Triangle: .getBarycoord() target is now required');
  5116. target = new Vector3();
  5117. } // collinear or singular triangle
  5118. if (denom === 0) {
  5119. // arbitrary location outside of triangle?
  5120. // not sure if this is the best idea, maybe should be returning undefined
  5121. return target.set(-2, -1, -1);
  5122. }
  5123. var invDenom = 1 / denom;
  5124. var u = (dot11 * dot02 - dot01 * dot12) * invDenom;
  5125. var v = (dot00 * dot12 - dot01 * dot02) * invDenom; // barycentric coordinates must always sum to 1
  5126. return target.set(1 - u - v, v, u);
  5127. },
  5128. containsPoint: function (point, a, b, c) {
  5129. Triangle.getBarycoord(point, a, b, c, _v3);
  5130. return _v3.x >= 0 && _v3.y >= 0 && _v3.x + _v3.y <= 1;
  5131. },
  5132. getUV: function (point, p1, p2, p3, uv1, uv2, uv3, target) {
  5133. this.getBarycoord(point, p1, p2, p3, _v3);
  5134. target.set(0, 0);
  5135. target.addScaledVector(uv1, _v3.x);
  5136. target.addScaledVector(uv2, _v3.y);
  5137. target.addScaledVector(uv3, _v3.z);
  5138. return target;
  5139. },
  5140. isFrontFacing: function (a, b, c, direction) {
  5141. _v0$1.subVectors(c, b);
  5142. _v1$3.subVectors(a, b); // strictly front facing
  5143. return _v0$1.cross(_v1$3).dot(direction) < 0 ? true : false;
  5144. }
  5145. });
  5146. Object.assign(Triangle.prototype, {
  5147. set: function (a, b, c) {
  5148. this.a.copy(a);
  5149. this.b.copy(b);
  5150. this.c.copy(c);
  5151. return this;
  5152. },
  5153. setFromPointsAndIndices: function (points, i0, i1, i2) {
  5154. this.a.copy(points[i0]);
  5155. this.b.copy(points[i1]);
  5156. this.c.copy(points[i2]);
  5157. return this;
  5158. },
  5159. clone: function () {
  5160. return new this.constructor().copy(this);
  5161. },
  5162. copy: function (triangle) {
  5163. this.a.copy(triangle.a);
  5164. this.b.copy(triangle.b);
  5165. this.c.copy(triangle.c);
  5166. return this;
  5167. },
  5168. getArea: function () {
  5169. _v0$1.subVectors(this.c, this.b);
  5170. _v1$3.subVectors(this.a, this.b);
  5171. return _v0$1.cross(_v1$3).length() * 0.5;
  5172. },
  5173. getMidpoint: function (target) {
  5174. if (target === undefined) {
  5175. console.warn('THREE.Triangle: .getMidpoint() target is now required');
  5176. target = new Vector3();
  5177. }
  5178. return target.addVectors(this.a, this.b).add(this.c).multiplyScalar(1 / 3);
  5179. },
  5180. getNormal: function (target) {
  5181. return Triangle.getNormal(this.a, this.b, this.c, target);
  5182. },
  5183. getPlane: function (target) {
  5184. if (target === undefined) {
  5185. console.warn('THREE.Triangle: .getPlane() target is now required');
  5186. target = new Vector3();
  5187. }
  5188. return target.setFromCoplanarPoints(this.a, this.b, this.c);
  5189. },
  5190. getBarycoord: function (point, target) {
  5191. return Triangle.getBarycoord(point, this.a, this.b, this.c, target);
  5192. },
  5193. getUV: function (point, uv1, uv2, uv3, target) {
  5194. return Triangle.getUV(point, this.a, this.b, this.c, uv1, uv2, uv3, target);
  5195. },
  5196. containsPoint: function (point) {
  5197. return Triangle.containsPoint(point, this.a, this.b, this.c);
  5198. },
  5199. isFrontFacing: function (direction) {
  5200. return Triangle.isFrontFacing(this.a, this.b, this.c, direction);
  5201. },
  5202. intersectsBox: function (box) {
  5203. return box.intersectsTriangle(this);
  5204. },
  5205. closestPointToPoint: function (p, target) {
  5206. if (target === undefined) {
  5207. console.warn('THREE.Triangle: .closestPointToPoint() target is now required');
  5208. target = new Vector3();
  5209. }
  5210. var a = this.a,
  5211. b = this.b,
  5212. c = this.c;
  5213. var v, w; // algorithm thanks to Real-Time Collision Detection by Christer Ericson,
  5214. // published by Morgan Kaufmann Publishers, (c) 2005 Elsevier Inc.,
  5215. // under the accompanying license; see chapter 5.1.5 for detailed explanation.
  5216. // basically, we're distinguishing which of the voronoi regions of the triangle
  5217. // the point lies in with the minimum amount of redundant computation.
  5218. _vab.subVectors(b, a);
  5219. _vac.subVectors(c, a);
  5220. _vap.subVectors(p, a);
  5221. var d1 = _vab.dot(_vap);
  5222. var d2 = _vac.dot(_vap);
  5223. if (d1 <= 0 && d2 <= 0) {
  5224. // vertex region of A; barycentric coords (1, 0, 0)
  5225. return target.copy(a);
  5226. }
  5227. _vbp.subVectors(p, b);
  5228. var d3 = _vab.dot(_vbp);
  5229. var d4 = _vac.dot(_vbp);
  5230. if (d3 >= 0 && d4 <= d3) {
  5231. // vertex region of B; barycentric coords (0, 1, 0)
  5232. return target.copy(b);
  5233. }
  5234. var vc = d1 * d4 - d3 * d2;
  5235. if (vc <= 0 && d1 >= 0 && d3 <= 0) {
  5236. v = d1 / (d1 - d3); // edge region of AB; barycentric coords (1-v, v, 0)
  5237. return target.copy(a).addScaledVector(_vab, v);
  5238. }
  5239. _vcp.subVectors(p, c);
  5240. var d5 = _vab.dot(_vcp);
  5241. var d6 = _vac.dot(_vcp);
  5242. if (d6 >= 0 && d5 <= d6) {
  5243. // vertex region of C; barycentric coords (0, 0, 1)
  5244. return target.copy(c);
  5245. }
  5246. var vb = d5 * d2 - d1 * d6;
  5247. if (vb <= 0 && d2 >= 0 && d6 <= 0) {
  5248. w = d2 / (d2 - d6); // edge region of AC; barycentric coords (1-w, 0, w)
  5249. return target.copy(a).addScaledVector(_vac, w);
  5250. }
  5251. var va = d3 * d6 - d5 * d4;
  5252. if (va <= 0 && d4 - d3 >= 0 && d5 - d6 >= 0) {
  5253. _vbc.subVectors(c, b);
  5254. w = (d4 - d3) / (d4 - d3 + (d5 - d6)); // edge region of BC; barycentric coords (0, 1-w, w)
  5255. return target.copy(b).addScaledVector(_vbc, w); // edge region of BC
  5256. } // face region
  5257. var denom = 1 / (va + vb + vc); // u = va * denom
  5258. v = vb * denom;
  5259. w = vc * denom;
  5260. return target.copy(a).addScaledVector(_vab, v).addScaledVector(_vac, w);
  5261. },
  5262. equals: function (triangle) {
  5263. return triangle.a.equals(this.a) && triangle.b.equals(this.b) && triangle.c.equals(this.c);
  5264. }
  5265. });
  5266. /**
  5267. * @author mrdoob / http://mrdoob.com/
  5268. */
  5269. var _colorKeywords = {
  5270. 'aliceblue': 0xF0F8FF,
  5271. 'antiquewhite': 0xFAEBD7,
  5272. 'aqua': 0x00FFFF,
  5273. 'aquamarine': 0x7FFFD4,
  5274. 'azure': 0xF0FFFF,
  5275. 'beige': 0xF5F5DC,
  5276. 'bisque': 0xFFE4C4,
  5277. 'black': 0x000000,
  5278. 'blanchedalmond': 0xFFEBCD,
  5279. 'blue': 0x0000FF,
  5280. 'blueviolet': 0x8A2BE2,
  5281. 'brown': 0xA52A2A,
  5282. 'burlywood': 0xDEB887,
  5283. 'cadetblue': 0x5F9EA0,
  5284. 'chartreuse': 0x7FFF00,
  5285. 'chocolate': 0xD2691E,
  5286. 'coral': 0xFF7F50,
  5287. 'cornflowerblue': 0x6495ED,
  5288. 'cornsilk': 0xFFF8DC,
  5289. 'crimson': 0xDC143C,
  5290. 'cyan': 0x00FFFF,
  5291. 'darkblue': 0x00008B,
  5292. 'darkcyan': 0x008B8B,
  5293. 'darkgoldenrod': 0xB8860B,
  5294. 'darkgray': 0xA9A9A9,
  5295. 'darkgreen': 0x006400,
  5296. 'darkgrey': 0xA9A9A9,
  5297. 'darkkhaki': 0xBDB76B,
  5298. 'darkmagenta': 0x8B008B,
  5299. 'darkolivegreen': 0x556B2F,
  5300. 'darkorange': 0xFF8C00,
  5301. 'darkorchid': 0x9932CC,
  5302. 'darkred': 0x8B0000,
  5303. 'darksalmon': 0xE9967A,
  5304. 'darkseagreen': 0x8FBC8F,
  5305. 'darkslateblue': 0x483D8B,
  5306. 'darkslategray': 0x2F4F4F,
  5307. 'darkslategrey': 0x2F4F4F,
  5308. 'darkturquoise': 0x00CED1,
  5309. 'darkviolet': 0x9400D3,
  5310. 'deeppink': 0xFF1493,
  5311. 'deepskyblue': 0x00BFFF,
  5312. 'dimgray': 0x696969,
  5313. 'dimgrey': 0x696969,
  5314. 'dodgerblue': 0x1E90FF,
  5315. 'firebrick': 0xB22222,
  5316. 'floralwhite': 0xFFFAF0,
  5317. 'forestgreen': 0x228B22,
  5318. 'fuchsia': 0xFF00FF,
  5319. 'gainsboro': 0xDCDCDC,
  5320. 'ghostwhite': 0xF8F8FF,
  5321. 'gold': 0xFFD700,
  5322. 'goldenrod': 0xDAA520,
  5323. 'gray': 0x808080,
  5324. 'green': 0x008000,
  5325. 'greenyellow': 0xADFF2F,
  5326. 'grey': 0x808080,
  5327. 'honeydew': 0xF0FFF0,
  5328. 'hotpink': 0xFF69B4,
  5329. 'indianred': 0xCD5C5C,
  5330. 'indigo': 0x4B0082,
  5331. 'ivory': 0xFFFFF0,
  5332. 'khaki': 0xF0E68C,
  5333. 'lavender': 0xE6E6FA,
  5334. 'lavenderblush': 0xFFF0F5,
  5335. 'lawngreen': 0x7CFC00,
  5336. 'lemonchiffon': 0xFFFACD,
  5337. 'lightblue': 0xADD8E6,
  5338. 'lightcoral': 0xF08080,
  5339. 'lightcyan': 0xE0FFFF,
  5340. 'lightgoldenrodyellow': 0xFAFAD2,
  5341. 'lightgray': 0xD3D3D3,
  5342. 'lightgreen': 0x90EE90,
  5343. 'lightgrey': 0xD3D3D3,
  5344. 'lightpink': 0xFFB6C1,
  5345. 'lightsalmon': 0xFFA07A,
  5346. 'lightseagreen': 0x20B2AA,
  5347. 'lightskyblue': 0x87CEFA,
  5348. 'lightslategray': 0x778899,
  5349. 'lightslategrey': 0x778899,
  5350. 'lightsteelblue': 0xB0C4DE,
  5351. 'lightyellow': 0xFFFFE0,
  5352. 'lime': 0x00FF00,
  5353. 'limegreen': 0x32CD32,
  5354. 'linen': 0xFAF0E6,
  5355. 'magenta': 0xFF00FF,
  5356. 'maroon': 0x800000,
  5357. 'mediumaquamarine': 0x66CDAA,
  5358. 'mediumblue': 0x0000CD,
  5359. 'mediumorchid': 0xBA55D3,
  5360. 'mediumpurple': 0x9370DB,
  5361. 'mediumseagreen': 0x3CB371,
  5362. 'mediumslateblue': 0x7B68EE,
  5363. 'mediumspringgreen': 0x00FA9A,
  5364. 'mediumturquoise': 0x48D1CC,
  5365. 'mediumvioletred': 0xC71585,
  5366. 'midnightblue': 0x191970,
  5367. 'mintcream': 0xF5FFFA,
  5368. 'mistyrose': 0xFFE4E1,
  5369. 'moccasin': 0xFFE4B5,
  5370. 'navajowhite': 0xFFDEAD,
  5371. 'navy': 0x000080,
  5372. 'oldlace': 0xFDF5E6,
  5373. 'olive': 0x808000,
  5374. 'olivedrab': 0x6B8E23,
  5375. 'orange': 0xFFA500,
  5376. 'orangered': 0xFF4500,
  5377. 'orchid': 0xDA70D6,
  5378. 'palegoldenrod': 0xEEE8AA,
  5379. 'palegreen': 0x98FB98,
  5380. 'paleturquoise': 0xAFEEEE,
  5381. 'palevioletred': 0xDB7093,
  5382. 'papayawhip': 0xFFEFD5,
  5383. 'peachpuff': 0xFFDAB9,
  5384. 'peru': 0xCD853F,
  5385. 'pink': 0xFFC0CB,
  5386. 'plum': 0xDDA0DD,
  5387. 'powderblue': 0xB0E0E6,
  5388. 'purple': 0x800080,
  5389. 'rebeccapurple': 0x663399,
  5390. 'red': 0xFF0000,
  5391. 'rosybrown': 0xBC8F8F,
  5392. 'royalblue': 0x4169E1,
  5393. 'saddlebrown': 0x8B4513,
  5394. 'salmon': 0xFA8072,
  5395. 'sandybrown': 0xF4A460,
  5396. 'seagreen': 0x2E8B57,
  5397. 'seashell': 0xFFF5EE,
  5398. 'sienna': 0xA0522D,
  5399. 'silver': 0xC0C0C0,
  5400. 'skyblue': 0x87CEEB,
  5401. 'slateblue': 0x6A5ACD,
  5402. 'slategray': 0x708090,
  5403. 'slategrey': 0x708090,
  5404. 'snow': 0xFFFAFA,
  5405. 'springgreen': 0x00FF7F,
  5406. 'steelblue': 0x4682B4,
  5407. 'tan': 0xD2B48C,
  5408. 'teal': 0x008080,
  5409. 'thistle': 0xD8BFD8,
  5410. 'tomato': 0xFF6347,
  5411. 'turquoise': 0x40E0D0,
  5412. 'violet': 0xEE82EE,
  5413. 'wheat': 0xF5DEB3,
  5414. 'white': 0xFFFFFF,
  5415. 'whitesmoke': 0xF5F5F5,
  5416. 'yellow': 0xFFFF00,
  5417. 'yellowgreen': 0x9ACD32
  5418. };
  5419. var _hslA = {
  5420. h: 0,
  5421. s: 0,
  5422. l: 0
  5423. };
  5424. var _hslB = {
  5425. h: 0,
  5426. s: 0,
  5427. l: 0
  5428. };
  5429. function Color(r, g, b) {
  5430. if (g === undefined && b === undefined) {
  5431. // r is THREE.Color, hex or string
  5432. return this.set(r);
  5433. }
  5434. return this.setRGB(r, g, b);
  5435. }
  5436. function hue2rgb(p, q, t) {
  5437. if (t < 0) t += 1;
  5438. if (t > 1) t -= 1;
  5439. if (t < 1 / 6) return p + (q - p) * 6 * t;
  5440. if (t < 1 / 2) return q;
  5441. if (t < 2 / 3) return p + (q - p) * 6 * (2 / 3 - t);
  5442. return p;
  5443. }
  5444. function SRGBToLinear(c) {
  5445. return c < 0.04045 ? c * 0.0773993808 : Math.pow(c * 0.9478672986 + 0.0521327014, 2.4);
  5446. }
  5447. function LinearToSRGB(c) {
  5448. return c < 0.0031308 ? c * 12.92 : 1.055 * Math.pow(c, 0.41666) - 0.055;
  5449. }
  5450. Object.assign(Color.prototype, {
  5451. isColor: true,
  5452. r: 1,
  5453. g: 1,
  5454. b: 1,
  5455. set: function (value) {
  5456. if (value && value.isColor) {
  5457. this.copy(value);
  5458. } else if (typeof value === 'number') {
  5459. this.setHex(value);
  5460. } else if (typeof value === 'string') {
  5461. this.setStyle(value);
  5462. }
  5463. return this;
  5464. },
  5465. setScalar: function (scalar) {
  5466. this.r = scalar;
  5467. this.g = scalar;
  5468. this.b = scalar;
  5469. return this;
  5470. },
  5471. setHex: function (hex) {
  5472. hex = Math.floor(hex);
  5473. this.r = (hex >> 16 & 255) / 255;
  5474. this.g = (hex >> 8 & 255) / 255;
  5475. this.b = (hex & 255) / 255;
  5476. return this;
  5477. },
  5478. setRGB: function (r, g, b) {
  5479. this.r = r;
  5480. this.g = g;
  5481. this.b = b;
  5482. return this;
  5483. },
  5484. setHSL: function (h, s, l) {
  5485. // h,s,l ranges are in 0.0 - 1.0
  5486. h = _Math.euclideanModulo(h, 1);
  5487. s = _Math.clamp(s, 0, 1);
  5488. l = _Math.clamp(l, 0, 1);
  5489. if (s === 0) {
  5490. this.r = this.g = this.b = l;
  5491. } else {
  5492. var p = l <= 0.5 ? l * (1 + s) : l + s - l * s;
  5493. var q = 2 * l - p;
  5494. this.r = hue2rgb(q, p, h + 1 / 3);
  5495. this.g = hue2rgb(q, p, h);
  5496. this.b = hue2rgb(q, p, h - 1 / 3);
  5497. }
  5498. return this;
  5499. },
  5500. setStyle: function (style) {
  5501. function handleAlpha(string) {
  5502. if (string === undefined) return;
  5503. if (parseFloat(string) < 1) {
  5504. console.warn('THREE.Color: Alpha component of ' + style + ' will be ignored.');
  5505. }
  5506. }
  5507. var m;
  5508. if (m = /^((?:rgb|hsl)a?)\(\s*([^\)]*)\)/.exec(style)) {
  5509. // rgb / hsl
  5510. var color;
  5511. var name = m[1];
  5512. var components = m[2];
  5513. switch (name) {
  5514. case 'rgb':
  5515. case 'rgba':
  5516. if (color = /^(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec(components)) {
  5517. // rgb(255,0,0) rgba(255,0,0,0.5)
  5518. this.r = Math.min(255, parseInt(color[1], 10)) / 255;
  5519. this.g = Math.min(255, parseInt(color[2], 10)) / 255;
  5520. this.b = Math.min(255, parseInt(color[3], 10)) / 255;
  5521. handleAlpha(color[5]);
  5522. return this;
  5523. }
  5524. if (color = /^(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec(components)) {
  5525. // rgb(100%,0%,0%) rgba(100%,0%,0%,0.5)
  5526. this.r = Math.min(100, parseInt(color[1], 10)) / 100;
  5527. this.g = Math.min(100, parseInt(color[2], 10)) / 100;
  5528. this.b = Math.min(100, parseInt(color[3], 10)) / 100;
  5529. handleAlpha(color[5]);
  5530. return this;
  5531. }
  5532. break;
  5533. case 'hsl':
  5534. case 'hsla':
  5535. if (color = /^([0-9]*\.?[0-9]+)\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec(components)) {
  5536. // hsl(120,50%,50%) hsla(120,50%,50%,0.5)
  5537. var h = parseFloat(color[1]) / 360;
  5538. var s = parseInt(color[2], 10) / 100;
  5539. var l = parseInt(color[3], 10) / 100;
  5540. handleAlpha(color[5]);
  5541. return this.setHSL(h, s, l);
  5542. }
  5543. break;
  5544. }
  5545. } else if (m = /^\#([A-Fa-f0-9]+)$/.exec(style)) {
  5546. // hex color
  5547. var hex = m[1];
  5548. var size = hex.length;
  5549. if (size === 3) {
  5550. // #ff0
  5551. this.r = parseInt(hex.charAt(0) + hex.charAt(0), 16) / 255;
  5552. this.g = parseInt(hex.charAt(1) + hex.charAt(1), 16) / 255;
  5553. this.b = parseInt(hex.charAt(2) + hex.charAt(2), 16) / 255;
  5554. return this;
  5555. } else if (size === 6) {
  5556. // #ff0000
  5557. this.r = parseInt(hex.charAt(0) + hex.charAt(1), 16) / 255;
  5558. this.g = parseInt(hex.charAt(2) + hex.charAt(3), 16) / 255;
  5559. this.b = parseInt(hex.charAt(4) + hex.charAt(5), 16) / 255;
  5560. return this;
  5561. }
  5562. }
  5563. if (style && style.length > 0) {
  5564. // color keywords
  5565. var hex = _colorKeywords[style];
  5566. if (hex !== undefined) {
  5567. // red
  5568. this.setHex(hex);
  5569. } else {
  5570. // unknown color
  5571. console.warn('THREE.Color: Unknown color ' + style);
  5572. }
  5573. }
  5574. return this;
  5575. },
  5576. clone: function () {
  5577. return new this.constructor(this.r, this.g, this.b);
  5578. },
  5579. copy: function (color) {
  5580. this.r = color.r;
  5581. this.g = color.g;
  5582. this.b = color.b;
  5583. return this;
  5584. },
  5585. copyGammaToLinear: function (color, gammaFactor) {
  5586. if (gammaFactor === undefined) gammaFactor = 2.0;
  5587. this.r = Math.pow(color.r, gammaFactor);
  5588. this.g = Math.pow(color.g, gammaFactor);
  5589. this.b = Math.pow(color.b, gammaFactor);
  5590. return this;
  5591. },
  5592. copyLinearToGamma: function (color, gammaFactor) {
  5593. if (gammaFactor === undefined) gammaFactor = 2.0;
  5594. var safeInverse = gammaFactor > 0 ? 1.0 / gammaFactor : 1.0;
  5595. this.r = Math.pow(color.r, safeInverse);
  5596. this.g = Math.pow(color.g, safeInverse);
  5597. this.b = Math.pow(color.b, safeInverse);
  5598. return this;
  5599. },
  5600. convertGammaToLinear: function (gammaFactor) {
  5601. this.copyGammaToLinear(this, gammaFactor);
  5602. return this;
  5603. },
  5604. convertLinearToGamma: function (gammaFactor) {
  5605. this.copyLinearToGamma(this, gammaFactor);
  5606. return this;
  5607. },
  5608. copySRGBToLinear: function (color) {
  5609. this.r = SRGBToLinear(color.r);
  5610. this.g = SRGBToLinear(color.g);
  5611. this.b = SRGBToLinear(color.b);
  5612. return this;
  5613. },
  5614. copyLinearToSRGB: function (color) {
  5615. this.r = LinearToSRGB(color.r);
  5616. this.g = LinearToSRGB(color.g);
  5617. this.b = LinearToSRGB(color.b);
  5618. return this;
  5619. },
  5620. convertSRGBToLinear: function () {
  5621. this.copySRGBToLinear(this);
  5622. return this;
  5623. },
  5624. convertLinearToSRGB: function () {
  5625. this.copyLinearToSRGB(this);
  5626. return this;
  5627. },
  5628. getHex: function () {
  5629. return this.r * 255 << 16 ^ this.g * 255 << 8 ^ this.b * 255 << 0;
  5630. },
  5631. getHexString: function () {
  5632. return ('000000' + this.getHex().toString(16)).slice(-6);
  5633. },
  5634. getHSL: function (target) {
  5635. // h,s,l ranges are in 0.0 - 1.0
  5636. if (target === undefined) {
  5637. console.warn('THREE.Color: .getHSL() target is now required');
  5638. target = {
  5639. h: 0,
  5640. s: 0,
  5641. l: 0
  5642. };
  5643. }
  5644. var r = this.r,
  5645. g = this.g,
  5646. b = this.b;
  5647. var max = Math.max(r, g, b);
  5648. var min = Math.min(r, g, b);
  5649. var hue, saturation;
  5650. var lightness = (min + max) / 2.0;
  5651. if (min === max) {
  5652. hue = 0;
  5653. saturation = 0;
  5654. } else {
  5655. var delta = max - min;
  5656. saturation = lightness <= 0.5 ? delta / (max + min) : delta / (2 - max - min);
  5657. switch (max) {
  5658. case r:
  5659. hue = (g - b) / delta + (g < b ? 6 : 0);
  5660. break;
  5661. case g:
  5662. hue = (b - r) / delta + 2;
  5663. break;
  5664. case b:
  5665. hue = (r - g) / delta + 4;
  5666. break;
  5667. }
  5668. hue /= 6;
  5669. }
  5670. target.h = hue;
  5671. target.s = saturation;
  5672. target.l = lightness;
  5673. return target;
  5674. },
  5675. getStyle: function () {
  5676. return 'rgb(' + (this.r * 255 | 0) + ',' + (this.g * 255 | 0) + ',' + (this.b * 255 | 0) + ')';
  5677. },
  5678. offsetHSL: function (h, s, l) {
  5679. this.getHSL(_hslA);
  5680. _hslA.h += h;
  5681. _hslA.s += s;
  5682. _hslA.l += l;
  5683. this.setHSL(_hslA.h, _hslA.s, _hslA.l);
  5684. return this;
  5685. },
  5686. add: function (color) {
  5687. this.r += color.r;
  5688. this.g += color.g;
  5689. this.b += color.b;
  5690. return this;
  5691. },
  5692. addColors: function (color1, color2) {
  5693. this.r = color1.r + color2.r;
  5694. this.g = color1.g + color2.g;
  5695. this.b = color1.b + color2.b;
  5696. return this;
  5697. },
  5698. addScalar: function (s) {
  5699. this.r += s;
  5700. this.g += s;
  5701. this.b += s;
  5702. return this;
  5703. },
  5704. sub: function (color) {
  5705. this.r = Math.max(0, this.r - color.r);
  5706. this.g = Math.max(0, this.g - color.g);
  5707. this.b = Math.max(0, this.b - color.b);
  5708. return this;
  5709. },
  5710. multiply: function (color) {
  5711. this.r *= color.r;
  5712. this.g *= color.g;
  5713. this.b *= color.b;
  5714. return this;
  5715. },
  5716. multiplyScalar: function (s) {
  5717. this.r *= s;
  5718. this.g *= s;
  5719. this.b *= s;
  5720. return this;
  5721. },
  5722. lerp: function (color, alpha) {
  5723. this.r += (color.r - this.r) * alpha;
  5724. this.g += (color.g - this.g) * alpha;
  5725. this.b += (color.b - this.b) * alpha;
  5726. return this;
  5727. },
  5728. lerpHSL: function (color, alpha) {
  5729. this.getHSL(_hslA);
  5730. color.getHSL(_hslB);
  5731. var h = _Math.lerp(_hslA.h, _hslB.h, alpha);
  5732. var s = _Math.lerp(_hslA.s, _hslB.s, alpha);
  5733. var l = _Math.lerp(_hslA.l, _hslB.l, alpha);
  5734. this.setHSL(h, s, l);
  5735. return this;
  5736. },
  5737. equals: function (c) {
  5738. return c.r === this.r && c.g === this.g && c.b === this.b;
  5739. },
  5740. fromArray: function (array, offset) {
  5741. if (offset === undefined) offset = 0;
  5742. this.r = array[offset];
  5743. this.g = array[offset + 1];
  5744. this.b = array[offset + 2];
  5745. return this;
  5746. },
  5747. toArray: function (array, offset) {
  5748. if (array === undefined) array = [];
  5749. if (offset === undefined) offset = 0;
  5750. array[offset] = this.r;
  5751. array[offset + 1] = this.g;
  5752. array[offset + 2] = this.b;
  5753. return array;
  5754. },
  5755. toJSON: function () {
  5756. return this.getHex();
  5757. }
  5758. });
  5759. /**
  5760. * @author mrdoob / http://mrdoob.com/
  5761. * @author alteredq / http://alteredqualia.com/
  5762. */
  5763. function Face3(a, b, c, normal, color, materialIndex) {
  5764. this.a = a;
  5765. this.b = b;
  5766. this.c = c;
  5767. this.normal = normal && normal.isVector3 ? normal : new Vector3();
  5768. this.vertexNormals = Array.isArray(normal) ? normal : [];
  5769. this.color = color && color.isColor ? color : new Color();
  5770. this.vertexColors = Array.isArray(color) ? color : [];
  5771. this.materialIndex = materialIndex !== undefined ? materialIndex : 0;
  5772. }
  5773. Object.assign(Face3.prototype, {
  5774. clone: function () {
  5775. return new this.constructor().copy(this);
  5776. },
  5777. copy: function (source) {
  5778. this.a = source.a;
  5779. this.b = source.b;
  5780. this.c = source.c;
  5781. this.normal.copy(source.normal);
  5782. this.color.copy(source.color);
  5783. this.materialIndex = source.materialIndex;
  5784. for (var i = 0, il = source.vertexNormals.length; i < il; i++) {
  5785. this.vertexNormals[i] = source.vertexNormals[i].clone();
  5786. }
  5787. for (var i = 0, il = source.vertexColors.length; i < il; i++) {
  5788. this.vertexColors[i] = source.vertexColors[i].clone();
  5789. }
  5790. return this;
  5791. }
  5792. });
  5793. /**
  5794. * @author mrdoob / http://mrdoob.com/
  5795. * @author alteredq / http://alteredqualia.com/
  5796. */
  5797. var materialId = 0;
  5798. function Material() {
  5799. Object.defineProperty(this, 'id', {
  5800. value: materialId++
  5801. });
  5802. this.uuid = _Math.generateUUID();
  5803. this.name = '';
  5804. this.type = 'Material';
  5805. this.fog = true;
  5806. this.blending = NormalBlending;
  5807. this.side = FrontSide;
  5808. this.flatShading = false;
  5809. this.vertexTangents = false;
  5810. this.vertexColors = NoColors; // THREE.NoColors, THREE.VertexColors, THREE.FaceColors
  5811. this.opacity = 1;
  5812. this.transparent = false;
  5813. this.blendSrc = SrcAlphaFactor;
  5814. this.blendDst = OneMinusSrcAlphaFactor;
  5815. this.blendEquation = AddEquation;
  5816. this.blendSrcAlpha = null;
  5817. this.blendDstAlpha = null;
  5818. this.blendEquationAlpha = null;
  5819. this.depthFunc = LessEqualDepth;
  5820. this.depthTest = true;
  5821. this.depthWrite = true;
  5822. this.stencilWriteMask = 0xff;
  5823. this.stencilFunc = AlwaysStencilFunc;
  5824. this.stencilRef = 0;
  5825. this.stencilFuncMask = 0xff;
  5826. this.stencilFail = KeepStencilOp;
  5827. this.stencilZFail = KeepStencilOp;
  5828. this.stencilZPass = KeepStencilOp;
  5829. this.stencilWrite = false;
  5830. this.clippingPlanes = null;
  5831. this.clipIntersection = false;
  5832. this.clipShadows = false;
  5833. this.shadowSide = null;
  5834. this.colorWrite = true;
  5835. this.precision = null; // override the renderer's default precision for this material
  5836. this.polygonOffset = false;
  5837. this.polygonOffsetFactor = 0;
  5838. this.polygonOffsetUnits = 0;
  5839. this.dithering = false;
  5840. this.alphaTest = 0;
  5841. this.premultipliedAlpha = false;
  5842. this.visible = true;
  5843. this.toneMapped = true;
  5844. this.userData = {};
  5845. this.needsUpdate = true;
  5846. }
  5847. Material.prototype = Object.assign(Object.create(EventDispatcher.prototype), {
  5848. constructor: Material,
  5849. isMaterial: true,
  5850. onBeforeCompile: function () {},
  5851. setValues: function (values) {
  5852. if (values === undefined) return;
  5853. for (var key in values) {
  5854. var newValue = values[key];
  5855. if (newValue === undefined) {
  5856. console.warn("THREE.Material: '" + key + "' parameter is undefined.");
  5857. continue;
  5858. } // for backward compatability if shading is set in the constructor
  5859. if (key === 'shading') {
  5860. console.warn('THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.');
  5861. this.flatShading = newValue === FlatShading ? true : false;
  5862. continue;
  5863. }
  5864. var currentValue = this[key];
  5865. if (currentValue === undefined) {
  5866. console.warn("THREE." + this.type + ": '" + key + "' is not a property of this material.");
  5867. continue;
  5868. }
  5869. if (currentValue && currentValue.isColor) {
  5870. currentValue.set(newValue);
  5871. } else if (currentValue && currentValue.isVector3 && newValue && newValue.isVector3) {
  5872. currentValue.copy(newValue);
  5873. } else {
  5874. this[key] = newValue;
  5875. }
  5876. }
  5877. },
  5878. toJSON: function (meta) {
  5879. var isRoot = meta === undefined || typeof meta === 'string';
  5880. if (isRoot) {
  5881. meta = {
  5882. textures: {},
  5883. images: {}
  5884. };
  5885. }
  5886. var data = {
  5887. metadata: {
  5888. version: 4.5,
  5889. type: 'Material',
  5890. generator: 'Material.toJSON'
  5891. }
  5892. }; // standard Material serialization
  5893. data.uuid = this.uuid;
  5894. data.type = this.type;
  5895. if (this.name !== '') data.name = this.name;
  5896. if (this.color && this.color.isColor) data.color = this.color.getHex();
  5897. if (this.roughness !== undefined) data.roughness = this.roughness;
  5898. if (this.metalness !== undefined) data.metalness = this.metalness;
  5899. if (this.sheen && this.sheen.isColor) data.sheen = this.sheen.getHex();
  5900. if (this.emissive && this.emissive.isColor) data.emissive = this.emissive.getHex();
  5901. if (this.emissiveIntensity && this.emissiveIntensity !== 1) data.emissiveIntensity = this.emissiveIntensity;
  5902. if (this.specular && this.specular.isColor) data.specular = this.specular.getHex();
  5903. if (this.shininess !== undefined) data.shininess = this.shininess;
  5904. if (this.clearcoat !== undefined) data.clearcoat = this.clearcoat;
  5905. if (this.clearcoatRoughness !== undefined) data.clearcoatRoughness = this.clearcoatRoughness;
  5906. if (this.clearcoatNormalMap && this.clearcoatNormalMap.isTexture) {
  5907. data.clearcoatNormalMap = this.clearcoatNormalMap.toJSON(meta).uuid;
  5908. data.clearcoatNormalScale = this.clearcoatNormalScale.toArray();
  5909. }
  5910. if (this.map && this.map.isTexture) data.map = this.map.toJSON(meta).uuid;
  5911. if (this.matcap && this.matcap.isTexture) data.matcap = this.matcap.toJSON(meta).uuid;
  5912. if (this.alphaMap && this.alphaMap.isTexture) data.alphaMap = this.alphaMap.toJSON(meta).uuid;
  5913. if (this.lightMap && this.lightMap.isTexture) data.lightMap = this.lightMap.toJSON(meta).uuid;
  5914. if (this.aoMap && this.aoMap.isTexture) {
  5915. data.aoMap = this.aoMap.toJSON(meta).uuid;
  5916. data.aoMapIntensity = this.aoMapIntensity;
  5917. }
  5918. if (this.bumpMap && this.bumpMap.isTexture) {
  5919. data.bumpMap = this.bumpMap.toJSON(meta).uuid;
  5920. data.bumpScale = this.bumpScale;
  5921. }
  5922. if (this.normalMap && this.normalMap.isTexture) {
  5923. data.normalMap = this.normalMap.toJSON(meta).uuid;
  5924. data.normalMapType = this.normalMapType;
  5925. data.normalScale = this.normalScale.toArray();
  5926. }
  5927. if (this.displacementMap && this.displacementMap.isTexture) {
  5928. data.displacementMap = this.displacementMap.toJSON(meta).uuid;
  5929. data.displacementScale = this.displacementScale;
  5930. data.displacementBias = this.displacementBias;
  5931. }
  5932. if (this.roughnessMap && this.roughnessMap.isTexture) data.roughnessMap = this.roughnessMap.toJSON(meta).uuid;
  5933. if (this.metalnessMap && this.metalnessMap.isTexture) data.metalnessMap = this.metalnessMap.toJSON(meta).uuid;
  5934. if (this.emissiveMap && this.emissiveMap.isTexture) data.emissiveMap = this.emissiveMap.toJSON(meta).uuid;
  5935. if (this.specularMap && this.specularMap.isTexture) data.specularMap = this.specularMap.toJSON(meta).uuid;
  5936. if (this.envMap && this.envMap.isTexture) {
  5937. data.envMap = this.envMap.toJSON(meta).uuid;
  5938. data.reflectivity = this.reflectivity; // Scale behind envMap
  5939. data.refractionRatio = this.refractionRatio;
  5940. if (this.combine !== undefined) data.combine = this.combine;
  5941. if (this.envMapIntensity !== undefined) data.envMapIntensity = this.envMapIntensity;
  5942. }
  5943. if (this.gradientMap && this.gradientMap.isTexture) {
  5944. data.gradientMap = this.gradientMap.toJSON(meta).uuid;
  5945. }
  5946. if (this.size !== undefined) data.size = this.size;
  5947. if (this.sizeAttenuation !== undefined) data.sizeAttenuation = this.sizeAttenuation;
  5948. if (this.blending !== NormalBlending) data.blending = this.blending;
  5949. if (this.flatShading === true) data.flatShading = this.flatShading;
  5950. if (this.side !== FrontSide) data.side = this.side;
  5951. if (this.vertexColors !== NoColors) data.vertexColors = this.vertexColors;
  5952. if (this.opacity < 1) data.opacity = this.opacity;
  5953. if (this.transparent === true) data.transparent = this.transparent;
  5954. data.depthFunc = this.depthFunc;
  5955. data.depthTest = this.depthTest;
  5956. data.depthWrite = this.depthWrite;
  5957. data.stencilWrite = this.stencilWrite;
  5958. data.stencilWriteMask = this.stencilWriteMask;
  5959. data.stencilFunc = this.stencilFunc;
  5960. data.stencilRef = this.stencilRef;
  5961. data.stencilFuncMask = this.stencilFuncMask;
  5962. data.stencilFail = this.stencilFail;
  5963. data.stencilZFail = this.stencilZFail;
  5964. data.stencilZPass = this.stencilZPass; // rotation (SpriteMaterial)
  5965. if (this.rotation && this.rotation !== 0) data.rotation = this.rotation;
  5966. if (this.polygonOffset === true) data.polygonOffset = true;
  5967. if (this.polygonOffsetFactor !== 0) data.polygonOffsetFactor = this.polygonOffsetFactor;
  5968. if (this.polygonOffsetUnits !== 0) data.polygonOffsetUnits = this.polygonOffsetUnits;
  5969. if (this.linewidth && this.linewidth !== 1) data.linewidth = this.linewidth;
  5970. if (this.dashSize !== undefined) data.dashSize = this.dashSize;
  5971. if (this.gapSize !== undefined) data.gapSize = this.gapSize;
  5972. if (this.scale !== undefined) data.scale = this.scale;
  5973. if (this.dithering === true) data.dithering = true;
  5974. if (this.alphaTest > 0) data.alphaTest = this.alphaTest;
  5975. if (this.premultipliedAlpha === true) data.premultipliedAlpha = this.premultipliedAlpha;
  5976. if (this.wireframe === true) data.wireframe = this.wireframe;
  5977. if (this.wireframeLinewidth > 1) data.wireframeLinewidth = this.wireframeLinewidth;
  5978. if (this.wireframeLinecap !== 'round') data.wireframeLinecap = this.wireframeLinecap;
  5979. if (this.wireframeLinejoin !== 'round') data.wireframeLinejoin = this.wireframeLinejoin;
  5980. if (this.morphTargets === true) data.morphTargets = true;
  5981. if (this.morphNormals === true) data.morphNormals = true;
  5982. if (this.skinning === true) data.skinning = true;
  5983. if (this.visible === false) data.visible = false;
  5984. if (this.toneMapped === false) data.toneMapped = false;
  5985. if (JSON.stringify(this.userData) !== '{}') data.userData = this.userData; // TODO: Copied from Object3D.toJSON
  5986. function extractFromCache(cache) {
  5987. var values = [];
  5988. for (var key in cache) {
  5989. var data = cache[key];
  5990. delete data.metadata;
  5991. values.push(data);
  5992. }
  5993. return values;
  5994. }
  5995. if (isRoot) {
  5996. var textures = extractFromCache(meta.textures);
  5997. var images = extractFromCache(meta.images);
  5998. if (textures.length > 0) data.textures = textures;
  5999. if (images.length > 0) data.images = images;
  6000. }
  6001. return data;
  6002. },
  6003. clone: function () {
  6004. return new this.constructor().copy(this);
  6005. },
  6006. copy: function (source) {
  6007. this.name = source.name;
  6008. this.fog = source.fog;
  6009. this.blending = source.blending;
  6010. this.side = source.side;
  6011. this.flatShading = source.flatShading;
  6012. this.vertexColors = source.vertexColors;
  6013. this.opacity = source.opacity;
  6014. this.transparent = source.transparent;
  6015. this.blendSrc = source.blendSrc;
  6016. this.blendDst = source.blendDst;
  6017. this.blendEquation = source.blendEquation;
  6018. this.blendSrcAlpha = source.blendSrcAlpha;
  6019. this.blendDstAlpha = source.blendDstAlpha;
  6020. this.blendEquationAlpha = source.blendEquationAlpha;
  6021. this.depthFunc = source.depthFunc;
  6022. this.depthTest = source.depthTest;
  6023. this.depthWrite = source.depthWrite;
  6024. this.stencilWrite = source.stencilWrite;
  6025. this.stencilWriteMask = source.stencilWriteMask;
  6026. this.stencilFunc = source.stencilFunc;
  6027. this.stencilRef = source.stencilRef;
  6028. this.stencilFuncMask = source.stencilFuncMask;
  6029. this.stencilFail = source.stencilFail;
  6030. this.stencilZFail = source.stencilZFail;
  6031. this.stencilZPass = source.stencilZPass;
  6032. this.colorWrite = source.colorWrite;
  6033. this.precision = source.precision;
  6034. this.polygonOffset = source.polygonOffset;
  6035. this.polygonOffsetFactor = source.polygonOffsetFactor;
  6036. this.polygonOffsetUnits = source.polygonOffsetUnits;
  6037. this.dithering = source.dithering;
  6038. this.alphaTest = source.alphaTest;
  6039. this.premultipliedAlpha = source.premultipliedAlpha;
  6040. this.visible = source.visible;
  6041. this.toneMapped = source.toneMapped;
  6042. this.userData = JSON.parse(JSON.stringify(source.userData));
  6043. this.clipShadows = source.clipShadows;
  6044. this.clipIntersection = source.clipIntersection;
  6045. var srcPlanes = source.clippingPlanes,
  6046. dstPlanes = null;
  6047. if (srcPlanes !== null) {
  6048. var n = srcPlanes.length;
  6049. dstPlanes = new Array(n);
  6050. for (var i = 0; i !== n; ++i) dstPlanes[i] = srcPlanes[i].clone();
  6051. }
  6052. this.clippingPlanes = dstPlanes;
  6053. this.shadowSide = source.shadowSide;
  6054. return this;
  6055. },
  6056. dispose: function () {
  6057. this.dispatchEvent({
  6058. type: 'dispose'
  6059. });
  6060. }
  6061. });
  6062. /**
  6063. * @author mrdoob / http://mrdoob.com/
  6064. * @author alteredq / http://alteredqualia.com/
  6065. *
  6066. * parameters = {
  6067. * color: <hex>,
  6068. * opacity: <float>,
  6069. * map: new THREE.Texture( <Image> ),
  6070. *
  6071. * lightMap: new THREE.Texture( <Image> ),
  6072. * lightMapIntensity: <float>
  6073. *
  6074. * aoMap: new THREE.Texture( <Image> ),
  6075. * aoMapIntensity: <float>
  6076. *
  6077. * specularMap: new THREE.Texture( <Image> ),
  6078. *
  6079. * alphaMap: new THREE.Texture( <Image> ),
  6080. *
  6081. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  6082. * combine: THREE.Multiply,
  6083. * reflectivity: <float>,
  6084. * refractionRatio: <float>,
  6085. *
  6086. * depthTest: <bool>,
  6087. * depthWrite: <bool>,
  6088. *
  6089. * wireframe: <boolean>,
  6090. * wireframeLinewidth: <float>,
  6091. *
  6092. * skinning: <bool>,
  6093. * morphTargets: <bool>
  6094. * }
  6095. */
  6096. function MeshBasicMaterial(parameters) {
  6097. Material.call(this);
  6098. this.type = 'MeshBasicMaterial';
  6099. this.color = new Color(0xffffff); // emissive
  6100. this.map = null;
  6101. this.lightMap = null;
  6102. this.lightMapIntensity = 1.0;
  6103. this.aoMap = null;
  6104. this.aoMapIntensity = 1.0;
  6105. this.specularMap = null;
  6106. this.alphaMap = null;
  6107. this.envMap = null;
  6108. this.combine = MultiplyOperation;
  6109. this.reflectivity = 1;
  6110. this.refractionRatio = 0.98;
  6111. this.wireframe = false;
  6112. this.wireframeLinewidth = 1;
  6113. this.wireframeLinecap = 'round';
  6114. this.wireframeLinejoin = 'round';
  6115. this.skinning = false;
  6116. this.morphTargets = false;
  6117. this.setValues(parameters);
  6118. }
  6119. MeshBasicMaterial.prototype = Object.create(Material.prototype);
  6120. MeshBasicMaterial.prototype.constructor = MeshBasicMaterial;
  6121. MeshBasicMaterial.prototype.isMeshBasicMaterial = true;
  6122. MeshBasicMaterial.prototype.copy = function (source) {
  6123. Material.prototype.copy.call(this, source);
  6124. this.color.copy(source.color);
  6125. this.map = source.map;
  6126. this.lightMap = source.lightMap;
  6127. this.lightMapIntensity = source.lightMapIntensity;
  6128. this.aoMap = source.aoMap;
  6129. this.aoMapIntensity = source.aoMapIntensity;
  6130. this.specularMap = source.specularMap;
  6131. this.alphaMap = source.alphaMap;
  6132. this.envMap = source.envMap;
  6133. this.combine = source.combine;
  6134. this.reflectivity = source.reflectivity;
  6135. this.refractionRatio = source.refractionRatio;
  6136. this.wireframe = source.wireframe;
  6137. this.wireframeLinewidth = source.wireframeLinewidth;
  6138. this.wireframeLinecap = source.wireframeLinecap;
  6139. this.wireframeLinejoin = source.wireframeLinejoin;
  6140. this.skinning = source.skinning;
  6141. this.morphTargets = source.morphTargets;
  6142. return this;
  6143. };
  6144. /**
  6145. * @author mrdoob / http://mrdoob.com/
  6146. */
  6147. function BufferAttribute(array, itemSize, normalized) {
  6148. if (Array.isArray(array)) {
  6149. throw new TypeError('THREE.BufferAttribute: array should be a Typed Array.');
  6150. }
  6151. this.name = '';
  6152. this.array = array;
  6153. this.itemSize = itemSize;
  6154. this.count = array !== undefined ? array.length / itemSize : 0;
  6155. this.normalized = normalized === true;
  6156. this.dynamic = false;
  6157. this.updateRange = {
  6158. offset: 0,
  6159. count: -1
  6160. };
  6161. this.version = 0;
  6162. }
  6163. Object.defineProperty(BufferAttribute.prototype, 'needsUpdate', {
  6164. set: function (value) {
  6165. if (value === true) this.version++;
  6166. }
  6167. });
  6168. Object.assign(BufferAttribute.prototype, {
  6169. isBufferAttribute: true,
  6170. onUploadCallback: function () {},
  6171. setDynamic: function (value) {
  6172. this.dynamic = value;
  6173. return this;
  6174. },
  6175. copy: function (source) {
  6176. this.name = source.name;
  6177. this.array = new source.array.constructor(source.array);
  6178. this.itemSize = source.itemSize;
  6179. this.count = source.count;
  6180. this.normalized = source.normalized;
  6181. this.dynamic = source.dynamic;
  6182. return this;
  6183. },
  6184. copyAt: function (index1, attribute, index2) {
  6185. index1 *= this.itemSize;
  6186. index2 *= attribute.itemSize;
  6187. for (var i = 0, l = this.itemSize; i < l; i++) {
  6188. this.array[index1 + i] = attribute.array[index2 + i];
  6189. }
  6190. return this;
  6191. },
  6192. copyArray: function (array) {
  6193. this.array.set(array);
  6194. return this;
  6195. },
  6196. copyColorsArray: function (colors) {
  6197. var array = this.array,
  6198. offset = 0;
  6199. for (var i = 0, l = colors.length; i < l; i++) {
  6200. var color = colors[i];
  6201. if (color === undefined) {
  6202. console.warn('THREE.BufferAttribute.copyColorsArray(): color is undefined', i);
  6203. color = new Color();
  6204. }
  6205. array[offset++] = color.r;
  6206. array[offset++] = color.g;
  6207. array[offset++] = color.b;
  6208. }
  6209. return this;
  6210. },
  6211. copyVector2sArray: function (vectors) {
  6212. var array = this.array,
  6213. offset = 0;
  6214. for (var i = 0, l = vectors.length; i < l; i++) {
  6215. var vector = vectors[i];
  6216. if (vector === undefined) {
  6217. console.warn('THREE.BufferAttribute.copyVector2sArray(): vector is undefined', i);
  6218. vector = new Vector2();
  6219. }
  6220. array[offset++] = vector.x;
  6221. array[offset++] = vector.y;
  6222. }
  6223. return this;
  6224. },
  6225. copyVector3sArray: function (vectors) {
  6226. var array = this.array,
  6227. offset = 0;
  6228. for (var i = 0, l = vectors.length; i < l; i++) {
  6229. var vector = vectors[i];
  6230. if (vector === undefined) {
  6231. console.warn('THREE.BufferAttribute.copyVector3sArray(): vector is undefined', i);
  6232. vector = new Vector3();
  6233. }
  6234. array[offset++] = vector.x;
  6235. array[offset++] = vector.y;
  6236. array[offset++] = vector.z;
  6237. }
  6238. return this;
  6239. },
  6240. copyVector4sArray: function (vectors) {
  6241. var array = this.array,
  6242. offset = 0;
  6243. for (var i = 0, l = vectors.length; i < l; i++) {
  6244. var vector = vectors[i];
  6245. if (vector === undefined) {
  6246. console.warn('THREE.BufferAttribute.copyVector4sArray(): vector is undefined', i);
  6247. vector = new Vector4();
  6248. }
  6249. array[offset++] = vector.x;
  6250. array[offset++] = vector.y;
  6251. array[offset++] = vector.z;
  6252. array[offset++] = vector.w;
  6253. }
  6254. return this;
  6255. },
  6256. set: function (value, offset) {
  6257. if (offset === undefined) offset = 0;
  6258. this.array.set(value, offset);
  6259. return this;
  6260. },
  6261. getX: function (index) {
  6262. return this.array[index * this.itemSize];
  6263. },
  6264. setX: function (index, x) {
  6265. this.array[index * this.itemSize] = x;
  6266. return this;
  6267. },
  6268. getY: function (index) {
  6269. return this.array[index * this.itemSize + 1];
  6270. },
  6271. setY: function (index, y) {
  6272. this.array[index * this.itemSize + 1] = y;
  6273. return this;
  6274. },
  6275. getZ: function (index) {
  6276. return this.array[index * this.itemSize + 2];
  6277. },
  6278. setZ: function (index, z) {
  6279. this.array[index * this.itemSize + 2] = z;
  6280. return this;
  6281. },
  6282. getW: function (index) {
  6283. return this.array[index * this.itemSize + 3];
  6284. },
  6285. setW: function (index, w) {
  6286. this.array[index * this.itemSize + 3] = w;
  6287. return this;
  6288. },
  6289. setXY: function (index, x, y) {
  6290. index *= this.itemSize;
  6291. this.array[index + 0] = x;
  6292. this.array[index + 1] = y;
  6293. return this;
  6294. },
  6295. setXYZ: function (index, x, y, z) {
  6296. index *= this.itemSize;
  6297. this.array[index + 0] = x;
  6298. this.array[index + 1] = y;
  6299. this.array[index + 2] = z;
  6300. return this;
  6301. },
  6302. setXYZW: function (index, x, y, z, w) {
  6303. index *= this.itemSize;
  6304. this.array[index + 0] = x;
  6305. this.array[index + 1] = y;
  6306. this.array[index + 2] = z;
  6307. this.array[index + 3] = w;
  6308. return this;
  6309. },
  6310. onUpload: function (callback) {
  6311. this.onUploadCallback = callback;
  6312. return this;
  6313. },
  6314. clone: function () {
  6315. return new this.constructor(this.array, this.itemSize).copy(this);
  6316. },
  6317. toJSON: function () {
  6318. return {
  6319. itemSize: this.itemSize,
  6320. type: this.array.constructor.name,
  6321. array: Array.prototype.slice.call(this.array),
  6322. normalized: this.normalized
  6323. };
  6324. }
  6325. }); //
  6326. function Int8BufferAttribute(array, itemSize, normalized) {
  6327. BufferAttribute.call(this, new Int8Array(array), itemSize, normalized);
  6328. }
  6329. Int8BufferAttribute.prototype = Object.create(BufferAttribute.prototype);
  6330. Int8BufferAttribute.prototype.constructor = Int8BufferAttribute;
  6331. function Uint8BufferAttribute(array, itemSize, normalized) {
  6332. BufferAttribute.call(this, new Uint8Array(array), itemSize, normalized);
  6333. }
  6334. Uint8BufferAttribute.prototype = Object.create(BufferAttribute.prototype);
  6335. Uint8BufferAttribute.prototype.constructor = Uint8BufferAttribute;
  6336. function Uint8ClampedBufferAttribute(array, itemSize, normalized) {
  6337. BufferAttribute.call(this, new Uint8ClampedArray(array), itemSize, normalized);
  6338. }
  6339. Uint8ClampedBufferAttribute.prototype = Object.create(BufferAttribute.prototype);
  6340. Uint8ClampedBufferAttribute.prototype.constructor = Uint8ClampedBufferAttribute;
  6341. function Int16BufferAttribute(array, itemSize, normalized) {
  6342. BufferAttribute.call(this, new Int16Array(array), itemSize, normalized);
  6343. }
  6344. Int16BufferAttribute.prototype = Object.create(BufferAttribute.prototype);
  6345. Int16BufferAttribute.prototype.constructor = Int16BufferAttribute;
  6346. function Uint16BufferAttribute(array, itemSize, normalized) {
  6347. BufferAttribute.call(this, new Uint16Array(array), itemSize, normalized);
  6348. }
  6349. Uint16BufferAttribute.prototype = Object.create(BufferAttribute.prototype);
  6350. Uint16BufferAttribute.prototype.constructor = Uint16BufferAttribute;
  6351. function Int32BufferAttribute(array, itemSize, normalized) {
  6352. BufferAttribute.call(this, new Int32Array(array), itemSize, normalized);
  6353. }
  6354. Int32BufferAttribute.prototype = Object.create(BufferAttribute.prototype);
  6355. Int32BufferAttribute.prototype.constructor = Int32BufferAttribute;
  6356. function Uint32BufferAttribute(array, itemSize, normalized) {
  6357. BufferAttribute.call(this, new Uint32Array(array), itemSize, normalized);
  6358. }
  6359. Uint32BufferAttribute.prototype = Object.create(BufferAttribute.prototype);
  6360. Uint32BufferAttribute.prototype.constructor = Uint32BufferAttribute;
  6361. function Float32BufferAttribute(array, itemSize, normalized) {
  6362. BufferAttribute.call(this, new Float32Array(array), itemSize, normalized);
  6363. }
  6364. Float32BufferAttribute.prototype = Object.create(BufferAttribute.prototype);
  6365. Float32BufferAttribute.prototype.constructor = Float32BufferAttribute;
  6366. function Float64BufferAttribute(array, itemSize, normalized) {
  6367. BufferAttribute.call(this, new Float64Array(array), itemSize, normalized);
  6368. }
  6369. Float64BufferAttribute.prototype = Object.create(BufferAttribute.prototype);
  6370. Float64BufferAttribute.prototype.constructor = Float64BufferAttribute;
  6371. /**
  6372. * @author mrdoob / http://mrdoob.com/
  6373. */
  6374. function DirectGeometry() {
  6375. this.vertices = [];
  6376. this.normals = [];
  6377. this.colors = [];
  6378. this.uvs = [];
  6379. this.uvs2 = [];
  6380. this.groups = [];
  6381. this.morphTargets = {};
  6382. this.skinWeights = [];
  6383. this.skinIndices = []; // this.lineDistances = [];
  6384. this.boundingBox = null;
  6385. this.boundingSphere = null; // update flags
  6386. this.verticesNeedUpdate = false;
  6387. this.normalsNeedUpdate = false;
  6388. this.colorsNeedUpdate = false;
  6389. this.uvsNeedUpdate = false;
  6390. this.groupsNeedUpdate = false;
  6391. }
  6392. Object.assign(DirectGeometry.prototype, {
  6393. computeGroups: function (geometry) {
  6394. var group;
  6395. var groups = [];
  6396. var materialIndex = undefined;
  6397. var faces = geometry.faces;
  6398. for (var i = 0; i < faces.length; i++) {
  6399. var face = faces[i]; // materials
  6400. if (face.materialIndex !== materialIndex) {
  6401. materialIndex = face.materialIndex;
  6402. if (group !== undefined) {
  6403. group.count = i * 3 - group.start;
  6404. groups.push(group);
  6405. }
  6406. group = {
  6407. start: i * 3,
  6408. materialIndex: materialIndex
  6409. };
  6410. }
  6411. }
  6412. if (group !== undefined) {
  6413. group.count = i * 3 - group.start;
  6414. groups.push(group);
  6415. }
  6416. this.groups = groups;
  6417. },
  6418. fromGeometry: function (geometry) {
  6419. var faces = geometry.faces;
  6420. var vertices = geometry.vertices;
  6421. var faceVertexUvs = geometry.faceVertexUvs;
  6422. var hasFaceVertexUv = faceVertexUvs[0] && faceVertexUvs[0].length > 0;
  6423. var hasFaceVertexUv2 = faceVertexUvs[1] && faceVertexUvs[1].length > 0; // morphs
  6424. var morphTargets = geometry.morphTargets;
  6425. var morphTargetsLength = morphTargets.length;
  6426. var morphTargetsPosition;
  6427. if (morphTargetsLength > 0) {
  6428. morphTargetsPosition = [];
  6429. for (var i = 0; i < morphTargetsLength; i++) {
  6430. morphTargetsPosition[i] = {
  6431. name: morphTargets[i].name,
  6432. data: []
  6433. };
  6434. }
  6435. this.morphTargets.position = morphTargetsPosition;
  6436. }
  6437. var morphNormals = geometry.morphNormals;
  6438. var morphNormalsLength = morphNormals.length;
  6439. var morphTargetsNormal;
  6440. if (morphNormalsLength > 0) {
  6441. morphTargetsNormal = [];
  6442. for (var i = 0; i < morphNormalsLength; i++) {
  6443. morphTargetsNormal[i] = {
  6444. name: morphNormals[i].name,
  6445. data: []
  6446. };
  6447. }
  6448. this.morphTargets.normal = morphTargetsNormal;
  6449. } // skins
  6450. var skinIndices = geometry.skinIndices;
  6451. var skinWeights = geometry.skinWeights;
  6452. var hasSkinIndices = skinIndices.length === vertices.length;
  6453. var hasSkinWeights = skinWeights.length === vertices.length; //
  6454. if (vertices.length > 0 && faces.length === 0) {
  6455. console.error('THREE.DirectGeometry: Faceless geometries are not supported.');
  6456. }
  6457. for (var i = 0; i < faces.length; i++) {
  6458. var face = faces[i];
  6459. this.vertices.push(vertices[face.a], vertices[face.b], vertices[face.c]);
  6460. var vertexNormals = face.vertexNormals;
  6461. if (vertexNormals.length === 3) {
  6462. this.normals.push(vertexNormals[0], vertexNormals[1], vertexNormals[2]);
  6463. } else {
  6464. var normal = face.normal;
  6465. this.normals.push(normal, normal, normal);
  6466. }
  6467. var vertexColors = face.vertexColors;
  6468. if (vertexColors.length === 3) {
  6469. this.colors.push(vertexColors[0], vertexColors[1], vertexColors[2]);
  6470. } else {
  6471. var color = face.color;
  6472. this.colors.push(color, color, color);
  6473. }
  6474. if (hasFaceVertexUv === true) {
  6475. var vertexUvs = faceVertexUvs[0][i];
  6476. if (vertexUvs !== undefined) {
  6477. this.uvs.push(vertexUvs[0], vertexUvs[1], vertexUvs[2]);
  6478. } else {
  6479. console.warn('THREE.DirectGeometry.fromGeometry(): Undefined vertexUv ', i);
  6480. this.uvs.push(new Vector2(), new Vector2(), new Vector2());
  6481. }
  6482. }
  6483. if (hasFaceVertexUv2 === true) {
  6484. var vertexUvs = faceVertexUvs[1][i];
  6485. if (vertexUvs !== undefined) {
  6486. this.uvs2.push(vertexUvs[0], vertexUvs[1], vertexUvs[2]);
  6487. } else {
  6488. console.warn('THREE.DirectGeometry.fromGeometry(): Undefined vertexUv2 ', i);
  6489. this.uvs2.push(new Vector2(), new Vector2(), new Vector2());
  6490. }
  6491. } // morphs
  6492. for (var j = 0; j < morphTargetsLength; j++) {
  6493. var morphTarget = morphTargets[j].vertices;
  6494. morphTargetsPosition[j].data.push(morphTarget[face.a], morphTarget[face.b], morphTarget[face.c]);
  6495. }
  6496. for (var j = 0; j < morphNormalsLength; j++) {
  6497. var morphNormal = morphNormals[j].vertexNormals[i];
  6498. morphTargetsNormal[j].data.push(morphNormal.a, morphNormal.b, morphNormal.c);
  6499. } // skins
  6500. if (hasSkinIndices) {
  6501. this.skinIndices.push(skinIndices[face.a], skinIndices[face.b], skinIndices[face.c]);
  6502. }
  6503. if (hasSkinWeights) {
  6504. this.skinWeights.push(skinWeights[face.a], skinWeights[face.b], skinWeights[face.c]);
  6505. }
  6506. }
  6507. this.computeGroups(geometry);
  6508. this.verticesNeedUpdate = geometry.verticesNeedUpdate;
  6509. this.normalsNeedUpdate = geometry.normalsNeedUpdate;
  6510. this.colorsNeedUpdate = geometry.colorsNeedUpdate;
  6511. this.uvsNeedUpdate = geometry.uvsNeedUpdate;
  6512. this.groupsNeedUpdate = geometry.groupsNeedUpdate;
  6513. if (geometry.boundingSphere !== null) {
  6514. this.boundingSphere = geometry.boundingSphere.clone();
  6515. }
  6516. if (geometry.boundingBox !== null) {
  6517. this.boundingBox = geometry.boundingBox.clone();
  6518. }
  6519. return this;
  6520. }
  6521. });
  6522. /**
  6523. * @author mrdoob / http://mrdoob.com/
  6524. */
  6525. function arrayMax(array) {
  6526. if (array.length === 0) return -Infinity;
  6527. var max = array[0];
  6528. for (var i = 1, l = array.length; i < l; ++i) {
  6529. if (array[i] > max) max = array[i];
  6530. }
  6531. return max;
  6532. }
  6533. /**
  6534. * @author alteredq / http://alteredqualia.com/
  6535. * @author mrdoob / http://mrdoob.com/
  6536. */
  6537. var _bufferGeometryId = 1; // BufferGeometry uses odd numbers as Id
  6538. var _m1$2 = new Matrix4();
  6539. var _obj = new Object3D();
  6540. var _offset = new Vector3();
  6541. var _box$1 = new Box3();
  6542. var _boxMorphTargets = new Box3();
  6543. var _vector$4 = new Vector3();
  6544. function BufferGeometry() {
  6545. Object.defineProperty(this, 'id', {
  6546. value: _bufferGeometryId += 2
  6547. });
  6548. this.uuid = _Math.generateUUID();
  6549. this.name = '';
  6550. this.type = 'BufferGeometry';
  6551. this.index = null;
  6552. this.attributes = {};
  6553. this.morphAttributes = {};
  6554. this.groups = [];
  6555. this.boundingBox = null;
  6556. this.boundingSphere = null;
  6557. this.drawRange = {
  6558. start: 0,
  6559. count: Infinity
  6560. };
  6561. this.userData = {};
  6562. }
  6563. BufferGeometry.prototype = Object.assign(Object.create(EventDispatcher.prototype), {
  6564. constructor: BufferGeometry,
  6565. isBufferGeometry: true,
  6566. getIndex: function () {
  6567. return this.index;
  6568. },
  6569. setIndex: function (index) {
  6570. if (Array.isArray(index)) {
  6571. this.index = new (arrayMax(index) > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute)(index, 1);
  6572. } else {
  6573. this.index = index;
  6574. }
  6575. },
  6576. addAttribute: function (name, attribute) {
  6577. if (!(attribute && attribute.isBufferAttribute) && !(attribute && attribute.isInterleavedBufferAttribute)) {
  6578. console.warn('THREE.BufferGeometry: .addAttribute() now expects ( name, attribute ).');
  6579. return this.addAttribute(name, new BufferAttribute(arguments[1], arguments[2]));
  6580. }
  6581. if (name === 'index') {
  6582. console.warn('THREE.BufferGeometry.addAttribute: Use .setIndex() for index attribute.');
  6583. this.setIndex(attribute);
  6584. return this;
  6585. }
  6586. return this.setAttribute(name, attribute);
  6587. },
  6588. getAttribute: function (name) {
  6589. return this.attributes[name];
  6590. },
  6591. setAttribute: function (name, attribute) {
  6592. this.attributes[name] = attribute;
  6593. return this;
  6594. },
  6595. removeAttribute: function (name) {
  6596. delete this.attributes[name];
  6597. return this;
  6598. },
  6599. addGroup: function (start, count, materialIndex) {
  6600. this.groups.push({
  6601. start: start,
  6602. count: count,
  6603. materialIndex: materialIndex !== undefined ? materialIndex : 0
  6604. });
  6605. },
  6606. clearGroups: function () {
  6607. this.groups = [];
  6608. },
  6609. setDrawRange: function (start, count) {
  6610. this.drawRange.start = start;
  6611. this.drawRange.count = count;
  6612. },
  6613. applyMatrix: function (matrix) {
  6614. var position = this.attributes.position;
  6615. if (position !== undefined) {
  6616. matrix.applyToBufferAttribute(position);
  6617. position.needsUpdate = true;
  6618. }
  6619. var normal = this.attributes.normal;
  6620. if (normal !== undefined) {
  6621. var normalMatrix = new Matrix3().getNormalMatrix(matrix);
  6622. normalMatrix.applyToBufferAttribute(normal);
  6623. normal.needsUpdate = true;
  6624. }
  6625. var tangent = this.attributes.tangent;
  6626. if (tangent !== undefined) {
  6627. var normalMatrix = new Matrix3().getNormalMatrix(matrix); // Tangent is vec4, but the '.w' component is a sign value (+1/-1).
  6628. normalMatrix.applyToBufferAttribute(tangent);
  6629. tangent.needsUpdate = true;
  6630. }
  6631. if (this.boundingBox !== null) {
  6632. this.computeBoundingBox();
  6633. }
  6634. if (this.boundingSphere !== null) {
  6635. this.computeBoundingSphere();
  6636. }
  6637. return this;
  6638. },
  6639. rotateX: function (angle) {
  6640. // rotate geometry around world x-axis
  6641. _m1$2.makeRotationX(angle);
  6642. this.applyMatrix(_m1$2);
  6643. return this;
  6644. },
  6645. rotateY: function (angle) {
  6646. // rotate geometry around world y-axis
  6647. _m1$2.makeRotationY(angle);
  6648. this.applyMatrix(_m1$2);
  6649. return this;
  6650. },
  6651. rotateZ: function (angle) {
  6652. // rotate geometry around world z-axis
  6653. _m1$2.makeRotationZ(angle);
  6654. this.applyMatrix(_m1$2);
  6655. return this;
  6656. },
  6657. translate: function (x, y, z) {
  6658. // translate geometry
  6659. _m1$2.makeTranslation(x, y, z);
  6660. this.applyMatrix(_m1$2);
  6661. return this;
  6662. },
  6663. scale: function (x, y, z) {
  6664. // scale geometry
  6665. _m1$2.makeScale(x, y, z);
  6666. this.applyMatrix(_m1$2);
  6667. return this;
  6668. },
  6669. lookAt: function (vector) {
  6670. _obj.lookAt(vector);
  6671. _obj.updateMatrix();
  6672. this.applyMatrix(_obj.matrix);
  6673. return this;
  6674. },
  6675. center: function () {
  6676. this.computeBoundingBox();
  6677. this.boundingBox.getCenter(_offset).negate();
  6678. this.translate(_offset.x, _offset.y, _offset.z);
  6679. return this;
  6680. },
  6681. setFromObject: function (object) {
  6682. // console.log( 'THREE.BufferGeometry.setFromObject(). Converting', object, this );
  6683. var geometry = object.geometry;
  6684. if (object.isPoints || object.isLine) {
  6685. var positions = new Float32BufferAttribute(geometry.vertices.length * 3, 3);
  6686. var colors = new Float32BufferAttribute(geometry.colors.length * 3, 3);
  6687. this.addAttribute('position', positions.copyVector3sArray(geometry.vertices));
  6688. this.addAttribute('color', colors.copyColorsArray(geometry.colors));
  6689. if (geometry.lineDistances && geometry.lineDistances.length === geometry.vertices.length) {
  6690. var lineDistances = new Float32BufferAttribute(geometry.lineDistances.length, 1);
  6691. this.addAttribute('lineDistance', lineDistances.copyArray(geometry.lineDistances));
  6692. }
  6693. if (geometry.boundingSphere !== null) {
  6694. this.boundingSphere = geometry.boundingSphere.clone();
  6695. }
  6696. if (geometry.boundingBox !== null) {
  6697. this.boundingBox = geometry.boundingBox.clone();
  6698. }
  6699. } else if (object.isMesh) {
  6700. if (geometry && geometry.isGeometry) {
  6701. this.fromGeometry(geometry);
  6702. }
  6703. }
  6704. return this;
  6705. },
  6706. setFromPoints: function (points) {
  6707. var position = [];
  6708. for (var i = 0, l = points.length; i < l; i++) {
  6709. var point = points[i];
  6710. position.push(point.x, point.y, point.z || 0);
  6711. }
  6712. this.addAttribute('position', new Float32BufferAttribute(position, 3));
  6713. return this;
  6714. },
  6715. updateFromObject: function (object) {
  6716. var geometry = object.geometry;
  6717. if (object.isMesh) {
  6718. var direct = geometry.__directGeometry;
  6719. if (geometry.elementsNeedUpdate === true) {
  6720. direct = undefined;
  6721. geometry.elementsNeedUpdate = false;
  6722. }
  6723. if (direct === undefined) {
  6724. return this.fromGeometry(geometry);
  6725. }
  6726. direct.verticesNeedUpdate = geometry.verticesNeedUpdate;
  6727. direct.normalsNeedUpdate = geometry.normalsNeedUpdate;
  6728. direct.colorsNeedUpdate = geometry.colorsNeedUpdate;
  6729. direct.uvsNeedUpdate = geometry.uvsNeedUpdate;
  6730. direct.groupsNeedUpdate = geometry.groupsNeedUpdate;
  6731. geometry.verticesNeedUpdate = false;
  6732. geometry.normalsNeedUpdate = false;
  6733. geometry.colorsNeedUpdate = false;
  6734. geometry.uvsNeedUpdate = false;
  6735. geometry.groupsNeedUpdate = false;
  6736. geometry = direct;
  6737. }
  6738. var attribute;
  6739. if (geometry.verticesNeedUpdate === true) {
  6740. attribute = this.attributes.position;
  6741. if (attribute !== undefined) {
  6742. attribute.copyVector3sArray(geometry.vertices);
  6743. attribute.needsUpdate = true;
  6744. }
  6745. geometry.verticesNeedUpdate = false;
  6746. }
  6747. if (geometry.normalsNeedUpdate === true) {
  6748. attribute = this.attributes.normal;
  6749. if (attribute !== undefined) {
  6750. attribute.copyVector3sArray(geometry.normals);
  6751. attribute.needsUpdate = true;
  6752. }
  6753. geometry.normalsNeedUpdate = false;
  6754. }
  6755. if (geometry.colorsNeedUpdate === true) {
  6756. attribute = this.attributes.color;
  6757. if (attribute !== undefined) {
  6758. attribute.copyColorsArray(geometry.colors);
  6759. attribute.needsUpdate = true;
  6760. }
  6761. geometry.colorsNeedUpdate = false;
  6762. }
  6763. if (geometry.uvsNeedUpdate) {
  6764. attribute = this.attributes.uv;
  6765. if (attribute !== undefined) {
  6766. attribute.copyVector2sArray(geometry.uvs);
  6767. attribute.needsUpdate = true;
  6768. }
  6769. geometry.uvsNeedUpdate = false;
  6770. }
  6771. if (geometry.lineDistancesNeedUpdate) {
  6772. attribute = this.attributes.lineDistance;
  6773. if (attribute !== undefined) {
  6774. attribute.copyArray(geometry.lineDistances);
  6775. attribute.needsUpdate = true;
  6776. }
  6777. geometry.lineDistancesNeedUpdate = false;
  6778. }
  6779. if (geometry.groupsNeedUpdate) {
  6780. geometry.computeGroups(object.geometry);
  6781. this.groups = geometry.groups;
  6782. geometry.groupsNeedUpdate = false;
  6783. }
  6784. return this;
  6785. },
  6786. fromGeometry: function (geometry) {
  6787. geometry.__directGeometry = new DirectGeometry().fromGeometry(geometry);
  6788. return this.fromDirectGeometry(geometry.__directGeometry);
  6789. },
  6790. fromDirectGeometry: function (geometry) {
  6791. var positions = new Float32Array(geometry.vertices.length * 3);
  6792. this.addAttribute('position', new BufferAttribute(positions, 3).copyVector3sArray(geometry.vertices));
  6793. if (geometry.normals.length > 0) {
  6794. var normals = new Float32Array(geometry.normals.length * 3);
  6795. this.addAttribute('normal', new BufferAttribute(normals, 3).copyVector3sArray(geometry.normals));
  6796. }
  6797. if (geometry.colors.length > 0) {
  6798. var colors = new Float32Array(geometry.colors.length * 3);
  6799. this.addAttribute('color', new BufferAttribute(colors, 3).copyColorsArray(geometry.colors));
  6800. }
  6801. if (geometry.uvs.length > 0) {
  6802. var uvs = new Float32Array(geometry.uvs.length * 2);
  6803. this.addAttribute('uv', new BufferAttribute(uvs, 2).copyVector2sArray(geometry.uvs));
  6804. }
  6805. if (geometry.uvs2.length > 0) {
  6806. var uvs2 = new Float32Array(geometry.uvs2.length * 2);
  6807. this.addAttribute('uv2', new BufferAttribute(uvs2, 2).copyVector2sArray(geometry.uvs2));
  6808. } // groups
  6809. this.groups = geometry.groups; // morphs
  6810. for (var name in geometry.morphTargets) {
  6811. var array = [];
  6812. var morphTargets = geometry.morphTargets[name];
  6813. for (var i = 0, l = morphTargets.length; i < l; i++) {
  6814. var morphTarget = morphTargets[i];
  6815. var attribute = new Float32BufferAttribute(morphTarget.data.length * 3, 3);
  6816. attribute.name = morphTarget.name;
  6817. array.push(attribute.copyVector3sArray(morphTarget.data));
  6818. }
  6819. this.morphAttributes[name] = array;
  6820. } // skinning
  6821. if (geometry.skinIndices.length > 0) {
  6822. var skinIndices = new Float32BufferAttribute(geometry.skinIndices.length * 4, 4);
  6823. this.addAttribute('skinIndex', skinIndices.copyVector4sArray(geometry.skinIndices));
  6824. }
  6825. if (geometry.skinWeights.length > 0) {
  6826. var skinWeights = new Float32BufferAttribute(geometry.skinWeights.length * 4, 4);
  6827. this.addAttribute('skinWeight', skinWeights.copyVector4sArray(geometry.skinWeights));
  6828. } //
  6829. if (geometry.boundingSphere !== null) {
  6830. this.boundingSphere = geometry.boundingSphere.clone();
  6831. }
  6832. if (geometry.boundingBox !== null) {
  6833. this.boundingBox = geometry.boundingBox.clone();
  6834. }
  6835. return this;
  6836. },
  6837. computeBoundingBox: function () {
  6838. if (this.boundingBox === null) {
  6839. this.boundingBox = new Box3();
  6840. }
  6841. var position = this.attributes.position;
  6842. var morphAttributesPosition = this.morphAttributes.position;
  6843. if (position !== undefined) {
  6844. this.boundingBox.setFromBufferAttribute(position); // process morph attributes if present
  6845. if (morphAttributesPosition) {
  6846. for (var i = 0, il = morphAttributesPosition.length; i < il; i++) {
  6847. var morphAttribute = morphAttributesPosition[i];
  6848. _box$1.setFromBufferAttribute(morphAttribute);
  6849. this.boundingBox.expandByPoint(_box$1.min);
  6850. this.boundingBox.expandByPoint(_box$1.max);
  6851. }
  6852. }
  6853. } else {
  6854. this.boundingBox.makeEmpty();
  6855. }
  6856. if (isNaN(this.boundingBox.min.x) || isNaN(this.boundingBox.min.y) || isNaN(this.boundingBox.min.z)) {
  6857. console.error('THREE.BufferGeometry.computeBoundingBox: Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this);
  6858. }
  6859. },
  6860. computeBoundingSphere: function () {
  6861. if (this.boundingSphere === null) {
  6862. this.boundingSphere = new Sphere();
  6863. }
  6864. var position = this.attributes.position;
  6865. var morphAttributesPosition = this.morphAttributes.position;
  6866. if (position) {
  6867. // first, find the center of the bounding sphere
  6868. var center = this.boundingSphere.center;
  6869. _box$1.setFromBufferAttribute(position); // process morph attributes if present
  6870. if (morphAttributesPosition) {
  6871. for (var i = 0, il = morphAttributesPosition.length; i < il; i++) {
  6872. var morphAttribute = morphAttributesPosition[i];
  6873. _boxMorphTargets.setFromBufferAttribute(morphAttribute);
  6874. _box$1.expandByPoint(_boxMorphTargets.min);
  6875. _box$1.expandByPoint(_boxMorphTargets.max);
  6876. }
  6877. }
  6878. _box$1.getCenter(center); // second, try to find a boundingSphere with a radius smaller than the
  6879. // boundingSphere of the boundingBox: sqrt(3) smaller in the best case
  6880. var maxRadiusSq = 0;
  6881. for (var i = 0, il = position.count; i < il; i++) {
  6882. _vector$4.fromBufferAttribute(position, i);
  6883. maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(_vector$4));
  6884. } // process morph attributes if present
  6885. if (morphAttributesPosition) {
  6886. for (var i = 0, il = morphAttributesPosition.length; i < il; i++) {
  6887. var morphAttribute = morphAttributesPosition[i];
  6888. for (var j = 0, jl = morphAttribute.count; j < jl; j++) {
  6889. _vector$4.fromBufferAttribute(morphAttribute, j);
  6890. maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(_vector$4));
  6891. }
  6892. }
  6893. }
  6894. this.boundingSphere.radius = Math.sqrt(maxRadiusSq);
  6895. if (isNaN(this.boundingSphere.radius)) {
  6896. console.error('THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this);
  6897. }
  6898. }
  6899. },
  6900. computeFaceNormals: function () {// backwards compatibility
  6901. },
  6902. computeVertexNormals: function () {
  6903. var index = this.index;
  6904. var attributes = this.attributes;
  6905. if (attributes.position) {
  6906. var positions = attributes.position.array;
  6907. if (attributes.normal === undefined) {
  6908. this.addAttribute('normal', new BufferAttribute(new Float32Array(positions.length), 3));
  6909. } else {
  6910. // reset existing normals to zero
  6911. var array = attributes.normal.array;
  6912. for (var i = 0, il = array.length; i < il; i++) {
  6913. array[i] = 0;
  6914. }
  6915. }
  6916. var normals = attributes.normal.array;
  6917. var vA, vB, vC;
  6918. var pA = new Vector3(),
  6919. pB = new Vector3(),
  6920. pC = new Vector3();
  6921. var cb = new Vector3(),
  6922. ab = new Vector3(); // indexed elements
  6923. if (index) {
  6924. var indices = index.array;
  6925. for (var i = 0, il = index.count; i < il; i += 3) {
  6926. vA = indices[i + 0] * 3;
  6927. vB = indices[i + 1] * 3;
  6928. vC = indices[i + 2] * 3;
  6929. pA.fromArray(positions, vA);
  6930. pB.fromArray(positions, vB);
  6931. pC.fromArray(positions, vC);
  6932. cb.subVectors(pC, pB);
  6933. ab.subVectors(pA, pB);
  6934. cb.cross(ab);
  6935. normals[vA] += cb.x;
  6936. normals[vA + 1] += cb.y;
  6937. normals[vA + 2] += cb.z;
  6938. normals[vB] += cb.x;
  6939. normals[vB + 1] += cb.y;
  6940. normals[vB + 2] += cb.z;
  6941. normals[vC] += cb.x;
  6942. normals[vC + 1] += cb.y;
  6943. normals[vC + 2] += cb.z;
  6944. }
  6945. } else {
  6946. // non-indexed elements (unconnected triangle soup)
  6947. for (var i = 0, il = positions.length; i < il; i += 9) {
  6948. pA.fromArray(positions, i);
  6949. pB.fromArray(positions, i + 3);
  6950. pC.fromArray(positions, i + 6);
  6951. cb.subVectors(pC, pB);
  6952. ab.subVectors(pA, pB);
  6953. cb.cross(ab);
  6954. normals[i] = cb.x;
  6955. normals[i + 1] = cb.y;
  6956. normals[i + 2] = cb.z;
  6957. normals[i + 3] = cb.x;
  6958. normals[i + 4] = cb.y;
  6959. normals[i + 5] = cb.z;
  6960. normals[i + 6] = cb.x;
  6961. normals[i + 7] = cb.y;
  6962. normals[i + 8] = cb.z;
  6963. }
  6964. }
  6965. this.normalizeNormals();
  6966. attributes.normal.needsUpdate = true;
  6967. }
  6968. },
  6969. merge: function (geometry, offset) {
  6970. if (!(geometry && geometry.isBufferGeometry)) {
  6971. console.error('THREE.BufferGeometry.merge(): geometry not an instance of THREE.BufferGeometry.', geometry);
  6972. return;
  6973. }
  6974. if (offset === undefined) {
  6975. offset = 0;
  6976. console.warn('THREE.BufferGeometry.merge(): Overwriting original geometry, starting at offset=0. ' + 'Use BufferGeometryUtils.mergeBufferGeometries() for lossless merge.');
  6977. }
  6978. var attributes = this.attributes;
  6979. for (var key in attributes) {
  6980. if (geometry.attributes[key] === undefined) continue;
  6981. var attribute1 = attributes[key];
  6982. var attributeArray1 = attribute1.array;
  6983. var attribute2 = geometry.attributes[key];
  6984. var attributeArray2 = attribute2.array;
  6985. var attributeOffset = attribute2.itemSize * offset;
  6986. var length = Math.min(attributeArray2.length, attributeArray1.length - attributeOffset);
  6987. for (var i = 0, j = attributeOffset; i < length; i++, j++) {
  6988. attributeArray1[j] = attributeArray2[i];
  6989. }
  6990. }
  6991. return this;
  6992. },
  6993. normalizeNormals: function () {
  6994. var normals = this.attributes.normal;
  6995. for (var i = 0, il = normals.count; i < il; i++) {
  6996. _vector$4.x = normals.getX(i);
  6997. _vector$4.y = normals.getY(i);
  6998. _vector$4.z = normals.getZ(i);
  6999. _vector$4.normalize();
  7000. normals.setXYZ(i, _vector$4.x, _vector$4.y, _vector$4.z);
  7001. }
  7002. },
  7003. toNonIndexed: function () {
  7004. function convertBufferAttribute(attribute, indices) {
  7005. var array = attribute.array;
  7006. var itemSize = attribute.itemSize;
  7007. var array2 = new array.constructor(indices.length * itemSize);
  7008. var index = 0,
  7009. index2 = 0;
  7010. for (var i = 0, l = indices.length; i < l; i++) {
  7011. index = indices[i] * itemSize;
  7012. for (var j = 0; j < itemSize; j++) {
  7013. array2[index2++] = array[index++];
  7014. }
  7015. }
  7016. return new BufferAttribute(array2, itemSize);
  7017. } //
  7018. if (this.index === null) {
  7019. console.warn('THREE.BufferGeometry.toNonIndexed(): Geometry is already non-indexed.');
  7020. return this;
  7021. }
  7022. var geometry2 = new BufferGeometry();
  7023. var indices = this.index.array;
  7024. var attributes = this.attributes; // attributes
  7025. for (var name in attributes) {
  7026. var attribute = attributes[name];
  7027. var newAttribute = convertBufferAttribute(attribute, indices);
  7028. geometry2.addAttribute(name, newAttribute);
  7029. } // morph attributes
  7030. var morphAttributes = this.morphAttributes;
  7031. for (name in morphAttributes) {
  7032. var morphArray = [];
  7033. var morphAttribute = morphAttributes[name]; // morphAttribute: array of Float32BufferAttributes
  7034. for (var i = 0, il = morphAttribute.length; i < il; i++) {
  7035. var attribute = morphAttribute[i];
  7036. var newAttribute = convertBufferAttribute(attribute, indices);
  7037. morphArray.push(newAttribute);
  7038. }
  7039. geometry2.morphAttributes[name] = morphArray;
  7040. } // groups
  7041. var groups = this.groups;
  7042. for (var i = 0, l = groups.length; i < l; i++) {
  7043. var group = groups[i];
  7044. geometry2.addGroup(group.start, group.count, group.materialIndex);
  7045. }
  7046. return geometry2;
  7047. },
  7048. toJSON: function () {
  7049. var data = {
  7050. metadata: {
  7051. version: 4.5,
  7052. type: 'BufferGeometry',
  7053. generator: 'BufferGeometry.toJSON'
  7054. }
  7055. }; // standard BufferGeometry serialization
  7056. data.uuid = this.uuid;
  7057. data.type = this.type;
  7058. if (this.name !== '') data.name = this.name;
  7059. if (Object.keys(this.userData).length > 0) data.userData = this.userData;
  7060. if (this.parameters !== undefined) {
  7061. var parameters = this.parameters;
  7062. for (var key in parameters) {
  7063. if (parameters[key] !== undefined) data[key] = parameters[key];
  7064. }
  7065. return data;
  7066. }
  7067. data.data = {
  7068. attributes: {}
  7069. };
  7070. var index = this.index;
  7071. if (index !== null) {
  7072. data.data.index = {
  7073. type: index.array.constructor.name,
  7074. array: Array.prototype.slice.call(index.array)
  7075. };
  7076. }
  7077. var attributes = this.attributes;
  7078. for (var key in attributes) {
  7079. var attribute = attributes[key];
  7080. var attributeData = attribute.toJSON();
  7081. if (attribute.name !== '') attributeData.name = attribute.name;
  7082. data.data.attributes[key] = attributeData;
  7083. }
  7084. var morphAttributes = {};
  7085. var hasMorphAttributes = false;
  7086. for (var key in this.morphAttributes) {
  7087. var attributeArray = this.morphAttributes[key];
  7088. var array = [];
  7089. for (var i = 0, il = attributeArray.length; i < il; i++) {
  7090. var attribute = attributeArray[i];
  7091. var attributeData = attribute.toJSON();
  7092. if (attribute.name !== '') attributeData.name = attribute.name;
  7093. array.push(attributeData);
  7094. }
  7095. if (array.length > 0) {
  7096. morphAttributes[key] = array;
  7097. hasMorphAttributes = true;
  7098. }
  7099. }
  7100. if (hasMorphAttributes) data.data.morphAttributes = morphAttributes;
  7101. var groups = this.groups;
  7102. if (groups.length > 0) {
  7103. data.data.groups = JSON.parse(JSON.stringify(groups));
  7104. }
  7105. var boundingSphere = this.boundingSphere;
  7106. if (boundingSphere !== null) {
  7107. data.data.boundingSphere = {
  7108. center: boundingSphere.center.toArray(),
  7109. radius: boundingSphere.radius
  7110. };
  7111. }
  7112. return data;
  7113. },
  7114. clone: function () {
  7115. /*
  7116. // Handle primitives
  7117. var parameters = this.parameters;
  7118. if ( parameters !== undefined ) {
  7119. var values = [];
  7120. for ( var key in parameters ) {
  7121. values.push( parameters[ key ] );
  7122. }
  7123. var geometry = Object.create( this.constructor.prototype );
  7124. this.constructor.apply( geometry, values );
  7125. return geometry;
  7126. }
  7127. return new this.constructor().copy( this );
  7128. */
  7129. return new BufferGeometry().copy(this);
  7130. },
  7131. copy: function (source) {
  7132. var name, i, l; // reset
  7133. this.index = null;
  7134. this.attributes = {};
  7135. this.morphAttributes = {};
  7136. this.groups = [];
  7137. this.boundingBox = null;
  7138. this.boundingSphere = null; // name
  7139. this.name = source.name; // index
  7140. var index = source.index;
  7141. if (index !== null) {
  7142. this.setIndex(index.clone());
  7143. } // attributes
  7144. var attributes = source.attributes;
  7145. for (name in attributes) {
  7146. var attribute = attributes[name];
  7147. this.addAttribute(name, attribute.clone());
  7148. } // morph attributes
  7149. var morphAttributes = source.morphAttributes;
  7150. for (name in morphAttributes) {
  7151. var array = [];
  7152. var morphAttribute = morphAttributes[name]; // morphAttribute: array of Float32BufferAttributes
  7153. for (i = 0, l = morphAttribute.length; i < l; i++) {
  7154. array.push(morphAttribute[i].clone());
  7155. }
  7156. this.morphAttributes[name] = array;
  7157. } // groups
  7158. var groups = source.groups;
  7159. for (i = 0, l = groups.length; i < l; i++) {
  7160. var group = groups[i];
  7161. this.addGroup(group.start, group.count, group.materialIndex);
  7162. } // bounding box
  7163. var boundingBox = source.boundingBox;
  7164. if (boundingBox !== null) {
  7165. this.boundingBox = boundingBox.clone();
  7166. } // bounding sphere
  7167. var boundingSphere = source.boundingSphere;
  7168. if (boundingSphere !== null) {
  7169. this.boundingSphere = boundingSphere.clone();
  7170. } // draw range
  7171. this.drawRange.start = source.drawRange.start;
  7172. this.drawRange.count = source.drawRange.count; // user data
  7173. this.userData = source.userData;
  7174. return this;
  7175. },
  7176. dispose: function () {
  7177. this.dispatchEvent({
  7178. type: 'dispose'
  7179. });
  7180. }
  7181. });
  7182. /**
  7183. * @author mrdoob / http://mrdoob.com/
  7184. * @author alteredq / http://alteredqualia.com/
  7185. * @author mikael emtinger / http://gomo.se/
  7186. * @author jonobr1 / http://jonobr1.com/
  7187. */
  7188. var _inverseMatrix = new Matrix4();
  7189. var _ray = new Ray();
  7190. var _sphere = new Sphere();
  7191. var _vA = new Vector3();
  7192. var _vB = new Vector3();
  7193. var _vC = new Vector3();
  7194. var _tempA = new Vector3();
  7195. var _tempB = new Vector3();
  7196. var _tempC = new Vector3();
  7197. var _morphA = new Vector3();
  7198. var _morphB = new Vector3();
  7199. var _morphC = new Vector3();
  7200. var _uvA = new Vector2();
  7201. var _uvB = new Vector2();
  7202. var _uvC = new Vector2();
  7203. var _intersectionPoint = new Vector3();
  7204. var _intersectionPointWorld = new Vector3();
  7205. function Mesh(geometry, material) {
  7206. Object3D.call(this);
  7207. this.type = 'Mesh';
  7208. this.geometry = geometry !== undefined ? geometry : new BufferGeometry();
  7209. this.material = material !== undefined ? material : new MeshBasicMaterial({
  7210. color: Math.random() * 0xffffff
  7211. });
  7212. this.drawMode = TrianglesDrawMode;
  7213. this.updateMorphTargets();
  7214. }
  7215. Mesh.prototype = Object.assign(Object.create(Object3D.prototype), {
  7216. constructor: Mesh,
  7217. isMesh: true,
  7218. setDrawMode: function (value) {
  7219. this.drawMode = value;
  7220. },
  7221. copy: function (source) {
  7222. Object3D.prototype.copy.call(this, source);
  7223. this.drawMode = source.drawMode;
  7224. if (source.morphTargetInfluences !== undefined) {
  7225. this.morphTargetInfluences = source.morphTargetInfluences.slice();
  7226. }
  7227. if (source.morphTargetDictionary !== undefined) {
  7228. this.morphTargetDictionary = Object.assign({}, source.morphTargetDictionary);
  7229. }
  7230. return this;
  7231. },
  7232. updateMorphTargets: function () {
  7233. var geometry = this.geometry;
  7234. var m, ml, name;
  7235. if (geometry.isBufferGeometry) {
  7236. var morphAttributes = geometry.morphAttributes;
  7237. var keys = Object.keys(morphAttributes);
  7238. if (keys.length > 0) {
  7239. var morphAttribute = morphAttributes[keys[0]];
  7240. if (morphAttribute !== undefined) {
  7241. this.morphTargetInfluences = [];
  7242. this.morphTargetDictionary = {};
  7243. for (m = 0, ml = morphAttribute.length; m < ml; m++) {
  7244. name = morphAttribute[m].name || String(m);
  7245. this.morphTargetInfluences.push(0);
  7246. this.morphTargetDictionary[name] = m;
  7247. }
  7248. }
  7249. }
  7250. } else {
  7251. var morphTargets = geometry.morphTargets;
  7252. if (morphTargets !== undefined && morphTargets.length > 0) {
  7253. console.error('THREE.Mesh.updateMorphTargets() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');
  7254. }
  7255. }
  7256. },
  7257. raycast: function (raycaster, intersects) {
  7258. var geometry = this.geometry;
  7259. var material = this.material;
  7260. var matrixWorld = this.matrixWorld;
  7261. if (material === undefined) return; // Checking boundingSphere distance to ray
  7262. if (geometry.boundingSphere === null) geometry.computeBoundingSphere();
  7263. _sphere.copy(geometry.boundingSphere);
  7264. _sphere.applyMatrix4(matrixWorld);
  7265. if (raycaster.ray.intersectsSphere(_sphere) === false) return; //
  7266. _inverseMatrix.getInverse(matrixWorld);
  7267. _ray.copy(raycaster.ray).applyMatrix4(_inverseMatrix); // Check boundingBox before continuing
  7268. if (geometry.boundingBox !== null) {
  7269. if (_ray.intersectsBox(geometry.boundingBox) === false) return;
  7270. }
  7271. var intersection;
  7272. if (geometry.isBufferGeometry) {
  7273. var a, b, c;
  7274. var index = geometry.index;
  7275. var position = geometry.attributes.position;
  7276. var morphPosition = geometry.morphAttributes.position;
  7277. var uv = geometry.attributes.uv;
  7278. var uv2 = geometry.attributes.uv2;
  7279. var groups = geometry.groups;
  7280. var drawRange = geometry.drawRange;
  7281. var i, j, il, jl;
  7282. var group, groupMaterial;
  7283. var start, end;
  7284. if (index !== null) {
  7285. // indexed buffer geometry
  7286. if (Array.isArray(material)) {
  7287. for (i = 0, il = groups.length; i < il; i++) {
  7288. group = groups[i];
  7289. groupMaterial = material[group.materialIndex];
  7290. start = Math.max(group.start, drawRange.start);
  7291. end = Math.min(group.start + group.count, drawRange.start + drawRange.count);
  7292. for (j = start, jl = end; j < jl; j += 3) {
  7293. a = index.getX(j);
  7294. b = index.getX(j + 1);
  7295. c = index.getX(j + 2);
  7296. intersection = checkBufferGeometryIntersection(this, groupMaterial, raycaster, _ray, position, morphPosition, uv, uv2, a, b, c);
  7297. if (intersection) {
  7298. intersection.faceIndex = Math.floor(j / 3); // triangle number in indexed buffer semantics
  7299. intersection.face.materialIndex = group.materialIndex;
  7300. intersects.push(intersection);
  7301. }
  7302. }
  7303. }
  7304. } else {
  7305. start = Math.max(0, drawRange.start);
  7306. end = Math.min(index.count, drawRange.start + drawRange.count);
  7307. for (i = start, il = end; i < il; i += 3) {
  7308. a = index.getX(i);
  7309. b = index.getX(i + 1);
  7310. c = index.getX(i + 2);
  7311. intersection = checkBufferGeometryIntersection(this, material, raycaster, _ray, position, morphPosition, uv, uv2, a, b, c);
  7312. if (intersection) {
  7313. intersection.faceIndex = Math.floor(i / 3); // triangle number in indexed buffer semantics
  7314. intersects.push(intersection);
  7315. }
  7316. }
  7317. }
  7318. } else if (position !== undefined) {
  7319. // non-indexed buffer geometry
  7320. if (Array.isArray(material)) {
  7321. for (i = 0, il = groups.length; i < il; i++) {
  7322. group = groups[i];
  7323. groupMaterial = material[group.materialIndex];
  7324. start = Math.max(group.start, drawRange.start);
  7325. end = Math.min(group.start + group.count, drawRange.start + drawRange.count);
  7326. for (j = start, jl = end; j < jl; j += 3) {
  7327. a = j;
  7328. b = j + 1;
  7329. c = j + 2;
  7330. intersection = checkBufferGeometryIntersection(this, groupMaterial, raycaster, _ray, position, morphPosition, uv, uv2, a, b, c);
  7331. if (intersection) {
  7332. intersection.faceIndex = Math.floor(j / 3); // triangle number in non-indexed buffer semantics
  7333. intersection.face.materialIndex = group.materialIndex;
  7334. intersects.push(intersection);
  7335. }
  7336. }
  7337. }
  7338. } else {
  7339. start = Math.max(0, drawRange.start);
  7340. end = Math.min(position.count, drawRange.start + drawRange.count);
  7341. for (i = start, il = end; i < il; i += 3) {
  7342. a = i;
  7343. b = i + 1;
  7344. c = i + 2;
  7345. intersection = checkBufferGeometryIntersection(this, material, raycaster, _ray, position, morphPosition, uv, uv2, a, b, c);
  7346. if (intersection) {
  7347. intersection.faceIndex = Math.floor(i / 3); // triangle number in non-indexed buffer semantics
  7348. intersects.push(intersection);
  7349. }
  7350. }
  7351. }
  7352. }
  7353. } else if (geometry.isGeometry) {
  7354. var fvA, fvB, fvC;
  7355. var isMultiMaterial = Array.isArray(material);
  7356. var vertices = geometry.vertices;
  7357. var faces = geometry.faces;
  7358. var uvs;
  7359. var faceVertexUvs = geometry.faceVertexUvs[0];
  7360. if (faceVertexUvs.length > 0) uvs = faceVertexUvs;
  7361. for (var f = 0, fl = faces.length; f < fl; f++) {
  7362. var face = faces[f];
  7363. var faceMaterial = isMultiMaterial ? material[face.materialIndex] : material;
  7364. if (faceMaterial === undefined) continue;
  7365. fvA = vertices[face.a];
  7366. fvB = vertices[face.b];
  7367. fvC = vertices[face.c];
  7368. intersection = checkIntersection(this, faceMaterial, raycaster, _ray, fvA, fvB, fvC, _intersectionPoint);
  7369. if (intersection) {
  7370. if (uvs && uvs[f]) {
  7371. var uvs_f = uvs[f];
  7372. _uvA.copy(uvs_f[0]);
  7373. _uvB.copy(uvs_f[1]);
  7374. _uvC.copy(uvs_f[2]);
  7375. intersection.uv = Triangle.getUV(_intersectionPoint, fvA, fvB, fvC, _uvA, _uvB, _uvC, new Vector2());
  7376. }
  7377. intersection.face = face;
  7378. intersection.faceIndex = f;
  7379. intersects.push(intersection);
  7380. }
  7381. }
  7382. }
  7383. },
  7384. clone: function () {
  7385. return new this.constructor(this.geometry, this.material).copy(this);
  7386. }
  7387. });
  7388. function checkIntersection(object, material, raycaster, ray, pA, pB, pC, point) {
  7389. var intersect;
  7390. if (material.side === BackSide) {
  7391. intersect = ray.intersectTriangle(pC, pB, pA, true, point);
  7392. } else {
  7393. intersect = ray.intersectTriangle(pA, pB, pC, material.side !== DoubleSide, point);
  7394. }
  7395. if (intersect === null) return null;
  7396. _intersectionPointWorld.copy(point);
  7397. _intersectionPointWorld.applyMatrix4(object.matrixWorld);
  7398. var distance = raycaster.ray.origin.distanceTo(_intersectionPointWorld);
  7399. if (distance < raycaster.near || distance > raycaster.far) return null;
  7400. return {
  7401. distance: distance,
  7402. point: _intersectionPointWorld.clone(),
  7403. object: object
  7404. };
  7405. }
  7406. function checkBufferGeometryIntersection(object, material, raycaster, ray, position, morphPosition, uv, uv2, a, b, c) {
  7407. _vA.fromBufferAttribute(position, a);
  7408. _vB.fromBufferAttribute(position, b);
  7409. _vC.fromBufferAttribute(position, c);
  7410. var morphInfluences = object.morphTargetInfluences;
  7411. if (material.morphTargets && morphPosition && morphInfluences) {
  7412. _morphA.set(0, 0, 0);
  7413. _morphB.set(0, 0, 0);
  7414. _morphC.set(0, 0, 0);
  7415. for (var i = 0, il = morphPosition.length; i < il; i++) {
  7416. var influence = morphInfluences[i];
  7417. var morphAttribute = morphPosition[i];
  7418. if (influence === 0) continue;
  7419. _tempA.fromBufferAttribute(morphAttribute, a);
  7420. _tempB.fromBufferAttribute(morphAttribute, b);
  7421. _tempC.fromBufferAttribute(morphAttribute, c);
  7422. _morphA.addScaledVector(_tempA.sub(_vA), influence);
  7423. _morphB.addScaledVector(_tempB.sub(_vB), influence);
  7424. _morphC.addScaledVector(_tempC.sub(_vC), influence);
  7425. }
  7426. _vA.add(_morphA);
  7427. _vB.add(_morphB);
  7428. _vC.add(_morphC);
  7429. }
  7430. var intersection = checkIntersection(object, material, raycaster, ray, _vA, _vB, _vC, _intersectionPoint);
  7431. if (intersection) {
  7432. if (uv) {
  7433. _uvA.fromBufferAttribute(uv, a);
  7434. _uvB.fromBufferAttribute(uv, b);
  7435. _uvC.fromBufferAttribute(uv, c);
  7436. intersection.uv = Triangle.getUV(_intersectionPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2());
  7437. }
  7438. if (uv2) {
  7439. _uvA.fromBufferAttribute(uv2, a);
  7440. _uvB.fromBufferAttribute(uv2, b);
  7441. _uvC.fromBufferAttribute(uv2, c);
  7442. intersection.uv2 = Triangle.getUV(_intersectionPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2());
  7443. }
  7444. var face = new Face3(a, b, c);
  7445. Triangle.getNormal(_vA, _vB, _vC, face.normal);
  7446. intersection.face = face;
  7447. }
  7448. return intersection;
  7449. }
  7450. /**
  7451. * @author mrdoob / http://mrdoob.com/
  7452. * @author kile / http://kile.stravaganza.org/
  7453. * @author alteredq / http://alteredqualia.com/
  7454. * @author mikael emtinger / http://gomo.se/
  7455. * @author zz85 / http://www.lab4games.net/zz85/blog
  7456. * @author bhouston / http://clara.io
  7457. */
  7458. var _geometryId = 0; // Geometry uses even numbers as Id
  7459. var _m1$3 = new Matrix4();
  7460. var _obj$1 = new Object3D();
  7461. var _offset$1 = new Vector3();
  7462. function Geometry() {
  7463. Object.defineProperty(this, 'id', {
  7464. value: _geometryId += 2
  7465. });
  7466. this.uuid = _Math.generateUUID();
  7467. this.name = '';
  7468. this.type = 'Geometry';
  7469. this.vertices = [];
  7470. this.colors = [];
  7471. this.faces = [];
  7472. this.faceVertexUvs = [[]];
  7473. this.morphTargets = [];
  7474. this.morphNormals = [];
  7475. this.skinWeights = [];
  7476. this.skinIndices = [];
  7477. this.lineDistances = [];
  7478. this.boundingBox = null;
  7479. this.boundingSphere = null; // update flags
  7480. this.elementsNeedUpdate = false;
  7481. this.verticesNeedUpdate = false;
  7482. this.uvsNeedUpdate = false;
  7483. this.normalsNeedUpdate = false;
  7484. this.colorsNeedUpdate = false;
  7485. this.lineDistancesNeedUpdate = false;
  7486. this.groupsNeedUpdate = false;
  7487. }
  7488. Geometry.prototype = Object.assign(Object.create(EventDispatcher.prototype), {
  7489. constructor: Geometry,
  7490. isGeometry: true,
  7491. applyMatrix: function (matrix) {
  7492. var normalMatrix = new Matrix3().getNormalMatrix(matrix);
  7493. for (var i = 0, il = this.vertices.length; i < il; i++) {
  7494. var vertex = this.vertices[i];
  7495. vertex.applyMatrix4(matrix);
  7496. }
  7497. for (var i = 0, il = this.faces.length; i < il; i++) {
  7498. var face = this.faces[i];
  7499. face.normal.applyMatrix3(normalMatrix).normalize();
  7500. for (var j = 0, jl = face.vertexNormals.length; j < jl; j++) {
  7501. face.vertexNormals[j].applyMatrix3(normalMatrix).normalize();
  7502. }
  7503. }
  7504. if (this.boundingBox !== null) {
  7505. this.computeBoundingBox();
  7506. }
  7507. if (this.boundingSphere !== null) {
  7508. this.computeBoundingSphere();
  7509. }
  7510. this.verticesNeedUpdate = true;
  7511. this.normalsNeedUpdate = true;
  7512. return this;
  7513. },
  7514. rotateX: function (angle) {
  7515. // rotate geometry around world x-axis
  7516. _m1$3.makeRotationX(angle);
  7517. this.applyMatrix(_m1$3);
  7518. return this;
  7519. },
  7520. rotateY: function (angle) {
  7521. // rotate geometry around world y-axis
  7522. _m1$3.makeRotationY(angle);
  7523. this.applyMatrix(_m1$3);
  7524. return this;
  7525. },
  7526. rotateZ: function (angle) {
  7527. // rotate geometry around world z-axis
  7528. _m1$3.makeRotationZ(angle);
  7529. this.applyMatrix(_m1$3);
  7530. return this;
  7531. },
  7532. translate: function (x, y, z) {
  7533. // translate geometry
  7534. _m1$3.makeTranslation(x, y, z);
  7535. this.applyMatrix(_m1$3);
  7536. return this;
  7537. },
  7538. scale: function (x, y, z) {
  7539. // scale geometry
  7540. _m1$3.makeScale(x, y, z);
  7541. this.applyMatrix(_m1$3);
  7542. return this;
  7543. },
  7544. lookAt: function (vector) {
  7545. _obj$1.lookAt(vector);
  7546. _obj$1.updateMatrix();
  7547. this.applyMatrix(_obj$1.matrix);
  7548. return this;
  7549. },
  7550. fromBufferGeometry: function (geometry) {
  7551. var scope = this;
  7552. var indices = geometry.index !== null ? geometry.index.array : undefined;
  7553. var attributes = geometry.attributes;
  7554. if (attributes.position === undefined) {
  7555. console.error('THREE.Geometry.fromBufferGeometry(): Position attribute required for conversion.');
  7556. return this;
  7557. }
  7558. var positions = attributes.position.array;
  7559. var normals = attributes.normal !== undefined ? attributes.normal.array : undefined;
  7560. var colors = attributes.color !== undefined ? attributes.color.array : undefined;
  7561. var uvs = attributes.uv !== undefined ? attributes.uv.array : undefined;
  7562. var uvs2 = attributes.uv2 !== undefined ? attributes.uv2.array : undefined;
  7563. if (uvs2 !== undefined) this.faceVertexUvs[1] = [];
  7564. for (var i = 0; i < positions.length; i += 3) {
  7565. scope.vertices.push(new Vector3().fromArray(positions, i));
  7566. if (colors !== undefined) {
  7567. scope.colors.push(new Color().fromArray(colors, i));
  7568. }
  7569. }
  7570. function addFace(a, b, c, materialIndex) {
  7571. var vertexColors = colors === undefined ? [] : [scope.colors[a].clone(), scope.colors[b].clone(), scope.colors[c].clone()];
  7572. var vertexNormals = normals === undefined ? [] : [new Vector3().fromArray(normals, a * 3), new Vector3().fromArray(normals, b * 3), new Vector3().fromArray(normals, c * 3)];
  7573. var face = new Face3(a, b, c, vertexNormals, vertexColors, materialIndex);
  7574. scope.faces.push(face);
  7575. if (uvs !== undefined) {
  7576. scope.faceVertexUvs[0].push([new Vector2().fromArray(uvs, a * 2), new Vector2().fromArray(uvs, b * 2), new Vector2().fromArray(uvs, c * 2)]);
  7577. }
  7578. if (uvs2 !== undefined) {
  7579. scope.faceVertexUvs[1].push([new Vector2().fromArray(uvs2, a * 2), new Vector2().fromArray(uvs2, b * 2), new Vector2().fromArray(uvs2, c * 2)]);
  7580. }
  7581. }
  7582. var groups = geometry.groups;
  7583. if (groups.length > 0) {
  7584. for (var i = 0; i < groups.length; i++) {
  7585. var group = groups[i];
  7586. var start = group.start;
  7587. var count = group.count;
  7588. for (var j = start, jl = start + count; j < jl; j += 3) {
  7589. if (indices !== undefined) {
  7590. addFace(indices[j], indices[j + 1], indices[j + 2], group.materialIndex);
  7591. } else {
  7592. addFace(j, j + 1, j + 2, group.materialIndex);
  7593. }
  7594. }
  7595. }
  7596. } else {
  7597. if (indices !== undefined) {
  7598. for (var i = 0; i < indices.length; i += 3) {
  7599. addFace(indices[i], indices[i + 1], indices[i + 2]);
  7600. }
  7601. } else {
  7602. for (var i = 0; i < positions.length / 3; i += 3) {
  7603. addFace(i, i + 1, i + 2);
  7604. }
  7605. }
  7606. }
  7607. this.computeFaceNormals();
  7608. if (geometry.boundingBox !== null) {
  7609. this.boundingBox = geometry.boundingBox.clone();
  7610. }
  7611. if (geometry.boundingSphere !== null) {
  7612. this.boundingSphere = geometry.boundingSphere.clone();
  7613. }
  7614. return this;
  7615. },
  7616. center: function () {
  7617. this.computeBoundingBox();
  7618. this.boundingBox.getCenter(_offset$1).negate();
  7619. this.translate(_offset$1.x, _offset$1.y, _offset$1.z);
  7620. return this;
  7621. },
  7622. normalize: function () {
  7623. this.computeBoundingSphere();
  7624. var center = this.boundingSphere.center;
  7625. var radius = this.boundingSphere.radius;
  7626. var s = radius === 0 ? 1 : 1.0 / radius;
  7627. var matrix = new Matrix4();
  7628. matrix.set(s, 0, 0, -s * center.x, 0, s, 0, -s * center.y, 0, 0, s, -s * center.z, 0, 0, 0, 1);
  7629. this.applyMatrix(matrix);
  7630. return this;
  7631. },
  7632. computeFaceNormals: function () {
  7633. var cb = new Vector3(),
  7634. ab = new Vector3();
  7635. for (var f = 0, fl = this.faces.length; f < fl; f++) {
  7636. var face = this.faces[f];
  7637. var vA = this.vertices[face.a];
  7638. var vB = this.vertices[face.b];
  7639. var vC = this.vertices[face.c];
  7640. cb.subVectors(vC, vB);
  7641. ab.subVectors(vA, vB);
  7642. cb.cross(ab);
  7643. cb.normalize();
  7644. face.normal.copy(cb);
  7645. }
  7646. },
  7647. computeVertexNormals: function (areaWeighted) {
  7648. if (areaWeighted === undefined) areaWeighted = true;
  7649. var v, vl, f, fl, face, vertices;
  7650. vertices = new Array(this.vertices.length);
  7651. for (v = 0, vl = this.vertices.length; v < vl; v++) {
  7652. vertices[v] = new Vector3();
  7653. }
  7654. if (areaWeighted) {
  7655. // vertex normals weighted by triangle areas
  7656. // http://www.iquilezles.org/www/articles/normals/normals.htm
  7657. var vA, vB, vC;
  7658. var cb = new Vector3(),
  7659. ab = new Vector3();
  7660. for (f = 0, fl = this.faces.length; f < fl; f++) {
  7661. face = this.faces[f];
  7662. vA = this.vertices[face.a];
  7663. vB = this.vertices[face.b];
  7664. vC = this.vertices[face.c];
  7665. cb.subVectors(vC, vB);
  7666. ab.subVectors(vA, vB);
  7667. cb.cross(ab);
  7668. vertices[face.a].add(cb);
  7669. vertices[face.b].add(cb);
  7670. vertices[face.c].add(cb);
  7671. }
  7672. } else {
  7673. this.computeFaceNormals();
  7674. for (f = 0, fl = this.faces.length; f < fl; f++) {
  7675. face = this.faces[f];
  7676. vertices[face.a].add(face.normal);
  7677. vertices[face.b].add(face.normal);
  7678. vertices[face.c].add(face.normal);
  7679. }
  7680. }
  7681. for (v = 0, vl = this.vertices.length; v < vl; v++) {
  7682. vertices[v].normalize();
  7683. }
  7684. for (f = 0, fl = this.faces.length; f < fl; f++) {
  7685. face = this.faces[f];
  7686. var vertexNormals = face.vertexNormals;
  7687. if (vertexNormals.length === 3) {
  7688. vertexNormals[0].copy(vertices[face.a]);
  7689. vertexNormals[1].copy(vertices[face.b]);
  7690. vertexNormals[2].copy(vertices[face.c]);
  7691. } else {
  7692. vertexNormals[0] = vertices[face.a].clone();
  7693. vertexNormals[1] = vertices[face.b].clone();
  7694. vertexNormals[2] = vertices[face.c].clone();
  7695. }
  7696. }
  7697. if (this.faces.length > 0) {
  7698. this.normalsNeedUpdate = true;
  7699. }
  7700. },
  7701. computeFlatVertexNormals: function () {
  7702. var f, fl, face;
  7703. this.computeFaceNormals();
  7704. for (f = 0, fl = this.faces.length; f < fl; f++) {
  7705. face = this.faces[f];
  7706. var vertexNormals = face.vertexNormals;
  7707. if (vertexNormals.length === 3) {
  7708. vertexNormals[0].copy(face.normal);
  7709. vertexNormals[1].copy(face.normal);
  7710. vertexNormals[2].copy(face.normal);
  7711. } else {
  7712. vertexNormals[0] = face.normal.clone();
  7713. vertexNormals[1] = face.normal.clone();
  7714. vertexNormals[2] = face.normal.clone();
  7715. }
  7716. }
  7717. if (this.faces.length > 0) {
  7718. this.normalsNeedUpdate = true;
  7719. }
  7720. },
  7721. computeMorphNormals: function () {
  7722. var i, il, f, fl, face; // save original normals
  7723. // - create temp variables on first access
  7724. // otherwise just copy (for faster repeated calls)
  7725. for (f = 0, fl = this.faces.length; f < fl; f++) {
  7726. face = this.faces[f];
  7727. if (!face.__originalFaceNormal) {
  7728. face.__originalFaceNormal = face.normal.clone();
  7729. } else {
  7730. face.__originalFaceNormal.copy(face.normal);
  7731. }
  7732. if (!face.__originalVertexNormals) face.__originalVertexNormals = [];
  7733. for (i = 0, il = face.vertexNormals.length; i < il; i++) {
  7734. if (!face.__originalVertexNormals[i]) {
  7735. face.__originalVertexNormals[i] = face.vertexNormals[i].clone();
  7736. } else {
  7737. face.__originalVertexNormals[i].copy(face.vertexNormals[i]);
  7738. }
  7739. }
  7740. } // use temp geometry to compute face and vertex normals for each morph
  7741. var tmpGeo = new Geometry();
  7742. tmpGeo.faces = this.faces;
  7743. for (i = 0, il = this.morphTargets.length; i < il; i++) {
  7744. // create on first access
  7745. if (!this.morphNormals[i]) {
  7746. this.morphNormals[i] = {};
  7747. this.morphNormals[i].faceNormals = [];
  7748. this.morphNormals[i].vertexNormals = [];
  7749. var dstNormalsFace = this.morphNormals[i].faceNormals;
  7750. var dstNormalsVertex = this.morphNormals[i].vertexNormals;
  7751. var faceNormal, vertexNormals;
  7752. for (f = 0, fl = this.faces.length; f < fl; f++) {
  7753. faceNormal = new Vector3();
  7754. vertexNormals = {
  7755. a: new Vector3(),
  7756. b: new Vector3(),
  7757. c: new Vector3()
  7758. };
  7759. dstNormalsFace.push(faceNormal);
  7760. dstNormalsVertex.push(vertexNormals);
  7761. }
  7762. }
  7763. var morphNormals = this.morphNormals[i]; // set vertices to morph target
  7764. tmpGeo.vertices = this.morphTargets[i].vertices; // compute morph normals
  7765. tmpGeo.computeFaceNormals();
  7766. tmpGeo.computeVertexNormals(); // store morph normals
  7767. var faceNormal, vertexNormals;
  7768. for (f = 0, fl = this.faces.length; f < fl; f++) {
  7769. face = this.faces[f];
  7770. faceNormal = morphNormals.faceNormals[f];
  7771. vertexNormals = morphNormals.vertexNormals[f];
  7772. faceNormal.copy(face.normal);
  7773. vertexNormals.a.copy(face.vertexNormals[0]);
  7774. vertexNormals.b.copy(face.vertexNormals[1]);
  7775. vertexNormals.c.copy(face.vertexNormals[2]);
  7776. }
  7777. } // restore original normals
  7778. for (f = 0, fl = this.faces.length; f < fl; f++) {
  7779. face = this.faces[f];
  7780. face.normal = face.__originalFaceNormal;
  7781. face.vertexNormals = face.__originalVertexNormals;
  7782. }
  7783. },
  7784. computeBoundingBox: function () {
  7785. if (this.boundingBox === null) {
  7786. this.boundingBox = new Box3();
  7787. }
  7788. this.boundingBox.setFromPoints(this.vertices);
  7789. },
  7790. computeBoundingSphere: function () {
  7791. if (this.boundingSphere === null) {
  7792. this.boundingSphere = new Sphere();
  7793. }
  7794. this.boundingSphere.setFromPoints(this.vertices);
  7795. },
  7796. merge: function (geometry, matrix, materialIndexOffset) {
  7797. if (!(geometry && geometry.isGeometry)) {
  7798. console.error('THREE.Geometry.merge(): geometry not an instance of THREE.Geometry.', geometry);
  7799. return;
  7800. }
  7801. var normalMatrix,
  7802. vertexOffset = this.vertices.length,
  7803. vertices1 = this.vertices,
  7804. vertices2 = geometry.vertices,
  7805. faces1 = this.faces,
  7806. faces2 = geometry.faces,
  7807. colors1 = this.colors,
  7808. colors2 = geometry.colors;
  7809. if (materialIndexOffset === undefined) materialIndexOffset = 0;
  7810. if (matrix !== undefined) {
  7811. normalMatrix = new Matrix3().getNormalMatrix(matrix);
  7812. } // vertices
  7813. for (var i = 0, il = vertices2.length; i < il; i++) {
  7814. var vertex = vertices2[i];
  7815. var vertexCopy = vertex.clone();
  7816. if (matrix !== undefined) vertexCopy.applyMatrix4(matrix);
  7817. vertices1.push(vertexCopy);
  7818. } // colors
  7819. for (var i = 0, il = colors2.length; i < il; i++) {
  7820. colors1.push(colors2[i].clone());
  7821. } // faces
  7822. for (i = 0, il = faces2.length; i < il; i++) {
  7823. var face = faces2[i],
  7824. faceCopy,
  7825. normal,
  7826. color,
  7827. faceVertexNormals = face.vertexNormals,
  7828. faceVertexColors = face.vertexColors;
  7829. faceCopy = new Face3(face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset);
  7830. faceCopy.normal.copy(face.normal);
  7831. if (normalMatrix !== undefined) {
  7832. faceCopy.normal.applyMatrix3(normalMatrix).normalize();
  7833. }
  7834. for (var j = 0, jl = faceVertexNormals.length; j < jl; j++) {
  7835. normal = faceVertexNormals[j].clone();
  7836. if (normalMatrix !== undefined) {
  7837. normal.applyMatrix3(normalMatrix).normalize();
  7838. }
  7839. faceCopy.vertexNormals.push(normal);
  7840. }
  7841. faceCopy.color.copy(face.color);
  7842. for (var j = 0, jl = faceVertexColors.length; j < jl; j++) {
  7843. color = faceVertexColors[j];
  7844. faceCopy.vertexColors.push(color.clone());
  7845. }
  7846. faceCopy.materialIndex = face.materialIndex + materialIndexOffset;
  7847. faces1.push(faceCopy);
  7848. } // uvs
  7849. for (var i = 0, il = geometry.faceVertexUvs.length; i < il; i++) {
  7850. var faceVertexUvs2 = geometry.faceVertexUvs[i];
  7851. if (this.faceVertexUvs[i] === undefined) this.faceVertexUvs[i] = [];
  7852. for (var j = 0, jl = faceVertexUvs2.length; j < jl; j++) {
  7853. var uvs2 = faceVertexUvs2[j],
  7854. uvsCopy = [];
  7855. for (var k = 0, kl = uvs2.length; k < kl; k++) {
  7856. uvsCopy.push(uvs2[k].clone());
  7857. }
  7858. this.faceVertexUvs[i].push(uvsCopy);
  7859. }
  7860. }
  7861. },
  7862. mergeMesh: function (mesh) {
  7863. if (!(mesh && mesh.isMesh)) {
  7864. console.error('THREE.Geometry.mergeMesh(): mesh not an instance of THREE.Mesh.', mesh);
  7865. return;
  7866. }
  7867. if (mesh.matrixAutoUpdate) mesh.updateMatrix();
  7868. this.merge(mesh.geometry, mesh.matrix);
  7869. },
  7870. /*
  7871. * Checks for duplicate vertices with hashmap.
  7872. * Duplicated vertices are removed
  7873. * and faces' vertices are updated.
  7874. */
  7875. mergeVertices: function () {
  7876. var verticesMap = {}; // Hashmap for looking up vertices by position coordinates (and making sure they are unique)
  7877. var unique = [],
  7878. changes = [];
  7879. var v, key;
  7880. var precisionPoints = 4; // number of decimal points, e.g. 4 for epsilon of 0.0001
  7881. var precision = Math.pow(10, precisionPoints);
  7882. var i, il, face;
  7883. var indices, j, jl;
  7884. for (i = 0, il = this.vertices.length; i < il; i++) {
  7885. v = this.vertices[i];
  7886. key = Math.round(v.x * precision) + '_' + Math.round(v.y * precision) + '_' + Math.round(v.z * precision);
  7887. if (verticesMap[key] === undefined) {
  7888. verticesMap[key] = i;
  7889. unique.push(this.vertices[i]);
  7890. changes[i] = unique.length - 1;
  7891. } else {
  7892. //console.log('Duplicate vertex found. ', i, ' could be using ', verticesMap[key]);
  7893. changes[i] = changes[verticesMap[key]];
  7894. }
  7895. } // if faces are completely degenerate after merging vertices, we
  7896. // have to remove them from the geometry.
  7897. var faceIndicesToRemove = [];
  7898. for (i = 0, il = this.faces.length; i < il; i++) {
  7899. face = this.faces[i];
  7900. face.a = changes[face.a];
  7901. face.b = changes[face.b];
  7902. face.c = changes[face.c];
  7903. indices = [face.a, face.b, face.c]; // if any duplicate vertices are found in a Face3
  7904. // we have to remove the face as nothing can be saved
  7905. for (var n = 0; n < 3; n++) {
  7906. if (indices[n] === indices[(n + 1) % 3]) {
  7907. faceIndicesToRemove.push(i);
  7908. break;
  7909. }
  7910. }
  7911. }
  7912. for (i = faceIndicesToRemove.length - 1; i >= 0; i--) {
  7913. var idx = faceIndicesToRemove[i];
  7914. this.faces.splice(idx, 1);
  7915. for (j = 0, jl = this.faceVertexUvs.length; j < jl; j++) {
  7916. this.faceVertexUvs[j].splice(idx, 1);
  7917. }
  7918. } // Use unique set of vertices
  7919. var diff = this.vertices.length - unique.length;
  7920. this.vertices = unique;
  7921. return diff;
  7922. },
  7923. setFromPoints: function (points) {
  7924. this.vertices = [];
  7925. for (var i = 0, l = points.length; i < l; i++) {
  7926. var point = points[i];
  7927. this.vertices.push(new Vector3(point.x, point.y, point.z || 0));
  7928. }
  7929. return this;
  7930. },
  7931. sortFacesByMaterialIndex: function () {
  7932. var faces = this.faces;
  7933. var length = faces.length; // tag faces
  7934. for (var i = 0; i < length; i++) {
  7935. faces[i]._id = i;
  7936. } // sort faces
  7937. function materialIndexSort(a, b) {
  7938. return a.materialIndex - b.materialIndex;
  7939. }
  7940. faces.sort(materialIndexSort); // sort uvs
  7941. var uvs1 = this.faceVertexUvs[0];
  7942. var uvs2 = this.faceVertexUvs[1];
  7943. var newUvs1, newUvs2;
  7944. if (uvs1 && uvs1.length === length) newUvs1 = [];
  7945. if (uvs2 && uvs2.length === length) newUvs2 = [];
  7946. for (var i = 0; i < length; i++) {
  7947. var id = faces[i]._id;
  7948. if (newUvs1) newUvs1.push(uvs1[id]);
  7949. if (newUvs2) newUvs2.push(uvs2[id]);
  7950. }
  7951. if (newUvs1) this.faceVertexUvs[0] = newUvs1;
  7952. if (newUvs2) this.faceVertexUvs[1] = newUvs2;
  7953. },
  7954. toJSON: function () {
  7955. var data = {
  7956. metadata: {
  7957. version: 4.5,
  7958. type: 'Geometry',
  7959. generator: 'Geometry.toJSON'
  7960. }
  7961. }; // standard Geometry serialization
  7962. data.uuid = this.uuid;
  7963. data.type = this.type;
  7964. if (this.name !== '') data.name = this.name;
  7965. if (this.parameters !== undefined) {
  7966. var parameters = this.parameters;
  7967. for (var key in parameters) {
  7968. if (parameters[key] !== undefined) data[key] = parameters[key];
  7969. }
  7970. return data;
  7971. }
  7972. var vertices = [];
  7973. for (var i = 0; i < this.vertices.length; i++) {
  7974. var vertex = this.vertices[i];
  7975. vertices.push(vertex.x, vertex.y, vertex.z);
  7976. }
  7977. var faces = [];
  7978. var normals = [];
  7979. var normalsHash = {};
  7980. var colors = [];
  7981. var colorsHash = {};
  7982. var uvs = [];
  7983. var uvsHash = {};
  7984. for (var i = 0; i < this.faces.length; i++) {
  7985. var face = this.faces[i];
  7986. var hasMaterial = true;
  7987. var hasFaceUv = false; // deprecated
  7988. var hasFaceVertexUv = this.faceVertexUvs[0][i] !== undefined;
  7989. var hasFaceNormal = face.normal.length() > 0;
  7990. var hasFaceVertexNormal = face.vertexNormals.length > 0;
  7991. var hasFaceColor = face.color.r !== 1 || face.color.g !== 1 || face.color.b !== 1;
  7992. var hasFaceVertexColor = face.vertexColors.length > 0;
  7993. var faceType = 0;
  7994. faceType = setBit(faceType, 0, 0); // isQuad
  7995. faceType = setBit(faceType, 1, hasMaterial);
  7996. faceType = setBit(faceType, 2, hasFaceUv);
  7997. faceType = setBit(faceType, 3, hasFaceVertexUv);
  7998. faceType = setBit(faceType, 4, hasFaceNormal);
  7999. faceType = setBit(faceType, 5, hasFaceVertexNormal);
  8000. faceType = setBit(faceType, 6, hasFaceColor);
  8001. faceType = setBit(faceType, 7, hasFaceVertexColor);
  8002. faces.push(faceType);
  8003. faces.push(face.a, face.b, face.c);
  8004. faces.push(face.materialIndex);
  8005. if (hasFaceVertexUv) {
  8006. var faceVertexUvs = this.faceVertexUvs[0][i];
  8007. faces.push(getUvIndex(faceVertexUvs[0]), getUvIndex(faceVertexUvs[1]), getUvIndex(faceVertexUvs[2]));
  8008. }
  8009. if (hasFaceNormal) {
  8010. faces.push(getNormalIndex(face.normal));
  8011. }
  8012. if (hasFaceVertexNormal) {
  8013. var vertexNormals = face.vertexNormals;
  8014. faces.push(getNormalIndex(vertexNormals[0]), getNormalIndex(vertexNormals[1]), getNormalIndex(vertexNormals[2]));
  8015. }
  8016. if (hasFaceColor) {
  8017. faces.push(getColorIndex(face.color));
  8018. }
  8019. if (hasFaceVertexColor) {
  8020. var vertexColors = face.vertexColors;
  8021. faces.push(getColorIndex(vertexColors[0]), getColorIndex(vertexColors[1]), getColorIndex(vertexColors[2]));
  8022. }
  8023. }
  8024. function setBit(value, position, enabled) {
  8025. return enabled ? value | 1 << position : value & ~(1 << position);
  8026. }
  8027. function getNormalIndex(normal) {
  8028. var hash = normal.x.toString() + normal.y.toString() + normal.z.toString();
  8029. if (normalsHash[hash] !== undefined) {
  8030. return normalsHash[hash];
  8031. }
  8032. normalsHash[hash] = normals.length / 3;
  8033. normals.push(normal.x, normal.y, normal.z);
  8034. return normalsHash[hash];
  8035. }
  8036. function getColorIndex(color) {
  8037. var hash = color.r.toString() + color.g.toString() + color.b.toString();
  8038. if (colorsHash[hash] !== undefined) {
  8039. return colorsHash[hash];
  8040. }
  8041. colorsHash[hash] = colors.length;
  8042. colors.push(color.getHex());
  8043. return colorsHash[hash];
  8044. }
  8045. function getUvIndex(uv) {
  8046. var hash = uv.x.toString() + uv.y.toString();
  8047. if (uvsHash[hash] !== undefined) {
  8048. return uvsHash[hash];
  8049. }
  8050. uvsHash[hash] = uvs.length / 2;
  8051. uvs.push(uv.x, uv.y);
  8052. return uvsHash[hash];
  8053. }
  8054. data.data = {};
  8055. data.data.vertices = vertices;
  8056. data.data.normals = normals;
  8057. if (colors.length > 0) data.data.colors = colors;
  8058. if (uvs.length > 0) data.data.uvs = [uvs]; // temporal backward compatibility
  8059. data.data.faces = faces;
  8060. return data;
  8061. },
  8062. clone: function () {
  8063. /*
  8064. // Handle primitives
  8065. var parameters = this.parameters;
  8066. if ( parameters !== undefined ) {
  8067. var values = [];
  8068. for ( var key in parameters ) {
  8069. values.push( parameters[ key ] );
  8070. }
  8071. var geometry = Object.create( this.constructor.prototype );
  8072. this.constructor.apply( geometry, values );
  8073. return geometry;
  8074. }
  8075. return new this.constructor().copy( this );
  8076. */
  8077. return new Geometry().copy(this);
  8078. },
  8079. copy: function (source) {
  8080. var i, il, j, jl, k, kl; // reset
  8081. this.vertices = [];
  8082. this.colors = [];
  8083. this.faces = [];
  8084. this.faceVertexUvs = [[]];
  8085. this.morphTargets = [];
  8086. this.morphNormals = [];
  8087. this.skinWeights = [];
  8088. this.skinIndices = [];
  8089. this.lineDistances = [];
  8090. this.boundingBox = null;
  8091. this.boundingSphere = null; // name
  8092. this.name = source.name; // vertices
  8093. var vertices = source.vertices;
  8094. for (i = 0, il = vertices.length; i < il; i++) {
  8095. this.vertices.push(vertices[i].clone());
  8096. } // colors
  8097. var colors = source.colors;
  8098. for (i = 0, il = colors.length; i < il; i++) {
  8099. this.colors.push(colors[i].clone());
  8100. } // faces
  8101. var faces = source.faces;
  8102. for (i = 0, il = faces.length; i < il; i++) {
  8103. this.faces.push(faces[i].clone());
  8104. } // face vertex uvs
  8105. for (i = 0, il = source.faceVertexUvs.length; i < il; i++) {
  8106. var faceVertexUvs = source.faceVertexUvs[i];
  8107. if (this.faceVertexUvs[i] === undefined) {
  8108. this.faceVertexUvs[i] = [];
  8109. }
  8110. for (j = 0, jl = faceVertexUvs.length; j < jl; j++) {
  8111. var uvs = faceVertexUvs[j],
  8112. uvsCopy = [];
  8113. for (k = 0, kl = uvs.length; k < kl; k++) {
  8114. var uv = uvs[k];
  8115. uvsCopy.push(uv.clone());
  8116. }
  8117. this.faceVertexUvs[i].push(uvsCopy);
  8118. }
  8119. } // morph targets
  8120. var morphTargets = source.morphTargets;
  8121. for (i = 0, il = morphTargets.length; i < il; i++) {
  8122. var morphTarget = {};
  8123. morphTarget.name = morphTargets[i].name; // vertices
  8124. if (morphTargets[i].vertices !== undefined) {
  8125. morphTarget.vertices = [];
  8126. for (j = 0, jl = morphTargets[i].vertices.length; j < jl; j++) {
  8127. morphTarget.vertices.push(morphTargets[i].vertices[j].clone());
  8128. }
  8129. } // normals
  8130. if (morphTargets[i].normals !== undefined) {
  8131. morphTarget.normals = [];
  8132. for (j = 0, jl = morphTargets[i].normals.length; j < jl; j++) {
  8133. morphTarget.normals.push(morphTargets[i].normals[j].clone());
  8134. }
  8135. }
  8136. this.morphTargets.push(morphTarget);
  8137. } // morph normals
  8138. var morphNormals = source.morphNormals;
  8139. for (i = 0, il = morphNormals.length; i < il; i++) {
  8140. var morphNormal = {}; // vertex normals
  8141. if (morphNormals[i].vertexNormals !== undefined) {
  8142. morphNormal.vertexNormals = [];
  8143. for (j = 0, jl = morphNormals[i].vertexNormals.length; j < jl; j++) {
  8144. var srcVertexNormal = morphNormals[i].vertexNormals[j];
  8145. var destVertexNormal = {};
  8146. destVertexNormal.a = srcVertexNormal.a.clone();
  8147. destVertexNormal.b = srcVertexNormal.b.clone();
  8148. destVertexNormal.c = srcVertexNormal.c.clone();
  8149. morphNormal.vertexNormals.push(destVertexNormal);
  8150. }
  8151. } // face normals
  8152. if (morphNormals[i].faceNormals !== undefined) {
  8153. morphNormal.faceNormals = [];
  8154. for (j = 0, jl = morphNormals[i].faceNormals.length; j < jl; j++) {
  8155. morphNormal.faceNormals.push(morphNormals[i].faceNormals[j].clone());
  8156. }
  8157. }
  8158. this.morphNormals.push(morphNormal);
  8159. } // skin weights
  8160. var skinWeights = source.skinWeights;
  8161. for (i = 0, il = skinWeights.length; i < il; i++) {
  8162. this.skinWeights.push(skinWeights[i].clone());
  8163. } // skin indices
  8164. var skinIndices = source.skinIndices;
  8165. for (i = 0, il = skinIndices.length; i < il; i++) {
  8166. this.skinIndices.push(skinIndices[i].clone());
  8167. } // line distances
  8168. var lineDistances = source.lineDistances;
  8169. for (i = 0, il = lineDistances.length; i < il; i++) {
  8170. this.lineDistances.push(lineDistances[i]);
  8171. } // bounding box
  8172. var boundingBox = source.boundingBox;
  8173. if (boundingBox !== null) {
  8174. this.boundingBox = boundingBox.clone();
  8175. } // bounding sphere
  8176. var boundingSphere = source.boundingSphere;
  8177. if (boundingSphere !== null) {
  8178. this.boundingSphere = boundingSphere.clone();
  8179. } // update flags
  8180. this.elementsNeedUpdate = source.elementsNeedUpdate;
  8181. this.verticesNeedUpdate = source.verticesNeedUpdate;
  8182. this.uvsNeedUpdate = source.uvsNeedUpdate;
  8183. this.normalsNeedUpdate = source.normalsNeedUpdate;
  8184. this.colorsNeedUpdate = source.colorsNeedUpdate;
  8185. this.lineDistancesNeedUpdate = source.lineDistancesNeedUpdate;
  8186. this.groupsNeedUpdate = source.groupsNeedUpdate;
  8187. return this;
  8188. },
  8189. dispose: function () {
  8190. this.dispatchEvent({
  8191. type: 'dispose'
  8192. });
  8193. }
  8194. });
  8195. /**
  8196. * @author mrdoob / http://mrdoob.com/
  8197. * @author Mugen87 / https://github.com/Mugen87
  8198. */
  8199. // BoxGeometry
  8200. class BoxGeometry extends Geometry {
  8201. constructor(width, height, depth, widthSegments, heightSegments, depthSegments) {
  8202. super();
  8203. this.type = 'BoxGeometry';
  8204. this.parameters = {
  8205. width: width,
  8206. height: height,
  8207. depth: depth,
  8208. widthSegments: widthSegments,
  8209. heightSegments: heightSegments,
  8210. depthSegments: depthSegments
  8211. };
  8212. this.fromBufferGeometry(new BoxBufferGeometry(width, height, depth, widthSegments, heightSegments, depthSegments));
  8213. this.mergeVertices();
  8214. }
  8215. } // BoxBufferGeometry
  8216. exports.CubeGeometry = exports.BoxGeometry = BoxGeometry;
  8217. class BoxBufferGeometry extends BufferGeometry {
  8218. constructor(width, height, depth, widthSegments, heightSegments, depthSegments) {
  8219. super();
  8220. this.type = 'BoxBufferGeometry';
  8221. this.parameters = {
  8222. width: width,
  8223. height: height,
  8224. depth: depth,
  8225. widthSegments: widthSegments,
  8226. heightSegments: heightSegments,
  8227. depthSegments: depthSegments
  8228. };
  8229. var scope = this;
  8230. width = width || 1;
  8231. height = height || 1;
  8232. depth = depth || 1; // segments
  8233. widthSegments = Math.floor(widthSegments) || 1;
  8234. heightSegments = Math.floor(heightSegments) || 1;
  8235. depthSegments = Math.floor(depthSegments) || 1; // buffers
  8236. var indices = [];
  8237. var vertices = [];
  8238. var normals = [];
  8239. var uvs = []; // helper variables
  8240. var numberOfVertices = 0;
  8241. var groupStart = 0; // build each side of the box geometry
  8242. buildPlane('z', 'y', 'x', -1, -1, depth, height, width, depthSegments, heightSegments, 0); // px
  8243. buildPlane('z', 'y', 'x', 1, -1, depth, height, -width, depthSegments, heightSegments, 1); // nx
  8244. buildPlane('x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2); // py
  8245. buildPlane('x', 'z', 'y', 1, -1, width, depth, -height, widthSegments, depthSegments, 3); // ny
  8246. buildPlane('x', 'y', 'z', 1, -1, width, height, depth, widthSegments, heightSegments, 4); // pz
  8247. buildPlane('x', 'y', 'z', -1, -1, width, height, -depth, widthSegments, heightSegments, 5); // nz
  8248. // build geometry
  8249. this.setIndex(indices);
  8250. this.addAttribute('position', new Float32BufferAttribute(vertices, 3));
  8251. this.addAttribute('normal', new Float32BufferAttribute(normals, 3));
  8252. this.addAttribute('uv', new Float32BufferAttribute(uvs, 2));
  8253. function buildPlane(u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex) {
  8254. var segmentWidth = width / gridX;
  8255. var segmentHeight = height / gridY;
  8256. var widthHalf = width / 2;
  8257. var heightHalf = height / 2;
  8258. var depthHalf = depth / 2;
  8259. var gridX1 = gridX + 1;
  8260. var gridY1 = gridY + 1;
  8261. var vertexCounter = 0;
  8262. var groupCount = 0;
  8263. var ix, iy;
  8264. var vector = new Vector3(); // generate vertices, normals and uvs
  8265. for (iy = 0; iy < gridY1; iy++) {
  8266. var y = iy * segmentHeight - heightHalf;
  8267. for (ix = 0; ix < gridX1; ix++) {
  8268. var x = ix * segmentWidth - widthHalf; // set values to correct vector component
  8269. vector[u] = x * udir;
  8270. vector[v] = y * vdir;
  8271. vector[w] = depthHalf; // now apply vector to vertex buffer
  8272. vertices.push(vector.x, vector.y, vector.z); // set values to correct vector component
  8273. vector[u] = 0;
  8274. vector[v] = 0;
  8275. vector[w] = depth > 0 ? 1 : -1; // now apply vector to normal buffer
  8276. normals.push(vector.x, vector.y, vector.z); // uvs
  8277. uvs.push(ix / gridX);
  8278. uvs.push(1 - iy / gridY); // counters
  8279. vertexCounter += 1;
  8280. }
  8281. } // indices
  8282. // 1. you need three indices to draw a single face
  8283. // 2. a single segment consists of two faces
  8284. // 3. so we need to generate six (2*3) indices per segment
  8285. for (iy = 0; iy < gridY; iy++) {
  8286. for (ix = 0; ix < gridX; ix++) {
  8287. var a = numberOfVertices + ix + gridX1 * iy;
  8288. var b = numberOfVertices + ix + gridX1 * (iy + 1);
  8289. var c = numberOfVertices + (ix + 1) + gridX1 * (iy + 1);
  8290. var d = numberOfVertices + (ix + 1) + gridX1 * iy; // faces
  8291. indices.push(a, b, d);
  8292. indices.push(b, c, d); // increase counter
  8293. groupCount += 6;
  8294. }
  8295. } // add a group to the geometry. this will ensure multi material support
  8296. scope.addGroup(groupStart, groupCount, materialIndex); // calculate new start value for groups
  8297. groupStart += groupCount; // update total number of vertices
  8298. numberOfVertices += vertexCounter;
  8299. }
  8300. }
  8301. }
  8302. /**
  8303. * Uniform Utilities
  8304. */
  8305. exports.BoxBufferGeometry = BoxBufferGeometry;
  8306. function cloneUniforms(src) {
  8307. var dst = {};
  8308. for (var u in src) {
  8309. dst[u] = {};
  8310. for (var p in src[u]) {
  8311. var property = src[u][p];
  8312. if (property && (property.isColor || property.isMatrix3 || property.isMatrix4 || property.isVector2 || property.isVector3 || property.isVector4 || property.isTexture)) {
  8313. dst[u][p] = property.clone();
  8314. } else if (Array.isArray(property)) {
  8315. dst[u][p] = property.slice();
  8316. } else {
  8317. dst[u][p] = property;
  8318. }
  8319. }
  8320. }
  8321. return dst;
  8322. }
  8323. function mergeUniforms(uniforms) {
  8324. var merged = {};
  8325. for (var u = 0; u < uniforms.length; u++) {
  8326. var tmp = cloneUniforms(uniforms[u]);
  8327. for (var p in tmp) {
  8328. merged[p] = tmp[p];
  8329. }
  8330. }
  8331. return merged;
  8332. } // Legacy
  8333. var UniformsUtils = {
  8334. clone: cloneUniforms,
  8335. merge: mergeUniforms
  8336. };
  8337. exports.UniformsUtils = UniformsUtils;
  8338. var default_vertex = "void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}";
  8339. var default_fragment = "void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}";
  8340. /**
  8341. * @author alteredq / http://alteredqualia.com/
  8342. *
  8343. * parameters = {
  8344. * defines: { "label" : "value" },
  8345. * uniforms: { "parameter1": { value: 1.0 }, "parameter2": { value2: 2 } },
  8346. *
  8347. * fragmentShader: <string>,
  8348. * vertexShader: <string>,
  8349. *
  8350. * wireframe: <boolean>,
  8351. * wireframeLinewidth: <float>,
  8352. *
  8353. * lights: <bool>,
  8354. *
  8355. * skinning: <bool>,
  8356. * morphTargets: <bool>,
  8357. * morphNormals: <bool>
  8358. * }
  8359. */
  8360. function ShaderMaterial(parameters) {
  8361. Material.call(this);
  8362. this.type = 'ShaderMaterial';
  8363. this.defines = {};
  8364. this.uniforms = {};
  8365. this.vertexShader = default_vertex;
  8366. this.fragmentShader = default_fragment;
  8367. this.linewidth = 1;
  8368. this.wireframe = false;
  8369. this.wireframeLinewidth = 1;
  8370. this.fog = false; // set to use scene fog
  8371. this.lights = false; // set to use scene lights
  8372. this.clipping = false; // set to use user-defined clipping planes
  8373. this.skinning = false; // set to use skinning attribute streams
  8374. this.morphTargets = false; // set to use morph targets
  8375. this.morphNormals = false; // set to use morph normals
  8376. this.extensions = {
  8377. derivatives: false,
  8378. // set to use derivatives
  8379. fragDepth: false,
  8380. // set to use fragment depth values
  8381. drawBuffers: false,
  8382. // set to use draw buffers
  8383. shaderTextureLOD: false // set to use shader texture LOD
  8384. }; // When rendered geometry doesn't include these attributes but the material does,
  8385. // use these default values in WebGL. This avoids errors when buffer data is missing.
  8386. this.defaultAttributeValues = {
  8387. 'color': [1, 1, 1],
  8388. 'uv': [0, 0],
  8389. 'uv2': [0, 0]
  8390. };
  8391. this.index0AttributeName = undefined;
  8392. this.uniformsNeedUpdate = false;
  8393. if (parameters !== undefined) {
  8394. if (parameters.attributes !== undefined) {
  8395. console.error('THREE.ShaderMaterial: attributes should now be defined in THREE.BufferGeometry instead.');
  8396. }
  8397. this.setValues(parameters);
  8398. }
  8399. }
  8400. ShaderMaterial.prototype = Object.create(Material.prototype);
  8401. ShaderMaterial.prototype.constructor = ShaderMaterial;
  8402. ShaderMaterial.prototype.isShaderMaterial = true;
  8403. ShaderMaterial.prototype.copy = function (source) {
  8404. Material.prototype.copy.call(this, source);
  8405. this.fragmentShader = source.fragmentShader;
  8406. this.vertexShader = source.vertexShader;
  8407. this.uniforms = cloneUniforms(source.uniforms);
  8408. this.defines = Object.assign({}, source.defines);
  8409. this.wireframe = source.wireframe;
  8410. this.wireframeLinewidth = source.wireframeLinewidth;
  8411. this.lights = source.lights;
  8412. this.clipping = source.clipping;
  8413. this.skinning = source.skinning;
  8414. this.morphTargets = source.morphTargets;
  8415. this.morphNormals = source.morphNormals;
  8416. this.extensions = source.extensions;
  8417. return this;
  8418. };
  8419. ShaderMaterial.prototype.toJSON = function (meta) {
  8420. var data = Material.prototype.toJSON.call(this, meta);
  8421. data.uniforms = {};
  8422. for (var name in this.uniforms) {
  8423. var uniform = this.uniforms[name];
  8424. var value = uniform.value;
  8425. if (value && value.isTexture) {
  8426. data.uniforms[name] = {
  8427. type: 't',
  8428. value: value.toJSON(meta).uuid
  8429. };
  8430. } else if (value && value.isColor) {
  8431. data.uniforms[name] = {
  8432. type: 'c',
  8433. value: value.getHex()
  8434. };
  8435. } else if (value && value.isVector2) {
  8436. data.uniforms[name] = {
  8437. type: 'v2',
  8438. value: value.toArray()
  8439. };
  8440. } else if (value && value.isVector3) {
  8441. data.uniforms[name] = {
  8442. type: 'v3',
  8443. value: value.toArray()
  8444. };
  8445. } else if (value && value.isVector4) {
  8446. data.uniforms[name] = {
  8447. type: 'v4',
  8448. value: value.toArray()
  8449. };
  8450. } else if (value && value.isMatrix3) {
  8451. data.uniforms[name] = {
  8452. type: 'm3',
  8453. value: value.toArray()
  8454. };
  8455. } else if (value && value.isMatrix4) {
  8456. data.uniforms[name] = {
  8457. type: 'm4',
  8458. value: value.toArray()
  8459. };
  8460. } else {
  8461. data.uniforms[name] = {
  8462. value: value
  8463. }; // note: the array variants v2v, v3v, v4v, m4v and tv are not supported so far
  8464. }
  8465. }
  8466. if (Object.keys(this.defines).length > 0) data.defines = this.defines;
  8467. data.vertexShader = this.vertexShader;
  8468. data.fragmentShader = this.fragmentShader;
  8469. var extensions = {};
  8470. for (var key in this.extensions) {
  8471. if (this.extensions[key] === true) extensions[key] = true;
  8472. }
  8473. if (Object.keys(extensions).length > 0) data.extensions = extensions;
  8474. return data;
  8475. };
  8476. /**
  8477. * @author mrdoob / http://mrdoob.com/
  8478. * @author mikael emtinger / http://gomo.se/
  8479. * @author WestLangley / http://github.com/WestLangley
  8480. */
  8481. function Camera() {
  8482. Object3D.call(this);
  8483. this.type = 'Camera';
  8484. this.matrixWorldInverse = new Matrix4();
  8485. this.projectionMatrix = new Matrix4();
  8486. this.projectionMatrixInverse = new Matrix4();
  8487. }
  8488. Camera.prototype = Object.assign(Object.create(Object3D.prototype), {
  8489. constructor: Camera,
  8490. isCamera: true,
  8491. copy: function (source, recursive) {
  8492. Object3D.prototype.copy.call(this, source, recursive);
  8493. this.matrixWorldInverse.copy(source.matrixWorldInverse);
  8494. this.projectionMatrix.copy(source.projectionMatrix);
  8495. this.projectionMatrixInverse.copy(source.projectionMatrixInverse);
  8496. return this;
  8497. },
  8498. getWorldDirection: function (target) {
  8499. if (target === undefined) {
  8500. console.warn('THREE.Camera: .getWorldDirection() target is now required');
  8501. target = new Vector3();
  8502. }
  8503. this.updateMatrixWorld(true);
  8504. var e = this.matrixWorld.elements;
  8505. return target.set(-e[8], -e[9], -e[10]).normalize();
  8506. },
  8507. updateMatrixWorld: function (force) {
  8508. Object3D.prototype.updateMatrixWorld.call(this, force);
  8509. this.matrixWorldInverse.getInverse(this.matrixWorld);
  8510. },
  8511. clone: function () {
  8512. return new this.constructor().copy(this);
  8513. }
  8514. });
  8515. /**
  8516. * @author mrdoob / http://mrdoob.com/
  8517. * @author greggman / http://games.greggman.com/
  8518. * @author zz85 / http://www.lab4games.net/zz85/blog
  8519. * @author tschw
  8520. */
  8521. function PerspectiveCamera(fov, aspect, near, far) {
  8522. Camera.call(this);
  8523. this.type = 'PerspectiveCamera';
  8524. this.fov = fov !== undefined ? fov : 50;
  8525. this.zoom = 1;
  8526. this.near = near !== undefined ? near : 0.1;
  8527. this.far = far !== undefined ? far : 2000;
  8528. this.focus = 10;
  8529. this.aspect = aspect !== undefined ? aspect : 1;
  8530. this.view = null;
  8531. this.filmGauge = 35; // width of the film (default in millimeters)
  8532. this.filmOffset = 0; // horizontal film offset (same unit as gauge)
  8533. this.updateProjectionMatrix();
  8534. }
  8535. PerspectiveCamera.prototype = Object.assign(Object.create(Camera.prototype), {
  8536. constructor: PerspectiveCamera,
  8537. isPerspectiveCamera: true,
  8538. copy: function (source, recursive) {
  8539. Camera.prototype.copy.call(this, source, recursive);
  8540. this.fov = source.fov;
  8541. this.zoom = source.zoom;
  8542. this.near = source.near;
  8543. this.far = source.far;
  8544. this.focus = source.focus;
  8545. this.aspect = source.aspect;
  8546. this.view = source.view === null ? null : Object.assign({}, source.view);
  8547. this.filmGauge = source.filmGauge;
  8548. this.filmOffset = source.filmOffset;
  8549. return this;
  8550. },
  8551. /**
  8552. * Sets the FOV by focal length in respect to the current .filmGauge.
  8553. *
  8554. * The default film gauge is 35, so that the focal length can be specified for
  8555. * a 35mm (full frame) camera.
  8556. *
  8557. * Values for focal length and film gauge must have the same unit.
  8558. */
  8559. setFocalLength: function (focalLength) {
  8560. // see http://www.bobatkins.com/photography/technical/field_of_view.html
  8561. var vExtentSlope = 0.5 * this.getFilmHeight() / focalLength;
  8562. this.fov = _Math.RAD2DEG * 2 * Math.atan(vExtentSlope);
  8563. this.updateProjectionMatrix();
  8564. },
  8565. /**
  8566. * Calculates the focal length from the current .fov and .filmGauge.
  8567. */
  8568. getFocalLength: function () {
  8569. var vExtentSlope = Math.tan(_Math.DEG2RAD * 0.5 * this.fov);
  8570. return 0.5 * this.getFilmHeight() / vExtentSlope;
  8571. },
  8572. getEffectiveFOV: function () {
  8573. return _Math.RAD2DEG * 2 * Math.atan(Math.tan(_Math.DEG2RAD * 0.5 * this.fov) / this.zoom);
  8574. },
  8575. getFilmWidth: function () {
  8576. // film not completely covered in portrait format (aspect < 1)
  8577. return this.filmGauge * Math.min(this.aspect, 1);
  8578. },
  8579. getFilmHeight: function () {
  8580. // film not completely covered in landscape format (aspect > 1)
  8581. return this.filmGauge / Math.max(this.aspect, 1);
  8582. },
  8583. /**
  8584. * Sets an offset in a larger frustum. This is useful for multi-window or
  8585. * multi-monitor/multi-machine setups.
  8586. *
  8587. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  8588. * the monitors are in grid like this
  8589. *
  8590. * +---+---+---+
  8591. * | A | B | C |
  8592. * +---+---+---+
  8593. * | D | E | F |
  8594. * +---+---+---+
  8595. *
  8596. * then for each monitor you would call it like this
  8597. *
  8598. * var w = 1920;
  8599. * var h = 1080;
  8600. * var fullWidth = w * 3;
  8601. * var fullHeight = h * 2;
  8602. *
  8603. * --A--
  8604. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  8605. * --B--
  8606. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  8607. * --C--
  8608. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  8609. * --D--
  8610. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  8611. * --E--
  8612. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  8613. * --F--
  8614. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  8615. *
  8616. * Note there is no reason monitors have to be the same size or in a grid.
  8617. */
  8618. setViewOffset: function (fullWidth, fullHeight, x, y, width, height) {
  8619. this.aspect = fullWidth / fullHeight;
  8620. if (this.view === null) {
  8621. this.view = {
  8622. enabled: true,
  8623. fullWidth: 1,
  8624. fullHeight: 1,
  8625. offsetX: 0,
  8626. offsetY: 0,
  8627. width: 1,
  8628. height: 1
  8629. };
  8630. }
  8631. this.view.enabled = true;
  8632. this.view.fullWidth = fullWidth;
  8633. this.view.fullHeight = fullHeight;
  8634. this.view.offsetX = x;
  8635. this.view.offsetY = y;
  8636. this.view.width = width;
  8637. this.view.height = height;
  8638. this.updateProjectionMatrix();
  8639. },
  8640. clearViewOffset: function () {
  8641. if (this.view !== null) {
  8642. this.view.enabled = false;
  8643. }
  8644. this.updateProjectionMatrix();
  8645. },
  8646. updateProjectionMatrix: function () {
  8647. var near = this.near,
  8648. top = near * Math.tan(_Math.DEG2RAD * 0.5 * this.fov) / this.zoom,
  8649. height = 2 * top,
  8650. width = this.aspect * height,
  8651. left = -0.5 * width,
  8652. view = this.view;
  8653. if (this.view !== null && this.view.enabled) {
  8654. var fullWidth = view.fullWidth,
  8655. fullHeight = view.fullHeight;
  8656. left += view.offsetX * width / fullWidth;
  8657. top -= view.offsetY * height / fullHeight;
  8658. width *= view.width / fullWidth;
  8659. height *= view.height / fullHeight;
  8660. }
  8661. var skew = this.filmOffset;
  8662. if (skew !== 0) left += near * skew / this.getFilmWidth();
  8663. this.projectionMatrix.makePerspective(left, left + width, top, top - height, near, this.far);
  8664. this.projectionMatrixInverse.getInverse(this.projectionMatrix);
  8665. },
  8666. toJSON: function (meta) {
  8667. var data = Object3D.prototype.toJSON.call(this, meta);
  8668. data.object.fov = this.fov;
  8669. data.object.zoom = this.zoom;
  8670. data.object.near = this.near;
  8671. data.object.far = this.far;
  8672. data.object.focus = this.focus;
  8673. data.object.aspect = this.aspect;
  8674. if (this.view !== null) data.object.view = Object.assign({}, this.view);
  8675. data.object.filmGauge = this.filmGauge;
  8676. data.object.filmOffset = this.filmOffset;
  8677. return data;
  8678. }
  8679. });
  8680. /**
  8681. * Camera for rendering cube maps
  8682. * - renders scene into axis-aligned cube
  8683. *
  8684. * @author alteredq / http://alteredqualia.com/
  8685. */
  8686. var fov = 90,
  8687. aspect = 1;
  8688. function CubeCamera(near, far, cubeResolution, options) {
  8689. Object3D.call(this);
  8690. this.type = 'CubeCamera';
  8691. var cameraPX = new PerspectiveCamera(fov, aspect, near, far);
  8692. cameraPX.up.set(0, -1, 0);
  8693. cameraPX.lookAt(new Vector3(1, 0, 0));
  8694. this.add(cameraPX);
  8695. var cameraNX = new PerspectiveCamera(fov, aspect, near, far);
  8696. cameraNX.up.set(0, -1, 0);
  8697. cameraNX.lookAt(new Vector3(-1, 0, 0));
  8698. this.add(cameraNX);
  8699. var cameraPY = new PerspectiveCamera(fov, aspect, near, far);
  8700. cameraPY.up.set(0, 0, 1);
  8701. cameraPY.lookAt(new Vector3(0, 1, 0));
  8702. this.add(cameraPY);
  8703. var cameraNY = new PerspectiveCamera(fov, aspect, near, far);
  8704. cameraNY.up.set(0, 0, -1);
  8705. cameraNY.lookAt(new Vector3(0, -1, 0));
  8706. this.add(cameraNY);
  8707. var cameraPZ = new PerspectiveCamera(fov, aspect, near, far);
  8708. cameraPZ.up.set(0, -1, 0);
  8709. cameraPZ.lookAt(new Vector3(0, 0, 1));
  8710. this.add(cameraPZ);
  8711. var cameraNZ = new PerspectiveCamera(fov, aspect, near, far);
  8712. cameraNZ.up.set(0, -1, 0);
  8713. cameraNZ.lookAt(new Vector3(0, 0, -1));
  8714. this.add(cameraNZ);
  8715. options = options || {
  8716. format: RGBFormat,
  8717. magFilter: LinearFilter,
  8718. minFilter: LinearFilter
  8719. };
  8720. this.renderTarget = new WebGLRenderTargetCube(cubeResolution, cubeResolution, options);
  8721. this.renderTarget.texture.name = "CubeCamera";
  8722. this.update = function (renderer, scene) {
  8723. if (this.parent === null) this.updateMatrixWorld();
  8724. var currentRenderTarget = renderer.getRenderTarget();
  8725. var renderTarget = this.renderTarget;
  8726. var generateMipmaps = renderTarget.texture.generateMipmaps;
  8727. renderTarget.texture.generateMipmaps = false;
  8728. renderer.setRenderTarget(renderTarget, 0);
  8729. renderer.render(scene, cameraPX);
  8730. renderer.setRenderTarget(renderTarget, 1);
  8731. renderer.render(scene, cameraNX);
  8732. renderer.setRenderTarget(renderTarget, 2);
  8733. renderer.render(scene, cameraPY);
  8734. renderer.setRenderTarget(renderTarget, 3);
  8735. renderer.render(scene, cameraNY);
  8736. renderer.setRenderTarget(renderTarget, 4);
  8737. renderer.render(scene, cameraPZ);
  8738. renderTarget.texture.generateMipmaps = generateMipmaps;
  8739. renderer.setRenderTarget(renderTarget, 5);
  8740. renderer.render(scene, cameraNZ);
  8741. renderer.setRenderTarget(currentRenderTarget);
  8742. };
  8743. this.clear = function (renderer, color, depth, stencil) {
  8744. var currentRenderTarget = renderer.getRenderTarget();
  8745. var renderTarget = this.renderTarget;
  8746. for (var i = 0; i < 6; i++) {
  8747. renderer.setRenderTarget(renderTarget, i);
  8748. renderer.clear(color, depth, stencil);
  8749. }
  8750. renderer.setRenderTarget(currentRenderTarget);
  8751. };
  8752. }
  8753. CubeCamera.prototype = Object.create(Object3D.prototype);
  8754. CubeCamera.prototype.constructor = CubeCamera;
  8755. /**
  8756. * @author alteredq / http://alteredqualia.com
  8757. * @author WestLangley / http://github.com/WestLangley
  8758. */
  8759. function WebGLRenderTargetCube(width, height, options) {
  8760. WebGLRenderTarget.call(this, width, height, options);
  8761. }
  8762. WebGLRenderTargetCube.prototype = Object.create(WebGLRenderTarget.prototype);
  8763. WebGLRenderTargetCube.prototype.constructor = WebGLRenderTargetCube;
  8764. WebGLRenderTargetCube.prototype.isWebGLRenderTargetCube = true;
  8765. WebGLRenderTargetCube.prototype.fromEquirectangularTexture = function (renderer, texture) {
  8766. this.texture.type = texture.type;
  8767. this.texture.format = texture.format;
  8768. this.texture.encoding = texture.encoding;
  8769. var scene = new Scene();
  8770. var shader = {
  8771. uniforms: {
  8772. tEquirect: {
  8773. value: null
  8774. }
  8775. },
  8776. 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'),
  8777. 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')
  8778. };
  8779. var material = new ShaderMaterial({
  8780. type: 'CubemapFromEquirect',
  8781. uniforms: cloneUniforms(shader.uniforms),
  8782. vertexShader: shader.vertexShader,
  8783. fragmentShader: shader.fragmentShader,
  8784. side: BackSide,
  8785. blending: NoBlending
  8786. });
  8787. material.uniforms.tEquirect.value = texture;
  8788. var mesh = new Mesh(new BoxBufferGeometry(5, 5, 5), material);
  8789. scene.add(mesh);
  8790. var camera = new CubeCamera(1, 10, 1);
  8791. camera.renderTarget = this;
  8792. camera.renderTarget.texture.name = 'CubeCameraTexture';
  8793. camera.update(renderer, scene);
  8794. mesh.geometry.dispose();
  8795. mesh.material.dispose();
  8796. return this;
  8797. };
  8798. /**
  8799. * @author alteredq / http://alteredqualia.com/
  8800. */
  8801. function DataTexture(data, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding) {
  8802. Texture.call(this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding);
  8803. this.image = {
  8804. data: data || null,
  8805. width: width || 1,
  8806. height: height || 1
  8807. };
  8808. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  8809. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  8810. this.generateMipmaps = false;
  8811. this.flipY = false;
  8812. this.unpackAlignment = 1;
  8813. this.needsUpdate = true;
  8814. }
  8815. DataTexture.prototype = Object.create(Texture.prototype);
  8816. DataTexture.prototype.constructor = DataTexture;
  8817. DataTexture.prototype.isDataTexture = true;
  8818. /**
  8819. * @author bhouston / http://clara.io
  8820. */
  8821. var _vector1 = new Vector3();
  8822. var _vector2 = new Vector3();
  8823. var _normalMatrix = new Matrix3();
  8824. function Plane(normal, constant) {
  8825. // normal is assumed to be normalized
  8826. this.normal = normal !== undefined ? normal : new Vector3(1, 0, 0);
  8827. this.constant = constant !== undefined ? constant : 0;
  8828. }
  8829. Object.assign(Plane.prototype, {
  8830. isPlane: true,
  8831. set: function (normal, constant) {
  8832. this.normal.copy(normal);
  8833. this.constant = constant;
  8834. return this;
  8835. },
  8836. setComponents: function (x, y, z, w) {
  8837. this.normal.set(x, y, z);
  8838. this.constant = w;
  8839. return this;
  8840. },
  8841. setFromNormalAndCoplanarPoint: function (normal, point) {
  8842. this.normal.copy(normal);
  8843. this.constant = -point.dot(this.normal);
  8844. return this;
  8845. },
  8846. setFromCoplanarPoints: function (a, b, c) {
  8847. 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)?
  8848. this.setFromNormalAndCoplanarPoint(normal, a);
  8849. return this;
  8850. },
  8851. clone: function () {
  8852. return new this.constructor().copy(this);
  8853. },
  8854. copy: function (plane) {
  8855. this.normal.copy(plane.normal);
  8856. this.constant = plane.constant;
  8857. return this;
  8858. },
  8859. normalize: function () {
  8860. // Note: will lead to a divide by zero if the plane is invalid.
  8861. var inverseNormalLength = 1.0 / this.normal.length();
  8862. this.normal.multiplyScalar(inverseNormalLength);
  8863. this.constant *= inverseNormalLength;
  8864. return this;
  8865. },
  8866. negate: function () {
  8867. this.constant *= -1;
  8868. this.normal.negate();
  8869. return this;
  8870. },
  8871. distanceToPoint: function (point) {
  8872. return this.normal.dot(point) + this.constant;
  8873. },
  8874. distanceToSphere: function (sphere) {
  8875. return this.distanceToPoint(sphere.center) - sphere.radius;
  8876. },
  8877. projectPoint: function (point, target) {
  8878. if (target === undefined) {
  8879. console.warn('THREE.Plane: .projectPoint() target is now required');
  8880. target = new Vector3();
  8881. }
  8882. return target.copy(this.normal).multiplyScalar(-this.distanceToPoint(point)).add(point);
  8883. },
  8884. intersectLine: function (line, target) {
  8885. if (target === undefined) {
  8886. console.warn('THREE.Plane: .intersectLine() target is now required');
  8887. target = new Vector3();
  8888. }
  8889. var direction = line.delta(_vector1);
  8890. var denominator = this.normal.dot(direction);
  8891. if (denominator === 0) {
  8892. // line is coplanar, return origin
  8893. if (this.distanceToPoint(line.start) === 0) {
  8894. return target.copy(line.start);
  8895. } // Unsure if this is the correct method to handle this case.
  8896. return undefined;
  8897. }
  8898. var t = -(line.start.dot(this.normal) + this.constant) / denominator;
  8899. if (t < 0 || t > 1) {
  8900. return undefined;
  8901. }
  8902. return target.copy(direction).multiplyScalar(t).add(line.start);
  8903. },
  8904. intersectsLine: function (line) {
  8905. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  8906. var startSign = this.distanceToPoint(line.start);
  8907. var endSign = this.distanceToPoint(line.end);
  8908. return startSign < 0 && endSign > 0 || endSign < 0 && startSign > 0;
  8909. },
  8910. intersectsBox: function (box) {
  8911. return box.intersectsPlane(this);
  8912. },
  8913. intersectsSphere: function (sphere) {
  8914. return sphere.intersectsPlane(this);
  8915. },
  8916. coplanarPoint: function (target) {
  8917. if (target === undefined) {
  8918. console.warn('THREE.Plane: .coplanarPoint() target is now required');
  8919. target = new Vector3();
  8920. }
  8921. return target.copy(this.normal).multiplyScalar(-this.constant);
  8922. },
  8923. applyMatrix4: function (matrix, optionalNormalMatrix) {
  8924. var normalMatrix = optionalNormalMatrix || _normalMatrix.getNormalMatrix(matrix);
  8925. var referencePoint = this.coplanarPoint(_vector1).applyMatrix4(matrix);
  8926. var normal = this.normal.applyMatrix3(normalMatrix).normalize();
  8927. this.constant = -referencePoint.dot(normal);
  8928. return this;
  8929. },
  8930. translate: function (offset) {
  8931. this.constant -= offset.dot(this.normal);
  8932. return this;
  8933. },
  8934. equals: function (plane) {
  8935. return plane.normal.equals(this.normal) && plane.constant === this.constant;
  8936. }
  8937. });
  8938. /**
  8939. * @author mrdoob / http://mrdoob.com/
  8940. * @author alteredq / http://alteredqualia.com/
  8941. * @author bhouston / http://clara.io
  8942. */
  8943. var _sphere$1 = new Sphere();
  8944. var _vector$5 = new Vector3();
  8945. function Frustum(p0, p1, p2, p3, p4, p5) {
  8946. 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()];
  8947. }
  8948. Object.assign(Frustum.prototype, {
  8949. set: function (p0, p1, p2, p3, p4, p5) {
  8950. var planes = this.planes;
  8951. planes[0].copy(p0);
  8952. planes[1].copy(p1);
  8953. planes[2].copy(p2);
  8954. planes[3].copy(p3);
  8955. planes[4].copy(p4);
  8956. planes[5].copy(p5);
  8957. return this;
  8958. },
  8959. clone: function () {
  8960. return new this.constructor().copy(this);
  8961. },
  8962. copy: function (frustum) {
  8963. var planes = this.planes;
  8964. for (var i = 0; i < 6; i++) {
  8965. planes[i].copy(frustum.planes[i]);
  8966. }
  8967. return this;
  8968. },
  8969. setFromMatrix: function (m) {
  8970. var planes = this.planes;
  8971. var me = m.elements;
  8972. var me0 = me[0],
  8973. me1 = me[1],
  8974. me2 = me[2],
  8975. me3 = me[3];
  8976. var me4 = me[4],
  8977. me5 = me[5],
  8978. me6 = me[6],
  8979. me7 = me[7];
  8980. var me8 = me[8],
  8981. me9 = me[9],
  8982. me10 = me[10],
  8983. me11 = me[11];
  8984. var me12 = me[12],
  8985. me13 = me[13],
  8986. me14 = me[14],
  8987. me15 = me[15];
  8988. planes[0].setComponents(me3 - me0, me7 - me4, me11 - me8, me15 - me12).normalize();
  8989. planes[1].setComponents(me3 + me0, me7 + me4, me11 + me8, me15 + me12).normalize();
  8990. planes[2].setComponents(me3 + me1, me7 + me5, me11 + me9, me15 + me13).normalize();
  8991. planes[3].setComponents(me3 - me1, me7 - me5, me11 - me9, me15 - me13).normalize();
  8992. planes[4].setComponents(me3 - me2, me7 - me6, me11 - me10, me15 - me14).normalize();
  8993. planes[5].setComponents(me3 + me2, me7 + me6, me11 + me10, me15 + me14).normalize();
  8994. return this;
  8995. },
  8996. intersectsObject: function (object) {
  8997. var geometry = object.geometry;
  8998. if (geometry.boundingSphere === null) geometry.computeBoundingSphere();
  8999. _sphere$1.copy(geometry.boundingSphere).applyMatrix4(object.matrixWorld);
  9000. return this.intersectsSphere(_sphere$1);
  9001. },
  9002. intersectsSprite: function (sprite) {
  9003. _sphere$1.center.set(0, 0, 0);
  9004. _sphere$1.radius = 0.7071067811865476;
  9005. _sphere$1.applyMatrix4(sprite.matrixWorld);
  9006. return this.intersectsSphere(_sphere$1);
  9007. },
  9008. intersectsSphere: function (sphere) {
  9009. var planes = this.planes;
  9010. var center = sphere.center;
  9011. var negRadius = -sphere.radius;
  9012. for (var i = 0; i < 6; i++) {
  9013. var distance = planes[i].distanceToPoint(center);
  9014. if (distance < negRadius) {
  9015. return false;
  9016. }
  9017. }
  9018. return true;
  9019. },
  9020. intersectsBox: function (box) {
  9021. var planes = this.planes;
  9022. for (var i = 0; i < 6; i++) {
  9023. var plane = planes[i]; // corner at max distance
  9024. _vector$5.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  9025. _vector$5.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  9026. _vector$5.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  9027. if (plane.distanceToPoint(_vector$5) < 0) {
  9028. return false;
  9029. }
  9030. }
  9031. return true;
  9032. },
  9033. containsPoint: function (point) {
  9034. var planes = this.planes;
  9035. for (var i = 0; i < 6; i++) {
  9036. if (planes[i].distanceToPoint(point) < 0) {
  9037. return false;
  9038. }
  9039. }
  9040. return true;
  9041. }
  9042. });
  9043. var alphamap_fragment = "#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, vUv ).g;\n#endif";
  9044. var alphamap_pars_fragment = "#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif";
  9045. var alphatest_fragment = "#ifdef ALPHATEST\n\tif ( diffuseColor.a < ALPHATEST ) discard;\n#endif";
  9046. 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";
  9047. var aomap_pars_fragment = "#ifdef USE_AOMAP\n\tuniform sampler2D aoMap;\n\tuniform float aoMapIntensity;\n#endif";
  9048. var begin_vertex = "vec3 transformed = vec3( position );";
  9049. var beginnormal_vertex = "vec3 objectNormal = vec3( normal );\n#ifdef USE_TANGENT\n\tvec3 objectTangent = vec3( tangent.xyz );\n#endif";
  9050. 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";
  9051. 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";
  9052. 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";
  9053. 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";
  9054. var clipping_planes_pars_vertex = "#if NUM_CLIPPING_PLANES > 0 && ! defined( STANDARD ) && ! defined( PHONG ) && ! defined( MATCAP )\n\tvarying vec3 vViewPosition;\n#endif";
  9055. var clipping_planes_vertex = "#if NUM_CLIPPING_PLANES > 0 && ! defined( STANDARD ) && ! defined( PHONG ) && ! defined( MATCAP )\n\tvViewPosition = - mvPosition.xyz;\n#endif";
  9056. var color_fragment = "#ifdef USE_COLOR\n\tdiffuseColor.rgb *= vColor;\n#endif";
  9057. var color_pars_fragment = "#ifdef USE_COLOR\n\tvarying vec3 vColor;\n#endif";
  9058. var color_pars_vertex = "#ifdef USE_COLOR\n\tvarying vec3 vColor;\n#endif";
  9059. var color_vertex = "#ifdef USE_COLOR\n\tvColor.xyz = color.xyz;\n#endif";
  9060. 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}";
  9061. 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";
  9062. 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";
  9063. var displacementmap_pars_vertex = "#ifdef USE_DISPLACEMENTMAP\n\tuniform sampler2D displacementMap;\n\tuniform float displacementScale;\n\tuniform float displacementBias;\n#endif";
  9064. var displacementmap_vertex = "#ifdef USE_DISPLACEMENTMAP\n\ttransformed += normalize( objectNormal ) * ( texture2D( displacementMap, vUv ).x * displacementScale + displacementBias );\n#endif";
  9065. var emissivemap_fragment = "#ifdef USE_EMISSIVEMAP\n\tvec4 emissiveColor = texture2D( emissiveMap, vUv );\n\temissiveColor.rgb = emissiveMapTexelToLinear( emissiveColor ).rgb;\n\ttotalEmissiveRadiance *= emissiveColor.rgb;\n#endif";
  9066. var emissivemap_pars_fragment = "#ifdef USE_EMISSIVEMAP\n\tuniform sampler2D emissiveMap;\n#endif";
  9067. var encodings_fragment = "gl_FragColor = linearToOutputTexel( gl_FragColor );";
  9068. 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}";
  9069. 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";
  9070. 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";
  9071. 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";
  9072. 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";
  9073. 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";
  9074. var fog_vertex = "#ifdef USE_FOG\n\tfogDepth = -mvPosition.z;\n#endif";
  9075. var fog_pars_vertex = "#ifdef USE_FOG\n\tvarying float fogDepth;\n#endif";
  9076. 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";
  9077. 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";
  9078. 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";
  9079. var lightmap_fragment = "#ifdef USE_LIGHTMAP\n\treflectedLight.indirectDiffuse += PI * texture2D( lightMap, vUv2 ).xyz * lightMapIntensity;\n#endif";
  9080. var lightmap_pars_fragment = "#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif";
  9081. 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";
  9082. 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";
  9083. 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";
  9084. var lights_phong_fragment = "BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;";
  9085. 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)";
  9086. 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";
  9087. 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}";
  9088. 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";
  9089. 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";
  9090. 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";
  9091. 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";
  9092. 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";
  9093. 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";
  9094. 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";
  9095. var map_fragment = "#ifdef USE_MAP\n\tvec4 texelColor = texture2D( map, vUv );\n\ttexelColor = mapTexelToLinear( texelColor );\n\tdiffuseColor *= texelColor;\n#endif";
  9096. var map_pars_fragment = "#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif";
  9097. 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";
  9098. var map_particle_pars_fragment = "#ifdef USE_MAP\n\tuniform mat3 uvTransform;\n\tuniform sampler2D map;\n#endif";
  9099. var metalnessmap_fragment = "float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n\tvec4 texelMetalness = texture2D( metalnessMap, vUv );\n\tmetalnessFactor *= texelMetalness.b;\n#endif";
  9100. var metalnessmap_pars_fragment = "#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif";
  9101. 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";
  9102. 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";
  9103. 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";
  9104. 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;";
  9105. 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";
  9106. 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";
  9107. var clearcoat_normal_fragment_begin = "#ifdef CLEARCOAT\n\tvec3 clearcoatNormal = geometryNormal;\n#endif";
  9108. 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";
  9109. var clearcoat_normalmap_pars_fragment = "#ifdef USE_CLEARCOAT_NORMALMAP\n\tuniform sampler2D clearcoatNormalMap;\n\tuniform vec2 clearcoatNormalScale;\n#endif";
  9110. 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}";
  9111. var premultiplied_alpha_fragment = "#ifdef PREMULTIPLIED_ALPHA\n\tgl_FragColor.rgb *= gl_FragColor.a;\n#endif";
  9112. 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;";
  9113. var dithering_fragment = "#ifdef DITHERING\n\tgl_FragColor.rgb = dithering( gl_FragColor.rgb );\n#endif";
  9114. 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";
  9115. var roughnessmap_fragment = "float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n\tvec4 texelRoughness = texture2D( roughnessMap, vUv );\n\troughnessFactor *= texelRoughness.g;\n#endif";
  9116. var roughnessmap_pars_fragment = "#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif";
  9117. 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";
  9118. 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";
  9119. 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";
  9120. 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}";
  9121. 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";
  9122. 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";
  9123. 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";
  9124. 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";
  9125. 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";
  9126. var specularmap_pars_fragment = "#ifdef USE_SPECULARMAP\n\tuniform sampler2D specularMap;\n#endif";
  9127. var tonemapping_fragment = "#if defined( TONE_MAPPING )\n\tgl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif";
  9128. 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}";
  9129. var uv_pars_fragment = "#ifdef USE_UV\n\tvarying vec2 vUv;\n#endif";
  9130. var uv_pars_vertex = "#ifdef USE_UV\n\tvarying vec2 vUv;\n\tuniform mat3 uvTransform;\n#endif";
  9131. var uv_vertex = "#ifdef USE_UV\n\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n#endif";
  9132. var uv2_pars_fragment = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvarying vec2 vUv2;\n#endif";
  9133. var uv2_pars_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tattribute vec2 uv2;\n\tvarying vec2 vUv2;\n#endif";
  9134. var uv2_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvUv2 = uv2;\n#endif";
  9135. 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";
  9136. 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}";
  9137. 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}";
  9138. 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}";
  9139. 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}";
  9140. 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}";
  9141. 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}";
  9142. 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}";
  9143. 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}";
  9144. 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}";
  9145. 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}";
  9146. 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}";
  9147. 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}";
  9148. 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}";
  9149. 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}";
  9150. 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}";
  9151. 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}";
  9152. 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}";
  9153. 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}";
  9154. 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}";
  9155. 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}";
  9156. 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}";
  9157. 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}";
  9158. 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}";
  9159. 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}";
  9160. 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}";
  9161. 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}";
  9162. 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}";
  9163. 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}";
  9164. 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}";
  9165. 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}";
  9166. var ShaderChunk = {
  9167. alphamap_fragment: alphamap_fragment,
  9168. alphamap_pars_fragment: alphamap_pars_fragment,
  9169. alphatest_fragment: alphatest_fragment,
  9170. aomap_fragment: aomap_fragment,
  9171. aomap_pars_fragment: aomap_pars_fragment,
  9172. begin_vertex: begin_vertex,
  9173. beginnormal_vertex: beginnormal_vertex,
  9174. bsdfs: bsdfs,
  9175. bumpmap_pars_fragment: bumpmap_pars_fragment,
  9176. clipping_planes_fragment: clipping_planes_fragment,
  9177. clipping_planes_pars_fragment: clipping_planes_pars_fragment,
  9178. clipping_planes_pars_vertex: clipping_planes_pars_vertex,
  9179. clipping_planes_vertex: clipping_planes_vertex,
  9180. color_fragment: color_fragment,
  9181. color_pars_fragment: color_pars_fragment,
  9182. color_pars_vertex: color_pars_vertex,
  9183. color_vertex: color_vertex,
  9184. common: common,
  9185. cube_uv_reflection_fragment: cube_uv_reflection_fragment,
  9186. defaultnormal_vertex: defaultnormal_vertex,
  9187. displacementmap_pars_vertex: displacementmap_pars_vertex,
  9188. displacementmap_vertex: displacementmap_vertex,
  9189. emissivemap_fragment: emissivemap_fragment,
  9190. emissivemap_pars_fragment: emissivemap_pars_fragment,
  9191. encodings_fragment: encodings_fragment,
  9192. encodings_pars_fragment: encodings_pars_fragment,
  9193. envmap_fragment: envmap_fragment,
  9194. envmap_common_pars_fragment: envmap_common_pars_fragment,
  9195. envmap_pars_fragment: envmap_pars_fragment,
  9196. envmap_pars_vertex: envmap_pars_vertex,
  9197. envmap_physical_pars_fragment: envmap_physical_pars_fragment,
  9198. envmap_vertex: envmap_vertex,
  9199. fog_vertex: fog_vertex,
  9200. fog_pars_vertex: fog_pars_vertex,
  9201. fog_fragment: fog_fragment,
  9202. fog_pars_fragment: fog_pars_fragment,
  9203. gradientmap_pars_fragment: gradientmap_pars_fragment,
  9204. lightmap_fragment: lightmap_fragment,
  9205. lightmap_pars_fragment: lightmap_pars_fragment,
  9206. lights_lambert_vertex: lights_lambert_vertex,
  9207. lights_pars_begin: lights_pars_begin,
  9208. lights_phong_fragment: lights_phong_fragment,
  9209. lights_phong_pars_fragment: lights_phong_pars_fragment,
  9210. lights_physical_fragment: lights_physical_fragment,
  9211. lights_physical_pars_fragment: lights_physical_pars_fragment,
  9212. lights_fragment_begin: lights_fragment_begin,
  9213. lights_fragment_maps: lights_fragment_maps,
  9214. lights_fragment_end: lights_fragment_end,
  9215. logdepthbuf_fragment: logdepthbuf_fragment,
  9216. logdepthbuf_pars_fragment: logdepthbuf_pars_fragment,
  9217. logdepthbuf_pars_vertex: logdepthbuf_pars_vertex,
  9218. logdepthbuf_vertex: logdepthbuf_vertex,
  9219. map_fragment: map_fragment,
  9220. map_pars_fragment: map_pars_fragment,
  9221. map_particle_fragment: map_particle_fragment,
  9222. map_particle_pars_fragment: map_particle_pars_fragment,
  9223. metalnessmap_fragment: metalnessmap_fragment,
  9224. metalnessmap_pars_fragment: metalnessmap_pars_fragment,
  9225. morphnormal_vertex: morphnormal_vertex,
  9226. morphtarget_pars_vertex: morphtarget_pars_vertex,
  9227. morphtarget_vertex: morphtarget_vertex,
  9228. normal_fragment_begin: normal_fragment_begin,
  9229. normal_fragment_maps: normal_fragment_maps,
  9230. normalmap_pars_fragment: normalmap_pars_fragment,
  9231. clearcoat_normal_fragment_begin: clearcoat_normal_fragment_begin,
  9232. clearcoat_normal_fragment_maps: clearcoat_normal_fragment_maps,
  9233. clearcoat_normalmap_pars_fragment: clearcoat_normalmap_pars_fragment,
  9234. packing: packing,
  9235. premultiplied_alpha_fragment: premultiplied_alpha_fragment,
  9236. project_vertex: project_vertex,
  9237. dithering_fragment: dithering_fragment,
  9238. dithering_pars_fragment: dithering_pars_fragment,
  9239. roughnessmap_fragment: roughnessmap_fragment,
  9240. roughnessmap_pars_fragment: roughnessmap_pars_fragment,
  9241. shadowmap_pars_fragment: shadowmap_pars_fragment,
  9242. shadowmap_pars_vertex: shadowmap_pars_vertex,
  9243. shadowmap_vertex: shadowmap_vertex,
  9244. shadowmask_pars_fragment: shadowmask_pars_fragment,
  9245. skinbase_vertex: skinbase_vertex,
  9246. skinning_pars_vertex: skinning_pars_vertex,
  9247. skinning_vertex: skinning_vertex,
  9248. skinnormal_vertex: skinnormal_vertex,
  9249. specularmap_fragment: specularmap_fragment,
  9250. specularmap_pars_fragment: specularmap_pars_fragment,
  9251. tonemapping_fragment: tonemapping_fragment,
  9252. tonemapping_pars_fragment: tonemapping_pars_fragment,
  9253. uv_pars_fragment: uv_pars_fragment,
  9254. uv_pars_vertex: uv_pars_vertex,
  9255. uv_vertex: uv_vertex,
  9256. uv2_pars_fragment: uv2_pars_fragment,
  9257. uv2_pars_vertex: uv2_pars_vertex,
  9258. uv2_vertex: uv2_vertex,
  9259. worldpos_vertex: worldpos_vertex,
  9260. background_frag: background_frag,
  9261. background_vert: background_vert,
  9262. cube_frag: cube_frag,
  9263. cube_vert: cube_vert,
  9264. depth_frag: depth_frag,
  9265. depth_vert: depth_vert,
  9266. distanceRGBA_frag: distanceRGBA_frag,
  9267. distanceRGBA_vert: distanceRGBA_vert,
  9268. equirect_frag: equirect_frag,
  9269. equirect_vert: equirect_vert,
  9270. linedashed_frag: linedashed_frag,
  9271. linedashed_vert: linedashed_vert,
  9272. meshbasic_frag: meshbasic_frag,
  9273. meshbasic_vert: meshbasic_vert,
  9274. meshlambert_frag: meshlambert_frag,
  9275. meshlambert_vert: meshlambert_vert,
  9276. meshmatcap_frag: meshmatcap_frag,
  9277. meshmatcap_vert: meshmatcap_vert,
  9278. meshphong_frag: meshphong_frag,
  9279. meshphong_vert: meshphong_vert,
  9280. meshphysical_frag: meshphysical_frag,
  9281. meshphysical_vert: meshphysical_vert,
  9282. normal_frag: normal_frag,
  9283. normal_vert: normal_vert,
  9284. points_frag: points_frag,
  9285. points_vert: points_vert,
  9286. shadow_frag: shadow_frag,
  9287. shadow_vert: shadow_vert,
  9288. sprite_frag: sprite_frag,
  9289. sprite_vert: sprite_vert
  9290. };
  9291. /**
  9292. * Uniforms library for shared webgl shaders
  9293. */
  9294. exports.ShaderChunk = ShaderChunk;
  9295. var UniformsLib = {
  9296. common: {
  9297. diffuse: {
  9298. value: new Color(0xeeeeee)
  9299. },
  9300. opacity: {
  9301. value: 1.0
  9302. },
  9303. map: {
  9304. value: null
  9305. },
  9306. uvTransform: {
  9307. value: new Matrix3()
  9308. },
  9309. alphaMap: {
  9310. value: null
  9311. }
  9312. },
  9313. specularmap: {
  9314. specularMap: {
  9315. value: null
  9316. }
  9317. },
  9318. envmap: {
  9319. envMap: {
  9320. value: null
  9321. },
  9322. flipEnvMap: {
  9323. value: -1
  9324. },
  9325. reflectivity: {
  9326. value: 1.0
  9327. },
  9328. refractionRatio: {
  9329. value: 0.98
  9330. },
  9331. maxMipLevel: {
  9332. value: 0
  9333. }
  9334. },
  9335. aomap: {
  9336. aoMap: {
  9337. value: null
  9338. },
  9339. aoMapIntensity: {
  9340. value: 1
  9341. }
  9342. },
  9343. lightmap: {
  9344. lightMap: {
  9345. value: null
  9346. },
  9347. lightMapIntensity: {
  9348. value: 1
  9349. }
  9350. },
  9351. emissivemap: {
  9352. emissiveMap: {
  9353. value: null
  9354. }
  9355. },
  9356. bumpmap: {
  9357. bumpMap: {
  9358. value: null
  9359. },
  9360. bumpScale: {
  9361. value: 1
  9362. }
  9363. },
  9364. normalmap: {
  9365. normalMap: {
  9366. value: null
  9367. },
  9368. normalScale: {
  9369. value: new Vector2(1, 1)
  9370. }
  9371. },
  9372. displacementmap: {
  9373. displacementMap: {
  9374. value: null
  9375. },
  9376. displacementScale: {
  9377. value: 1
  9378. },
  9379. displacementBias: {
  9380. value: 0
  9381. }
  9382. },
  9383. roughnessmap: {
  9384. roughnessMap: {
  9385. value: null
  9386. }
  9387. },
  9388. metalnessmap: {
  9389. metalnessMap: {
  9390. value: null
  9391. }
  9392. },
  9393. gradientmap: {
  9394. gradientMap: {
  9395. value: null
  9396. }
  9397. },
  9398. fog: {
  9399. fogDensity: {
  9400. value: 0.00025
  9401. },
  9402. fogNear: {
  9403. value: 1
  9404. },
  9405. fogFar: {
  9406. value: 2000
  9407. },
  9408. fogColor: {
  9409. value: new Color(0xffffff)
  9410. }
  9411. },
  9412. lights: {
  9413. ambientLightColor: {
  9414. value: []
  9415. },
  9416. lightProbe: {
  9417. value: []
  9418. },
  9419. directionalLights: {
  9420. value: [],
  9421. properties: {
  9422. direction: {},
  9423. color: {},
  9424. shadow: {},
  9425. shadowBias: {},
  9426. shadowRadius: {},
  9427. shadowMapSize: {}
  9428. }
  9429. },
  9430. directionalShadowMap: {
  9431. value: []
  9432. },
  9433. directionalShadowMatrix: {
  9434. value: []
  9435. },
  9436. spotLights: {
  9437. value: [],
  9438. properties: {
  9439. color: {},
  9440. position: {},
  9441. direction: {},
  9442. distance: {},
  9443. coneCos: {},
  9444. penumbraCos: {},
  9445. decay: {},
  9446. shadow: {},
  9447. shadowBias: {},
  9448. shadowRadius: {},
  9449. shadowMapSize: {}
  9450. }
  9451. },
  9452. spotShadowMap: {
  9453. value: []
  9454. },
  9455. spotShadowMatrix: {
  9456. value: []
  9457. },
  9458. pointLights: {
  9459. value: [],
  9460. properties: {
  9461. color: {},
  9462. position: {},
  9463. decay: {},
  9464. distance: {},
  9465. shadow: {},
  9466. shadowBias: {},
  9467. shadowRadius: {},
  9468. shadowMapSize: {},
  9469. shadowCameraNear: {},
  9470. shadowCameraFar: {}
  9471. }
  9472. },
  9473. pointShadowMap: {
  9474. value: []
  9475. },
  9476. pointShadowMatrix: {
  9477. value: []
  9478. },
  9479. hemisphereLights: {
  9480. value: [],
  9481. properties: {
  9482. direction: {},
  9483. skyColor: {},
  9484. groundColor: {}
  9485. }
  9486. },
  9487. // TODO (abelnation): RectAreaLight BRDF data needs to be moved from example to main src
  9488. rectAreaLights: {
  9489. value: [],
  9490. properties: {
  9491. color: {},
  9492. position: {},
  9493. width: {},
  9494. height: {}
  9495. }
  9496. }
  9497. },
  9498. points: {
  9499. diffuse: {
  9500. value: new Color(0xeeeeee)
  9501. },
  9502. opacity: {
  9503. value: 1.0
  9504. },
  9505. size: {
  9506. value: 1.0
  9507. },
  9508. scale: {
  9509. value: 1.0
  9510. },
  9511. map: {
  9512. value: null
  9513. },
  9514. uvTransform: {
  9515. value: new Matrix3()
  9516. }
  9517. },
  9518. sprite: {
  9519. diffuse: {
  9520. value: new Color(0xeeeeee)
  9521. },
  9522. opacity: {
  9523. value: 1.0
  9524. },
  9525. center: {
  9526. value: new Vector2(0.5, 0.5)
  9527. },
  9528. rotation: {
  9529. value: 0.0
  9530. },
  9531. map: {
  9532. value: null
  9533. },
  9534. uvTransform: {
  9535. value: new Matrix3()
  9536. }
  9537. }
  9538. };
  9539. /**
  9540. * @author alteredq / http://alteredqualia.com/
  9541. * @author mrdoob / http://mrdoob.com/
  9542. * @author mikael emtinger / http://gomo.se/
  9543. */
  9544. exports.UniformsLib = UniformsLib;
  9545. var ShaderLib = {
  9546. basic: {
  9547. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.specularmap, UniformsLib.envmap, UniformsLib.aomap, UniformsLib.lightmap, UniformsLib.fog]),
  9548. vertexShader: ShaderChunk.meshbasic_vert,
  9549. fragmentShader: ShaderChunk.meshbasic_frag
  9550. },
  9551. lambert: {
  9552. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.specularmap, UniformsLib.envmap, UniformsLib.aomap, UniformsLib.lightmap, UniformsLib.emissivemap, UniformsLib.fog, UniformsLib.lights, {
  9553. emissive: {
  9554. value: new Color(0x000000)
  9555. }
  9556. }]),
  9557. vertexShader: ShaderChunk.meshlambert_vert,
  9558. fragmentShader: ShaderChunk.meshlambert_frag
  9559. },
  9560. phong: {
  9561. 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, {
  9562. emissive: {
  9563. value: new Color(0x000000)
  9564. },
  9565. specular: {
  9566. value: new Color(0x111111)
  9567. },
  9568. shininess: {
  9569. value: 30
  9570. }
  9571. }]),
  9572. vertexShader: ShaderChunk.meshphong_vert,
  9573. fragmentShader: ShaderChunk.meshphong_frag
  9574. },
  9575. standard: {
  9576. 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, {
  9577. emissive: {
  9578. value: new Color(0x000000)
  9579. },
  9580. roughness: {
  9581. value: 0.5
  9582. },
  9583. metalness: {
  9584. value: 0.5
  9585. },
  9586. envMapIntensity: {
  9587. value: 1
  9588. } // temporary
  9589. }]),
  9590. vertexShader: ShaderChunk.meshphysical_vert,
  9591. fragmentShader: ShaderChunk.meshphysical_frag
  9592. },
  9593. matcap: {
  9594. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, UniformsLib.fog, {
  9595. matcap: {
  9596. value: null
  9597. }
  9598. }]),
  9599. vertexShader: ShaderChunk.meshmatcap_vert,
  9600. fragmentShader: ShaderChunk.meshmatcap_frag
  9601. },
  9602. points: {
  9603. uniforms: mergeUniforms([UniformsLib.points, UniformsLib.fog]),
  9604. vertexShader: ShaderChunk.points_vert,
  9605. fragmentShader: ShaderChunk.points_frag
  9606. },
  9607. dashed: {
  9608. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.fog, {
  9609. scale: {
  9610. value: 1
  9611. },
  9612. dashSize: {
  9613. value: 1
  9614. },
  9615. totalSize: {
  9616. value: 2
  9617. }
  9618. }]),
  9619. vertexShader: ShaderChunk.linedashed_vert,
  9620. fragmentShader: ShaderChunk.linedashed_frag
  9621. },
  9622. depth: {
  9623. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.displacementmap]),
  9624. vertexShader: ShaderChunk.depth_vert,
  9625. fragmentShader: ShaderChunk.depth_frag
  9626. },
  9627. normal: {
  9628. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, {
  9629. opacity: {
  9630. value: 1.0
  9631. }
  9632. }]),
  9633. vertexShader: ShaderChunk.normal_vert,
  9634. fragmentShader: ShaderChunk.normal_frag
  9635. },
  9636. sprite: {
  9637. uniforms: mergeUniforms([UniformsLib.sprite, UniformsLib.fog]),
  9638. vertexShader: ShaderChunk.sprite_vert,
  9639. fragmentShader: ShaderChunk.sprite_frag
  9640. },
  9641. background: {
  9642. uniforms: {
  9643. uvTransform: {
  9644. value: new Matrix3()
  9645. },
  9646. t2D: {
  9647. value: null
  9648. }
  9649. },
  9650. vertexShader: ShaderChunk.background_vert,
  9651. fragmentShader: ShaderChunk.background_frag
  9652. },
  9653. /* -------------------------------------------------------------------------
  9654. // Cube map shader
  9655. ------------------------------------------------------------------------- */
  9656. cube: {
  9657. uniforms: {
  9658. tCube: {
  9659. value: null
  9660. },
  9661. tFlip: {
  9662. value: -1
  9663. },
  9664. opacity: {
  9665. value: 1.0
  9666. }
  9667. },
  9668. vertexShader: ShaderChunk.cube_vert,
  9669. fragmentShader: ShaderChunk.cube_frag
  9670. },
  9671. equirect: {
  9672. uniforms: {
  9673. tEquirect: {
  9674. value: null
  9675. }
  9676. },
  9677. vertexShader: ShaderChunk.equirect_vert,
  9678. fragmentShader: ShaderChunk.equirect_frag
  9679. },
  9680. distanceRGBA: {
  9681. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.displacementmap, {
  9682. referencePosition: {
  9683. value: new Vector3()
  9684. },
  9685. nearDistance: {
  9686. value: 1
  9687. },
  9688. farDistance: {
  9689. value: 1000
  9690. }
  9691. }]),
  9692. vertexShader: ShaderChunk.distanceRGBA_vert,
  9693. fragmentShader: ShaderChunk.distanceRGBA_frag
  9694. },
  9695. shadow: {
  9696. uniforms: mergeUniforms([UniformsLib.lights, UniformsLib.fog, {
  9697. color: {
  9698. value: new Color(0x00000)
  9699. },
  9700. opacity: {
  9701. value: 1.0
  9702. }
  9703. }]),
  9704. vertexShader: ShaderChunk.shadow_vert,
  9705. fragmentShader: ShaderChunk.shadow_frag
  9706. }
  9707. };
  9708. exports.ShaderLib = ShaderLib;
  9709. ShaderLib.physical = {
  9710. uniforms: mergeUniforms([ShaderLib.standard.uniforms, {
  9711. transparency: {
  9712. value: 0
  9713. },
  9714. clearcoat: {
  9715. value: 0
  9716. },
  9717. clearcoatRoughness: {
  9718. value: 0
  9719. },
  9720. sheen: {
  9721. value: new Color(0x000000)
  9722. },
  9723. clearcoatNormalScale: {
  9724. value: new Vector2(1, 1)
  9725. },
  9726. clearcoatNormalMap: {
  9727. value: null
  9728. }
  9729. }]),
  9730. vertexShader: ShaderChunk.meshphysical_vert,
  9731. fragmentShader: ShaderChunk.meshphysical_frag
  9732. };
  9733. /**
  9734. * @author mrdoob / http://mrdoob.com/
  9735. */
  9736. function WebGLAnimation() {
  9737. var context = null;
  9738. var isAnimating = false;
  9739. var animationLoop = null;
  9740. function onAnimationFrame(time, frame) {
  9741. if (isAnimating === false) return;
  9742. animationLoop(time, frame);
  9743. context.requestAnimationFrame(onAnimationFrame);
  9744. }
  9745. return {
  9746. start: function () {
  9747. if (isAnimating === true) return;
  9748. if (animationLoop === null) return;
  9749. context.requestAnimationFrame(onAnimationFrame);
  9750. isAnimating = true;
  9751. },
  9752. stop: function () {
  9753. isAnimating = false;
  9754. },
  9755. setAnimationLoop: function (callback) {
  9756. animationLoop = callback;
  9757. },
  9758. setContext: function (value) {
  9759. context = value;
  9760. }
  9761. };
  9762. }
  9763. /**
  9764. * @author mrdoob / http://mrdoob.com/
  9765. */
  9766. function WebGLAttributes(gl) {
  9767. var buffers = new WeakMap();
  9768. function createBuffer(attribute, bufferType) {
  9769. var array = attribute.array;
  9770. var usage = attribute.dynamic ? 35048 : 35044;
  9771. var buffer = gl.createBuffer();
  9772. gl.bindBuffer(bufferType, buffer);
  9773. gl.bufferData(bufferType, array, usage);
  9774. attribute.onUploadCallback();
  9775. var type = 5126;
  9776. if (array instanceof Float32Array) {
  9777. type = 5126;
  9778. } else if (array instanceof Float64Array) {
  9779. console.warn('THREE.WebGLAttributes: Unsupported data buffer format: Float64Array.');
  9780. } else if (array instanceof Uint16Array) {
  9781. type = 5123;
  9782. } else if (array instanceof Int16Array) {
  9783. type = 5122;
  9784. } else if (array instanceof Uint32Array) {
  9785. type = 5125;
  9786. } else if (array instanceof Int32Array) {
  9787. type = 5124;
  9788. } else if (array instanceof Int8Array) {
  9789. type = 5120;
  9790. } else if (array instanceof Uint8Array) {
  9791. type = 5121;
  9792. }
  9793. return {
  9794. buffer: buffer,
  9795. type: type,
  9796. bytesPerElement: array.BYTES_PER_ELEMENT,
  9797. version: attribute.version
  9798. };
  9799. }
  9800. function updateBuffer(buffer, attribute, bufferType) {
  9801. var array = attribute.array;
  9802. var updateRange = attribute.updateRange;
  9803. gl.bindBuffer(bufferType, buffer);
  9804. if (attribute.dynamic === false) {
  9805. gl.bufferData(bufferType, array, 35044);
  9806. } else if (updateRange.count === -1) {
  9807. // Not using update ranges
  9808. gl.bufferSubData(bufferType, 0, array);
  9809. } else if (updateRange.count === 0) {
  9810. 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.');
  9811. } else {
  9812. gl.bufferSubData(bufferType, updateRange.offset * array.BYTES_PER_ELEMENT, array.subarray(updateRange.offset, updateRange.offset + updateRange.count));
  9813. updateRange.count = -1; // reset range
  9814. }
  9815. } //
  9816. function get(attribute) {
  9817. if (attribute.isInterleavedBufferAttribute) attribute = attribute.data;
  9818. return buffers.get(attribute);
  9819. }
  9820. function remove(attribute) {
  9821. if (attribute.isInterleavedBufferAttribute) attribute = attribute.data;
  9822. var data = buffers.get(attribute);
  9823. if (data) {
  9824. gl.deleteBuffer(data.buffer);
  9825. buffers.delete(attribute);
  9826. }
  9827. }
  9828. function update(attribute, bufferType) {
  9829. if (attribute.isInterleavedBufferAttribute) attribute = attribute.data;
  9830. var data = buffers.get(attribute);
  9831. if (data === undefined) {
  9832. buffers.set(attribute, createBuffer(attribute, bufferType));
  9833. } else if (data.version < attribute.version) {
  9834. updateBuffer(data.buffer, attribute, bufferType);
  9835. data.version = attribute.version;
  9836. }
  9837. }
  9838. return {
  9839. get: get,
  9840. remove: remove,
  9841. update: update
  9842. };
  9843. }
  9844. /**
  9845. * @author mrdoob / http://mrdoob.com/
  9846. * @author Mugen87 / https://github.com/Mugen87
  9847. */
  9848. // PlaneGeometry
  9849. function PlaneGeometry(width, height, widthSegments, heightSegments) {
  9850. Geometry.call(this);
  9851. this.type = 'PlaneGeometry';
  9852. this.parameters = {
  9853. width: width,
  9854. height: height,
  9855. widthSegments: widthSegments,
  9856. heightSegments: heightSegments
  9857. };
  9858. this.fromBufferGeometry(new PlaneBufferGeometry(width, height, widthSegments, heightSegments));
  9859. this.mergeVertices();
  9860. }
  9861. PlaneGeometry.prototype = Object.create(Geometry.prototype);
  9862. PlaneGeometry.prototype.constructor = PlaneGeometry; // PlaneBufferGeometry
  9863. function PlaneBufferGeometry(width, height, widthSegments, heightSegments) {
  9864. BufferGeometry.call(this);
  9865. this.type = 'PlaneBufferGeometry';
  9866. this.parameters = {
  9867. width: width,
  9868. height: height,
  9869. widthSegments: widthSegments,
  9870. heightSegments: heightSegments
  9871. };
  9872. width = width || 1;
  9873. height = height || 1;
  9874. var width_half = width / 2;
  9875. var height_half = height / 2;
  9876. var gridX = Math.floor(widthSegments) || 1;
  9877. var gridY = Math.floor(heightSegments) || 1;
  9878. var gridX1 = gridX + 1;
  9879. var gridY1 = gridY + 1;
  9880. var segment_width = width / gridX;
  9881. var segment_height = height / gridY;
  9882. var ix, iy; // buffers
  9883. var indices = [];
  9884. var vertices = [];
  9885. var normals = [];
  9886. var uvs = []; // generate vertices, normals and uvs
  9887. for (iy = 0; iy < gridY1; iy++) {
  9888. var y = iy * segment_height - height_half;
  9889. for (ix = 0; ix < gridX1; ix++) {
  9890. var x = ix * segment_width - width_half;
  9891. vertices.push(x, -y, 0);
  9892. normals.push(0, 0, 1);
  9893. uvs.push(ix / gridX);
  9894. uvs.push(1 - iy / gridY);
  9895. }
  9896. } // indices
  9897. for (iy = 0; iy < gridY; iy++) {
  9898. for (ix = 0; ix < gridX; ix++) {
  9899. var a = ix + gridX1 * iy;
  9900. var b = ix + gridX1 * (iy + 1);
  9901. var c = ix + 1 + gridX1 * (iy + 1);
  9902. var d = ix + 1 + gridX1 * iy; // faces
  9903. indices.push(a, b, d);
  9904. indices.push(b, c, d);
  9905. }
  9906. } // build geometry
  9907. this.setIndex(indices);
  9908. this.addAttribute('position', new Float32BufferAttribute(vertices, 3));
  9909. this.addAttribute('normal', new Float32BufferAttribute(normals, 3));
  9910. this.addAttribute('uv', new Float32BufferAttribute(uvs, 2));
  9911. }
  9912. PlaneBufferGeometry.prototype = Object.create(BufferGeometry.prototype);
  9913. PlaneBufferGeometry.prototype.constructor = PlaneBufferGeometry;
  9914. /**
  9915. * @author mrdoob / http://mrdoob.com/
  9916. */
  9917. function WebGLBackground(renderer, state, objects, premultipliedAlpha) {
  9918. var clearColor = new Color(0x000000);
  9919. var clearAlpha = 0;
  9920. var planeMesh;
  9921. var boxMesh; // Store the current background texture and its `version`
  9922. // so we can recompile the material accordingly.
  9923. var currentBackground = null;
  9924. var currentBackgroundVersion = 0;
  9925. function render(renderList, scene, camera, forceClear) {
  9926. var background = scene.background; // Ignore background in AR
  9927. // TODO: Reconsider this.
  9928. var vr = renderer.vr;
  9929. var session = vr.getSession && vr.getSession();
  9930. if (session && session.environmentBlendMode === 'additive') {
  9931. background = null;
  9932. }
  9933. if (background === null) {
  9934. setClear(clearColor, clearAlpha);
  9935. currentBackground = null;
  9936. currentBackgroundVersion = 0;
  9937. } else if (background && background.isColor) {
  9938. setClear(background, 1);
  9939. forceClear = true;
  9940. currentBackground = null;
  9941. currentBackgroundVersion = 0;
  9942. }
  9943. if (renderer.autoClear || forceClear) {
  9944. renderer.clear(renderer.autoClearColor, renderer.autoClearDepth, renderer.autoClearStencil);
  9945. }
  9946. if (background && (background.isCubeTexture || background.isWebGLRenderTargetCube)) {
  9947. if (boxMesh === undefined) {
  9948. boxMesh = new Mesh(new BoxBufferGeometry(1, 1, 1), new ShaderMaterial({
  9949. type: 'BackgroundCubeMaterial',
  9950. uniforms: cloneUniforms(ShaderLib.cube.uniforms),
  9951. vertexShader: ShaderLib.cube.vertexShader,
  9952. fragmentShader: ShaderLib.cube.fragmentShader,
  9953. side: BackSide,
  9954. depthTest: false,
  9955. depthWrite: false,
  9956. fog: false
  9957. }));
  9958. boxMesh.geometry.removeAttribute('normal');
  9959. boxMesh.geometry.removeAttribute('uv');
  9960. boxMesh.onBeforeRender = function (renderer, scene, camera) {
  9961. this.matrixWorld.copyPosition(camera.matrixWorld);
  9962. }; // enable code injection for non-built-in material
  9963. Object.defineProperty(boxMesh.material, 'map', {
  9964. get: function () {
  9965. return this.uniforms.tCube.value;
  9966. }
  9967. });
  9968. objects.update(boxMesh);
  9969. }
  9970. var texture = background.isWebGLRenderTargetCube ? background.texture : background;
  9971. boxMesh.material.uniforms.tCube.value = texture;
  9972. boxMesh.material.uniforms.tFlip.value = background.isWebGLRenderTargetCube ? 1 : -1;
  9973. if (currentBackground !== background || currentBackgroundVersion !== texture.version) {
  9974. boxMesh.material.needsUpdate = true;
  9975. currentBackground = background;
  9976. currentBackgroundVersion = texture.version;
  9977. } // push to the pre-sorted opaque render list
  9978. renderList.unshift(boxMesh, boxMesh.geometry, boxMesh.material, 0, 0, null);
  9979. } else if (background && background.isTexture) {
  9980. if (planeMesh === undefined) {
  9981. planeMesh = new Mesh(new PlaneBufferGeometry(2, 2), new ShaderMaterial({
  9982. type: 'BackgroundMaterial',
  9983. uniforms: cloneUniforms(ShaderLib.background.uniforms),
  9984. vertexShader: ShaderLib.background.vertexShader,
  9985. fragmentShader: ShaderLib.background.fragmentShader,
  9986. side: FrontSide,
  9987. depthTest: false,
  9988. depthWrite: false,
  9989. fog: false
  9990. }));
  9991. planeMesh.geometry.removeAttribute('normal'); // enable code injection for non-built-in material
  9992. Object.defineProperty(planeMesh.material, 'map', {
  9993. get: function () {
  9994. return this.uniforms.t2D.value;
  9995. }
  9996. });
  9997. objects.update(planeMesh);
  9998. }
  9999. planeMesh.material.uniforms.t2D.value = background;
  10000. if (background.matrixAutoUpdate === true) {
  10001. background.updateMatrix();
  10002. }
  10003. planeMesh.material.uniforms.uvTransform.value.copy(background.matrix);
  10004. if (currentBackground !== background || currentBackgroundVersion !== background.version) {
  10005. planeMesh.material.needsUpdate = true;
  10006. currentBackground = background;
  10007. currentBackgroundVersion = background.version;
  10008. } // push to the pre-sorted opaque render list
  10009. renderList.unshift(planeMesh, planeMesh.geometry, planeMesh.material, 0, 0, null);
  10010. }
  10011. }
  10012. function setClear(color, alpha) {
  10013. state.buffers.color.setClear(color.r, color.g, color.b, alpha, premultipliedAlpha);
  10014. }
  10015. return {
  10016. getClearColor: function () {
  10017. return clearColor;
  10018. },
  10019. setClearColor: function (color, alpha) {
  10020. clearColor.set(color);
  10021. clearAlpha = alpha !== undefined ? alpha : 1;
  10022. setClear(clearColor, clearAlpha);
  10023. },
  10024. getClearAlpha: function () {
  10025. return clearAlpha;
  10026. },
  10027. setClearAlpha: function (alpha) {
  10028. clearAlpha = alpha;
  10029. setClear(clearColor, clearAlpha);
  10030. },
  10031. render: render
  10032. };
  10033. }
  10034. /**
  10035. * @author mrdoob / http://mrdoob.com/
  10036. */
  10037. function WebGLBufferRenderer(gl, extensions, info, capabilities) {
  10038. var mode;
  10039. function setMode(value) {
  10040. mode = value;
  10041. }
  10042. function render(start, count) {
  10043. gl.drawArrays(mode, start, count);
  10044. info.update(count, mode);
  10045. }
  10046. function renderInstances(geometry, start, count, primcount) {
  10047. if (primcount === 0) return;
  10048. var extension, methodName;
  10049. if (capabilities.isWebGL2) {
  10050. extension = gl;
  10051. methodName = 'drawArraysInstanced';
  10052. } else {
  10053. extension = extensions.get('ANGLE_instanced_arrays');
  10054. methodName = 'drawArraysInstancedANGLE';
  10055. if (extension === null) {
  10056. console.error('THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.');
  10057. return;
  10058. }
  10059. }
  10060. extension[methodName](mode, start, count, primcount);
  10061. info.update(count, mode, primcount);
  10062. } //
  10063. this.setMode = setMode;
  10064. this.render = render;
  10065. this.renderInstances = renderInstances;
  10066. }
  10067. /**
  10068. * @author mrdoob / http://mrdoob.com/
  10069. */
  10070. function WebGLCapabilities(gl, extensions, parameters) {
  10071. var maxAnisotropy;
  10072. function getMaxAnisotropy() {
  10073. if (maxAnisotropy !== undefined) return maxAnisotropy;
  10074. var extension = extensions.get('EXT_texture_filter_anisotropic');
  10075. if (extension !== null) {
  10076. maxAnisotropy = gl.getParameter(extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT);
  10077. } else {
  10078. maxAnisotropy = 0;
  10079. }
  10080. return maxAnisotropy;
  10081. }
  10082. function getMaxPrecision(precision) {
  10083. if (precision === 'highp') {
  10084. if (gl.getShaderPrecisionFormat(35633, 36338).precision > 0 && gl.getShaderPrecisionFormat(35632, 36338).precision > 0) {
  10085. return 'highp';
  10086. }
  10087. precision = 'mediump';
  10088. }
  10089. if (precision === 'mediump') {
  10090. if (gl.getShaderPrecisionFormat(35633, 36337).precision > 0 && gl.getShaderPrecisionFormat(35632, 36337).precision > 0) {
  10091. return 'mediump';
  10092. }
  10093. }
  10094. return 'lowp';
  10095. }
  10096. var isWebGL2 = typeof WebGL2RenderingContext !== 'undefined' && gl instanceof WebGL2RenderingContext;
  10097. var precision = parameters.precision !== undefined ? parameters.precision : 'highp';
  10098. var maxPrecision = getMaxPrecision(precision);
  10099. if (maxPrecision !== precision) {
  10100. console.warn('THREE.WebGLRenderer:', precision, 'not supported, using', maxPrecision, 'instead.');
  10101. precision = maxPrecision;
  10102. }
  10103. var logarithmicDepthBuffer = parameters.logarithmicDepthBuffer === true;
  10104. var maxTextures = gl.getParameter(34930);
  10105. var maxVertexTextures = gl.getParameter(35660);
  10106. var maxTextureSize = gl.getParameter(3379);
  10107. var maxCubemapSize = gl.getParameter(34076);
  10108. var maxAttributes = gl.getParameter(34921);
  10109. var maxVertexUniforms = gl.getParameter(36347);
  10110. var maxVaryings = gl.getParameter(36348);
  10111. var maxFragmentUniforms = gl.getParameter(36349);
  10112. var vertexTextures = maxVertexTextures > 0;
  10113. var floatFragmentTextures = isWebGL2 || !!extensions.get('OES_texture_float');
  10114. var floatVertexTextures = vertexTextures && floatFragmentTextures;
  10115. var maxSamples = isWebGL2 ? gl.getParameter(36183) : 0;
  10116. return {
  10117. isWebGL2: isWebGL2,
  10118. getMaxAnisotropy: getMaxAnisotropy,
  10119. getMaxPrecision: getMaxPrecision,
  10120. precision: precision,
  10121. logarithmicDepthBuffer: logarithmicDepthBuffer,
  10122. maxTextures: maxTextures,
  10123. maxVertexTextures: maxVertexTextures,
  10124. maxTextureSize: maxTextureSize,
  10125. maxCubemapSize: maxCubemapSize,
  10126. maxAttributes: maxAttributes,
  10127. maxVertexUniforms: maxVertexUniforms,
  10128. maxVaryings: maxVaryings,
  10129. maxFragmentUniforms: maxFragmentUniforms,
  10130. vertexTextures: vertexTextures,
  10131. floatFragmentTextures: floatFragmentTextures,
  10132. floatVertexTextures: floatVertexTextures,
  10133. maxSamples: maxSamples
  10134. };
  10135. }
  10136. /**
  10137. * @author tschw
  10138. */
  10139. function WebGLClipping() {
  10140. var scope = this,
  10141. globalState = null,
  10142. numGlobalPlanes = 0,
  10143. localClippingEnabled = false,
  10144. renderingShadows = false,
  10145. plane = new Plane(),
  10146. viewNormalMatrix = new Matrix3(),
  10147. uniform = {
  10148. value: null,
  10149. needsUpdate: false
  10150. };
  10151. this.uniform = uniform;
  10152. this.numPlanes = 0;
  10153. this.numIntersection = 0;
  10154. this.init = function (planes, enableLocalClipping, camera) {
  10155. var enabled = planes.length !== 0 || enableLocalClipping || // enable state of previous frame - the clipping code has to
  10156. // run another frame in order to reset the state:
  10157. numGlobalPlanes !== 0 || localClippingEnabled;
  10158. localClippingEnabled = enableLocalClipping;
  10159. globalState = projectPlanes(planes, camera, 0);
  10160. numGlobalPlanes = planes.length;
  10161. return enabled;
  10162. };
  10163. this.beginShadows = function () {
  10164. renderingShadows = true;
  10165. projectPlanes(null);
  10166. };
  10167. this.endShadows = function () {
  10168. renderingShadows = false;
  10169. resetGlobalState();
  10170. };
  10171. this.setState = function (planes, clipIntersection, clipShadows, camera, cache, fromCache) {
  10172. if (!localClippingEnabled || planes === null || planes.length === 0 || renderingShadows && !clipShadows) {
  10173. // there's no local clipping
  10174. if (renderingShadows) {
  10175. // there's no global clipping
  10176. projectPlanes(null);
  10177. } else {
  10178. resetGlobalState();
  10179. }
  10180. } else {
  10181. var nGlobal = renderingShadows ? 0 : numGlobalPlanes,
  10182. lGlobal = nGlobal * 4,
  10183. dstArray = cache.clippingState || null;
  10184. uniform.value = dstArray; // ensure unique state
  10185. dstArray = projectPlanes(planes, camera, lGlobal, fromCache);
  10186. for (var i = 0; i !== lGlobal; ++i) {
  10187. dstArray[i] = globalState[i];
  10188. }
  10189. cache.clippingState = dstArray;
  10190. this.numIntersection = clipIntersection ? this.numPlanes : 0;
  10191. this.numPlanes += nGlobal;
  10192. }
  10193. };
  10194. function resetGlobalState() {
  10195. if (uniform.value !== globalState) {
  10196. uniform.value = globalState;
  10197. uniform.needsUpdate = numGlobalPlanes > 0;
  10198. }
  10199. scope.numPlanes = numGlobalPlanes;
  10200. scope.numIntersection = 0;
  10201. }
  10202. function projectPlanes(planes, camera, dstOffset, skipTransform) {
  10203. var nPlanes = planes !== null ? planes.length : 0,
  10204. dstArray = null;
  10205. if (nPlanes !== 0) {
  10206. dstArray = uniform.value;
  10207. if (skipTransform !== true || dstArray === null) {
  10208. var flatSize = dstOffset + nPlanes * 4,
  10209. viewMatrix = camera.matrixWorldInverse;
  10210. viewNormalMatrix.getNormalMatrix(viewMatrix);
  10211. if (dstArray === null || dstArray.length < flatSize) {
  10212. dstArray = new Float32Array(flatSize);
  10213. }
  10214. for (var i = 0, i4 = dstOffset; i !== nPlanes; ++i, i4 += 4) {
  10215. plane.copy(planes[i]).applyMatrix4(viewMatrix, viewNormalMatrix);
  10216. plane.normal.toArray(dstArray, i4);
  10217. dstArray[i4 + 3] = plane.constant;
  10218. }
  10219. }
  10220. uniform.value = dstArray;
  10221. uniform.needsUpdate = true;
  10222. }
  10223. scope.numPlanes = nPlanes;
  10224. return dstArray;
  10225. }
  10226. }
  10227. /**
  10228. * @author mrdoob / http://mrdoob.com/
  10229. */
  10230. function WebGLExtensions(gl) {
  10231. var extensions = {};
  10232. return {
  10233. get: function (name) {
  10234. if (extensions[name] !== undefined) {
  10235. return extensions[name];
  10236. }
  10237. var extension;
  10238. switch (name) {
  10239. case 'WEBGL_depth_texture':
  10240. extension = gl.getExtension('WEBGL_depth_texture') || gl.getExtension('MOZ_WEBGL_depth_texture') || gl.getExtension('WEBKIT_WEBGL_depth_texture');
  10241. break;
  10242. case 'EXT_texture_filter_anisotropic':
  10243. extension = gl.getExtension('EXT_texture_filter_anisotropic') || gl.getExtension('MOZ_EXT_texture_filter_anisotropic') || gl.getExtension('WEBKIT_EXT_texture_filter_anisotropic');
  10244. break;
  10245. case 'WEBGL_compressed_texture_s3tc':
  10246. extension = gl.getExtension('WEBGL_compressed_texture_s3tc') || gl.getExtension('MOZ_WEBGL_compressed_texture_s3tc') || gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  10247. break;
  10248. case 'WEBGL_compressed_texture_pvrtc':
  10249. extension = gl.getExtension('WEBGL_compressed_texture_pvrtc') || gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  10250. break;
  10251. default:
  10252. extension = gl.getExtension(name);
  10253. }
  10254. if (extension === null) {
  10255. console.warn('THREE.WebGLRenderer: ' + name + ' extension not supported.');
  10256. }
  10257. extensions[name] = extension;
  10258. return extension;
  10259. }
  10260. };
  10261. }
  10262. /**
  10263. * @author mrdoob / http://mrdoob.com/
  10264. */
  10265. function WebGLGeometries(gl, attributes, info) {
  10266. var geometries = new WeakMap();
  10267. var wireframeAttributes = new WeakMap();
  10268. function onGeometryDispose(event) {
  10269. var geometry = event.target;
  10270. var buffergeometry = geometries.get(geometry);
  10271. if (buffergeometry.index !== null) {
  10272. attributes.remove(buffergeometry.index);
  10273. }
  10274. for (var name in buffergeometry.attributes) {
  10275. attributes.remove(buffergeometry.attributes[name]);
  10276. }
  10277. geometry.removeEventListener('dispose', onGeometryDispose);
  10278. geometries.delete(geometry);
  10279. var attribute = wireframeAttributes.get(buffergeometry);
  10280. if (attribute) {
  10281. attributes.remove(attribute);
  10282. wireframeAttributes.delete(buffergeometry);
  10283. } //
  10284. info.memory.geometries--;
  10285. }
  10286. function get(object, geometry) {
  10287. var buffergeometry = geometries.get(geometry);
  10288. if (buffergeometry) return buffergeometry;
  10289. geometry.addEventListener('dispose', onGeometryDispose);
  10290. if (geometry.isBufferGeometry) {
  10291. buffergeometry = geometry;
  10292. } else if (geometry.isGeometry) {
  10293. if (geometry._bufferGeometry === undefined) {
  10294. geometry._bufferGeometry = new BufferGeometry().setFromObject(object);
  10295. }
  10296. buffergeometry = geometry._bufferGeometry;
  10297. }
  10298. geometries.set(geometry, buffergeometry);
  10299. info.memory.geometries++;
  10300. return buffergeometry;
  10301. }
  10302. function update(geometry) {
  10303. var index = geometry.index;
  10304. var geometryAttributes = geometry.attributes;
  10305. if (index !== null) {
  10306. attributes.update(index, 34963);
  10307. }
  10308. for (var name in geometryAttributes) {
  10309. attributes.update(geometryAttributes[name], 34962);
  10310. } // morph targets
  10311. var morphAttributes = geometry.morphAttributes;
  10312. for (var name in morphAttributes) {
  10313. var array = morphAttributes[name];
  10314. for (var i = 0, l = array.length; i < l; i++) {
  10315. attributes.update(array[i], 34962);
  10316. }
  10317. }
  10318. }
  10319. function updateWireframeAttribute(geometry) {
  10320. var indices = [];
  10321. var geometryIndex = geometry.index;
  10322. var geometryPosition = geometry.attributes.position;
  10323. var version = 0;
  10324. if (geometryIndex !== null) {
  10325. var array = geometryIndex.array;
  10326. version = geometryIndex.version;
  10327. for (var i = 0, l = array.length; i < l; i += 3) {
  10328. var a = array[i + 0];
  10329. var b = array[i + 1];
  10330. var c = array[i + 2];
  10331. indices.push(a, b, b, c, c, a);
  10332. }
  10333. } else {
  10334. var array = geometryPosition.array;
  10335. version = geometryPosition.version;
  10336. for (var i = 0, l = array.length / 3 - 1; i < l; i += 3) {
  10337. var a = i + 0;
  10338. var b = i + 1;
  10339. var c = i + 2;
  10340. indices.push(a, b, b, c, c, a);
  10341. }
  10342. }
  10343. var attribute = new (arrayMax(indices) > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute)(indices, 1);
  10344. attribute.version = version;
  10345. attributes.update(attribute, 34963); //
  10346. var previousAttribute = wireframeAttributes.get(geometry);
  10347. if (previousAttribute) attributes.remove(previousAttribute); //
  10348. wireframeAttributes.set(geometry, attribute);
  10349. }
  10350. function getWireframeAttribute(geometry) {
  10351. var currentAttribute = wireframeAttributes.get(geometry);
  10352. if (currentAttribute) {
  10353. var geometryIndex = geometry.index;
  10354. if (geometryIndex !== null) {
  10355. // if the attribute is obsolete, create a new one
  10356. if (currentAttribute.version < geometryIndex.version) {
  10357. updateWireframeAttribute(geometry);
  10358. }
  10359. }
  10360. } else {
  10361. updateWireframeAttribute(geometry);
  10362. }
  10363. return wireframeAttributes.get(geometry);
  10364. }
  10365. return {
  10366. get: get,
  10367. update: update,
  10368. getWireframeAttribute: getWireframeAttribute
  10369. };
  10370. }
  10371. /**
  10372. * @author mrdoob / http://mrdoob.com/
  10373. */
  10374. function WebGLIndexedBufferRenderer(gl, extensions, info, capabilities) {
  10375. var mode;
  10376. function setMode(value) {
  10377. mode = value;
  10378. }
  10379. var type, bytesPerElement;
  10380. function setIndex(value) {
  10381. type = value.type;
  10382. bytesPerElement = value.bytesPerElement;
  10383. }
  10384. function render(start, count) {
  10385. gl.drawElements(mode, count, type, start * bytesPerElement);
  10386. info.update(count, mode);
  10387. }
  10388. function renderInstances(geometry, start, count, primcount) {
  10389. if (primcount === 0) return;
  10390. var extension, methodName;
  10391. if (capabilities.isWebGL2) {
  10392. extension = gl;
  10393. methodName = 'drawElementsInstanced';
  10394. } else {
  10395. extension = extensions.get('ANGLE_instanced_arrays');
  10396. methodName = 'drawElementsInstancedANGLE';
  10397. if (extension === null) {
  10398. console.error('THREE.WebGLIndexedBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.');
  10399. return;
  10400. }
  10401. }
  10402. extension[methodName](mode, count, type, start * bytesPerElement, primcount);
  10403. info.update(count, mode, primcount);
  10404. } //
  10405. this.setMode = setMode;
  10406. this.setIndex = setIndex;
  10407. this.render = render;
  10408. this.renderInstances = renderInstances;
  10409. }
  10410. /**
  10411. * @author Mugen87 / https://github.com/Mugen87
  10412. */
  10413. function WebGLInfo(gl) {
  10414. var memory = {
  10415. geometries: 0,
  10416. textures: 0
  10417. };
  10418. var render = {
  10419. frame: 0,
  10420. calls: 0,
  10421. triangles: 0,
  10422. points: 0,
  10423. lines: 0
  10424. };
  10425. function update(count, mode, instanceCount) {
  10426. instanceCount = instanceCount || 1;
  10427. render.calls++;
  10428. switch (mode) {
  10429. case 4:
  10430. render.triangles += instanceCount * (count / 3);
  10431. break;
  10432. case 5:
  10433. case 6:
  10434. render.triangles += instanceCount * (count - 2);
  10435. break;
  10436. case 1:
  10437. render.lines += instanceCount * (count / 2);
  10438. break;
  10439. case 3:
  10440. render.lines += instanceCount * (count - 1);
  10441. break;
  10442. case 2:
  10443. render.lines += instanceCount * count;
  10444. break;
  10445. case 0:
  10446. render.points += instanceCount * count;
  10447. break;
  10448. default:
  10449. console.error('THREE.WebGLInfo: Unknown draw mode:', mode);
  10450. break;
  10451. }
  10452. }
  10453. function reset() {
  10454. render.frame++;
  10455. render.calls = 0;
  10456. render.triangles = 0;
  10457. render.points = 0;
  10458. render.lines = 0;
  10459. }
  10460. return {
  10461. memory: memory,
  10462. render: render,
  10463. programs: null,
  10464. autoReset: true,
  10465. reset: reset,
  10466. update: update
  10467. };
  10468. }
  10469. /**
  10470. * @author mrdoob / http://mrdoob.com/
  10471. */
  10472. function absNumericalSort(a, b) {
  10473. return Math.abs(b[1]) - Math.abs(a[1]);
  10474. }
  10475. function WebGLMorphtargets(gl) {
  10476. var influencesList = {};
  10477. var morphInfluences = new Float32Array(8);
  10478. function update(object, geometry, material, program) {
  10479. var objectInfluences = object.morphTargetInfluences;
  10480. var length = objectInfluences.length;
  10481. var influences = influencesList[geometry.id];
  10482. if (influences === undefined) {
  10483. // initialise list
  10484. influences = [];
  10485. for (var i = 0; i < length; i++) {
  10486. influences[i] = [i, 0];
  10487. }
  10488. influencesList[geometry.id] = influences;
  10489. }
  10490. var morphTargets = material.morphTargets && geometry.morphAttributes.position;
  10491. var morphNormals = material.morphNormals && geometry.morphAttributes.normal; // Remove current morphAttributes
  10492. for (var i = 0; i < length; i++) {
  10493. var influence = influences[i];
  10494. if (influence[1] !== 0) {
  10495. if (morphTargets) geometry.removeAttribute('morphTarget' + i);
  10496. if (morphNormals) geometry.removeAttribute('morphNormal' + i);
  10497. }
  10498. } // Collect influences
  10499. for (var i = 0; i < length; i++) {
  10500. var influence = influences[i];
  10501. influence[0] = i;
  10502. influence[1] = objectInfluences[i];
  10503. }
  10504. influences.sort(absNumericalSort); // Add morphAttributes
  10505. for (var i = 0; i < 8; i++) {
  10506. var influence = influences[i];
  10507. if (influence) {
  10508. var index = influence[0];
  10509. var value = influence[1];
  10510. if (value) {
  10511. if (morphTargets) geometry.addAttribute('morphTarget' + i, morphTargets[index]);
  10512. if (morphNormals) geometry.addAttribute('morphNormal' + i, morphNormals[index]);
  10513. morphInfluences[i] = value;
  10514. continue;
  10515. }
  10516. }
  10517. morphInfluences[i] = 0;
  10518. }
  10519. program.getUniforms().setValue(gl, 'morphTargetInfluences', morphInfluences);
  10520. }
  10521. return {
  10522. update: update
  10523. };
  10524. }
  10525. /**
  10526. * @author mrdoob / http://mrdoob.com/
  10527. */
  10528. function WebGLObjects(gl, geometries, attributes, info) {
  10529. var updateList = {};
  10530. function update(object) {
  10531. var frame = info.render.frame;
  10532. var geometry = object.geometry;
  10533. var buffergeometry = geometries.get(object, geometry); // Update once per frame
  10534. if (updateList[buffergeometry.id] !== frame) {
  10535. if (geometry.isGeometry) {
  10536. buffergeometry.updateFromObject(object);
  10537. }
  10538. geometries.update(buffergeometry);
  10539. updateList[buffergeometry.id] = frame;
  10540. }
  10541. if (object.isInstancedMesh) {
  10542. attributes.update(object.instanceMatrix, 34962);
  10543. }
  10544. return buffergeometry;
  10545. }
  10546. function dispose() {
  10547. updateList = {};
  10548. }
  10549. return {
  10550. update: update,
  10551. dispose: dispose
  10552. };
  10553. }
  10554. /**
  10555. * @author mrdoob / http://mrdoob.com/
  10556. */
  10557. function CubeTexture(images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding) {
  10558. images = images !== undefined ? images : [];
  10559. mapping = mapping !== undefined ? mapping : CubeReflectionMapping;
  10560. format = format !== undefined ? format : RGBFormat;
  10561. Texture.call(this, images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding);
  10562. this.flipY = false;
  10563. }
  10564. CubeTexture.prototype = Object.create(Texture.prototype);
  10565. CubeTexture.prototype.constructor = CubeTexture;
  10566. CubeTexture.prototype.isCubeTexture = true;
  10567. Object.defineProperty(CubeTexture.prototype, 'images', {
  10568. get: function () {
  10569. return this.image;
  10570. },
  10571. set: function (value) {
  10572. this.image = value;
  10573. }
  10574. });
  10575. /**
  10576. * @author Takahiro https://github.com/takahirox
  10577. */
  10578. function DataTexture2DArray(data, width, height, depth) {
  10579. Texture.call(this, null);
  10580. this.image = {
  10581. data: data || null,
  10582. width: width || 1,
  10583. height: height || 1,
  10584. depth: depth || 1
  10585. };
  10586. this.magFilter = NearestFilter;
  10587. this.minFilter = NearestFilter;
  10588. this.wrapR = ClampToEdgeWrapping;
  10589. this.generateMipmaps = false;
  10590. this.flipY = false;
  10591. this.needsUpdate = true;
  10592. }
  10593. DataTexture2DArray.prototype = Object.create(Texture.prototype);
  10594. DataTexture2DArray.prototype.constructor = DataTexture2DArray;
  10595. DataTexture2DArray.prototype.isDataTexture2DArray = true;
  10596. /**
  10597. * @author Artur Trzesiok
  10598. */
  10599. function DataTexture3D(data, width, height, depth) {
  10600. // We're going to add .setXXX() methods for setting properties later.
  10601. // Users can still set in DataTexture3D directly.
  10602. //
  10603. // var texture = new THREE.DataTexture3D( data, width, height, depth );
  10604. // texture.anisotropy = 16;
  10605. //
  10606. // See #14839
  10607. Texture.call(this, null);
  10608. this.image = {
  10609. data: data || null,
  10610. width: width || 1,
  10611. height: height || 1,
  10612. depth: depth || 1
  10613. };
  10614. this.magFilter = NearestFilter;
  10615. this.minFilter = NearestFilter;
  10616. this.wrapR = ClampToEdgeWrapping;
  10617. this.generateMipmaps = false;
  10618. this.flipY = false;
  10619. this.needsUpdate = true;
  10620. }
  10621. DataTexture3D.prototype = Object.create(Texture.prototype);
  10622. DataTexture3D.prototype.constructor = DataTexture3D;
  10623. DataTexture3D.prototype.isDataTexture3D = true;
  10624. /**
  10625. * @author tschw
  10626. * @author Mugen87 / https://github.com/Mugen87
  10627. * @author mrdoob / http://mrdoob.com/
  10628. *
  10629. * Uniforms of a program.
  10630. * Those form a tree structure with a special top-level container for the root,
  10631. * which you get by calling 'new WebGLUniforms( gl, program )'.
  10632. *
  10633. *
  10634. * Properties of inner nodes including the top-level container:
  10635. *
  10636. * .seq - array of nested uniforms
  10637. * .map - nested uniforms by name
  10638. *
  10639. *
  10640. * Methods of all nodes except the top-level container:
  10641. *
  10642. * .setValue( gl, value, [textures] )
  10643. *
  10644. * uploads a uniform value(s)
  10645. * the 'textures' parameter is needed for sampler uniforms
  10646. *
  10647. *
  10648. * Static methods of the top-level container (textures factorizations):
  10649. *
  10650. * .upload( gl, seq, values, textures )
  10651. *
  10652. * sets uniforms in 'seq' to 'values[id].value'
  10653. *
  10654. * .seqWithValue( seq, values ) : filteredSeq
  10655. *
  10656. * filters 'seq' entries with corresponding entry in values
  10657. *
  10658. *
  10659. * Methods of the top-level container (textures factorizations):
  10660. *
  10661. * .setValue( gl, name, value, textures )
  10662. *
  10663. * sets uniform with name 'name' to 'value'
  10664. *
  10665. * .setOptional( gl, obj, prop )
  10666. *
  10667. * like .set for an optional property of the object
  10668. *
  10669. */
  10670. var emptyTexture = new Texture();
  10671. var emptyTexture2dArray = new DataTexture2DArray();
  10672. var emptyTexture3d = new DataTexture3D();
  10673. var emptyCubeTexture = new CubeTexture(); // --- Utilities ---
  10674. // Array Caches (provide typed arrays for temporary by size)
  10675. var arrayCacheF32 = [];
  10676. var arrayCacheI32 = []; // Float32Array caches used for uploading Matrix uniforms
  10677. var mat4array = new Float32Array(16);
  10678. var mat3array = new Float32Array(9);
  10679. var mat2array = new Float32Array(4); // Flattening for arrays of vectors and matrices
  10680. function flatten(array, nBlocks, blockSize) {
  10681. var firstElem = array[0];
  10682. if (firstElem <= 0 || firstElem > 0) return array; // unoptimized: ! isNaN( firstElem )
  10683. // see http://jacksondunstan.com/articles/983
  10684. var n = nBlocks * blockSize,
  10685. r = arrayCacheF32[n];
  10686. if (r === undefined) {
  10687. r = new Float32Array(n);
  10688. arrayCacheF32[n] = r;
  10689. }
  10690. if (nBlocks !== 0) {
  10691. firstElem.toArray(r, 0);
  10692. for (var i = 1, offset = 0; i !== nBlocks; ++i) {
  10693. offset += blockSize;
  10694. array[i].toArray(r, offset);
  10695. }
  10696. }
  10697. return r;
  10698. }
  10699. function arraysEqual(a, b) {
  10700. if (a.length !== b.length) return false;
  10701. for (var i = 0, l = a.length; i < l; i++) {
  10702. if (a[i] !== b[i]) return false;
  10703. }
  10704. return true;
  10705. }
  10706. function copyArray(a, b) {
  10707. for (var i = 0, l = b.length; i < l; i++) {
  10708. a[i] = b[i];
  10709. }
  10710. } // Texture unit allocation
  10711. function allocTexUnits(textures, n) {
  10712. var r = arrayCacheI32[n];
  10713. if (r === undefined) {
  10714. r = new Int32Array(n);
  10715. arrayCacheI32[n] = r;
  10716. }
  10717. for (var i = 0; i !== n; ++i) r[i] = textures.allocateTextureUnit();
  10718. return r;
  10719. } // --- Setters ---
  10720. // Note: Defining these methods externally, because they come in a bunch
  10721. // and this way their names minify.
  10722. // Single scalar
  10723. function setValueV1f(gl, v) {
  10724. var cache = this.cache;
  10725. if (cache[0] === v) return;
  10726. gl.uniform1f(this.addr, v);
  10727. cache[0] = v;
  10728. } // Single float vector (from flat array or THREE.VectorN)
  10729. function setValueV2f(gl, v) {
  10730. var cache = this.cache;
  10731. if (v.x !== undefined) {
  10732. if (cache[0] !== v.x || cache[1] !== v.y) {
  10733. gl.uniform2f(this.addr, v.x, v.y);
  10734. cache[0] = v.x;
  10735. cache[1] = v.y;
  10736. }
  10737. } else {
  10738. if (arraysEqual(cache, v)) return;
  10739. gl.uniform2fv(this.addr, v);
  10740. copyArray(cache, v);
  10741. }
  10742. }
  10743. function setValueV3f(gl, v) {
  10744. var cache = this.cache;
  10745. if (v.x !== undefined) {
  10746. if (cache[0] !== v.x || cache[1] !== v.y || cache[2] !== v.z) {
  10747. gl.uniform3f(this.addr, v.x, v.y, v.z);
  10748. cache[0] = v.x;
  10749. cache[1] = v.y;
  10750. cache[2] = v.z;
  10751. }
  10752. } else if (v.r !== undefined) {
  10753. if (cache[0] !== v.r || cache[1] !== v.g || cache[2] !== v.b) {
  10754. gl.uniform3f(this.addr, v.r, v.g, v.b);
  10755. cache[0] = v.r;
  10756. cache[1] = v.g;
  10757. cache[2] = v.b;
  10758. }
  10759. } else {
  10760. if (arraysEqual(cache, v)) return;
  10761. gl.uniform3fv(this.addr, v);
  10762. copyArray(cache, v);
  10763. }
  10764. }
  10765. function setValueV4f(gl, v) {
  10766. var cache = this.cache;
  10767. if (v.x !== undefined) {
  10768. if (cache[0] !== v.x || cache[1] !== v.y || cache[2] !== v.z || cache[3] !== v.w) {
  10769. gl.uniform4f(this.addr, v.x, v.y, v.z, v.w);
  10770. cache[0] = v.x;
  10771. cache[1] = v.y;
  10772. cache[2] = v.z;
  10773. cache[3] = v.w;
  10774. }
  10775. } else {
  10776. if (arraysEqual(cache, v)) return;
  10777. gl.uniform4fv(this.addr, v);
  10778. copyArray(cache, v);
  10779. }
  10780. } // Single matrix (from flat array or MatrixN)
  10781. function setValueM2(gl, v) {
  10782. var cache = this.cache;
  10783. var elements = v.elements;
  10784. if (elements === undefined) {
  10785. if (arraysEqual(cache, v)) return;
  10786. gl.uniformMatrix2fv(this.addr, false, v);
  10787. copyArray(cache, v);
  10788. } else {
  10789. if (arraysEqual(cache, elements)) return;
  10790. mat2array.set(elements);
  10791. gl.uniformMatrix2fv(this.addr, false, mat2array);
  10792. copyArray(cache, elements);
  10793. }
  10794. }
  10795. function setValueM3(gl, v) {
  10796. var cache = this.cache;
  10797. var elements = v.elements;
  10798. if (elements === undefined) {
  10799. if (arraysEqual(cache, v)) return;
  10800. gl.uniformMatrix3fv(this.addr, false, v);
  10801. copyArray(cache, v);
  10802. } else {
  10803. if (arraysEqual(cache, elements)) return;
  10804. mat3array.set(elements);
  10805. gl.uniformMatrix3fv(this.addr, false, mat3array);
  10806. copyArray(cache, elements);
  10807. }
  10808. }
  10809. function setValueM4(gl, v) {
  10810. var cache = this.cache;
  10811. var elements = v.elements;
  10812. if (elements === undefined) {
  10813. if (arraysEqual(cache, v)) return;
  10814. gl.uniformMatrix4fv(this.addr, false, v);
  10815. copyArray(cache, v);
  10816. } else {
  10817. if (arraysEqual(cache, elements)) return;
  10818. mat4array.set(elements);
  10819. gl.uniformMatrix4fv(this.addr, false, mat4array);
  10820. copyArray(cache, elements);
  10821. }
  10822. } // Single texture (2D / Cube)
  10823. function setValueT1(gl, v, textures) {
  10824. var cache = this.cache;
  10825. var unit = textures.allocateTextureUnit();
  10826. if (cache[0] !== unit) {
  10827. gl.uniform1i(this.addr, unit);
  10828. cache[0] = unit;
  10829. }
  10830. textures.safeSetTexture2D(v || emptyTexture, unit);
  10831. }
  10832. function setValueT2DArray1(gl, v, textures) {
  10833. var cache = this.cache;
  10834. var unit = textures.allocateTextureUnit();
  10835. if (cache[0] !== unit) {
  10836. gl.uniform1i(this.addr, unit);
  10837. cache[0] = unit;
  10838. }
  10839. textures.setTexture2DArray(v || emptyTexture2dArray, unit);
  10840. }
  10841. function setValueT3D1(gl, v, textures) {
  10842. var cache = this.cache;
  10843. var unit = textures.allocateTextureUnit();
  10844. if (cache[0] !== unit) {
  10845. gl.uniform1i(this.addr, unit);
  10846. cache[0] = unit;
  10847. }
  10848. textures.setTexture3D(v || emptyTexture3d, unit);
  10849. }
  10850. function setValueT6(gl, v, textures) {
  10851. var cache = this.cache;
  10852. var unit = textures.allocateTextureUnit();
  10853. if (cache[0] !== unit) {
  10854. gl.uniform1i(this.addr, unit);
  10855. cache[0] = unit;
  10856. }
  10857. textures.safeSetTextureCube(v || emptyCubeTexture, unit);
  10858. } // Integer / Boolean vectors or arrays thereof (always flat arrays)
  10859. function setValueV1i(gl, v) {
  10860. var cache = this.cache;
  10861. if (cache[0] === v) return;
  10862. gl.uniform1i(this.addr, v);
  10863. cache[0] = v;
  10864. }
  10865. function setValueV2i(gl, v) {
  10866. var cache = this.cache;
  10867. if (arraysEqual(cache, v)) return;
  10868. gl.uniform2iv(this.addr, v);
  10869. copyArray(cache, v);
  10870. }
  10871. function setValueV3i(gl, v) {
  10872. var cache = this.cache;
  10873. if (arraysEqual(cache, v)) return;
  10874. gl.uniform3iv(this.addr, v);
  10875. copyArray(cache, v);
  10876. }
  10877. function setValueV4i(gl, v) {
  10878. var cache = this.cache;
  10879. if (arraysEqual(cache, v)) return;
  10880. gl.uniform4iv(this.addr, v);
  10881. copyArray(cache, v);
  10882. } // Helper to pick the right setter for the singular case
  10883. function getSingularSetter(type) {
  10884. switch (type) {
  10885. case 0x1406:
  10886. return setValueV1f;
  10887. // FLOAT
  10888. case 0x8b50:
  10889. return setValueV2f;
  10890. // _VEC2
  10891. case 0x8b51:
  10892. return setValueV3f;
  10893. // _VEC3
  10894. case 0x8b52:
  10895. return setValueV4f;
  10896. // _VEC4
  10897. case 0x8b5a:
  10898. return setValueM2;
  10899. // _MAT2
  10900. case 0x8b5b:
  10901. return setValueM3;
  10902. // _MAT3
  10903. case 0x8b5c:
  10904. return setValueM4;
  10905. // _MAT4
  10906. case 0x8b5e:
  10907. case 0x8d66:
  10908. return setValueT1;
  10909. // SAMPLER_2D, SAMPLER_EXTERNAL_OES
  10910. case 0x8b5f:
  10911. return setValueT3D1;
  10912. // SAMPLER_3D
  10913. case 0x8b60:
  10914. return setValueT6;
  10915. // SAMPLER_CUBE
  10916. case 0x8DC1:
  10917. return setValueT2DArray1;
  10918. // SAMPLER_2D_ARRAY
  10919. case 0x1404:
  10920. case 0x8b56:
  10921. return setValueV1i;
  10922. // INT, BOOL
  10923. case 0x8b53:
  10924. case 0x8b57:
  10925. return setValueV2i;
  10926. // _VEC2
  10927. case 0x8b54:
  10928. case 0x8b58:
  10929. return setValueV3i;
  10930. // _VEC3
  10931. case 0x8b55:
  10932. case 0x8b59:
  10933. return setValueV4i;
  10934. // _VEC4
  10935. }
  10936. } // Array of scalars
  10937. function setValueV1fArray(gl, v) {
  10938. gl.uniform1fv(this.addr, v);
  10939. } // Integer / Boolean vectors or arrays thereof (always flat arrays)
  10940. function setValueV1iArray(gl, v) {
  10941. gl.uniform1iv(this.addr, v);
  10942. }
  10943. function setValueV2iArray(gl, v) {
  10944. gl.uniform2iv(this.addr, v);
  10945. }
  10946. function setValueV3iArray(gl, v) {
  10947. gl.uniform3iv(this.addr, v);
  10948. }
  10949. function setValueV4iArray(gl, v) {
  10950. gl.uniform4iv(this.addr, v);
  10951. } // Array of vectors (flat or from THREE classes)
  10952. function setValueV2fArray(gl, v) {
  10953. var data = flatten(v, this.size, 2);
  10954. gl.uniform2fv(this.addr, data);
  10955. }
  10956. function setValueV3fArray(gl, v) {
  10957. var data = flatten(v, this.size, 3);
  10958. gl.uniform3fv(this.addr, data);
  10959. }
  10960. function setValueV4fArray(gl, v) {
  10961. var data = flatten(v, this.size, 4);
  10962. gl.uniform4fv(this.addr, data);
  10963. } // Array of matrices (flat or from THREE clases)
  10964. function setValueM2Array(gl, v) {
  10965. var data = flatten(v, this.size, 4);
  10966. gl.uniformMatrix2fv(this.addr, false, data);
  10967. }
  10968. function setValueM3Array(gl, v) {
  10969. var data = flatten(v, this.size, 9);
  10970. gl.uniformMatrix3fv(this.addr, false, data);
  10971. }
  10972. function setValueM4Array(gl, v) {
  10973. var data = flatten(v, this.size, 16);
  10974. gl.uniformMatrix4fv(this.addr, false, data);
  10975. } // Array of textures (2D / Cube)
  10976. function setValueT1Array(gl, v, textures) {
  10977. var n = v.length;
  10978. var units = allocTexUnits(textures, n);
  10979. gl.uniform1iv(this.addr, units);
  10980. for (var i = 0; i !== n; ++i) {
  10981. textures.safeSetTexture2D(v[i] || emptyTexture, units[i]);
  10982. }
  10983. }
  10984. function setValueT6Array(gl, v, textures) {
  10985. var n = v.length;
  10986. var units = allocTexUnits(textures, n);
  10987. gl.uniform1iv(this.addr, units);
  10988. for (var i = 0; i !== n; ++i) {
  10989. textures.safeSetTextureCube(v[i] || emptyCubeTexture, units[i]);
  10990. }
  10991. } // Helper to pick the right setter for a pure (bottom-level) array
  10992. function getPureArraySetter(type) {
  10993. switch (type) {
  10994. case 0x1406:
  10995. return setValueV1fArray;
  10996. // FLOAT
  10997. case 0x8b50:
  10998. return setValueV2fArray;
  10999. // _VEC2
  11000. case 0x8b51:
  11001. return setValueV3fArray;
  11002. // _VEC3
  11003. case 0x8b52:
  11004. return setValueV4fArray;
  11005. // _VEC4
  11006. case 0x8b5a:
  11007. return setValueM2Array;
  11008. // _MAT2
  11009. case 0x8b5b:
  11010. return setValueM3Array;
  11011. // _MAT3
  11012. case 0x8b5c:
  11013. return setValueM4Array;
  11014. // _MAT4
  11015. case 0x8b5e:
  11016. return setValueT1Array;
  11017. // SAMPLER_2D
  11018. case 0x8b60:
  11019. return setValueT6Array;
  11020. // SAMPLER_CUBE
  11021. case 0x1404:
  11022. case 0x8b56:
  11023. return setValueV1iArray;
  11024. // INT, BOOL
  11025. case 0x8b53:
  11026. case 0x8b57:
  11027. return setValueV2iArray;
  11028. // _VEC2
  11029. case 0x8b54:
  11030. case 0x8b58:
  11031. return setValueV3iArray;
  11032. // _VEC3
  11033. case 0x8b55:
  11034. case 0x8b59:
  11035. return setValueV4iArray;
  11036. // _VEC4
  11037. }
  11038. } // --- Uniform Classes ---
  11039. function SingleUniform(id, activeInfo, addr) {
  11040. this.id = id;
  11041. this.addr = addr;
  11042. this.cache = [];
  11043. this.setValue = getSingularSetter(activeInfo.type); // this.path = activeInfo.name; // DEBUG
  11044. }
  11045. function PureArrayUniform(id, activeInfo, addr) {
  11046. this.id = id;
  11047. this.addr = addr;
  11048. this.cache = [];
  11049. this.size = activeInfo.size;
  11050. this.setValue = getPureArraySetter(activeInfo.type); // this.path = activeInfo.name; // DEBUG
  11051. }
  11052. PureArrayUniform.prototype.updateCache = function (data) {
  11053. var cache = this.cache;
  11054. if (data instanceof Float32Array && cache.length !== data.length) {
  11055. this.cache = new Float32Array(data.length);
  11056. }
  11057. copyArray(cache, data);
  11058. };
  11059. function StructuredUniform(id) {
  11060. this.id = id;
  11061. this.seq = [];
  11062. this.map = {};
  11063. }
  11064. StructuredUniform.prototype.setValue = function (gl, value, textures) {
  11065. var seq = this.seq;
  11066. for (var i = 0, n = seq.length; i !== n; ++i) {
  11067. var u = seq[i];
  11068. u.setValue(gl, value[u.id], textures);
  11069. }
  11070. }; // --- Top-level ---
  11071. // Parser - builds up the property tree from the path strings
  11072. var RePathPart = /([\w\d_]+)(\])?(\[|\.)?/g; // extracts
  11073. // - the identifier (member name or array index)
  11074. // - followed by an optional right bracket (found when array index)
  11075. // - followed by an optional left bracket or dot (type of subscript)
  11076. //
  11077. // Note: These portions can be read in a non-overlapping fashion and
  11078. // allow straightforward parsing of the hierarchy that WebGL encodes
  11079. // in the uniform names.
  11080. function addUniform(container, uniformObject) {
  11081. container.seq.push(uniformObject);
  11082. container.map[uniformObject.id] = uniformObject;
  11083. }
  11084. function parseUniform(activeInfo, addr, container) {
  11085. var path = activeInfo.name,
  11086. pathLength = path.length; // reset RegExp object, because of the early exit of a previous run
  11087. RePathPart.lastIndex = 0;
  11088. while (true) {
  11089. var match = RePathPart.exec(path),
  11090. matchEnd = RePathPart.lastIndex,
  11091. id = match[1],
  11092. idIsIndex = match[2] === ']',
  11093. subscript = match[3];
  11094. if (idIsIndex) id = id | 0; // convert to integer
  11095. if (subscript === undefined || subscript === '[' && matchEnd + 2 === pathLength) {
  11096. // bare name or "pure" bottom-level array "[0]" suffix
  11097. addUniform(container, subscript === undefined ? new SingleUniform(id, activeInfo, addr) : new PureArrayUniform(id, activeInfo, addr));
  11098. break;
  11099. } else {
  11100. // step into inner node / create it in case it doesn't exist
  11101. var map = container.map,
  11102. next = map[id];
  11103. if (next === undefined) {
  11104. next = new StructuredUniform(id);
  11105. addUniform(container, next);
  11106. }
  11107. container = next;
  11108. }
  11109. }
  11110. } // Root Container
  11111. function WebGLUniforms(gl, program) {
  11112. this.seq = [];
  11113. this.map = {};
  11114. var n = gl.getProgramParameter(program, 35718);
  11115. for (var i = 0; i < n; ++i) {
  11116. var info = gl.getActiveUniform(program, i),
  11117. addr = gl.getUniformLocation(program, info.name);
  11118. parseUniform(info, addr, this);
  11119. }
  11120. }
  11121. WebGLUniforms.prototype.setValue = function (gl, name, value, textures) {
  11122. var u = this.map[name];
  11123. if (u !== undefined) u.setValue(gl, value, textures);
  11124. };
  11125. WebGLUniforms.prototype.setOptional = function (gl, object, name) {
  11126. var v = object[name];
  11127. if (v !== undefined) this.setValue(gl, name, v);
  11128. }; // Static interface
  11129. WebGLUniforms.upload = function (gl, seq, values, textures) {
  11130. for (var i = 0, n = seq.length; i !== n; ++i) {
  11131. var u = seq[i],
  11132. v = values[u.id];
  11133. if (v.needsUpdate !== false) {
  11134. // note: always updating when .needsUpdate is undefined
  11135. u.setValue(gl, v.value, textures);
  11136. }
  11137. }
  11138. };
  11139. WebGLUniforms.seqWithValue = function (seq, values) {
  11140. var r = [];
  11141. for (var i = 0, n = seq.length; i !== n; ++i) {
  11142. var u = seq[i];
  11143. if (u.id in values) r.push(u);
  11144. }
  11145. return r;
  11146. };
  11147. /**
  11148. * @author mrdoob / http://mrdoob.com/
  11149. */
  11150. function WebGLShader(gl, type, string) {
  11151. var shader = gl.createShader(type);
  11152. gl.shaderSource(shader, string);
  11153. gl.compileShader(shader);
  11154. return shader;
  11155. }
  11156. /**
  11157. * @author mrdoob / http://mrdoob.com/
  11158. */
  11159. var programIdCount = 0;
  11160. function addLineNumbers(string) {
  11161. var lines = string.split('\n');
  11162. for (var i = 0; i < lines.length; i++) {
  11163. lines[i] = i + 1 + ': ' + lines[i];
  11164. }
  11165. return lines.join('\n');
  11166. }
  11167. function getEncodingComponents(encoding) {
  11168. switch (encoding) {
  11169. case LinearEncoding:
  11170. return ['Linear', '( value )'];
  11171. case sRGBEncoding:
  11172. return ['sRGB', '( value )'];
  11173. case RGBEEncoding:
  11174. return ['RGBE', '( value )'];
  11175. case RGBM7Encoding:
  11176. return ['RGBM', '( value, 7.0 )'];
  11177. case RGBM16Encoding:
  11178. return ['RGBM', '( value, 16.0 )'];
  11179. case RGBDEncoding:
  11180. return ['RGBD', '( value, 256.0 )'];
  11181. case GammaEncoding:
  11182. return ['Gamma', '( value, float( GAMMA_FACTOR ) )'];
  11183. case LogLuvEncoding:
  11184. return ['LogLuv', '( value )'];
  11185. default:
  11186. throw new Error('unsupported encoding: ' + encoding);
  11187. }
  11188. }
  11189. function getShaderErrors(gl, shader, type) {
  11190. var status = gl.getShaderParameter(shader, 35713);
  11191. var log = gl.getShaderInfoLog(shader).trim();
  11192. if (status && log === '') return ''; // --enable-privileged-webgl-extension
  11193. // console.log( '**' + type + '**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) );
  11194. var source = gl.getShaderSource(shader);
  11195. return 'THREE.WebGLShader: gl.getShaderInfoLog() ' + type + '\n' + log + addLineNumbers(source);
  11196. }
  11197. function getTexelDecodingFunction(functionName, encoding) {
  11198. var components = getEncodingComponents(encoding);
  11199. return 'vec4 ' + functionName + '( vec4 value ) { return ' + components[0] + 'ToLinear' + components[1] + '; }';
  11200. }
  11201. function getTexelEncodingFunction(functionName, encoding) {
  11202. var components = getEncodingComponents(encoding);
  11203. return 'vec4 ' + functionName + '( vec4 value ) { return LinearTo' + components[0] + components[1] + '; }';
  11204. }
  11205. function getToneMappingFunction(functionName, toneMapping) {
  11206. var toneMappingName;
  11207. switch (toneMapping) {
  11208. case LinearToneMapping:
  11209. toneMappingName = 'Linear';
  11210. break;
  11211. case ReinhardToneMapping:
  11212. toneMappingName = 'Reinhard';
  11213. break;
  11214. case Uncharted2ToneMapping:
  11215. toneMappingName = 'Uncharted2';
  11216. break;
  11217. case CineonToneMapping:
  11218. toneMappingName = 'OptimizedCineon';
  11219. break;
  11220. case ACESFilmicToneMapping:
  11221. toneMappingName = 'ACESFilmic';
  11222. break;
  11223. default:
  11224. throw new Error('unsupported toneMapping: ' + toneMapping);
  11225. }
  11226. return 'vec3 ' + functionName + '( vec3 color ) { return ' + toneMappingName + 'ToneMapping( color ); }';
  11227. }
  11228. function generateExtensions(extensions, parameters, rendererExtensions) {
  11229. extensions = extensions || {};
  11230. 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' : ''];
  11231. return chunks.filter(filterEmptyLine).join('\n');
  11232. }
  11233. function generateDefines(defines) {
  11234. var chunks = [];
  11235. for (var name in defines) {
  11236. var value = defines[name];
  11237. if (value === false) continue;
  11238. chunks.push('#define ' + name + ' ' + value);
  11239. }
  11240. return chunks.join('\n');
  11241. }
  11242. function fetchAttributeLocations(gl, program) {
  11243. var attributes = {};
  11244. var n = gl.getProgramParameter(program, 35721);
  11245. for (var i = 0; i < n; i++) {
  11246. var info = gl.getActiveAttrib(program, i);
  11247. var name = info.name; // console.log( 'THREE.WebGLProgram: ACTIVE VERTEX ATTRIBUTE:', name, i );
  11248. attributes[name] = gl.getAttribLocation(program, name);
  11249. }
  11250. return attributes;
  11251. }
  11252. function filterEmptyLine(string) {
  11253. return string !== '';
  11254. }
  11255. function replaceLightNums(string, parameters) {
  11256. 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);
  11257. }
  11258. function replaceClippingPlaneNums(string, parameters) {
  11259. return string.replace(/NUM_CLIPPING_PLANES/g, parameters.numClippingPlanes).replace(/UNION_CLIPPING_PLANES/g, parameters.numClippingPlanes - parameters.numClipIntersection);
  11260. } // Resolve Includes
  11261. var includePattern = /^[ \t]*#include +<([\w\d./]+)>/gm;
  11262. function resolveIncludes(string) {
  11263. return string.replace(includePattern, includeReplacer);
  11264. }
  11265. function includeReplacer(match, include) {
  11266. var string = ShaderChunk[include];
  11267. if (string === undefined) {
  11268. throw new Error('Can not resolve #include <' + include + '>');
  11269. }
  11270. return resolveIncludes(string);
  11271. } // Unroll Loops
  11272. var loopPattern = /#pragma unroll_loop[\s]+?for \( int i \= (\d+)\; i < (\d+)\; i \+\+ \) \{([\s\S]+?)(?=\})\}/g;
  11273. function unrollLoops(string) {
  11274. return string.replace(loopPattern, loopReplacer);
  11275. }
  11276. function loopReplacer(match, start, end, snippet) {
  11277. var string = '';
  11278. for (var i = parseInt(start); i < parseInt(end); i++) {
  11279. string += snippet.replace(/\[ i \]/g, '[ ' + i + ' ]').replace(/UNROLLED_LOOP_INDEX/g, i);
  11280. }
  11281. return string;
  11282. } //
  11283. function generatePrecision(parameters) {
  11284. var precisionstring = "precision " + parameters.precision + " float;\nprecision " + parameters.precision + " int;";
  11285. if (parameters.precision === "highp") {
  11286. precisionstring += "\n#define HIGH_PRECISION";
  11287. } else if (parameters.precision === "mediump") {
  11288. precisionstring += "\n#define MEDIUM_PRECISION";
  11289. } else if (parameters.precision === "lowp") {
  11290. precisionstring += "\n#define LOW_PRECISION";
  11291. }
  11292. return precisionstring;
  11293. }
  11294. function generateShadowMapTypeDefine(parameters) {
  11295. var shadowMapTypeDefine = 'SHADOWMAP_TYPE_BASIC';
  11296. if (parameters.shadowMapType === PCFShadowMap) {
  11297. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF';
  11298. } else if (parameters.shadowMapType === PCFSoftShadowMap) {
  11299. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF_SOFT';
  11300. } else if (parameters.shadowMapType === VSMShadowMap) {
  11301. shadowMapTypeDefine = 'SHADOWMAP_TYPE_VSM';
  11302. }
  11303. return shadowMapTypeDefine;
  11304. }
  11305. function generateEnvMapTypeDefine(parameters, material) {
  11306. var envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  11307. if (parameters.envMap) {
  11308. switch (material.envMap.mapping) {
  11309. case CubeReflectionMapping:
  11310. case CubeRefractionMapping:
  11311. envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  11312. break;
  11313. case CubeUVReflectionMapping:
  11314. case CubeUVRefractionMapping:
  11315. envMapTypeDefine = 'ENVMAP_TYPE_CUBE_UV';
  11316. break;
  11317. case EquirectangularReflectionMapping:
  11318. case EquirectangularRefractionMapping:
  11319. envMapTypeDefine = 'ENVMAP_TYPE_EQUIREC';
  11320. break;
  11321. case SphericalReflectionMapping:
  11322. envMapTypeDefine = 'ENVMAP_TYPE_SPHERE';
  11323. break;
  11324. }
  11325. }
  11326. return envMapTypeDefine;
  11327. }
  11328. function generateEnvMapModeDefine(parameters, material) {
  11329. var envMapModeDefine = 'ENVMAP_MODE_REFLECTION';
  11330. if (parameters.envMap) {
  11331. switch (material.envMap.mapping) {
  11332. case CubeRefractionMapping:
  11333. case EquirectangularRefractionMapping:
  11334. envMapModeDefine = 'ENVMAP_MODE_REFRACTION';
  11335. break;
  11336. }
  11337. }
  11338. return envMapModeDefine;
  11339. }
  11340. function generateEnvMapBlendingDefine(parameters, material) {
  11341. var envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  11342. if (parameters.envMap) {
  11343. switch (material.combine) {
  11344. case MultiplyOperation:
  11345. envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  11346. break;
  11347. case MixOperation:
  11348. envMapBlendingDefine = 'ENVMAP_BLENDING_MIX';
  11349. break;
  11350. case AddOperation:
  11351. envMapBlendingDefine = 'ENVMAP_BLENDING_ADD';
  11352. break;
  11353. }
  11354. }
  11355. return envMapBlendingDefine;
  11356. }
  11357. function WebGLProgram(renderer, extensions, code, material, shader, parameters) {
  11358. var gl = renderer.getContext();
  11359. var defines = material.defines;
  11360. var vertexShader = shader.vertexShader;
  11361. var fragmentShader = shader.fragmentShader;
  11362. var shadowMapTypeDefine = generateShadowMapTypeDefine(parameters);
  11363. var envMapTypeDefine = generateEnvMapTypeDefine(parameters, material);
  11364. var envMapModeDefine = generateEnvMapModeDefine(parameters, material);
  11365. var envMapBlendingDefine = generateEnvMapBlendingDefine(parameters, material);
  11366. var gammaFactorDefine = renderer.gammaFactor > 0 ? renderer.gammaFactor : 1.0;
  11367. var customExtensions = parameters.isWebGL2 ? '' : generateExtensions(material.extensions, parameters, extensions);
  11368. var customDefines = generateDefines(defines);
  11369. var program = gl.createProgram();
  11370. var prefixVertex, prefixFragment;
  11371. var renderTarget = renderer.getRenderTarget();
  11372. var numMultiviewViews = renderTarget && renderTarget.isWebGLMultiviewRenderTarget ? renderTarget.numViews : 0;
  11373. if (material.isRawShaderMaterial) {
  11374. prefixVertex = [customDefines].filter(filterEmptyLine).join('\n');
  11375. if (prefixVertex.length > 0) {
  11376. prefixVertex += '\n';
  11377. }
  11378. prefixFragment = [customExtensions, customDefines].filter(filterEmptyLine).join('\n');
  11379. if (prefixFragment.length > 0) {
  11380. prefixFragment += '\n';
  11381. }
  11382. } else {
  11383. 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');
  11384. prefixFragment = [customExtensions, generatePrecision(parameters), '#define SHADER_NAME ' + shader.name, customDefines, parameters.alphaTest ? '#define ALPHATEST ' + parameters.alphaTest + (parameters.alphaTest % 1 ? '' : '.0') : '', // add '.0' if integer
  11385. '#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
  11386. 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
  11387. 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');
  11388. }
  11389. vertexShader = resolveIncludes(vertexShader);
  11390. vertexShader = replaceLightNums(vertexShader, parameters);
  11391. vertexShader = replaceClippingPlaneNums(vertexShader, parameters);
  11392. fragmentShader = resolveIncludes(fragmentShader);
  11393. fragmentShader = replaceLightNums(fragmentShader, parameters);
  11394. fragmentShader = replaceClippingPlaneNums(fragmentShader, parameters);
  11395. vertexShader = unrollLoops(vertexShader);
  11396. fragmentShader = unrollLoops(fragmentShader);
  11397. if (parameters.isWebGL2 && !material.isRawShaderMaterial) {
  11398. var isGLSL3ShaderMaterial = false;
  11399. var versionRegex = /^\s*#version\s+300\s+es\s*\n/;
  11400. if (material.isShaderMaterial && vertexShader.match(versionRegex) !== null && fragmentShader.match(versionRegex) !== null) {
  11401. isGLSL3ShaderMaterial = true;
  11402. vertexShader = vertexShader.replace(versionRegex, '');
  11403. fragmentShader = fragmentShader.replace(versionRegex, '');
  11404. } // GLSL 3.0 conversion
  11405. prefixVertex = ['#version 300 es\n', '#define attribute in', '#define varying out', '#define texture2D texture'].join('\n') + '\n' + prefixVertex;
  11406. 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
  11407. if (numMultiviewViews > 0) {
  11408. 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'));
  11409. 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'));
  11410. prefixFragment = prefixFragment.replace('#version 300 es\n', ['#version 300 es\n', '#extension GL_OVR_multiview2 : require', '#define VIEW_ID gl_ViewID_OVR'].join('\n'));
  11411. prefixFragment = prefixFragment.replace('uniform mat4 viewMatrix;', ['uniform mat4 viewMatrices[' + numMultiviewViews + '];', '#define viewMatrix viewMatrices[VIEW_ID]'].join('\n'));
  11412. }
  11413. }
  11414. var vertexGlsl = prefixVertex + vertexShader;
  11415. var fragmentGlsl = prefixFragment + fragmentShader; // console.log( '*VERTEX*', vertexGlsl );
  11416. // console.log( '*FRAGMENT*', fragmentGlsl );
  11417. var glVertexShader = WebGLShader(gl, 35633, vertexGlsl);
  11418. var glFragmentShader = WebGLShader(gl, 35632, fragmentGlsl);
  11419. gl.attachShader(program, glVertexShader);
  11420. gl.attachShader(program, glFragmentShader); // Force a particular attribute to index 0.
  11421. if (material.index0AttributeName !== undefined) {
  11422. gl.bindAttribLocation(program, 0, material.index0AttributeName);
  11423. } else if (parameters.morphTargets === true) {
  11424. // programs with morphTargets displace position out of attribute 0
  11425. gl.bindAttribLocation(program, 0, 'position');
  11426. }
  11427. gl.linkProgram(program); // check for link errors
  11428. if (renderer.debug.checkShaderErrors) {
  11429. var programLog = gl.getProgramInfoLog(program).trim();
  11430. var vertexLog = gl.getShaderInfoLog(glVertexShader).trim();
  11431. var fragmentLog = gl.getShaderInfoLog(glFragmentShader).trim();
  11432. var runnable = true;
  11433. var haveDiagnostics = true;
  11434. if (gl.getProgramParameter(program, 35714) === false) {
  11435. runnable = false;
  11436. var vertexErrors = getShaderErrors(gl, glVertexShader, 'vertex');
  11437. var fragmentErrors = getShaderErrors(gl, glFragmentShader, 'fragment');
  11438. console.error('THREE.WebGLProgram: shader error: ', gl.getError(), '35715', gl.getProgramParameter(program, 35715), 'gl.getProgramInfoLog', programLog, vertexErrors, fragmentErrors);
  11439. } else if (programLog !== '') {
  11440. console.warn('THREE.WebGLProgram: gl.getProgramInfoLog()', programLog);
  11441. } else if (vertexLog === '' || fragmentLog === '') {
  11442. haveDiagnostics = false;
  11443. }
  11444. if (haveDiagnostics) {
  11445. this.diagnostics = {
  11446. runnable: runnable,
  11447. material: material,
  11448. programLog: programLog,
  11449. vertexShader: {
  11450. log: vertexLog,
  11451. prefix: prefixVertex
  11452. },
  11453. fragmentShader: {
  11454. log: fragmentLog,
  11455. prefix: prefixFragment
  11456. }
  11457. };
  11458. }
  11459. } // clean up
  11460. gl.deleteShader(glVertexShader);
  11461. gl.deleteShader(glFragmentShader); // set up caching for uniform locations
  11462. var cachedUniforms;
  11463. this.getUniforms = function () {
  11464. if (cachedUniforms === undefined) {
  11465. cachedUniforms = new WebGLUniforms(gl, program);
  11466. }
  11467. return cachedUniforms;
  11468. }; // set up caching for attribute locations
  11469. var cachedAttributes;
  11470. this.getAttributes = function () {
  11471. if (cachedAttributes === undefined) {
  11472. cachedAttributes = fetchAttributeLocations(gl, program);
  11473. }
  11474. return cachedAttributes;
  11475. }; // free resource
  11476. this.destroy = function () {
  11477. gl.deleteProgram(program);
  11478. this.program = undefined;
  11479. }; //
  11480. this.name = shader.name;
  11481. this.id = programIdCount++;
  11482. this.code = code;
  11483. this.usedTimes = 1;
  11484. this.program = program;
  11485. this.vertexShader = glVertexShader;
  11486. this.fragmentShader = glFragmentShader;
  11487. this.numMultiviewViews = numMultiviewViews;
  11488. return this;
  11489. }
  11490. /**
  11491. * @author mrdoob / http://mrdoob.com/
  11492. */
  11493. function WebGLPrograms(renderer, extensions, capabilities) {
  11494. var programs = [];
  11495. var shaderIDs = {
  11496. MeshDepthMaterial: 'depth',
  11497. MeshDistanceMaterial: 'distanceRGBA',
  11498. MeshNormalMaterial: 'normal',
  11499. MeshBasicMaterial: 'basic',
  11500. MeshLambertMaterial: 'lambert',
  11501. MeshPhongMaterial: 'phong',
  11502. MeshToonMaterial: 'phong',
  11503. MeshStandardMaterial: 'physical',
  11504. MeshPhysicalMaterial: 'physical',
  11505. MeshMatcapMaterial: 'matcap',
  11506. LineBasicMaterial: 'basic',
  11507. LineDashedMaterial: 'dashed',
  11508. PointsMaterial: 'points',
  11509. ShadowMaterial: 'shadow',
  11510. SpriteMaterial: 'sprite'
  11511. };
  11512. 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"];
  11513. function allocateBones(object) {
  11514. var skeleton = object.skeleton;
  11515. var bones = skeleton.bones;
  11516. if (capabilities.floatVertexTextures) {
  11517. return 1024;
  11518. } else {
  11519. // default for when object is not specified
  11520. // ( for example when prebuilding shader to be used with multiple objects )
  11521. //
  11522. // - leave some extra space for other uniforms
  11523. // - limit here is ANGLE's 254 max uniform vectors
  11524. // (up to 54 should be safe)
  11525. var nVertexUniforms = capabilities.maxVertexUniforms;
  11526. var nVertexMatrices = Math.floor((nVertexUniforms - 20) / 4);
  11527. var maxBones = Math.min(nVertexMatrices, bones.length);
  11528. if (maxBones < bones.length) {
  11529. console.warn('THREE.WebGLRenderer: Skeleton has ' + bones.length + ' bones. This GPU supports ' + maxBones + '.');
  11530. return 0;
  11531. }
  11532. return maxBones;
  11533. }
  11534. }
  11535. function getTextureEncodingFromMap(map, gammaOverrideLinear) {
  11536. var encoding;
  11537. if (!map) {
  11538. encoding = LinearEncoding;
  11539. } else if (map.isTexture) {
  11540. encoding = map.encoding;
  11541. } else if (map.isWebGLRenderTarget) {
  11542. console.warn("THREE.WebGLPrograms.getTextureEncodingFromMap: don't use render targets as textures. Use their .texture property instead.");
  11543. encoding = map.texture.encoding;
  11544. } // add backwards compatibility for WebGLRenderer.gammaInput/gammaOutput parameter, should probably be removed at some point.
  11545. if (encoding === LinearEncoding && gammaOverrideLinear) {
  11546. encoding = GammaEncoding;
  11547. }
  11548. return encoding;
  11549. }
  11550. this.getParameters = function (material, lights, shadows, fog, nClipPlanes, nClipIntersection, object) {
  11551. var shaderID = shaderIDs[material.type]; // heuristics to create shader parameters according to lights in the scene
  11552. // (not to blow over maxLights budget)
  11553. var maxBones = object.isSkinnedMesh ? allocateBones(object) : 0;
  11554. var precision = capabilities.precision;
  11555. if (material.precision !== null) {
  11556. precision = capabilities.getMaxPrecision(material.precision);
  11557. if (precision !== material.precision) {
  11558. console.warn('THREE.WebGLProgram.getParameters:', material.precision, 'not supported, using', precision, 'instead.');
  11559. }
  11560. }
  11561. var currentRenderTarget = renderer.getRenderTarget();
  11562. var parameters = {
  11563. isWebGL2: capabilities.isWebGL2,
  11564. shaderID: shaderID,
  11565. precision: precision,
  11566. instancing: object.isInstancedMesh === true,
  11567. supportsVertexTextures: capabilities.vertexTextures,
  11568. outputEncoding: getTextureEncodingFromMap(!currentRenderTarget ? null : currentRenderTarget.texture, renderer.gammaOutput),
  11569. map: !!material.map,
  11570. mapEncoding: getTextureEncodingFromMap(material.map, renderer.gammaInput),
  11571. matcap: !!material.matcap,
  11572. matcapEncoding: getTextureEncodingFromMap(material.matcap, renderer.gammaInput),
  11573. envMap: !!material.envMap,
  11574. envMapMode: material.envMap && material.envMap.mapping,
  11575. envMapEncoding: getTextureEncodingFromMap(material.envMap, renderer.gammaInput),
  11576. envMapCubeUV: !!material.envMap && (material.envMap.mapping === CubeUVReflectionMapping || material.envMap.mapping === CubeUVRefractionMapping),
  11577. lightMap: !!material.lightMap,
  11578. aoMap: !!material.aoMap,
  11579. emissiveMap: !!material.emissiveMap,
  11580. emissiveMapEncoding: getTextureEncodingFromMap(material.emissiveMap, renderer.gammaInput),
  11581. bumpMap: !!material.bumpMap,
  11582. normalMap: !!material.normalMap,
  11583. objectSpaceNormalMap: material.normalMapType === ObjectSpaceNormalMap,
  11584. tangentSpaceNormalMap: material.normalMapType === TangentSpaceNormalMap,
  11585. clearcoatNormalMap: !!material.clearcoatNormalMap,
  11586. displacementMap: !!material.displacementMap,
  11587. roughnessMap: !!material.roughnessMap,
  11588. metalnessMap: !!material.metalnessMap,
  11589. specularMap: !!material.specularMap,
  11590. alphaMap: !!material.alphaMap,
  11591. gradientMap: !!material.gradientMap,
  11592. sheen: !!material.sheen,
  11593. combine: material.combine,
  11594. vertexTangents: material.normalMap && material.vertexTangents,
  11595. vertexColors: material.vertexColors,
  11596. vertexUvs: !!material.map || !!material.bumpMap || !!material.normalMap || !!material.specularMap || !!material.alphaMap || !!material.emissiveMap || !!material.roughnessMap || !!material.metalnessMap || !!material.clearcoatNormalMap,
  11597. fog: !!fog,
  11598. useFog: material.fog,
  11599. fogExp2: fog && fog.isFogExp2,
  11600. flatShading: material.flatShading,
  11601. sizeAttenuation: material.sizeAttenuation,
  11602. logarithmicDepthBuffer: capabilities.logarithmicDepthBuffer,
  11603. skinning: material.skinning && maxBones > 0,
  11604. maxBones: maxBones,
  11605. useVertexTexture: capabilities.floatVertexTextures,
  11606. morphTargets: material.morphTargets,
  11607. morphNormals: material.morphNormals,
  11608. maxMorphTargets: renderer.maxMorphTargets,
  11609. maxMorphNormals: renderer.maxMorphNormals,
  11610. numDirLights: lights.directional.length,
  11611. numPointLights: lights.point.length,
  11612. numSpotLights: lights.spot.length,
  11613. numRectAreaLights: lights.rectArea.length,
  11614. numHemiLights: lights.hemi.length,
  11615. numDirLightShadows: lights.directionalShadowMap.length,
  11616. numPointLightShadows: lights.pointShadowMap.length,
  11617. numSpotLightShadows: lights.spotShadowMap.length,
  11618. numClippingPlanes: nClipPlanes,
  11619. numClipIntersection: nClipIntersection,
  11620. dithering: material.dithering,
  11621. shadowMapEnabled: renderer.shadowMap.enabled && shadows.length > 0,
  11622. shadowMapType: renderer.shadowMap.type,
  11623. toneMapping: material.toneMapped ? renderer.toneMapping : NoToneMapping,
  11624. physicallyCorrectLights: renderer.physicallyCorrectLights,
  11625. premultipliedAlpha: material.premultipliedAlpha,
  11626. alphaTest: material.alphaTest,
  11627. doubleSided: material.side === DoubleSide,
  11628. flipSided: material.side === BackSide,
  11629. depthPacking: material.depthPacking !== undefined ? material.depthPacking : false
  11630. };
  11631. return parameters;
  11632. };
  11633. this.getProgramCode = function (material, parameters) {
  11634. var array = [];
  11635. if (parameters.shaderID) {
  11636. array.push(parameters.shaderID);
  11637. } else {
  11638. array.push(material.fragmentShader);
  11639. array.push(material.vertexShader);
  11640. }
  11641. if (material.defines !== undefined) {
  11642. for (var name in material.defines) {
  11643. array.push(name);
  11644. array.push(material.defines[name]);
  11645. }
  11646. }
  11647. for (var i = 0; i < parameterNames.length; i++) {
  11648. array.push(parameters[parameterNames[i]]);
  11649. }
  11650. array.push(material.onBeforeCompile.toString());
  11651. array.push(renderer.gammaOutput);
  11652. array.push(renderer.gammaFactor);
  11653. return array.join();
  11654. };
  11655. this.acquireProgram = function (material, shader, parameters, code) {
  11656. var program; // Check if code has been already compiled
  11657. for (var p = 0, pl = programs.length; p < pl; p++) {
  11658. var programInfo = programs[p];
  11659. if (programInfo.code === code) {
  11660. program = programInfo;
  11661. ++program.usedTimes;
  11662. break;
  11663. }
  11664. }
  11665. if (program === undefined) {
  11666. program = new WebGLProgram(renderer, extensions, code, material, shader, parameters);
  11667. programs.push(program);
  11668. }
  11669. return program;
  11670. };
  11671. this.releaseProgram = function (program) {
  11672. if (--program.usedTimes === 0) {
  11673. // Remove from unordered set
  11674. var i = programs.indexOf(program);
  11675. programs[i] = programs[programs.length - 1];
  11676. programs.pop(); // Free WebGL resources
  11677. program.destroy();
  11678. }
  11679. }; // Exposed for resource monitoring & error feedback via renderer.info:
  11680. this.programs = programs;
  11681. }
  11682. /**
  11683. * @author fordacious / fordacious.github.io
  11684. */
  11685. function WebGLProperties() {
  11686. var properties = new WeakMap();
  11687. function get(object) {
  11688. var map = properties.get(object);
  11689. if (map === undefined) {
  11690. map = {};
  11691. properties.set(object, map);
  11692. }
  11693. return map;
  11694. }
  11695. function remove(object) {
  11696. properties.delete(object);
  11697. }
  11698. function update(object, key, value) {
  11699. properties.get(object)[key] = value;
  11700. }
  11701. function dispose() {
  11702. properties = new WeakMap();
  11703. }
  11704. return {
  11705. get: get,
  11706. remove: remove,
  11707. update: update,
  11708. dispose: dispose
  11709. };
  11710. }
  11711. /**
  11712. * @author mrdoob / http://mrdoob.com/
  11713. */
  11714. function painterSortStable(a, b) {
  11715. if (a.groupOrder !== b.groupOrder) {
  11716. return a.groupOrder - b.groupOrder;
  11717. } else if (a.renderOrder !== b.renderOrder) {
  11718. return a.renderOrder - b.renderOrder;
  11719. } else if (a.program !== b.program) {
  11720. return a.program.id - b.program.id;
  11721. } else if (a.material.id !== b.material.id) {
  11722. return a.material.id - b.material.id;
  11723. } else if (a.z !== b.z) {
  11724. return a.z - b.z;
  11725. } else {
  11726. return a.id - b.id;
  11727. }
  11728. }
  11729. function reversePainterSortStable(a, b) {
  11730. if (a.groupOrder !== b.groupOrder) {
  11731. return a.groupOrder - b.groupOrder;
  11732. } else if (a.renderOrder !== b.renderOrder) {
  11733. return a.renderOrder - b.renderOrder;
  11734. } else if (a.z !== b.z) {
  11735. return b.z - a.z;
  11736. } else {
  11737. return a.id - b.id;
  11738. }
  11739. }
  11740. function WebGLRenderList() {
  11741. var renderItems = [];
  11742. var renderItemsIndex = 0;
  11743. var opaque = [];
  11744. var transparent = [];
  11745. var defaultProgram = {
  11746. id: -1
  11747. };
  11748. function init() {
  11749. renderItemsIndex = 0;
  11750. opaque.length = 0;
  11751. transparent.length = 0;
  11752. }
  11753. function getNextRenderItem(object, geometry, material, groupOrder, z, group) {
  11754. var renderItem = renderItems[renderItemsIndex];
  11755. if (renderItem === undefined) {
  11756. renderItem = {
  11757. id: object.id,
  11758. object: object,
  11759. geometry: geometry,
  11760. material: material,
  11761. program: material.program || defaultProgram,
  11762. groupOrder: groupOrder,
  11763. renderOrder: object.renderOrder,
  11764. z: z,
  11765. group: group
  11766. };
  11767. renderItems[renderItemsIndex] = renderItem;
  11768. } else {
  11769. renderItem.id = object.id;
  11770. renderItem.object = object;
  11771. renderItem.geometry = geometry;
  11772. renderItem.material = material;
  11773. renderItem.program = material.program || defaultProgram;
  11774. renderItem.groupOrder = groupOrder;
  11775. renderItem.renderOrder = object.renderOrder;
  11776. renderItem.z = z;
  11777. renderItem.group = group;
  11778. }
  11779. renderItemsIndex++;
  11780. return renderItem;
  11781. }
  11782. function push(object, geometry, material, groupOrder, z, group) {
  11783. var renderItem = getNextRenderItem(object, geometry, material, groupOrder, z, group);
  11784. (material.transparent === true ? transparent : opaque).push(renderItem);
  11785. }
  11786. function unshift(object, geometry, material, groupOrder, z, group) {
  11787. var renderItem = getNextRenderItem(object, geometry, material, groupOrder, z, group);
  11788. (material.transparent === true ? transparent : opaque).unshift(renderItem);
  11789. }
  11790. function sort() {
  11791. if (opaque.length > 1) opaque.sort(painterSortStable);
  11792. if (transparent.length > 1) transparent.sort(reversePainterSortStable);
  11793. }
  11794. return {
  11795. opaque: opaque,
  11796. transparent: transparent,
  11797. init: init,
  11798. push: push,
  11799. unshift: unshift,
  11800. sort: sort
  11801. };
  11802. }
  11803. function WebGLRenderLists() {
  11804. var lists = new WeakMap();
  11805. function onSceneDispose(event) {
  11806. var scene = event.target;
  11807. scene.removeEventListener('dispose', onSceneDispose);
  11808. lists.delete(scene);
  11809. }
  11810. function get(scene, camera) {
  11811. var cameras = lists.get(scene);
  11812. var list;
  11813. if (cameras === undefined) {
  11814. list = new WebGLRenderList();
  11815. lists.set(scene, new WeakMap());
  11816. lists.get(scene).set(camera, list);
  11817. scene.addEventListener('dispose', onSceneDispose);
  11818. } else {
  11819. list = cameras.get(camera);
  11820. if (list === undefined) {
  11821. list = new WebGLRenderList();
  11822. cameras.set(camera, list);
  11823. }
  11824. }
  11825. return list;
  11826. }
  11827. function dispose() {
  11828. lists = new WeakMap();
  11829. }
  11830. return {
  11831. get: get,
  11832. dispose: dispose
  11833. };
  11834. }
  11835. /**
  11836. * @author mrdoob / http://mrdoob.com/
  11837. */
  11838. function UniformsCache() {
  11839. var lights = {};
  11840. return {
  11841. get: function (light) {
  11842. if (lights[light.id] !== undefined) {
  11843. return lights[light.id];
  11844. }
  11845. var uniforms;
  11846. switch (light.type) {
  11847. case 'DirectionalLight':
  11848. uniforms = {
  11849. direction: new Vector3(),
  11850. color: new Color(),
  11851. shadow: false,
  11852. shadowBias: 0,
  11853. shadowRadius: 1,
  11854. shadowMapSize: new Vector2()
  11855. };
  11856. break;
  11857. case 'SpotLight':
  11858. uniforms = {
  11859. position: new Vector3(),
  11860. direction: new Vector3(),
  11861. color: new Color(),
  11862. distance: 0,
  11863. coneCos: 0,
  11864. penumbraCos: 0,
  11865. decay: 0,
  11866. shadow: false,
  11867. shadowBias: 0,
  11868. shadowRadius: 1,
  11869. shadowMapSize: new Vector2()
  11870. };
  11871. break;
  11872. case 'PointLight':
  11873. uniforms = {
  11874. position: new Vector3(),
  11875. color: new Color(),
  11876. distance: 0,
  11877. decay: 0,
  11878. shadow: false,
  11879. shadowBias: 0,
  11880. shadowRadius: 1,
  11881. shadowMapSize: new Vector2(),
  11882. shadowCameraNear: 1,
  11883. shadowCameraFar: 1000
  11884. };
  11885. break;
  11886. case 'HemisphereLight':
  11887. uniforms = {
  11888. direction: new Vector3(),
  11889. skyColor: new Color(),
  11890. groundColor: new Color()
  11891. };
  11892. break;
  11893. case 'RectAreaLight':
  11894. uniforms = {
  11895. color: new Color(),
  11896. position: new Vector3(),
  11897. halfWidth: new Vector3(),
  11898. halfHeight: new Vector3() // TODO (abelnation): set RectAreaLight shadow uniforms
  11899. };
  11900. break;
  11901. }
  11902. lights[light.id] = uniforms;
  11903. return uniforms;
  11904. }
  11905. };
  11906. }
  11907. var nextVersion = 0;
  11908. function shadowCastingLightsFirst(lightA, lightB) {
  11909. return (lightB.castShadow ? 1 : 0) - (lightA.castShadow ? 1 : 0);
  11910. }
  11911. function WebGLLights() {
  11912. var cache = new UniformsCache();
  11913. var state = {
  11914. version: 0,
  11915. hash: {
  11916. directionalLength: -1,
  11917. pointLength: -1,
  11918. spotLength: -1,
  11919. rectAreaLength: -1,
  11920. hemiLength: -1,
  11921. numDirectionalShadows: -1,
  11922. numPointShadows: -1,
  11923. numSpotShadows: -1
  11924. },
  11925. ambient: [0, 0, 0],
  11926. probe: [],
  11927. directional: [],
  11928. directionalShadowMap: [],
  11929. directionalShadowMatrix: [],
  11930. spot: [],
  11931. spotShadowMap: [],
  11932. spotShadowMatrix: [],
  11933. rectArea: [],
  11934. point: [],
  11935. pointShadowMap: [],
  11936. pointShadowMatrix: [],
  11937. hemi: [],
  11938. numDirectionalShadows: -1,
  11939. numPointShadows: -1,
  11940. numSpotShadows: -1
  11941. };
  11942. for (var i = 0; i < 9; i++) state.probe.push(new Vector3());
  11943. var vector3 = new Vector3();
  11944. var matrix4 = new Matrix4();
  11945. var matrix42 = new Matrix4();
  11946. function setup(lights, shadows, camera) {
  11947. var r = 0,
  11948. g = 0,
  11949. b = 0;
  11950. for (var i = 0; i < 9; i++) state.probe[i].set(0, 0, 0);
  11951. var directionalLength = 0;
  11952. var pointLength = 0;
  11953. var spotLength = 0;
  11954. var rectAreaLength = 0;
  11955. var hemiLength = 0;
  11956. var numDirectionalShadows = 0;
  11957. var numPointShadows = 0;
  11958. var numSpotShadows = 0;
  11959. var viewMatrix = camera.matrixWorldInverse;
  11960. lights.sort(shadowCastingLightsFirst);
  11961. for (var i = 0, l = lights.length; i < l; i++) {
  11962. var light = lights[i];
  11963. var color = light.color;
  11964. var intensity = light.intensity;
  11965. var distance = light.distance;
  11966. var shadowMap = light.shadow && light.shadow.map ? light.shadow.map.texture : null;
  11967. if (light.isAmbientLight) {
  11968. r += color.r * intensity;
  11969. g += color.g * intensity;
  11970. b += color.b * intensity;
  11971. } else if (light.isLightProbe) {
  11972. for (var j = 0; j < 9; j++) {
  11973. state.probe[j].addScaledVector(light.sh.coefficients[j], intensity);
  11974. }
  11975. } else if (light.isDirectionalLight) {
  11976. var uniforms = cache.get(light);
  11977. uniforms.color.copy(light.color).multiplyScalar(light.intensity);
  11978. uniforms.direction.setFromMatrixPosition(light.matrixWorld);
  11979. vector3.setFromMatrixPosition(light.target.matrixWorld);
  11980. uniforms.direction.sub(vector3);
  11981. uniforms.direction.transformDirection(viewMatrix);
  11982. uniforms.shadow = light.castShadow;
  11983. if (light.castShadow) {
  11984. var shadow = light.shadow;
  11985. uniforms.shadowBias = shadow.bias;
  11986. uniforms.shadowRadius = shadow.radius;
  11987. uniforms.shadowMapSize = shadow.mapSize;
  11988. state.directionalShadowMap[directionalLength] = shadowMap;
  11989. state.directionalShadowMatrix[directionalLength] = light.shadow.matrix;
  11990. numDirectionalShadows++;
  11991. }
  11992. state.directional[directionalLength] = uniforms;
  11993. directionalLength++;
  11994. } else if (light.isSpotLight) {
  11995. var uniforms = cache.get(light);
  11996. uniforms.position.setFromMatrixPosition(light.matrixWorld);
  11997. uniforms.position.applyMatrix4(viewMatrix);
  11998. uniforms.color.copy(color).multiplyScalar(intensity);
  11999. uniforms.distance = distance;
  12000. uniforms.direction.setFromMatrixPosition(light.matrixWorld);
  12001. vector3.setFromMatrixPosition(light.target.matrixWorld);
  12002. uniforms.direction.sub(vector3);
  12003. uniforms.direction.transformDirection(viewMatrix);
  12004. uniforms.coneCos = Math.cos(light.angle);
  12005. uniforms.penumbraCos = Math.cos(light.angle * (1 - light.penumbra));
  12006. uniforms.decay = light.decay;
  12007. uniforms.shadow = light.castShadow;
  12008. if (light.castShadow) {
  12009. var shadow = light.shadow;
  12010. uniforms.shadowBias = shadow.bias;
  12011. uniforms.shadowRadius = shadow.radius;
  12012. uniforms.shadowMapSize = shadow.mapSize;
  12013. state.spotShadowMap[spotLength] = shadowMap;
  12014. state.spotShadowMatrix[spotLength] = light.shadow.matrix;
  12015. numSpotShadows++;
  12016. }
  12017. state.spot[spotLength] = uniforms;
  12018. spotLength++;
  12019. } else if (light.isRectAreaLight) {
  12020. var uniforms = cache.get(light); // (a) intensity is the total visible light emitted
  12021. //uniforms.color.copy( color ).multiplyScalar( intensity / ( light.width * light.height * Math.PI ) );
  12022. // (b) intensity is the brightness of the light
  12023. uniforms.color.copy(color).multiplyScalar(intensity);
  12024. uniforms.position.setFromMatrixPosition(light.matrixWorld);
  12025. uniforms.position.applyMatrix4(viewMatrix); // extract local rotation of light to derive width/height half vectors
  12026. matrix42.identity();
  12027. matrix4.copy(light.matrixWorld);
  12028. matrix4.premultiply(viewMatrix);
  12029. matrix42.extractRotation(matrix4);
  12030. uniforms.halfWidth.set(light.width * 0.5, 0.0, 0.0);
  12031. uniforms.halfHeight.set(0.0, light.height * 0.5, 0.0);
  12032. uniforms.halfWidth.applyMatrix4(matrix42);
  12033. uniforms.halfHeight.applyMatrix4(matrix42); // TODO (abelnation): RectAreaLight distance?
  12034. // uniforms.distance = distance;
  12035. state.rectArea[rectAreaLength] = uniforms;
  12036. rectAreaLength++;
  12037. } else if (light.isPointLight) {
  12038. var uniforms = cache.get(light);
  12039. uniforms.position.setFromMatrixPosition(light.matrixWorld);
  12040. uniforms.position.applyMatrix4(viewMatrix);
  12041. uniforms.color.copy(light.color).multiplyScalar(light.intensity);
  12042. uniforms.distance = light.distance;
  12043. uniforms.decay = light.decay;
  12044. uniforms.shadow = light.castShadow;
  12045. if (light.castShadow) {
  12046. var shadow = light.shadow;
  12047. uniforms.shadowBias = shadow.bias;
  12048. uniforms.shadowRadius = shadow.radius;
  12049. uniforms.shadowMapSize = shadow.mapSize;
  12050. uniforms.shadowCameraNear = shadow.camera.near;
  12051. uniforms.shadowCameraFar = shadow.camera.far;
  12052. state.pointShadowMap[pointLength] = shadowMap;
  12053. state.pointShadowMatrix[pointLength] = light.shadow.matrix;
  12054. numPointShadows++;
  12055. }
  12056. state.point[pointLength] = uniforms;
  12057. pointLength++;
  12058. } else if (light.isHemisphereLight) {
  12059. var uniforms = cache.get(light);
  12060. uniforms.direction.setFromMatrixPosition(light.matrixWorld);
  12061. uniforms.direction.transformDirection(viewMatrix);
  12062. uniforms.direction.normalize();
  12063. uniforms.skyColor.copy(light.color).multiplyScalar(intensity);
  12064. uniforms.groundColor.copy(light.groundColor).multiplyScalar(intensity);
  12065. state.hemi[hemiLength] = uniforms;
  12066. hemiLength++;
  12067. }
  12068. }
  12069. state.ambient[0] = r;
  12070. state.ambient[1] = g;
  12071. state.ambient[2] = b;
  12072. var hash = state.hash;
  12073. 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) {
  12074. state.directional.length = directionalLength;
  12075. state.spot.length = spotLength;
  12076. state.rectArea.length = rectAreaLength;
  12077. state.point.length = pointLength;
  12078. state.hemi.length = hemiLength;
  12079. state.directionalShadowMap.length = numDirectionalShadows;
  12080. state.pointShadowMap.length = numPointShadows;
  12081. state.spotShadowMap.length = numSpotShadows;
  12082. state.directionalShadowMatrix.length = numDirectionalShadows;
  12083. state.pointShadowMatrix.length = numPointShadows;
  12084. state.spotShadowMatrix.length = numSpotShadows;
  12085. hash.directionalLength = directionalLength;
  12086. hash.pointLength = pointLength;
  12087. hash.spotLength = spotLength;
  12088. hash.rectAreaLength = rectAreaLength;
  12089. hash.hemiLength = hemiLength;
  12090. hash.numDirectionalShadows = numDirectionalShadows;
  12091. hash.numPointShadows = numPointShadows;
  12092. hash.numSpotShadows = numSpotShadows;
  12093. state.version = nextVersion++;
  12094. }
  12095. }
  12096. return {
  12097. setup: setup,
  12098. state: state
  12099. };
  12100. }
  12101. /**
  12102. * @author Mugen87 / https://github.com/Mugen87
  12103. */
  12104. function WebGLRenderState() {
  12105. var lights = new WebGLLights();
  12106. var lightsArray = [];
  12107. var shadowsArray = [];
  12108. function init() {
  12109. lightsArray.length = 0;
  12110. shadowsArray.length = 0;
  12111. }
  12112. function pushLight(light) {
  12113. lightsArray.push(light);
  12114. }
  12115. function pushShadow(shadowLight) {
  12116. shadowsArray.push(shadowLight);
  12117. }
  12118. function setupLights(camera) {
  12119. lights.setup(lightsArray, shadowsArray, camera);
  12120. }
  12121. var state = {
  12122. lightsArray: lightsArray,
  12123. shadowsArray: shadowsArray,
  12124. lights: lights
  12125. };
  12126. return {
  12127. init: init,
  12128. state: state,
  12129. setupLights: setupLights,
  12130. pushLight: pushLight,
  12131. pushShadow: pushShadow
  12132. };
  12133. }
  12134. function WebGLRenderStates() {
  12135. var renderStates = new WeakMap();
  12136. function onSceneDispose(event) {
  12137. var scene = event.target;
  12138. scene.removeEventListener('dispose', onSceneDispose);
  12139. renderStates.delete(scene);
  12140. }
  12141. function get(scene, camera) {
  12142. var renderState;
  12143. if (renderStates.has(scene) === false) {
  12144. renderState = new WebGLRenderState();
  12145. renderStates.set(scene, new WeakMap());
  12146. renderStates.get(scene).set(camera, renderState);
  12147. scene.addEventListener('dispose', onSceneDispose);
  12148. } else {
  12149. if (renderStates.get(scene).has(camera) === false) {
  12150. renderState = new WebGLRenderState();
  12151. renderStates.get(scene).set(camera, renderState);
  12152. } else {
  12153. renderState = renderStates.get(scene).get(camera);
  12154. }
  12155. }
  12156. return renderState;
  12157. }
  12158. function dispose() {
  12159. renderStates = new WeakMap();
  12160. }
  12161. return {
  12162. get: get,
  12163. dispose: dispose
  12164. };
  12165. }
  12166. /**
  12167. * @author mrdoob / http://mrdoob.com/
  12168. * @author alteredq / http://alteredqualia.com/
  12169. * @author bhouston / https://clara.io
  12170. * @author WestLangley / http://github.com/WestLangley
  12171. *
  12172. * parameters = {
  12173. *
  12174. * opacity: <float>,
  12175. *
  12176. * map: new THREE.Texture( <Image> ),
  12177. *
  12178. * alphaMap: new THREE.Texture( <Image> ),
  12179. *
  12180. * displacementMap: new THREE.Texture( <Image> ),
  12181. * displacementScale: <float>,
  12182. * displacementBias: <float>,
  12183. *
  12184. * wireframe: <boolean>,
  12185. * wireframeLinewidth: <float>
  12186. * }
  12187. */
  12188. function MeshDepthMaterial(parameters) {
  12189. Material.call(this);
  12190. this.type = 'MeshDepthMaterial';
  12191. this.depthPacking = BasicDepthPacking;
  12192. this.skinning = false;
  12193. this.morphTargets = false;
  12194. this.map = null;
  12195. this.alphaMap = null;
  12196. this.displacementMap = null;
  12197. this.displacementScale = 1;
  12198. this.displacementBias = 0;
  12199. this.wireframe = false;
  12200. this.wireframeLinewidth = 1;
  12201. this.fog = false;
  12202. this.setValues(parameters);
  12203. }
  12204. MeshDepthMaterial.prototype = Object.create(Material.prototype);
  12205. MeshDepthMaterial.prototype.constructor = MeshDepthMaterial;
  12206. MeshDepthMaterial.prototype.isMeshDepthMaterial = true;
  12207. MeshDepthMaterial.prototype.copy = function (source) {
  12208. Material.prototype.copy.call(this, source);
  12209. this.depthPacking = source.depthPacking;
  12210. this.skinning = source.skinning;
  12211. this.morphTargets = source.morphTargets;
  12212. this.map = source.map;
  12213. this.alphaMap = source.alphaMap;
  12214. this.displacementMap = source.displacementMap;
  12215. this.displacementScale = source.displacementScale;
  12216. this.displacementBias = source.displacementBias;
  12217. this.wireframe = source.wireframe;
  12218. this.wireframeLinewidth = source.wireframeLinewidth;
  12219. return this;
  12220. };
  12221. /**
  12222. * @author WestLangley / http://github.com/WestLangley
  12223. *
  12224. * parameters = {
  12225. *
  12226. * referencePosition: <float>,
  12227. * nearDistance: <float>,
  12228. * farDistance: <float>,
  12229. *
  12230. * skinning: <bool>,
  12231. * morphTargets: <bool>,
  12232. *
  12233. * map: new THREE.Texture( <Image> ),
  12234. *
  12235. * alphaMap: new THREE.Texture( <Image> ),
  12236. *
  12237. * displacementMap: new THREE.Texture( <Image> ),
  12238. * displacementScale: <float>,
  12239. * displacementBias: <float>
  12240. *
  12241. * }
  12242. */
  12243. function MeshDistanceMaterial(parameters) {
  12244. Material.call(this);
  12245. this.type = 'MeshDistanceMaterial';
  12246. this.referencePosition = new Vector3();
  12247. this.nearDistance = 1;
  12248. this.farDistance = 1000;
  12249. this.skinning = false;
  12250. this.morphTargets = false;
  12251. this.map = null;
  12252. this.alphaMap = null;
  12253. this.displacementMap = null;
  12254. this.displacementScale = 1;
  12255. this.displacementBias = 0;
  12256. this.fog = false;
  12257. this.setValues(parameters);
  12258. }
  12259. MeshDistanceMaterial.prototype = Object.create(Material.prototype);
  12260. MeshDistanceMaterial.prototype.constructor = MeshDistanceMaterial;
  12261. MeshDistanceMaterial.prototype.isMeshDistanceMaterial = true;
  12262. MeshDistanceMaterial.prototype.copy = function (source) {
  12263. Material.prototype.copy.call(this, source);
  12264. this.referencePosition.copy(source.referencePosition);
  12265. this.nearDistance = source.nearDistance;
  12266. this.farDistance = source.farDistance;
  12267. this.skinning = source.skinning;
  12268. this.morphTargets = source.morphTargets;
  12269. this.map = source.map;
  12270. this.alphaMap = source.alphaMap;
  12271. this.displacementMap = source.displacementMap;
  12272. this.displacementScale = source.displacementScale;
  12273. this.displacementBias = source.displacementBias;
  12274. return this;
  12275. };
  12276. 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}";
  12277. var vsm_vert = "void main() {\n\tgl_Position = vec4( position, 1.0 );\n}";
  12278. /**
  12279. * @author alteredq / http://alteredqualia.com/
  12280. * @author mrdoob / http://mrdoob.com/
  12281. */
  12282. function WebGLShadowMap(_renderer, _objects, maxTextureSize) {
  12283. var _frustum = new Frustum(),
  12284. _shadowMapSize = new Vector2(),
  12285. _viewportSize = new Vector2(),
  12286. _viewport = new Vector4(),
  12287. _MorphingFlag = 1,
  12288. _SkinningFlag = 2,
  12289. _NumberOfMaterialVariants = (_MorphingFlag | _SkinningFlag) + 1,
  12290. _depthMaterials = new Array(_NumberOfMaterialVariants),
  12291. _distanceMaterials = new Array(_NumberOfMaterialVariants),
  12292. _materialCache = {};
  12293. var shadowSide = {
  12294. 0: BackSide,
  12295. 1: FrontSide,
  12296. 2: DoubleSide
  12297. };
  12298. var shadowMaterialVertical = new ShaderMaterial({
  12299. defines: {
  12300. SAMPLE_RATE: 2.0 / 8.0,
  12301. HALF_SAMPLE_RATE: 1.0 / 8.0
  12302. },
  12303. uniforms: {
  12304. shadow_pass: {
  12305. value: null
  12306. },
  12307. resolution: {
  12308. value: new Vector2()
  12309. },
  12310. radius: {
  12311. value: 4.0
  12312. }
  12313. },
  12314. vertexShader: vsm_vert,
  12315. fragmentShader: vsm_frag
  12316. });
  12317. var shadowMaterialHorizonal = shadowMaterialVertical.clone();
  12318. shadowMaterialHorizonal.defines.HORIZONAL_PASS = 1;
  12319. var fullScreenTri = new BufferGeometry();
  12320. fullScreenTri.addAttribute("position", new BufferAttribute(new Float32Array([-1, -1, 0.5, 3, -1, 0.5, -1, 3, 0.5]), 3));
  12321. var fullScreenMesh = new Mesh(fullScreenTri, shadowMaterialVertical); // init
  12322. for (var i = 0; i !== _NumberOfMaterialVariants; ++i) {
  12323. var useMorphing = (i & _MorphingFlag) !== 0;
  12324. var useSkinning = (i & _SkinningFlag) !== 0;
  12325. var depthMaterial = new MeshDepthMaterial({
  12326. depthPacking: RGBADepthPacking,
  12327. morphTargets: useMorphing,
  12328. skinning: useSkinning
  12329. });
  12330. _depthMaterials[i] = depthMaterial;
  12331. var distanceMaterial = new MeshDistanceMaterial({
  12332. morphTargets: useMorphing,
  12333. skinning: useSkinning
  12334. });
  12335. _distanceMaterials[i] = distanceMaterial;
  12336. }
  12337. var scope = this;
  12338. this.enabled = false;
  12339. this.autoUpdate = true;
  12340. this.needsUpdate = false;
  12341. this.type = PCFShadowMap;
  12342. this.render = function (lights, scene, camera) {
  12343. if (scope.enabled === false) return;
  12344. if (scope.autoUpdate === false && scope.needsUpdate === false) return;
  12345. if (lights.length === 0) return;
  12346. var currentRenderTarget = _renderer.getRenderTarget();
  12347. var activeCubeFace = _renderer.getActiveCubeFace();
  12348. var activeMipmapLevel = _renderer.getActiveMipmapLevel();
  12349. var _state = _renderer.state; // Set GL state for depth map.
  12350. _state.setBlending(NoBlending);
  12351. _state.buffers.color.setClear(1, 1, 1, 1);
  12352. _state.buffers.depth.setTest(true);
  12353. _state.setScissorTest(false); // render depth map
  12354. for (var i = 0, il = lights.length; i < il; i++) {
  12355. var light = lights[i];
  12356. var shadow = light.shadow;
  12357. if (shadow === undefined) {
  12358. console.warn('THREE.WebGLShadowMap:', light, 'has no shadow.');
  12359. continue;
  12360. }
  12361. _shadowMapSize.copy(shadow.mapSize);
  12362. var shadowFrameExtents = shadow.getFrameExtents();
  12363. _shadowMapSize.multiply(shadowFrameExtents);
  12364. _viewportSize.copy(shadow.mapSize);
  12365. if (_shadowMapSize.x > maxTextureSize || _shadowMapSize.y > maxTextureSize) {
  12366. console.warn('THREE.WebGLShadowMap:', light, 'has shadow exceeding max texture size, reducing');
  12367. if (_shadowMapSize.x > maxTextureSize) {
  12368. _viewportSize.x = Math.floor(maxTextureSize / shadowFrameExtents.x);
  12369. _shadowMapSize.x = _viewportSize.x * shadowFrameExtents.x;
  12370. shadow.mapSize.x = _viewportSize.x;
  12371. }
  12372. if (_shadowMapSize.y > maxTextureSize) {
  12373. _viewportSize.y = Math.floor(maxTextureSize / shadowFrameExtents.y);
  12374. _shadowMapSize.y = _viewportSize.y * shadowFrameExtents.y;
  12375. shadow.mapSize.y = _viewportSize.y;
  12376. }
  12377. }
  12378. if (shadow.map === null && !shadow.isPointLightShadow && this.type === VSMShadowMap) {
  12379. var pars = {
  12380. minFilter: LinearFilter,
  12381. magFilter: LinearFilter,
  12382. format: RGBAFormat
  12383. };
  12384. shadow.map = new WebGLRenderTarget(_shadowMapSize.x, _shadowMapSize.y, pars);
  12385. shadow.map.texture.name = light.name + ".shadowMap";
  12386. shadow.mapPass = new WebGLRenderTarget(_shadowMapSize.x, _shadowMapSize.y, pars);
  12387. shadow.camera.updateProjectionMatrix();
  12388. }
  12389. if (shadow.map === null) {
  12390. var pars = {
  12391. minFilter: NearestFilter,
  12392. magFilter: NearestFilter,
  12393. format: RGBAFormat
  12394. };
  12395. shadow.map = new WebGLRenderTarget(_shadowMapSize.x, _shadowMapSize.y, pars);
  12396. shadow.map.texture.name = light.name + ".shadowMap";
  12397. shadow.camera.updateProjectionMatrix();
  12398. }
  12399. _renderer.setRenderTarget(shadow.map);
  12400. _renderer.clear();
  12401. var viewportCount = shadow.getViewportCount();
  12402. for (var vp = 0; vp < viewportCount; vp++) {
  12403. var viewport = shadow.getViewport(vp);
  12404. _viewport.set(_viewportSize.x * viewport.x, _viewportSize.y * viewport.y, _viewportSize.x * viewport.z, _viewportSize.y * viewport.w);
  12405. _state.viewport(_viewport);
  12406. shadow.updateMatrices(light, camera, vp);
  12407. _frustum = shadow.getFrustum();
  12408. renderObject(scene, camera, shadow.camera, light, this.type);
  12409. } // do blur pass for VSM
  12410. if (!shadow.isPointLightShadow && this.type === VSMShadowMap) {
  12411. VSMPass(shadow, camera);
  12412. }
  12413. }
  12414. scope.needsUpdate = false;
  12415. _renderer.setRenderTarget(currentRenderTarget, activeCubeFace, activeMipmapLevel);
  12416. };
  12417. function VSMPass(shadow, camera) {
  12418. var geometry = _objects.update(fullScreenMesh); // vertical pass
  12419. shadowMaterialVertical.uniforms.shadow_pass.value = shadow.map.texture;
  12420. shadowMaterialVertical.uniforms.resolution.value = shadow.mapSize;
  12421. shadowMaterialVertical.uniforms.radius.value = shadow.radius;
  12422. _renderer.setRenderTarget(shadow.mapPass);
  12423. _renderer.clear();
  12424. _renderer.renderBufferDirect(camera, null, geometry, shadowMaterialVertical, fullScreenMesh, null); // horizonal pass
  12425. shadowMaterialHorizonal.uniforms.shadow_pass.value = shadow.mapPass.texture;
  12426. shadowMaterialHorizonal.uniforms.resolution.value = shadow.mapSize;
  12427. shadowMaterialHorizonal.uniforms.radius.value = shadow.radius;
  12428. _renderer.setRenderTarget(shadow.map);
  12429. _renderer.clear();
  12430. _renderer.renderBufferDirect(camera, null, geometry, shadowMaterialHorizonal, fullScreenMesh, null);
  12431. }
  12432. function getDepthMaterial(object, material, light, shadowCameraNear, shadowCameraFar, type) {
  12433. var geometry = object.geometry;
  12434. var result = null;
  12435. var materialVariants = _depthMaterials;
  12436. var customMaterial = object.customDepthMaterial;
  12437. if (light.isPointLight) {
  12438. materialVariants = _distanceMaterials;
  12439. customMaterial = object.customDistanceMaterial;
  12440. }
  12441. if (!customMaterial) {
  12442. var useMorphing = false;
  12443. if (material.morphTargets) {
  12444. if (geometry && geometry.isBufferGeometry) {
  12445. useMorphing = geometry.morphAttributes && geometry.morphAttributes.position && geometry.morphAttributes.position.length > 0;
  12446. } else if (geometry && geometry.isGeometry) {
  12447. useMorphing = geometry.morphTargets && geometry.morphTargets.length > 0;
  12448. }
  12449. }
  12450. if (object.isSkinnedMesh && material.skinning === false) {
  12451. console.warn('THREE.WebGLShadowMap: THREE.SkinnedMesh with material.skinning set to false:', object);
  12452. }
  12453. var useSkinning = object.isSkinnedMesh && material.skinning;
  12454. var variantIndex = 0;
  12455. if (useMorphing) variantIndex |= _MorphingFlag;
  12456. if (useSkinning) variantIndex |= _SkinningFlag;
  12457. result = materialVariants[variantIndex];
  12458. } else {
  12459. result = customMaterial;
  12460. }
  12461. if (_renderer.localClippingEnabled && material.clipShadows === true && material.clippingPlanes.length !== 0) {
  12462. // in this case we need a unique material instance reflecting the
  12463. // appropriate state
  12464. var keyA = result.uuid,
  12465. keyB = material.uuid;
  12466. var materialsForVariant = _materialCache[keyA];
  12467. if (materialsForVariant === undefined) {
  12468. materialsForVariant = {};
  12469. _materialCache[keyA] = materialsForVariant;
  12470. }
  12471. var cachedMaterial = materialsForVariant[keyB];
  12472. if (cachedMaterial === undefined) {
  12473. cachedMaterial = result.clone();
  12474. materialsForVariant[keyB] = cachedMaterial;
  12475. }
  12476. result = cachedMaterial;
  12477. }
  12478. result.visible = material.visible;
  12479. result.wireframe = material.wireframe;
  12480. if (type === VSMShadowMap) {
  12481. result.side = material.shadowSide != null ? material.shadowSide : material.side;
  12482. } else {
  12483. result.side = material.shadowSide != null ? material.shadowSide : shadowSide[material.side];
  12484. }
  12485. result.clipShadows = material.clipShadows;
  12486. result.clippingPlanes = material.clippingPlanes;
  12487. result.clipIntersection = material.clipIntersection;
  12488. result.wireframeLinewidth = material.wireframeLinewidth;
  12489. result.linewidth = material.linewidth;
  12490. if (light.isPointLight && result.isMeshDistanceMaterial) {
  12491. result.referencePosition.setFromMatrixPosition(light.matrixWorld);
  12492. result.nearDistance = shadowCameraNear;
  12493. result.farDistance = shadowCameraFar;
  12494. }
  12495. return result;
  12496. }
  12497. function renderObject(object, camera, shadowCamera, light, type) {
  12498. if (object.visible === false) return;
  12499. var visible = object.layers.test(camera.layers);
  12500. if (visible && (object.isMesh || object.isLine || object.isPoints)) {
  12501. if ((object.castShadow || object.receiveShadow && type === VSMShadowMap) && (!object.frustumCulled || _frustum.intersectsObject(object))) {
  12502. object.modelViewMatrix.multiplyMatrices(shadowCamera.matrixWorldInverse, object.matrixWorld);
  12503. var geometry = _objects.update(object);
  12504. var material = object.material;
  12505. if (Array.isArray(material)) {
  12506. var groups = geometry.groups;
  12507. for (var k = 0, kl = groups.length; k < kl; k++) {
  12508. var group = groups[k];
  12509. var groupMaterial = material[group.materialIndex];
  12510. if (groupMaterial && groupMaterial.visible) {
  12511. var depthMaterial = getDepthMaterial(object, groupMaterial, light, shadowCamera.near, shadowCamera.far, type);
  12512. _renderer.renderBufferDirect(shadowCamera, null, geometry, depthMaterial, object, group);
  12513. }
  12514. }
  12515. } else if (material.visible) {
  12516. var depthMaterial = getDepthMaterial(object, material, light, shadowCamera.near, shadowCamera.far, type);
  12517. _renderer.renderBufferDirect(shadowCamera, null, geometry, depthMaterial, object, null);
  12518. }
  12519. }
  12520. }
  12521. var children = object.children;
  12522. for (var i = 0, l = children.length; i < l; i++) {
  12523. renderObject(children[i], camera, shadowCamera, light, type);
  12524. }
  12525. }
  12526. }
  12527. /**
  12528. * @author mrdoob / http://mrdoob.com/
  12529. */
  12530. function WebGLState(gl, extensions, utils, capabilities) {
  12531. function ColorBuffer() {
  12532. var locked = false;
  12533. var color = new Vector4();
  12534. var currentColorMask = null;
  12535. var currentColorClear = new Vector4(0, 0, 0, 0);
  12536. return {
  12537. setMask: function (colorMask) {
  12538. if (currentColorMask !== colorMask && !locked) {
  12539. gl.colorMask(colorMask, colorMask, colorMask, colorMask);
  12540. currentColorMask = colorMask;
  12541. }
  12542. },
  12543. setLocked: function (lock) {
  12544. locked = lock;
  12545. },
  12546. setClear: function (r, g, b, a, premultipliedAlpha) {
  12547. if (premultipliedAlpha === true) {
  12548. r *= a;
  12549. g *= a;
  12550. b *= a;
  12551. }
  12552. color.set(r, g, b, a);
  12553. if (currentColorClear.equals(color) === false) {
  12554. gl.clearColor(r, g, b, a);
  12555. currentColorClear.copy(color);
  12556. }
  12557. },
  12558. reset: function () {
  12559. locked = false;
  12560. currentColorMask = null;
  12561. currentColorClear.set(-1, 0, 0, 0); // set to invalid state
  12562. }
  12563. };
  12564. }
  12565. function DepthBuffer() {
  12566. var locked = false;
  12567. var currentDepthMask = null;
  12568. var currentDepthFunc = null;
  12569. var currentDepthClear = null;
  12570. return {
  12571. setTest: function (depthTest) {
  12572. if (depthTest) {
  12573. enable(2929);
  12574. } else {
  12575. disable(2929);
  12576. }
  12577. },
  12578. setMask: function (depthMask) {
  12579. if (currentDepthMask !== depthMask && !locked) {
  12580. gl.depthMask(depthMask);
  12581. currentDepthMask = depthMask;
  12582. }
  12583. },
  12584. setFunc: function (depthFunc) {
  12585. if (currentDepthFunc !== depthFunc) {
  12586. if (depthFunc) {
  12587. switch (depthFunc) {
  12588. case NeverDepth:
  12589. gl.depthFunc(512);
  12590. break;
  12591. case AlwaysDepth:
  12592. gl.depthFunc(519);
  12593. break;
  12594. case LessDepth:
  12595. gl.depthFunc(513);
  12596. break;
  12597. case LessEqualDepth:
  12598. gl.depthFunc(515);
  12599. break;
  12600. case EqualDepth:
  12601. gl.depthFunc(514);
  12602. break;
  12603. case GreaterEqualDepth:
  12604. gl.depthFunc(518);
  12605. break;
  12606. case GreaterDepth:
  12607. gl.depthFunc(516);
  12608. break;
  12609. case NotEqualDepth:
  12610. gl.depthFunc(517);
  12611. break;
  12612. default:
  12613. gl.depthFunc(515);
  12614. }
  12615. } else {
  12616. gl.depthFunc(515);
  12617. }
  12618. currentDepthFunc = depthFunc;
  12619. }
  12620. },
  12621. setLocked: function (lock) {
  12622. locked = lock;
  12623. },
  12624. setClear: function (depth) {
  12625. if (currentDepthClear !== depth) {
  12626. gl.clearDepth(depth);
  12627. currentDepthClear = depth;
  12628. }
  12629. },
  12630. reset: function () {
  12631. locked = false;
  12632. currentDepthMask = null;
  12633. currentDepthFunc = null;
  12634. currentDepthClear = null;
  12635. }
  12636. };
  12637. }
  12638. function StencilBuffer() {
  12639. var locked = false;
  12640. var currentStencilMask = null;
  12641. var currentStencilFunc = null;
  12642. var currentStencilRef = null;
  12643. var currentStencilFuncMask = null;
  12644. var currentStencilFail = null;
  12645. var currentStencilZFail = null;
  12646. var currentStencilZPass = null;
  12647. var currentStencilClear = null;
  12648. return {
  12649. setTest: function (stencilTest) {
  12650. if (!locked) {
  12651. if (stencilTest) {
  12652. enable(2960);
  12653. } else {
  12654. disable(2960);
  12655. }
  12656. }
  12657. },
  12658. setMask: function (stencilMask) {
  12659. if (currentStencilMask !== stencilMask && !locked) {
  12660. gl.stencilMask(stencilMask);
  12661. currentStencilMask = stencilMask;
  12662. }
  12663. },
  12664. setFunc: function (stencilFunc, stencilRef, stencilMask) {
  12665. if (currentStencilFunc !== stencilFunc || currentStencilRef !== stencilRef || currentStencilFuncMask !== stencilMask) {
  12666. gl.stencilFunc(stencilFunc, stencilRef, stencilMask);
  12667. currentStencilFunc = stencilFunc;
  12668. currentStencilRef = stencilRef;
  12669. currentStencilFuncMask = stencilMask;
  12670. }
  12671. },
  12672. setOp: function (stencilFail, stencilZFail, stencilZPass) {
  12673. if (currentStencilFail !== stencilFail || currentStencilZFail !== stencilZFail || currentStencilZPass !== stencilZPass) {
  12674. gl.stencilOp(stencilFail, stencilZFail, stencilZPass);
  12675. currentStencilFail = stencilFail;
  12676. currentStencilZFail = stencilZFail;
  12677. currentStencilZPass = stencilZPass;
  12678. }
  12679. },
  12680. setLocked: function (lock) {
  12681. locked = lock;
  12682. },
  12683. setClear: function (stencil) {
  12684. if (currentStencilClear !== stencil) {
  12685. gl.clearStencil(stencil);
  12686. currentStencilClear = stencil;
  12687. }
  12688. },
  12689. reset: function () {
  12690. locked = false;
  12691. currentStencilMask = null;
  12692. currentStencilFunc = null;
  12693. currentStencilRef = null;
  12694. currentStencilFuncMask = null;
  12695. currentStencilFail = null;
  12696. currentStencilZFail = null;
  12697. currentStencilZPass = null;
  12698. currentStencilClear = null;
  12699. }
  12700. };
  12701. } //
  12702. var colorBuffer = new ColorBuffer();
  12703. var depthBuffer = new DepthBuffer();
  12704. var stencilBuffer = new StencilBuffer();
  12705. var maxVertexAttributes = gl.getParameter(34921);
  12706. var newAttributes = new Uint8Array(maxVertexAttributes);
  12707. var enabledAttributes = new Uint8Array(maxVertexAttributes);
  12708. var attributeDivisors = new Uint8Array(maxVertexAttributes);
  12709. var enabledCapabilities = {};
  12710. var compressedTextureFormats = null;
  12711. var currentProgram = null;
  12712. var currentBlendingEnabled = null;
  12713. var currentBlending = null;
  12714. var currentBlendEquation = null;
  12715. var currentBlendSrc = null;
  12716. var currentBlendDst = null;
  12717. var currentBlendEquationAlpha = null;
  12718. var currentBlendSrcAlpha = null;
  12719. var currentBlendDstAlpha = null;
  12720. var currentPremultipledAlpha = false;
  12721. var currentFlipSided = null;
  12722. var currentCullFace = null;
  12723. var currentLineWidth = null;
  12724. var currentPolygonOffsetFactor = null;
  12725. var currentPolygonOffsetUnits = null;
  12726. var maxTextures = gl.getParameter(35661);
  12727. var lineWidthAvailable = false;
  12728. var version = 0;
  12729. var glVersion = gl.getParameter(7938);
  12730. if (glVersion.indexOf('WebGL') !== -1) {
  12731. version = parseFloat(/^WebGL\ ([0-9])/.exec(glVersion)[1]);
  12732. lineWidthAvailable = version >= 1.0;
  12733. } else if (glVersion.indexOf('OpenGL ES') !== -1) {
  12734. version = parseFloat(/^OpenGL\ ES\ ([0-9])/.exec(glVersion)[1]);
  12735. lineWidthAvailable = version >= 2.0;
  12736. }
  12737. var currentTextureSlot = null;
  12738. var currentBoundTextures = {};
  12739. var currentScissor = new Vector4();
  12740. var currentViewport = new Vector4();
  12741. function createTexture(type, target, count) {
  12742. var data = new Uint8Array(4); // 4 is required to match default unpack alignment of 4.
  12743. var texture = gl.createTexture();
  12744. gl.bindTexture(type, texture);
  12745. gl.texParameteri(type, 10241, 9728);
  12746. gl.texParameteri(type, 10240, 9728);
  12747. for (var i = 0; i < count; i++) {
  12748. gl.texImage2D(target + i, 0, 6408, 1, 1, 0, 6408, 5121, data);
  12749. }
  12750. return texture;
  12751. }
  12752. var emptyTextures = {};
  12753. emptyTextures[3553] = createTexture(3553, 3553, 1);
  12754. emptyTextures[34067] = createTexture(34067, 34069, 6); // init
  12755. colorBuffer.setClear(0, 0, 0, 1);
  12756. depthBuffer.setClear(1);
  12757. stencilBuffer.setClear(0);
  12758. enable(2929);
  12759. depthBuffer.setFunc(LessEqualDepth);
  12760. setFlipSided(false);
  12761. setCullFace(CullFaceBack);
  12762. enable(2884);
  12763. setBlending(NoBlending); //
  12764. function initAttributes() {
  12765. for (var i = 0, l = newAttributes.length; i < l; i++) {
  12766. newAttributes[i] = 0;
  12767. }
  12768. }
  12769. function enableAttribute(attribute) {
  12770. enableAttributeAndDivisor(attribute, 0);
  12771. }
  12772. function enableAttributeAndDivisor(attribute, meshPerAttribute) {
  12773. newAttributes[attribute] = 1;
  12774. if (enabledAttributes[attribute] === 0) {
  12775. gl.enableVertexAttribArray(attribute);
  12776. enabledAttributes[attribute] = 1;
  12777. }
  12778. if (attributeDivisors[attribute] !== meshPerAttribute) {
  12779. var extension = capabilities.isWebGL2 ? gl : extensions.get('ANGLE_instanced_arrays');
  12780. extension[capabilities.isWebGL2 ? 'vertexAttribDivisor' : 'vertexAttribDivisorANGLE'](attribute, meshPerAttribute);
  12781. attributeDivisors[attribute] = meshPerAttribute;
  12782. }
  12783. }
  12784. function disableUnusedAttributes() {
  12785. for (var i = 0, l = enabledAttributes.length; i !== l; ++i) {
  12786. if (enabledAttributes[i] !== newAttributes[i]) {
  12787. gl.disableVertexAttribArray(i);
  12788. enabledAttributes[i] = 0;
  12789. }
  12790. }
  12791. }
  12792. function enable(id) {
  12793. if (enabledCapabilities[id] !== true) {
  12794. gl.enable(id);
  12795. enabledCapabilities[id] = true;
  12796. }
  12797. }
  12798. function disable(id) {
  12799. if (enabledCapabilities[id] !== false) {
  12800. gl.disable(id);
  12801. enabledCapabilities[id] = false;
  12802. }
  12803. }
  12804. function getCompressedTextureFormats() {
  12805. if (compressedTextureFormats === null) {
  12806. compressedTextureFormats = [];
  12807. 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')) {
  12808. var formats = gl.getParameter(34467);
  12809. for (var i = 0; i < formats.length; i++) {
  12810. compressedTextureFormats.push(formats[i]);
  12811. }
  12812. }
  12813. }
  12814. return compressedTextureFormats;
  12815. }
  12816. function useProgram(program) {
  12817. if (currentProgram !== program) {
  12818. gl.useProgram(program);
  12819. currentProgram = program;
  12820. return true;
  12821. }
  12822. return false;
  12823. }
  12824. function setBlending(blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha) {
  12825. if (blending === NoBlending) {
  12826. if (currentBlendingEnabled) {
  12827. disable(3042);
  12828. currentBlendingEnabled = false;
  12829. }
  12830. return;
  12831. }
  12832. if (!currentBlendingEnabled) {
  12833. enable(3042);
  12834. currentBlendingEnabled = true;
  12835. }
  12836. if (blending !== CustomBlending) {
  12837. if (blending !== currentBlending || premultipliedAlpha !== currentPremultipledAlpha) {
  12838. if (currentBlendEquation !== AddEquation || currentBlendEquationAlpha !== AddEquation) {
  12839. gl.blendEquation(32774);
  12840. currentBlendEquation = AddEquation;
  12841. currentBlendEquationAlpha = AddEquation;
  12842. }
  12843. if (premultipliedAlpha) {
  12844. switch (blending) {
  12845. case NormalBlending:
  12846. gl.blendFuncSeparate(1, 771, 1, 771);
  12847. break;
  12848. case AdditiveBlending:
  12849. gl.blendFunc(1, 1);
  12850. break;
  12851. case SubtractiveBlending:
  12852. gl.blendFuncSeparate(0, 0, 769, 771);
  12853. break;
  12854. case MultiplyBlending:
  12855. gl.blendFuncSeparate(0, 768, 0, 770);
  12856. break;
  12857. default:
  12858. console.error('THREE.WebGLState: Invalid blending: ', blending);
  12859. break;
  12860. }
  12861. } else {
  12862. switch (blending) {
  12863. case NormalBlending:
  12864. gl.blendFuncSeparate(770, 771, 1, 771);
  12865. break;
  12866. case AdditiveBlending:
  12867. gl.blendFunc(770, 1);
  12868. break;
  12869. case SubtractiveBlending:
  12870. gl.blendFunc(0, 769);
  12871. break;
  12872. case MultiplyBlending:
  12873. gl.blendFunc(0, 768);
  12874. break;
  12875. default:
  12876. console.error('THREE.WebGLState: Invalid blending: ', blending);
  12877. break;
  12878. }
  12879. }
  12880. currentBlendSrc = null;
  12881. currentBlendDst = null;
  12882. currentBlendSrcAlpha = null;
  12883. currentBlendDstAlpha = null;
  12884. currentBlending = blending;
  12885. currentPremultipledAlpha = premultipliedAlpha;
  12886. }
  12887. return;
  12888. } // custom blending
  12889. blendEquationAlpha = blendEquationAlpha || blendEquation;
  12890. blendSrcAlpha = blendSrcAlpha || blendSrc;
  12891. blendDstAlpha = blendDstAlpha || blendDst;
  12892. if (blendEquation !== currentBlendEquation || blendEquationAlpha !== currentBlendEquationAlpha) {
  12893. gl.blendEquationSeparate(utils.convert(blendEquation), utils.convert(blendEquationAlpha));
  12894. currentBlendEquation = blendEquation;
  12895. currentBlendEquationAlpha = blendEquationAlpha;
  12896. }
  12897. if (blendSrc !== currentBlendSrc || blendDst !== currentBlendDst || blendSrcAlpha !== currentBlendSrcAlpha || blendDstAlpha !== currentBlendDstAlpha) {
  12898. gl.blendFuncSeparate(utils.convert(blendSrc), utils.convert(blendDst), utils.convert(blendSrcAlpha), utils.convert(blendDstAlpha));
  12899. currentBlendSrc = blendSrc;
  12900. currentBlendDst = blendDst;
  12901. currentBlendSrcAlpha = blendSrcAlpha;
  12902. currentBlendDstAlpha = blendDstAlpha;
  12903. }
  12904. currentBlending = blending;
  12905. currentPremultipledAlpha = null;
  12906. }
  12907. function setMaterial(material, frontFaceCW) {
  12908. material.side === DoubleSide ? disable(2884) : enable(2884);
  12909. var flipSided = material.side === BackSide;
  12910. if (frontFaceCW) flipSided = !flipSided;
  12911. setFlipSided(flipSided);
  12912. 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);
  12913. depthBuffer.setFunc(material.depthFunc);
  12914. depthBuffer.setTest(material.depthTest);
  12915. depthBuffer.setMask(material.depthWrite);
  12916. colorBuffer.setMask(material.colorWrite);
  12917. var stencilWrite = material.stencilWrite;
  12918. stencilBuffer.setTest(stencilWrite);
  12919. if (stencilWrite) {
  12920. stencilBuffer.setMask(material.stencilWriteMask);
  12921. stencilBuffer.setFunc(material.stencilFunc, material.stencilRef, material.stencilFuncMask);
  12922. stencilBuffer.setOp(material.stencilFail, material.stencilZFail, material.stencilZPass);
  12923. }
  12924. setPolygonOffset(material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits);
  12925. } //
  12926. function setFlipSided(flipSided) {
  12927. if (currentFlipSided !== flipSided) {
  12928. if (flipSided) {
  12929. gl.frontFace(2304);
  12930. } else {
  12931. gl.frontFace(2305);
  12932. }
  12933. currentFlipSided = flipSided;
  12934. }
  12935. }
  12936. function setCullFace(cullFace) {
  12937. if (cullFace !== CullFaceNone) {
  12938. enable(2884);
  12939. if (cullFace !== currentCullFace) {
  12940. if (cullFace === CullFaceBack) {
  12941. gl.cullFace(1029);
  12942. } else if (cullFace === CullFaceFront) {
  12943. gl.cullFace(1028);
  12944. } else {
  12945. gl.cullFace(1032);
  12946. }
  12947. }
  12948. } else {
  12949. disable(2884);
  12950. }
  12951. currentCullFace = cullFace;
  12952. }
  12953. function setLineWidth(width) {
  12954. if (width !== currentLineWidth) {
  12955. if (lineWidthAvailable) gl.lineWidth(width);
  12956. currentLineWidth = width;
  12957. }
  12958. }
  12959. function setPolygonOffset(polygonOffset, factor, units) {
  12960. if (polygonOffset) {
  12961. enable(32823);
  12962. if (currentPolygonOffsetFactor !== factor || currentPolygonOffsetUnits !== units) {
  12963. gl.polygonOffset(factor, units);
  12964. currentPolygonOffsetFactor = factor;
  12965. currentPolygonOffsetUnits = units;
  12966. }
  12967. } else {
  12968. disable(32823);
  12969. }
  12970. }
  12971. function setScissorTest(scissorTest) {
  12972. if (scissorTest) {
  12973. enable(3089);
  12974. } else {
  12975. disable(3089);
  12976. }
  12977. } // texture
  12978. function activeTexture(webglSlot) {
  12979. if (webglSlot === undefined) webglSlot = 33984 + maxTextures - 1;
  12980. if (currentTextureSlot !== webglSlot) {
  12981. gl.activeTexture(webglSlot);
  12982. currentTextureSlot = webglSlot;
  12983. }
  12984. }
  12985. function bindTexture(webglType, webglTexture) {
  12986. if (currentTextureSlot === null) {
  12987. activeTexture();
  12988. }
  12989. var boundTexture = currentBoundTextures[currentTextureSlot];
  12990. if (boundTexture === undefined) {
  12991. boundTexture = {
  12992. type: undefined,
  12993. texture: undefined
  12994. };
  12995. currentBoundTextures[currentTextureSlot] = boundTexture;
  12996. }
  12997. if (boundTexture.type !== webglType || boundTexture.texture !== webglTexture) {
  12998. gl.bindTexture(webglType, webglTexture || emptyTextures[webglType]);
  12999. boundTexture.type = webglType;
  13000. boundTexture.texture = webglTexture;
  13001. }
  13002. }
  13003. function compressedTexImage2D() {
  13004. try {
  13005. gl.compressedTexImage2D.apply(gl, arguments);
  13006. } catch (error) {
  13007. console.error('THREE.WebGLState:', error);
  13008. }
  13009. }
  13010. function texImage2D() {
  13011. try {
  13012. gl.texImage2D.apply(gl, arguments);
  13013. } catch (error) {
  13014. console.error('THREE.WebGLState:', error);
  13015. }
  13016. }
  13017. function texImage3D() {
  13018. try {
  13019. gl.texImage3D.apply(gl, arguments);
  13020. } catch (error) {
  13021. console.error('THREE.WebGLState:', error);
  13022. }
  13023. } //
  13024. function scissor(scissor) {
  13025. if (currentScissor.equals(scissor) === false) {
  13026. gl.scissor(scissor.x, scissor.y, scissor.z, scissor.w);
  13027. currentScissor.copy(scissor);
  13028. }
  13029. }
  13030. function viewport(viewport) {
  13031. if (currentViewport.equals(viewport) === false) {
  13032. gl.viewport(viewport.x, viewport.y, viewport.z, viewport.w);
  13033. currentViewport.copy(viewport);
  13034. }
  13035. } //
  13036. function reset() {
  13037. for (var i = 0; i < enabledAttributes.length; i++) {
  13038. if (enabledAttributes[i] === 1) {
  13039. gl.disableVertexAttribArray(i);
  13040. enabledAttributes[i] = 0;
  13041. }
  13042. }
  13043. enabledCapabilities = {};
  13044. compressedTextureFormats = null;
  13045. currentTextureSlot = null;
  13046. currentBoundTextures = {};
  13047. currentProgram = null;
  13048. currentBlending = null;
  13049. currentFlipSided = null;
  13050. currentCullFace = null;
  13051. colorBuffer.reset();
  13052. depthBuffer.reset();
  13053. stencilBuffer.reset();
  13054. }
  13055. return {
  13056. buffers: {
  13057. color: colorBuffer,
  13058. depth: depthBuffer,
  13059. stencil: stencilBuffer
  13060. },
  13061. initAttributes: initAttributes,
  13062. enableAttribute: enableAttribute,
  13063. enableAttributeAndDivisor: enableAttributeAndDivisor,
  13064. disableUnusedAttributes: disableUnusedAttributes,
  13065. enable: enable,
  13066. disable: disable,
  13067. getCompressedTextureFormats: getCompressedTextureFormats,
  13068. useProgram: useProgram,
  13069. setBlending: setBlending,
  13070. setMaterial: setMaterial,
  13071. setFlipSided: setFlipSided,
  13072. setCullFace: setCullFace,
  13073. setLineWidth: setLineWidth,
  13074. setPolygonOffset: setPolygonOffset,
  13075. setScissorTest: setScissorTest,
  13076. activeTexture: activeTexture,
  13077. bindTexture: bindTexture,
  13078. compressedTexImage2D: compressedTexImage2D,
  13079. texImage2D: texImage2D,
  13080. texImage3D: texImage3D,
  13081. scissor: scissor,
  13082. viewport: viewport,
  13083. reset: reset
  13084. };
  13085. }
  13086. /**
  13087. * @author mrdoob / http://mrdoob.com/
  13088. */
  13089. function WebGLTextures(_gl, extensions, state, properties, capabilities, utils, info) {
  13090. var _videoTextures = new WeakMap();
  13091. var _canvas; // cordova iOS (as of 5.0) still uses UIWebView, which provides OffscreenCanvas,
  13092. // also OffscreenCanvas.getContext("webgl"), but not OffscreenCanvas.getContext("2d")!
  13093. var useOffscreenCanvas = typeof OffscreenCanvas !== 'undefined' && new OffscreenCanvas(1, 1).getContext("2d") !== null;
  13094. function createCanvas(width, height) {
  13095. // Use OffscreenCanvas when available. Specially needed in web workers
  13096. return useOffscreenCanvas ? new OffscreenCanvas(width, height) : document.createElementNS('http://www.w3.org/1999/xhtml', 'canvas');
  13097. }
  13098. function resizeImage(image, needsPowerOfTwo, needsNewCanvas, maxSize) {
  13099. var scale = 1; // handle case if texture exceeds max size
  13100. if (image.width > maxSize || image.height > maxSize) {
  13101. scale = maxSize / Math.max(image.width, image.height);
  13102. } // only perform resize if necessary
  13103. if (scale < 1 || needsPowerOfTwo === true) {
  13104. // only perform resize for certain image types
  13105. if (typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement || typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement || typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap) {
  13106. var floor = needsPowerOfTwo ? _Math.floorPowerOfTwo : Math.floor;
  13107. var width = floor(scale * image.width);
  13108. var height = floor(scale * image.height);
  13109. if (_canvas === undefined) _canvas = createCanvas(width, height); // cube textures can't reuse the same canvas
  13110. var canvas = needsNewCanvas ? createCanvas(width, height) : _canvas;
  13111. canvas.width = width;
  13112. canvas.height = height;
  13113. var context = canvas.getContext('2d');
  13114. context.drawImage(image, 0, 0, width, height);
  13115. console.warn('THREE.WebGLRenderer: Texture has been resized from (' + image.width + 'x' + image.height + ') to (' + width + 'x' + height + ').');
  13116. return canvas;
  13117. } else {
  13118. if ('data' in image) {
  13119. console.warn('THREE.WebGLRenderer: Image in DataTexture is too big (' + image.width + 'x' + image.height + ').');
  13120. }
  13121. return image;
  13122. }
  13123. }
  13124. return image;
  13125. }
  13126. function isPowerOfTwo(image) {
  13127. return _Math.isPowerOfTwo(image.width) && _Math.isPowerOfTwo(image.height);
  13128. }
  13129. function textureNeedsPowerOfTwo(texture) {
  13130. if (capabilities.isWebGL2) return false;
  13131. return texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping || texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter;
  13132. }
  13133. function textureNeedsGenerateMipmaps(texture, supportsMips) {
  13134. return texture.generateMipmaps && supportsMips && texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter;
  13135. }
  13136. function generateMipmap(target, texture, width, height) {
  13137. _gl.generateMipmap(target);
  13138. var textureProperties = properties.get(texture); // Note: Math.log( x ) * Math.LOG2E used instead of Math.log2( x ) which is not supported by IE11
  13139. textureProperties.__maxMipLevel = Math.log(Math.max(width, height)) * Math.LOG2E;
  13140. }
  13141. function getInternalFormat(glFormat, glType) {
  13142. if (!capabilities.isWebGL2) return glFormat;
  13143. var internalFormat = glFormat;
  13144. if (glFormat === 6403) {
  13145. if (glType === 5126) internalFormat = 33326;
  13146. if (glType === 5131) internalFormat = 33325;
  13147. if (glType === 5121) internalFormat = 33321;
  13148. }
  13149. if (glFormat === 6407) {
  13150. if (glType === 5126) internalFormat = 34837;
  13151. if (glType === 5131) internalFormat = 34843;
  13152. if (glType === 5121) internalFormat = 32849;
  13153. }
  13154. if (glFormat === 6408) {
  13155. if (glType === 5126) internalFormat = 34836;
  13156. if (glType === 5131) internalFormat = 34842;
  13157. if (glType === 5121) internalFormat = 32856;
  13158. }
  13159. if (internalFormat === 33325 || internalFormat === 33326 || internalFormat === 34842 || internalFormat === 34836) {
  13160. extensions.get('EXT_color_buffer_float');
  13161. } else if (internalFormat === 34843 || internalFormat === 34837) {
  13162. console.warn('THREE.WebGLRenderer: Floating point textures with RGB format not supported. Please use RGBA instead.');
  13163. }
  13164. return internalFormat;
  13165. } // Fallback filters for non-power-of-2 textures
  13166. function filterFallback(f) {
  13167. if (f === NearestFilter || f === NearestMipmapNearestFilter || f === NearestMipmapLinearFilter) {
  13168. return 9728;
  13169. }
  13170. return 9729;
  13171. } //
  13172. function onTextureDispose(event) {
  13173. var texture = event.target;
  13174. texture.removeEventListener('dispose', onTextureDispose);
  13175. deallocateTexture(texture);
  13176. if (texture.isVideoTexture) {
  13177. _videoTextures.delete(texture);
  13178. }
  13179. info.memory.textures--;
  13180. }
  13181. function onRenderTargetDispose(event) {
  13182. var renderTarget = event.target;
  13183. renderTarget.removeEventListener('dispose', onRenderTargetDispose);
  13184. deallocateRenderTarget(renderTarget);
  13185. info.memory.textures--;
  13186. } //
  13187. function deallocateTexture(texture) {
  13188. var textureProperties = properties.get(texture);
  13189. if (textureProperties.__webglInit === undefined) return;
  13190. _gl.deleteTexture(textureProperties.__webglTexture);
  13191. properties.remove(texture);
  13192. }
  13193. function deallocateRenderTarget(renderTarget) {
  13194. var renderTargetProperties = properties.get(renderTarget);
  13195. var textureProperties = properties.get(renderTarget.texture);
  13196. if (!renderTarget) return;
  13197. if (textureProperties.__webglTexture !== undefined) {
  13198. _gl.deleteTexture(textureProperties.__webglTexture);
  13199. }
  13200. if (renderTarget.depthTexture) {
  13201. renderTarget.depthTexture.dispose();
  13202. }
  13203. if (renderTarget.isWebGLRenderTargetCube) {
  13204. for (var i = 0; i < 6; i++) {
  13205. _gl.deleteFramebuffer(renderTargetProperties.__webglFramebuffer[i]);
  13206. if (renderTargetProperties.__webglDepthbuffer) _gl.deleteRenderbuffer(renderTargetProperties.__webglDepthbuffer[i]);
  13207. }
  13208. } else {
  13209. _gl.deleteFramebuffer(renderTargetProperties.__webglFramebuffer);
  13210. if (renderTargetProperties.__webglDepthbuffer) _gl.deleteRenderbuffer(renderTargetProperties.__webglDepthbuffer);
  13211. }
  13212. if (renderTarget.isWebGLMultiviewRenderTarget) {
  13213. _gl.deleteTexture(renderTargetProperties.__webglColorTexture);
  13214. _gl.deleteTexture(renderTargetProperties.__webglDepthStencilTexture);
  13215. info.memory.textures -= 2;
  13216. for (var i = 0, il = renderTargetProperties.__webglViewFramebuffers.length; i < il; i++) {
  13217. _gl.deleteFramebuffer(renderTargetProperties.__webglViewFramebuffers[i]);
  13218. }
  13219. }
  13220. properties.remove(renderTarget.texture);
  13221. properties.remove(renderTarget);
  13222. } //
  13223. var textureUnits = 0;
  13224. function resetTextureUnits() {
  13225. textureUnits = 0;
  13226. }
  13227. function allocateTextureUnit() {
  13228. var textureUnit = textureUnits;
  13229. if (textureUnit >= capabilities.maxTextures) {
  13230. console.warn('THREE.WebGLTextures: Trying to use ' + textureUnit + ' texture units while this GPU supports only ' + capabilities.maxTextures);
  13231. }
  13232. textureUnits += 1;
  13233. return textureUnit;
  13234. } //
  13235. function setTexture2D(texture, slot) {
  13236. var textureProperties = properties.get(texture);
  13237. if (texture.isVideoTexture) updateVideoTexture(texture);
  13238. if (texture.version > 0 && textureProperties.__version !== texture.version) {
  13239. var image = texture.image;
  13240. if (image === undefined) {
  13241. console.warn('THREE.WebGLRenderer: Texture marked for update but image is undefined');
  13242. } else if (image.complete === false) {
  13243. console.warn('THREE.WebGLRenderer: Texture marked for update but image is incomplete');
  13244. } else {
  13245. uploadTexture(textureProperties, texture, slot);
  13246. return;
  13247. }
  13248. }
  13249. state.activeTexture(33984 + slot);
  13250. state.bindTexture(3553, textureProperties.__webglTexture);
  13251. }
  13252. function setTexture2DArray(texture, slot) {
  13253. var textureProperties = properties.get(texture);
  13254. if (texture.version > 0 && textureProperties.__version !== texture.version) {
  13255. uploadTexture(textureProperties, texture, slot);
  13256. return;
  13257. }
  13258. state.activeTexture(33984 + slot);
  13259. state.bindTexture(35866, textureProperties.__webglTexture);
  13260. }
  13261. function setTexture3D(texture, slot) {
  13262. var textureProperties = properties.get(texture);
  13263. if (texture.version > 0 && textureProperties.__version !== texture.version) {
  13264. uploadTexture(textureProperties, texture, slot);
  13265. return;
  13266. }
  13267. state.activeTexture(33984 + slot);
  13268. state.bindTexture(32879, textureProperties.__webglTexture);
  13269. }
  13270. function setTextureCube(texture, slot) {
  13271. if (texture.image.length !== 6) return;
  13272. var textureProperties = properties.get(texture);
  13273. if (texture.version > 0 && textureProperties.__version !== texture.version) {
  13274. initTexture(textureProperties, texture);
  13275. state.activeTexture(33984 + slot);
  13276. state.bindTexture(34067, textureProperties.__webglTexture);
  13277. _gl.pixelStorei(37440, texture.flipY);
  13278. var isCompressed = texture && texture.isCompressedTexture;
  13279. var isDataTexture = texture.image[0] && texture.image[0].isDataTexture;
  13280. var cubeImage = [];
  13281. for (var i = 0; i < 6; i++) {
  13282. if (!isCompressed && !isDataTexture) {
  13283. cubeImage[i] = resizeImage(texture.image[i], false, true, capabilities.maxCubemapSize);
  13284. } else {
  13285. cubeImage[i] = isDataTexture ? texture.image[i].image : texture.image[i];
  13286. }
  13287. }
  13288. var image = cubeImage[0],
  13289. supportsMips = isPowerOfTwo(image) || capabilities.isWebGL2,
  13290. glFormat = utils.convert(texture.format),
  13291. glType = utils.convert(texture.type),
  13292. glInternalFormat = getInternalFormat(glFormat, glType);
  13293. setTextureParameters(34067, texture, supportsMips);
  13294. var mipmaps;
  13295. if (isCompressed) {
  13296. for (var i = 0; i < 6; i++) {
  13297. mipmaps = cubeImage[i].mipmaps;
  13298. for (var j = 0; j < mipmaps.length; j++) {
  13299. var mipmap = mipmaps[j];
  13300. if (texture.format !== RGBAFormat && texture.format !== RGBFormat) {
  13301. if (state.getCompressedTextureFormats().indexOf(glFormat) > -1) {
  13302. state.compressedTexImage2D(34069 + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data);
  13303. } else {
  13304. console.warn('THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()');
  13305. }
  13306. } else {
  13307. state.texImage2D(34069 + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data);
  13308. }
  13309. }
  13310. }
  13311. textureProperties.__maxMipLevel = mipmaps.length - 1;
  13312. } else {
  13313. mipmaps = texture.mipmaps;
  13314. for (var i = 0; i < 6; i++) {
  13315. if (isDataTexture) {
  13316. state.texImage2D(34069 + i, 0, glInternalFormat, cubeImage[i].width, cubeImage[i].height, 0, glFormat, glType, cubeImage[i].data);
  13317. for (var j = 0; j < mipmaps.length; j++) {
  13318. var mipmap = mipmaps[j];
  13319. var mipmapImage = mipmap.image[i].image;
  13320. state.texImage2D(34069 + i, j + 1, glInternalFormat, mipmapImage.width, mipmapImage.height, 0, glFormat, glType, mipmapImage.data);
  13321. }
  13322. } else {
  13323. state.texImage2D(34069 + i, 0, glInternalFormat, glFormat, glType, cubeImage[i]);
  13324. for (var j = 0; j < mipmaps.length; j++) {
  13325. var mipmap = mipmaps[j];
  13326. state.texImage2D(34069 + i, j + 1, glInternalFormat, glFormat, glType, mipmap.image[i]);
  13327. }
  13328. }
  13329. }
  13330. textureProperties.__maxMipLevel = mipmaps.length;
  13331. }
  13332. if (textureNeedsGenerateMipmaps(texture, supportsMips)) {
  13333. // We assume images for cube map have the same size.
  13334. generateMipmap(34067, texture, image.width, image.height);
  13335. }
  13336. textureProperties.__version = texture.version;
  13337. if (texture.onUpdate) texture.onUpdate(texture);
  13338. } else {
  13339. state.activeTexture(33984 + slot);
  13340. state.bindTexture(34067, textureProperties.__webglTexture);
  13341. }
  13342. }
  13343. function setTextureCubeDynamic(texture, slot) {
  13344. state.activeTexture(33984 + slot);
  13345. state.bindTexture(34067, properties.get(texture).__webglTexture);
  13346. }
  13347. function setTextureParameters(textureType, texture, supportsMips) {
  13348. var extension;
  13349. if (supportsMips) {
  13350. _gl.texParameteri(textureType, 10242, utils.convert(texture.wrapS));
  13351. _gl.texParameteri(textureType, 10243, utils.convert(texture.wrapT));
  13352. if (textureType === 32879 || textureType === 35866) {
  13353. _gl.texParameteri(textureType, 32882, utils.convert(texture.wrapR));
  13354. }
  13355. _gl.texParameteri(textureType, 10240, utils.convert(texture.magFilter));
  13356. _gl.texParameteri(textureType, 10241, utils.convert(texture.minFilter));
  13357. } else {
  13358. _gl.texParameteri(textureType, 10242, 33071);
  13359. _gl.texParameteri(textureType, 10243, 33071);
  13360. if (textureType === 32879 || textureType === 35866) {
  13361. _gl.texParameteri(textureType, 32882, 33071);
  13362. }
  13363. if (texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping) {
  13364. console.warn('THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping.');
  13365. }
  13366. _gl.texParameteri(textureType, 10240, filterFallback(texture.magFilter));
  13367. _gl.texParameteri(textureType, 10241, filterFallback(texture.minFilter));
  13368. if (texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter) {
  13369. console.warn('THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.');
  13370. }
  13371. }
  13372. extension = extensions.get('EXT_texture_filter_anisotropic');
  13373. if (extension) {
  13374. if (texture.type === FloatType && extensions.get('OES_texture_float_linear') === null) return;
  13375. if (texture.type === HalfFloatType && (capabilities.isWebGL2 || extensions.get('OES_texture_half_float_linear')) === null) return;
  13376. if (texture.anisotropy > 1 || properties.get(texture).__currentAnisotropy) {
  13377. _gl.texParameterf(textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(texture.anisotropy, capabilities.getMaxAnisotropy()));
  13378. properties.get(texture).__currentAnisotropy = texture.anisotropy;
  13379. }
  13380. }
  13381. }
  13382. function initTexture(textureProperties, texture) {
  13383. if (textureProperties.__webglInit === undefined) {
  13384. textureProperties.__webglInit = true;
  13385. texture.addEventListener('dispose', onTextureDispose);
  13386. textureProperties.__webglTexture = _gl.createTexture();
  13387. info.memory.textures++;
  13388. }
  13389. }
  13390. function uploadTexture(textureProperties, texture, slot) {
  13391. var textureType = 3553;
  13392. if (texture.isDataTexture2DArray) textureType = 35866;
  13393. if (texture.isDataTexture3D) textureType = 32879;
  13394. initTexture(textureProperties, texture);
  13395. state.activeTexture(33984 + slot);
  13396. state.bindTexture(textureType, textureProperties.__webglTexture);
  13397. _gl.pixelStorei(37440, texture.flipY);
  13398. _gl.pixelStorei(37441, texture.premultiplyAlpha);
  13399. _gl.pixelStorei(3317, texture.unpackAlignment);
  13400. var needsPowerOfTwo = textureNeedsPowerOfTwo(texture) && isPowerOfTwo(texture.image) === false;
  13401. var image = resizeImage(texture.image, needsPowerOfTwo, false, capabilities.maxTextureSize);
  13402. var supportsMips = isPowerOfTwo(image) || capabilities.isWebGL2,
  13403. glFormat = utils.convert(texture.format),
  13404. glType = utils.convert(texture.type),
  13405. glInternalFormat = getInternalFormat(glFormat, glType);
  13406. setTextureParameters(textureType, texture, supportsMips);
  13407. var mipmap,
  13408. mipmaps = texture.mipmaps;
  13409. if (texture.isDepthTexture) {
  13410. // populate depth texture with dummy data
  13411. glInternalFormat = 6402;
  13412. if (texture.type === FloatType) {
  13413. if (!capabilities.isWebGL2) throw new Error('Float Depth Texture only supported in WebGL2.0');
  13414. glInternalFormat = 36012;
  13415. } else if (capabilities.isWebGL2) {
  13416. // WebGL 2.0 requires signed internalformat for glTexImage2D
  13417. glInternalFormat = 33189;
  13418. }
  13419. if (texture.format === DepthFormat && glInternalFormat === 6402) {
  13420. // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  13421. // DEPTH_COMPONENT and type is not UNSIGNED_SHORT or UNSIGNED_INT
  13422. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  13423. if (texture.type !== UnsignedShortType && texture.type !== UnsignedIntType) {
  13424. console.warn('THREE.WebGLRenderer: Use UnsignedShortType or UnsignedIntType for DepthFormat DepthTexture.');
  13425. texture.type = UnsignedShortType;
  13426. glType = utils.convert(texture.type);
  13427. }
  13428. } // Depth stencil textures need the DEPTH_STENCIL internal format
  13429. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  13430. if (texture.format === DepthStencilFormat) {
  13431. glInternalFormat = 34041; // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  13432. // DEPTH_STENCIL and type is not UNSIGNED_INT_24_8_WEBGL.
  13433. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  13434. if (texture.type !== UnsignedInt248Type) {
  13435. console.warn('THREE.WebGLRenderer: Use UnsignedInt248Type for DepthStencilFormat DepthTexture.');
  13436. texture.type = UnsignedInt248Type;
  13437. glType = utils.convert(texture.type);
  13438. }
  13439. }
  13440. state.texImage2D(3553, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, null);
  13441. } else if (texture.isDataTexture) {
  13442. // use manually created mipmaps if available
  13443. // if there are no manual mipmaps
  13444. // set 0 level mipmap and then use GL to generate other mipmap levels
  13445. if (mipmaps.length > 0 && supportsMips) {
  13446. for (var i = 0, il = mipmaps.length; i < il; i++) {
  13447. mipmap = mipmaps[i];
  13448. state.texImage2D(3553, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data);
  13449. }
  13450. texture.generateMipmaps = false;
  13451. textureProperties.__maxMipLevel = mipmaps.length - 1;
  13452. } else {
  13453. state.texImage2D(3553, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, image.data);
  13454. textureProperties.__maxMipLevel = 0;
  13455. }
  13456. } else if (texture.isCompressedTexture) {
  13457. for (var i = 0, il = mipmaps.length; i < il; i++) {
  13458. mipmap = mipmaps[i];
  13459. if (texture.format !== RGBAFormat && texture.format !== RGBFormat) {
  13460. if (state.getCompressedTextureFormats().indexOf(glFormat) > -1) {
  13461. state.compressedTexImage2D(3553, i, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data);
  13462. } else {
  13463. console.warn('THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()');
  13464. }
  13465. } else {
  13466. state.texImage2D(3553, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data);
  13467. }
  13468. }
  13469. textureProperties.__maxMipLevel = mipmaps.length - 1;
  13470. } else if (texture.isDataTexture2DArray) {
  13471. state.texImage3D(35866, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data);
  13472. textureProperties.__maxMipLevel = 0;
  13473. } else if (texture.isDataTexture3D) {
  13474. state.texImage3D(32879, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data);
  13475. textureProperties.__maxMipLevel = 0;
  13476. } else {
  13477. // regular Texture (image, video, canvas)
  13478. // use manually created mipmaps if available
  13479. // if there are no manual mipmaps
  13480. // set 0 level mipmap and then use GL to generate other mipmap levels
  13481. if (mipmaps.length > 0 && supportsMips) {
  13482. for (var i = 0, il = mipmaps.length; i < il; i++) {
  13483. mipmap = mipmaps[i];
  13484. state.texImage2D(3553, i, glInternalFormat, glFormat, glType, mipmap);
  13485. }
  13486. texture.generateMipmaps = false;
  13487. textureProperties.__maxMipLevel = mipmaps.length - 1;
  13488. } else {
  13489. state.texImage2D(3553, 0, glInternalFormat, glFormat, glType, image);
  13490. textureProperties.__maxMipLevel = 0;
  13491. }
  13492. }
  13493. if (textureNeedsGenerateMipmaps(texture, supportsMips)) {
  13494. generateMipmap(3553, texture, image.width, image.height);
  13495. }
  13496. textureProperties.__version = texture.version;
  13497. if (texture.onUpdate) texture.onUpdate(texture);
  13498. } // Render targets
  13499. // Setup storage for target texture and bind it to correct framebuffer
  13500. function setupFrameBufferTexture(framebuffer, renderTarget, attachment, textureTarget) {
  13501. var glFormat = utils.convert(renderTarget.texture.format);
  13502. var glType = utils.convert(renderTarget.texture.type);
  13503. var glInternalFormat = getInternalFormat(glFormat, glType);
  13504. state.texImage2D(textureTarget, 0, glInternalFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null);
  13505. _gl.bindFramebuffer(36160, framebuffer);
  13506. _gl.framebufferTexture2D(36160, attachment, textureTarget, properties.get(renderTarget.texture).__webglTexture, 0);
  13507. _gl.bindFramebuffer(36160, null);
  13508. } // Setup storage for internal depth/stencil buffers and bind to correct framebuffer
  13509. function setupRenderBufferStorage(renderbuffer, renderTarget, isMultisample) {
  13510. _gl.bindRenderbuffer(36161, renderbuffer);
  13511. if (renderTarget.depthBuffer && !renderTarget.stencilBuffer) {
  13512. if (isMultisample) {
  13513. var samples = getRenderTargetSamples(renderTarget);
  13514. _gl.renderbufferStorageMultisample(36161, samples, 33189, renderTarget.width, renderTarget.height);
  13515. } else {
  13516. _gl.renderbufferStorage(36161, 33189, renderTarget.width, renderTarget.height);
  13517. }
  13518. _gl.framebufferRenderbuffer(36160, 36096, 36161, renderbuffer);
  13519. } else if (renderTarget.depthBuffer && renderTarget.stencilBuffer) {
  13520. if (isMultisample) {
  13521. var samples = getRenderTargetSamples(renderTarget);
  13522. _gl.renderbufferStorageMultisample(36161, samples, 35056, renderTarget.width, renderTarget.height);
  13523. } else {
  13524. _gl.renderbufferStorage(36161, 34041, renderTarget.width, renderTarget.height);
  13525. }
  13526. _gl.framebufferRenderbuffer(36160, 33306, 36161, renderbuffer);
  13527. } else {
  13528. var glFormat = utils.convert(renderTarget.texture.format);
  13529. var glType = utils.convert(renderTarget.texture.type);
  13530. var glInternalFormat = getInternalFormat(glFormat, glType);
  13531. if (isMultisample) {
  13532. var samples = getRenderTargetSamples(renderTarget);
  13533. _gl.renderbufferStorageMultisample(36161, samples, glInternalFormat, renderTarget.width, renderTarget.height);
  13534. } else {
  13535. _gl.renderbufferStorage(36161, glInternalFormat, renderTarget.width, renderTarget.height);
  13536. }
  13537. }
  13538. _gl.bindRenderbuffer(36161, null);
  13539. } // Setup resources for a Depth Texture for a FBO (needs an extension)
  13540. function setupDepthTexture(framebuffer, renderTarget) {
  13541. var isCube = renderTarget && renderTarget.isWebGLRenderTargetCube;
  13542. if (isCube) throw new Error('Depth Texture with cube render targets is not supported');
  13543. _gl.bindFramebuffer(36160, framebuffer);
  13544. if (!(renderTarget.depthTexture && renderTarget.depthTexture.isDepthTexture)) {
  13545. throw new Error('renderTarget.depthTexture must be an instance of THREE.DepthTexture');
  13546. } // upload an empty depth texture with framebuffer size
  13547. if (!properties.get(renderTarget.depthTexture).__webglTexture || renderTarget.depthTexture.image.width !== renderTarget.width || renderTarget.depthTexture.image.height !== renderTarget.height) {
  13548. renderTarget.depthTexture.image.width = renderTarget.width;
  13549. renderTarget.depthTexture.image.height = renderTarget.height;
  13550. renderTarget.depthTexture.needsUpdate = true;
  13551. }
  13552. setTexture2D(renderTarget.depthTexture, 0);
  13553. var webglDepthTexture = properties.get(renderTarget.depthTexture).__webglTexture;
  13554. if (renderTarget.depthTexture.format === DepthFormat) {
  13555. _gl.framebufferTexture2D(36160, 36096, 3553, webglDepthTexture, 0);
  13556. } else if (renderTarget.depthTexture.format === DepthStencilFormat) {
  13557. _gl.framebufferTexture2D(36160, 33306, 3553, webglDepthTexture, 0);
  13558. } else {
  13559. throw new Error('Unknown depthTexture format');
  13560. }
  13561. } // Setup GL resources for a non-texture depth buffer
  13562. function setupDepthRenderbuffer(renderTarget) {
  13563. var renderTargetProperties = properties.get(renderTarget);
  13564. var isCube = renderTarget.isWebGLRenderTargetCube === true;
  13565. if (renderTarget.depthTexture) {
  13566. if (isCube) throw new Error('target.depthTexture not supported in Cube render targets');
  13567. setupDepthTexture(renderTargetProperties.__webglFramebuffer, renderTarget);
  13568. } else {
  13569. if (isCube) {
  13570. renderTargetProperties.__webglDepthbuffer = [];
  13571. for (var i = 0; i < 6; i++) {
  13572. _gl.bindFramebuffer(36160, renderTargetProperties.__webglFramebuffer[i]);
  13573. renderTargetProperties.__webglDepthbuffer[i] = _gl.createRenderbuffer();
  13574. setupRenderBufferStorage(renderTargetProperties.__webglDepthbuffer[i], renderTarget);
  13575. }
  13576. } else {
  13577. _gl.bindFramebuffer(36160, renderTargetProperties.__webglFramebuffer);
  13578. renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer();
  13579. setupRenderBufferStorage(renderTargetProperties.__webglDepthbuffer, renderTarget);
  13580. }
  13581. }
  13582. _gl.bindFramebuffer(36160, null);
  13583. } // Set up GL resources for the render target
  13584. function setupRenderTarget(renderTarget) {
  13585. var renderTargetProperties = properties.get(renderTarget);
  13586. var textureProperties = properties.get(renderTarget.texture);
  13587. renderTarget.addEventListener('dispose', onRenderTargetDispose);
  13588. textureProperties.__webglTexture = _gl.createTexture();
  13589. info.memory.textures++;
  13590. var isCube = renderTarget.isWebGLRenderTargetCube === true;
  13591. var isMultisample = renderTarget.isWebGLMultisampleRenderTarget === true;
  13592. var isMultiview = renderTarget.isWebGLMultiviewRenderTarget === true;
  13593. var supportsMips = isPowerOfTwo(renderTarget) || capabilities.isWebGL2; // Setup framebuffer
  13594. if (isCube) {
  13595. renderTargetProperties.__webglFramebuffer = [];
  13596. for (var i = 0; i < 6; i++) {
  13597. renderTargetProperties.__webglFramebuffer[i] = _gl.createFramebuffer();
  13598. }
  13599. } else {
  13600. renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer();
  13601. if (isMultisample) {
  13602. if (capabilities.isWebGL2) {
  13603. renderTargetProperties.__webglMultisampledFramebuffer = _gl.createFramebuffer();
  13604. renderTargetProperties.__webglColorRenderbuffer = _gl.createRenderbuffer();
  13605. _gl.bindRenderbuffer(36161, renderTargetProperties.__webglColorRenderbuffer);
  13606. var glFormat = utils.convert(renderTarget.texture.format);
  13607. var glType = utils.convert(renderTarget.texture.type);
  13608. var glInternalFormat = getInternalFormat(glFormat, glType);
  13609. var samples = getRenderTargetSamples(renderTarget);
  13610. _gl.renderbufferStorageMultisample(36161, samples, glInternalFormat, renderTarget.width, renderTarget.height);
  13611. _gl.bindFramebuffer(36160, renderTargetProperties.__webglMultisampledFramebuffer);
  13612. _gl.framebufferRenderbuffer(36160, 36064, 36161, renderTargetProperties.__webglColorRenderbuffer);
  13613. _gl.bindRenderbuffer(36161, null);
  13614. if (renderTarget.depthBuffer) {
  13615. renderTargetProperties.__webglDepthRenderbuffer = _gl.createRenderbuffer();
  13616. setupRenderBufferStorage(renderTargetProperties.__webglDepthRenderbuffer, renderTarget, true);
  13617. }
  13618. _gl.bindFramebuffer(36160, null);
  13619. } else {
  13620. console.warn('THREE.WebGLRenderer: WebGLMultisampleRenderTarget can only be used with WebGL2.');
  13621. }
  13622. } else if (isMultiview) {
  13623. var width = renderTarget.width;
  13624. var height = renderTarget.height;
  13625. var numViews = renderTarget.numViews;
  13626. _gl.bindFramebuffer(36160, renderTargetProperties.__webglFramebuffer);
  13627. var ext = extensions.get('OVR_multiview2');
  13628. info.memory.textures += 2;
  13629. var colorTexture = _gl.createTexture();
  13630. _gl.bindTexture(35866, colorTexture);
  13631. _gl.texParameteri(35866, 10240, 9728);
  13632. _gl.texParameteri(35866, 10241, 9728);
  13633. _gl.texImage3D(35866, 0, 32856, width, height, numViews, 0, 6408, 5121, null);
  13634. ext.framebufferTextureMultiviewOVR(36160, 36064, colorTexture, 0, 0, numViews);
  13635. var depthStencilTexture = _gl.createTexture();
  13636. _gl.bindTexture(35866, depthStencilTexture);
  13637. _gl.texParameteri(35866, 10240, 9728);
  13638. _gl.texParameteri(35866, 10241, 9728);
  13639. _gl.texImage3D(35866, 0, 35056, width, height, numViews, 0, 34041, 34042, null);
  13640. ext.framebufferTextureMultiviewOVR(36160, 33306, depthStencilTexture, 0, 0, numViews);
  13641. var viewFramebuffers = new Array(numViews);
  13642. for (var i = 0; i < numViews; ++i) {
  13643. viewFramebuffers[i] = _gl.createFramebuffer();
  13644. _gl.bindFramebuffer(36160, viewFramebuffers[i]);
  13645. _gl.framebufferTextureLayer(36160, 36064, colorTexture, 0, i);
  13646. }
  13647. renderTargetProperties.__webglColorTexture = colorTexture;
  13648. renderTargetProperties.__webglDepthStencilTexture = depthStencilTexture;
  13649. renderTargetProperties.__webglViewFramebuffers = viewFramebuffers;
  13650. _gl.bindFramebuffer(36160, null);
  13651. _gl.bindTexture(35866, null);
  13652. }
  13653. } // Setup color buffer
  13654. if (isCube) {
  13655. state.bindTexture(34067, textureProperties.__webglTexture);
  13656. setTextureParameters(34067, renderTarget.texture, supportsMips);
  13657. for (var i = 0; i < 6; i++) {
  13658. setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer[i], renderTarget, 36064, 34069 + i);
  13659. }
  13660. if (textureNeedsGenerateMipmaps(renderTarget.texture, supportsMips)) {
  13661. generateMipmap(34067, renderTarget.texture, renderTarget.width, renderTarget.height);
  13662. }
  13663. state.bindTexture(34067, null);
  13664. } else if (!isMultiview) {
  13665. state.bindTexture(3553, textureProperties.__webglTexture);
  13666. setTextureParameters(3553, renderTarget.texture, supportsMips);
  13667. setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer, renderTarget, 36064, 3553);
  13668. if (textureNeedsGenerateMipmaps(renderTarget.texture, supportsMips)) {
  13669. generateMipmap(3553, renderTarget.texture, renderTarget.width, renderTarget.height);
  13670. }
  13671. state.bindTexture(3553, null);
  13672. } // Setup depth and stencil buffers
  13673. if (renderTarget.depthBuffer) {
  13674. setupDepthRenderbuffer(renderTarget);
  13675. }
  13676. }
  13677. function updateRenderTargetMipmap(renderTarget) {
  13678. var texture = renderTarget.texture;
  13679. var supportsMips = isPowerOfTwo(renderTarget) || capabilities.isWebGL2;
  13680. if (textureNeedsGenerateMipmaps(texture, supportsMips)) {
  13681. var target = renderTarget.isWebGLRenderTargetCube ? 34067 : 3553;
  13682. var webglTexture = properties.get(texture).__webglTexture;
  13683. state.bindTexture(target, webglTexture);
  13684. generateMipmap(target, texture, renderTarget.width, renderTarget.height);
  13685. state.bindTexture(target, null);
  13686. }
  13687. }
  13688. function updateMultisampleRenderTarget(renderTarget) {
  13689. if (renderTarget.isWebGLMultisampleRenderTarget) {
  13690. if (capabilities.isWebGL2) {
  13691. var renderTargetProperties = properties.get(renderTarget);
  13692. _gl.bindFramebuffer(36008, renderTargetProperties.__webglMultisampledFramebuffer);
  13693. _gl.bindFramebuffer(36009, renderTargetProperties.__webglFramebuffer);
  13694. var width = renderTarget.width;
  13695. var height = renderTarget.height;
  13696. var mask = 16384;
  13697. if (renderTarget.depthBuffer) mask |= 256;
  13698. if (renderTarget.stencilBuffer) mask |= 1024;
  13699. _gl.blitFramebuffer(0, 0, width, height, 0, 0, width, height, mask, 9728);
  13700. } else {
  13701. console.warn('THREE.WebGLRenderer: WebGLMultisampleRenderTarget can only be used with WebGL2.');
  13702. }
  13703. }
  13704. }
  13705. function getRenderTargetSamples(renderTarget) {
  13706. return capabilities.isWebGL2 && renderTarget.isWebGLMultisampleRenderTarget ? Math.min(capabilities.maxSamples, renderTarget.samples) : 0;
  13707. }
  13708. function updateVideoTexture(texture) {
  13709. var frame = info.render.frame; // Check the last frame we updated the VideoTexture
  13710. if (_videoTextures.get(texture) !== frame) {
  13711. _videoTextures.set(texture, frame);
  13712. texture.update();
  13713. }
  13714. } // backwards compatibility
  13715. var warnedTexture2D = false;
  13716. var warnedTextureCube = false;
  13717. function safeSetTexture2D(texture, slot) {
  13718. if (texture && texture.isWebGLRenderTarget) {
  13719. if (warnedTexture2D === false) {
  13720. console.warn("THREE.WebGLTextures.safeSetTexture2D: don't use render targets as textures. Use their .texture property instead.");
  13721. warnedTexture2D = true;
  13722. }
  13723. texture = texture.texture;
  13724. }
  13725. setTexture2D(texture, slot);
  13726. }
  13727. function safeSetTextureCube(texture, slot) {
  13728. if (texture && texture.isWebGLRenderTargetCube) {
  13729. if (warnedTextureCube === false) {
  13730. console.warn("THREE.WebGLTextures.safeSetTextureCube: don't use cube render targets as textures. Use their .texture property instead.");
  13731. warnedTextureCube = true;
  13732. }
  13733. texture = texture.texture;
  13734. } // currently relying on the fact that WebGLRenderTargetCube.texture is a Texture and NOT a CubeTexture
  13735. // TODO: unify these code paths
  13736. if (texture && texture.isCubeTexture || Array.isArray(texture.image) && texture.image.length === 6) {
  13737. // CompressedTexture can have Array in image :/
  13738. // this function alone should take care of cube textures
  13739. setTextureCube(texture, slot);
  13740. } else {
  13741. // assumed: texture property of THREE.WebGLRenderTargetCube
  13742. setTextureCubeDynamic(texture, slot);
  13743. }
  13744. } //
  13745. this.allocateTextureUnit = allocateTextureUnit;
  13746. this.resetTextureUnits = resetTextureUnits;
  13747. this.setTexture2D = setTexture2D;
  13748. this.setTexture2DArray = setTexture2DArray;
  13749. this.setTexture3D = setTexture3D;
  13750. this.setTextureCube = setTextureCube;
  13751. this.setTextureCubeDynamic = setTextureCubeDynamic;
  13752. this.setupRenderTarget = setupRenderTarget;
  13753. this.updateRenderTargetMipmap = updateRenderTargetMipmap;
  13754. this.updateMultisampleRenderTarget = updateMultisampleRenderTarget;
  13755. this.safeSetTexture2D = safeSetTexture2D;
  13756. this.safeSetTextureCube = safeSetTextureCube;
  13757. }
  13758. /**
  13759. * @author thespite / http://www.twitter.com/thespite
  13760. */
  13761. function WebGLUtils(gl, extensions, capabilities) {
  13762. function convert(p) {
  13763. var extension;
  13764. if (p === RepeatWrapping) return 10497;
  13765. if (p === ClampToEdgeWrapping) return 33071;
  13766. if (p === MirroredRepeatWrapping) return 33648;
  13767. if (p === NearestFilter) return 9728;
  13768. if (p === NearestMipmapNearestFilter) return 9984;
  13769. if (p === NearestMipmapLinearFilter) return 9986;
  13770. if (p === LinearFilter) return 9729;
  13771. if (p === LinearMipmapNearestFilter) return 9985;
  13772. if (p === LinearMipmapLinearFilter) return 9987;
  13773. if (p === UnsignedByteType) return 5121;
  13774. if (p === UnsignedShort4444Type) return 32819;
  13775. if (p === UnsignedShort5551Type) return 32820;
  13776. if (p === UnsignedShort565Type) return 33635;
  13777. if (p === ByteType) return 5120;
  13778. if (p === ShortType) return 5122;
  13779. if (p === UnsignedShortType) return 5123;
  13780. if (p === IntType) return 5124;
  13781. if (p === UnsignedIntType) return 5125;
  13782. if (p === FloatType) return 5126;
  13783. if (p === HalfFloatType) {
  13784. if (capabilities.isWebGL2) return 5131;
  13785. extension = extensions.get('OES_texture_half_float');
  13786. if (extension !== null) return extension.HALF_FLOAT_OES;
  13787. }
  13788. if (p === AlphaFormat) return 6406;
  13789. if (p === RGBFormat) return 6407;
  13790. if (p === RGBAFormat) return 6408;
  13791. if (p === LuminanceFormat) return 6409;
  13792. if (p === LuminanceAlphaFormat) return 6410;
  13793. if (p === DepthFormat) return 6402;
  13794. if (p === DepthStencilFormat) return 34041;
  13795. if (p === RedFormat) return 6403;
  13796. if (p === AddEquation) return 32774;
  13797. if (p === SubtractEquation) return 32778;
  13798. if (p === ReverseSubtractEquation) return 32779;
  13799. if (p === ZeroFactor) return 0;
  13800. if (p === OneFactor) return 1;
  13801. if (p === SrcColorFactor) return 768;
  13802. if (p === OneMinusSrcColorFactor) return 769;
  13803. if (p === SrcAlphaFactor) return 770;
  13804. if (p === OneMinusSrcAlphaFactor) return 771;
  13805. if (p === DstAlphaFactor) return 772;
  13806. if (p === OneMinusDstAlphaFactor) return 773;
  13807. if (p === DstColorFactor) return 774;
  13808. if (p === OneMinusDstColorFactor) return 775;
  13809. if (p === SrcAlphaSaturateFactor) return 776;
  13810. if (p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format) {
  13811. extension = extensions.get('WEBGL_compressed_texture_s3tc');
  13812. if (extension !== null) {
  13813. if (p === RGB_S3TC_DXT1_Format) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  13814. if (p === RGBA_S3TC_DXT1_Format) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  13815. if (p === RGBA_S3TC_DXT3_Format) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  13816. if (p === RGBA_S3TC_DXT5_Format) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  13817. }
  13818. }
  13819. if (p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format) {
  13820. extension = extensions.get('WEBGL_compressed_texture_pvrtc');
  13821. if (extension !== null) {
  13822. if (p === RGB_PVRTC_4BPPV1_Format) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  13823. if (p === RGB_PVRTC_2BPPV1_Format) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  13824. if (p === RGBA_PVRTC_4BPPV1_Format) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  13825. if (p === RGBA_PVRTC_2BPPV1_Format) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  13826. }
  13827. }
  13828. if (p === RGB_ETC1_Format) {
  13829. extension = extensions.get('WEBGL_compressed_texture_etc1');
  13830. if (extension !== null) return extension.COMPRESSED_RGB_ETC1_WEBGL;
  13831. }
  13832. 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) {
  13833. extension = extensions.get('WEBGL_compressed_texture_astc');
  13834. if (extension !== null) {
  13835. return p;
  13836. }
  13837. }
  13838. if (p === MinEquation || p === MaxEquation) {
  13839. if (capabilities.isWebGL2) {
  13840. if (p === MinEquation) return 32775;
  13841. if (p === MaxEquation) return 32776;
  13842. }
  13843. extension = extensions.get('EXT_blend_minmax');
  13844. if (extension !== null) {
  13845. if (p === MinEquation) return extension.MIN_EXT;
  13846. if (p === MaxEquation) return extension.MAX_EXT;
  13847. }
  13848. }
  13849. if (p === UnsignedInt248Type) {
  13850. if (capabilities.isWebGL2) return 34042;
  13851. extension = extensions.get('WEBGL_depth_texture');
  13852. if (extension !== null) return extension.UNSIGNED_INT_24_8_WEBGL;
  13853. }
  13854. return 0;
  13855. }
  13856. return {
  13857. convert: convert
  13858. };
  13859. }
  13860. /**
  13861. * @author fernandojsg / http://fernandojsg.com
  13862. * @author Takahiro https://github.com/takahirox
  13863. */
  13864. function WebGLMultiviewRenderTarget(width, height, numViews, options) {
  13865. WebGLRenderTarget.call(this, width, height, options);
  13866. this.depthBuffer = false;
  13867. this.stencilBuffer = false;
  13868. this.numViews = numViews;
  13869. }
  13870. WebGLMultiviewRenderTarget.prototype = Object.assign(Object.create(WebGLRenderTarget.prototype), {
  13871. constructor: WebGLMultiviewRenderTarget,
  13872. isWebGLMultiviewRenderTarget: true,
  13873. copy: function (source) {
  13874. WebGLRenderTarget.prototype.copy.call(this, source);
  13875. this.numViews = source.numViews;
  13876. return this;
  13877. },
  13878. setNumViews: function (numViews) {
  13879. if (this.numViews !== numViews) {
  13880. this.numViews = numViews;
  13881. this.dispose();
  13882. }
  13883. return this;
  13884. }
  13885. });
  13886. /**
  13887. * @author fernandojsg / http://fernandojsg.com
  13888. * @author Takahiro https://github.com/takahirox
  13889. */
  13890. function WebGLMultiview(renderer, gl) {
  13891. var DEFAULT_NUMVIEWS = 2;
  13892. var extensions = renderer.extensions;
  13893. var properties = renderer.properties;
  13894. var renderTarget, currentRenderTarget;
  13895. var mat3, mat4, cameraArray, renderSize;
  13896. var available;
  13897. var maxNumViews = 0; //
  13898. function isAvailable() {
  13899. if (available === undefined) {
  13900. var extension = extensions.get('OVR_multiview2');
  13901. available = extension !== null && gl.getContextAttributes().antialias === false;
  13902. if (available) {
  13903. maxNumViews = gl.getParameter(extension.MAX_VIEWS_OVR);
  13904. renderTarget = new WebGLMultiviewRenderTarget(0, 0, DEFAULT_NUMVIEWS);
  13905. renderSize = new Vector2();
  13906. mat4 = [];
  13907. mat3 = [];
  13908. cameraArray = [];
  13909. for (var i = 0; i < maxNumViews; i++) {
  13910. mat4[i] = new Matrix4();
  13911. mat3[i] = new Matrix3();
  13912. }
  13913. }
  13914. }
  13915. return available;
  13916. }
  13917. function getCameraArray(camera) {
  13918. if (camera.isArrayCamera) return camera.cameras;
  13919. cameraArray[0] = camera;
  13920. return cameraArray;
  13921. }
  13922. function updateCameraProjectionMatricesUniform(camera, uniforms) {
  13923. var cameras = getCameraArray(camera);
  13924. for (var i = 0; i < cameras.length; i++) {
  13925. mat4[i].copy(cameras[i].projectionMatrix);
  13926. }
  13927. uniforms.setValue(gl, 'projectionMatrices', mat4);
  13928. }
  13929. function updateCameraViewMatricesUniform(camera, uniforms) {
  13930. var cameras = getCameraArray(camera);
  13931. for (var i = 0; i < cameras.length; i++) {
  13932. mat4[i].copy(cameras[i].matrixWorldInverse);
  13933. }
  13934. uniforms.setValue(gl, 'viewMatrices', mat4);
  13935. }
  13936. function updateObjectMatricesUniforms(object, camera, uniforms) {
  13937. var cameras = getCameraArray(camera);
  13938. for (var i = 0; i < cameras.length; i++) {
  13939. mat4[i].multiplyMatrices(cameras[i].matrixWorldInverse, object.matrixWorld);
  13940. mat3[i].getNormalMatrix(mat4[i]);
  13941. }
  13942. uniforms.setValue(gl, 'modelViewMatrices', mat4);
  13943. uniforms.setValue(gl, 'normalMatrices', mat3);
  13944. }
  13945. function isMultiviewCompatible(camera) {
  13946. if (camera.isArrayCamera === undefined) return true;
  13947. var cameras = camera.cameras;
  13948. if (cameras.length > maxNumViews) return false;
  13949. for (var i = 1, il = cameras.length; i < il; i++) {
  13950. if (cameras[0].viewport.z !== cameras[i].viewport.z || cameras[0].viewport.w !== cameras[i].viewport.w) return false;
  13951. }
  13952. return true;
  13953. }
  13954. function resizeRenderTarget(camera) {
  13955. if (currentRenderTarget) {
  13956. renderSize.set(currentRenderTarget.width, currentRenderTarget.height);
  13957. } else {
  13958. renderer.getDrawingBufferSize(renderSize);
  13959. }
  13960. if (camera.isArrayCamera) {
  13961. var viewport = camera.cameras[0].viewport;
  13962. renderTarget.setSize(viewport.z, viewport.w);
  13963. renderTarget.setNumViews(camera.cameras.length);
  13964. } else {
  13965. renderTarget.setSize(renderSize.x, renderSize.y);
  13966. renderTarget.setNumViews(DEFAULT_NUMVIEWS);
  13967. }
  13968. }
  13969. function attachCamera(camera) {
  13970. if (isMultiviewCompatible(camera) === false) return;
  13971. currentRenderTarget = renderer.getRenderTarget();
  13972. resizeRenderTarget(camera);
  13973. renderer.setRenderTarget(renderTarget);
  13974. }
  13975. function detachCamera(camera) {
  13976. if (renderTarget !== renderer.getRenderTarget()) return;
  13977. renderer.setRenderTarget(currentRenderTarget);
  13978. flush(camera);
  13979. }
  13980. function flush(camera) {
  13981. var srcRenderTarget = renderTarget;
  13982. var numViews = srcRenderTarget.numViews;
  13983. var srcFramebuffers = properties.get(srcRenderTarget).__webglViewFramebuffers;
  13984. var viewWidth = srcRenderTarget.width;
  13985. var viewHeight = srcRenderTarget.height;
  13986. if (camera.isArrayCamera) {
  13987. for (var i = 0; i < numViews; i++) {
  13988. var viewport = camera.cameras[i].viewport;
  13989. var x1 = viewport.x;
  13990. var y1 = viewport.y;
  13991. var x2 = x1 + viewport.z;
  13992. var y2 = y1 + viewport.w;
  13993. gl.bindFramebuffer(36008, srcFramebuffers[i]);
  13994. gl.blitFramebuffer(0, 0, viewWidth, viewHeight, x1, y1, x2, y2, 16384, 9728);
  13995. }
  13996. } else {
  13997. gl.bindFramebuffer(36008, srcFramebuffers[0]);
  13998. gl.blitFramebuffer(0, 0, viewWidth, viewHeight, 0, 0, renderSize.x, renderSize.y, 16384, 9728);
  13999. }
  14000. }
  14001. this.isAvailable = isAvailable;
  14002. this.attachCamera = attachCamera;
  14003. this.detachCamera = detachCamera;
  14004. this.updateCameraProjectionMatricesUniform = updateCameraProjectionMatricesUniform;
  14005. this.updateCameraViewMatricesUniform = updateCameraViewMatricesUniform;
  14006. this.updateObjectMatricesUniforms = updateObjectMatricesUniforms;
  14007. }
  14008. /**
  14009. * @author mrdoob / http://mrdoob.com/
  14010. */
  14011. function Group() {
  14012. Object3D.call(this);
  14013. this.type = 'Group';
  14014. }
  14015. Group.prototype = Object.assign(Object.create(Object3D.prototype), {
  14016. constructor: Group,
  14017. isGroup: true
  14018. });
  14019. /**
  14020. * @author mrdoob / http://mrdoob.com/
  14021. */
  14022. function ArrayCamera(array) {
  14023. PerspectiveCamera.call(this);
  14024. this.cameras = array || [];
  14025. }
  14026. ArrayCamera.prototype = Object.assign(Object.create(PerspectiveCamera.prototype), {
  14027. constructor: ArrayCamera,
  14028. isArrayCamera: true
  14029. });
  14030. /**
  14031. * @author jsantell / https://www.jsantell.com/
  14032. * @author mrdoob / http://mrdoob.com/
  14033. */
  14034. var cameraLPos = new Vector3();
  14035. var cameraRPos = new Vector3();
  14036. /**
  14037. * Assumes 2 cameras that are parallel and share an X-axis, and that
  14038. * the cameras' projection and world matrices have already been set.
  14039. * And that near and far planes are identical for both cameras.
  14040. * Visualization of this technique: https://computergraphics.stackexchange.com/a/4765
  14041. */
  14042. function setProjectionFromUnion(camera, cameraL, cameraR) {
  14043. cameraLPos.setFromMatrixPosition(cameraL.matrixWorld);
  14044. cameraRPos.setFromMatrixPosition(cameraR.matrixWorld);
  14045. var ipd = cameraLPos.distanceTo(cameraRPos);
  14046. var projL = cameraL.projectionMatrix.elements;
  14047. var projR = cameraR.projectionMatrix.elements; // VR systems will have identical far and near planes, and
  14048. // most likely identical top and bottom frustum extents.
  14049. // Use the left camera for these values.
  14050. var near = projL[14] / (projL[10] - 1);
  14051. var far = projL[14] / (projL[10] + 1);
  14052. var topFov = (projL[9] + 1) / projL[5];
  14053. var bottomFov = (projL[9] - 1) / projL[5];
  14054. var leftFov = (projL[8] - 1) / projL[0];
  14055. var rightFov = (projR[8] + 1) / projR[0];
  14056. var left = near * leftFov;
  14057. var right = near * rightFov; // Calculate the new camera's position offset from the
  14058. // left camera. xOffset should be roughly half `ipd`.
  14059. var zOffset = ipd / (-leftFov + rightFov);
  14060. var xOffset = zOffset * -leftFov; // TODO: Better way to apply this offset?
  14061. cameraL.matrixWorld.decompose(camera.position, camera.quaternion, camera.scale);
  14062. camera.translateX(xOffset);
  14063. camera.translateZ(zOffset);
  14064. camera.matrixWorld.compose(camera.position, camera.quaternion, camera.scale);
  14065. camera.matrixWorldInverse.getInverse(camera.matrixWorld); // Find the union of the frustum values of the cameras and scale
  14066. // the values so that the near plane's position does not change in world space,
  14067. // although must now be relative to the new union camera.
  14068. var near2 = near + zOffset;
  14069. var far2 = far + zOffset;
  14070. var left2 = left - xOffset;
  14071. var right2 = right + (ipd - xOffset);
  14072. var top2 = topFov * far / far2 * near2;
  14073. var bottom2 = bottomFov * far / far2 * near2;
  14074. camera.projectionMatrix.makePerspective(left2, right2, top2, bottom2, near2, far2);
  14075. }
  14076. /**
  14077. * @author mrdoob / http://mrdoob.com/
  14078. */
  14079. function WebVRManager(renderer) {
  14080. var renderWidth, renderHeight;
  14081. var scope = this;
  14082. var device = null;
  14083. var frameData = null;
  14084. var poseTarget = null;
  14085. var controllers = [];
  14086. var standingMatrix = new Matrix4();
  14087. var standingMatrixInverse = new Matrix4();
  14088. var framebufferScaleFactor = 1.0;
  14089. var referenceSpaceType = 'local-floor';
  14090. if (typeof window !== 'undefined' && 'VRFrameData' in window) {
  14091. frameData = new window.VRFrameData();
  14092. window.addEventListener('vrdisplaypresentchange', onVRDisplayPresentChange, false);
  14093. }
  14094. var matrixWorldInverse = new Matrix4();
  14095. var tempQuaternion = new Quaternion();
  14096. var tempPosition = new Vector3();
  14097. var cameraL = new PerspectiveCamera();
  14098. cameraL.viewport = new Vector4();
  14099. cameraL.layers.enable(1);
  14100. var cameraR = new PerspectiveCamera();
  14101. cameraR.viewport = new Vector4();
  14102. cameraR.layers.enable(2);
  14103. var cameraVR = new ArrayCamera([cameraL, cameraR]);
  14104. cameraVR.layers.enable(1);
  14105. cameraVR.layers.enable(2); //
  14106. function isPresenting() {
  14107. return device !== null && device.isPresenting === true;
  14108. }
  14109. var currentSize = new Vector2(),
  14110. currentPixelRatio;
  14111. function onVRDisplayPresentChange() {
  14112. if (isPresenting()) {
  14113. var eyeParameters = device.getEyeParameters('left');
  14114. renderWidth = 2 * eyeParameters.renderWidth * framebufferScaleFactor;
  14115. renderHeight = eyeParameters.renderHeight * framebufferScaleFactor;
  14116. currentPixelRatio = renderer.getPixelRatio();
  14117. renderer.getSize(currentSize);
  14118. renderer.setDrawingBufferSize(renderWidth, renderHeight, 1);
  14119. cameraL.viewport.set(0, 0, renderWidth / 2, renderHeight);
  14120. cameraR.viewport.set(renderWidth / 2, 0, renderWidth / 2, renderHeight);
  14121. animation.start();
  14122. scope.dispatchEvent({
  14123. type: 'sessionstart'
  14124. });
  14125. } else {
  14126. if (scope.enabled) {
  14127. renderer.setDrawingBufferSize(currentSize.width, currentSize.height, currentPixelRatio);
  14128. }
  14129. animation.stop();
  14130. scope.dispatchEvent({
  14131. type: 'sessionend'
  14132. });
  14133. }
  14134. } //
  14135. var triggers = [];
  14136. function findGamepad(id) {
  14137. var gamepads = navigator.getGamepads && navigator.getGamepads();
  14138. for (var i = 0, j = 0, l = gamepads.length; i < l; i++) {
  14139. var gamepad = gamepads[i];
  14140. 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'))) {
  14141. if (j === id) return gamepad;
  14142. j++;
  14143. }
  14144. }
  14145. }
  14146. function updateControllers() {
  14147. for (var i = 0; i < controllers.length; i++) {
  14148. var controller = controllers[i];
  14149. var gamepad = findGamepad(i);
  14150. if (gamepad !== undefined && gamepad.pose !== undefined) {
  14151. if (gamepad.pose === null) return; // Pose
  14152. var pose = gamepad.pose;
  14153. if (pose.hasPosition === false) controller.position.set(0.2, -0.6, -0.05);
  14154. if (pose.position !== null) controller.position.fromArray(pose.position);
  14155. if (pose.orientation !== null) controller.quaternion.fromArray(pose.orientation);
  14156. controller.matrix.compose(controller.position, controller.quaternion, controller.scale);
  14157. controller.matrix.premultiply(standingMatrix);
  14158. controller.matrix.decompose(controller.position, controller.quaternion, controller.scale);
  14159. controller.matrixWorldNeedsUpdate = true;
  14160. controller.visible = true; // Trigger
  14161. var buttonId = gamepad.id === 'Daydream Controller' ? 0 : 1;
  14162. if (triggers[i] === undefined) triggers[i] = false;
  14163. if (triggers[i] !== gamepad.buttons[buttonId].pressed) {
  14164. triggers[i] = gamepad.buttons[buttonId].pressed;
  14165. if (triggers[i] === true) {
  14166. controller.dispatchEvent({
  14167. type: 'selectstart'
  14168. });
  14169. } else {
  14170. controller.dispatchEvent({
  14171. type: 'selectend'
  14172. });
  14173. controller.dispatchEvent({
  14174. type: 'select'
  14175. });
  14176. }
  14177. }
  14178. } else {
  14179. controller.visible = false;
  14180. }
  14181. }
  14182. }
  14183. function updateViewportFromBounds(viewport, bounds) {
  14184. if (bounds !== null && bounds.length === 4) {
  14185. viewport.set(bounds[0] * renderWidth, bounds[1] * renderHeight, bounds[2] * renderWidth, bounds[3] * renderHeight);
  14186. }
  14187. } //
  14188. this.enabled = false;
  14189. this.getController = function (id) {
  14190. var controller = controllers[id];
  14191. if (controller === undefined) {
  14192. controller = new Group();
  14193. controller.matrixAutoUpdate = false;
  14194. controller.visible = false;
  14195. controllers[id] = controller;
  14196. }
  14197. return controller;
  14198. };
  14199. this.getDevice = function () {
  14200. return device;
  14201. };
  14202. this.setDevice = function (value) {
  14203. if (value !== undefined) device = value;
  14204. animation.setContext(value);
  14205. };
  14206. this.setFramebufferScaleFactor = function (value) {
  14207. framebufferScaleFactor = value;
  14208. };
  14209. this.setReferenceSpaceType = function (value) {
  14210. referenceSpaceType = value;
  14211. };
  14212. this.setPoseTarget = function (object) {
  14213. if (object !== undefined) poseTarget = object;
  14214. };
  14215. this.getCamera = function (camera) {
  14216. var userHeight = referenceSpaceType === 'local-floor' ? 1.6 : 0;
  14217. if (isPresenting() === false) {
  14218. camera.position.set(0, userHeight, 0);
  14219. camera.rotation.set(0, 0, 0);
  14220. return camera;
  14221. }
  14222. device.depthNear = camera.near;
  14223. device.depthFar = camera.far;
  14224. device.getFrameData(frameData); //
  14225. if (referenceSpaceType === 'local-floor') {
  14226. var stageParameters = device.stageParameters;
  14227. if (stageParameters) {
  14228. standingMatrix.fromArray(stageParameters.sittingToStandingTransform);
  14229. } else {
  14230. standingMatrix.makeTranslation(0, userHeight, 0);
  14231. }
  14232. }
  14233. var pose = frameData.pose;
  14234. var poseObject = poseTarget !== null ? poseTarget : camera; // We want to manipulate poseObject by its position and quaternion components since users may rely on them.
  14235. poseObject.matrix.copy(standingMatrix);
  14236. poseObject.matrix.decompose(poseObject.position, poseObject.quaternion, poseObject.scale);
  14237. if (pose.orientation !== null) {
  14238. tempQuaternion.fromArray(pose.orientation);
  14239. poseObject.quaternion.multiply(tempQuaternion);
  14240. }
  14241. if (pose.position !== null) {
  14242. tempQuaternion.setFromRotationMatrix(standingMatrix);
  14243. tempPosition.fromArray(pose.position);
  14244. tempPosition.applyQuaternion(tempQuaternion);
  14245. poseObject.position.add(tempPosition);
  14246. }
  14247. poseObject.updateMatrixWorld(); //
  14248. cameraL.near = camera.near;
  14249. cameraR.near = camera.near;
  14250. cameraL.far = camera.far;
  14251. cameraR.far = camera.far;
  14252. cameraL.matrixWorldInverse.fromArray(frameData.leftViewMatrix);
  14253. cameraR.matrixWorldInverse.fromArray(frameData.rightViewMatrix); // TODO (mrdoob) Double check this code
  14254. standingMatrixInverse.getInverse(standingMatrix);
  14255. if (referenceSpaceType === 'local-floor') {
  14256. cameraL.matrixWorldInverse.multiply(standingMatrixInverse);
  14257. cameraR.matrixWorldInverse.multiply(standingMatrixInverse);
  14258. }
  14259. var parent = poseObject.parent;
  14260. if (parent !== null) {
  14261. matrixWorldInverse.getInverse(parent.matrixWorld);
  14262. cameraL.matrixWorldInverse.multiply(matrixWorldInverse);
  14263. cameraR.matrixWorldInverse.multiply(matrixWorldInverse);
  14264. } // envMap and Mirror needs camera.matrixWorld
  14265. cameraL.matrixWorld.getInverse(cameraL.matrixWorldInverse);
  14266. cameraR.matrixWorld.getInverse(cameraR.matrixWorldInverse);
  14267. cameraL.projectionMatrix.fromArray(frameData.leftProjectionMatrix);
  14268. cameraR.projectionMatrix.fromArray(frameData.rightProjectionMatrix);
  14269. setProjectionFromUnion(cameraVR, cameraL, cameraR); //
  14270. var layers = device.getLayers();
  14271. if (layers.length) {
  14272. var layer = layers[0];
  14273. updateViewportFromBounds(cameraL.viewport, layer.leftBounds);
  14274. updateViewportFromBounds(cameraR.viewport, layer.rightBounds);
  14275. }
  14276. updateControllers();
  14277. return cameraVR;
  14278. };
  14279. this.getStandingMatrix = function () {
  14280. return standingMatrix;
  14281. };
  14282. this.isPresenting = isPresenting; // Animation Loop
  14283. var animation = new WebGLAnimation();
  14284. this.setAnimationLoop = function (callback) {
  14285. animation.setAnimationLoop(callback);
  14286. if (isPresenting()) animation.start();
  14287. };
  14288. this.submitFrame = function () {
  14289. if (isPresenting()) device.submitFrame();
  14290. };
  14291. this.dispose = function () {
  14292. if (typeof window !== 'undefined') {
  14293. window.removeEventListener('vrdisplaypresentchange', onVRDisplayPresentChange);
  14294. }
  14295. }; // DEPRECATED
  14296. this.setFrameOfReferenceType = function () {
  14297. console.warn('THREE.WebVRManager: setFrameOfReferenceType() has been deprecated.');
  14298. };
  14299. }
  14300. Object.assign(WebVRManager.prototype, EventDispatcher.prototype);
  14301. /**
  14302. * @author mrdoob / http://mrdoob.com/
  14303. */
  14304. function WebXRManager(renderer, gl) {
  14305. var scope = this;
  14306. var session = null; // var framebufferScaleFactor = 1.0;
  14307. var referenceSpace = null;
  14308. var referenceSpaceType = 'local-floor';
  14309. var pose = null;
  14310. var controllers = [];
  14311. var inputSources = [];
  14312. function isPresenting() {
  14313. return session !== null && referenceSpace !== null;
  14314. } //
  14315. var cameraL = new PerspectiveCamera();
  14316. cameraL.layers.enable(1);
  14317. cameraL.viewport = new Vector4();
  14318. var cameraR = new PerspectiveCamera();
  14319. cameraR.layers.enable(2);
  14320. cameraR.viewport = new Vector4();
  14321. var cameraVR = new ArrayCamera([cameraL, cameraR]);
  14322. cameraVR.layers.enable(1);
  14323. cameraVR.layers.enable(2); //
  14324. this.enabled = false;
  14325. this.getController = function (id) {
  14326. var controller = controllers[id];
  14327. if (controller === undefined) {
  14328. controller = new Group();
  14329. controller.matrixAutoUpdate = false;
  14330. controller.visible = false;
  14331. controllers[id] = controller;
  14332. }
  14333. return controller;
  14334. }; //
  14335. function onSessionEvent(event) {
  14336. for (var i = 0; i < controllers.length; i++) {
  14337. if (inputSources[i] === event.inputSource) {
  14338. controllers[i].dispatchEvent({
  14339. type: event.type
  14340. });
  14341. }
  14342. }
  14343. }
  14344. function onSessionEnd() {
  14345. renderer.setFramebuffer(null);
  14346. renderer.setRenderTarget(renderer.getRenderTarget()); // Hack #15830
  14347. animation.stop();
  14348. scope.dispatchEvent({
  14349. type: 'sessionend'
  14350. });
  14351. }
  14352. function onRequestReferenceSpace(value) {
  14353. referenceSpace = value;
  14354. animation.setContext(session);
  14355. animation.start();
  14356. scope.dispatchEvent({
  14357. type: 'sessionstart'
  14358. });
  14359. }
  14360. this.setFramebufferScaleFactor = function ()
  14361. /* value */
  14362. {// framebufferScaleFactor = value;
  14363. };
  14364. this.setReferenceSpaceType = function (value) {
  14365. referenceSpaceType = value;
  14366. };
  14367. this.getSession = function () {
  14368. return session;
  14369. };
  14370. this.setSession = function (value) {
  14371. session = value;
  14372. if (session !== null) {
  14373. session.addEventListener('select', onSessionEvent);
  14374. session.addEventListener('selectstart', onSessionEvent);
  14375. session.addEventListener('selectend', onSessionEvent);
  14376. session.addEventListener('end', onSessionEnd); // eslint-disable-next-line no-undef
  14377. session.updateRenderState({
  14378. baseLayer: new XRWebGLLayer(session, gl)
  14379. });
  14380. session.requestReferenceSpace(referenceSpaceType).then(onRequestReferenceSpace); //
  14381. inputSources = session.inputSources;
  14382. session.addEventListener('inputsourceschange', function () {
  14383. inputSources = session.inputSources;
  14384. console.log(inputSources);
  14385. for (var i = 0; i < controllers.length; i++) {
  14386. var controller = controllers[i];
  14387. controller.userData.inputSource = inputSources[i];
  14388. }
  14389. });
  14390. }
  14391. };
  14392. function updateCamera(camera, parent) {
  14393. if (parent === null) {
  14394. camera.matrixWorld.copy(camera.matrix);
  14395. } else {
  14396. camera.matrixWorld.multiplyMatrices(parent.matrixWorld, camera.matrix);
  14397. }
  14398. camera.matrixWorldInverse.getInverse(camera.matrixWorld);
  14399. }
  14400. this.getCamera = function (camera) {
  14401. if (isPresenting()) {
  14402. var parent = camera.parent;
  14403. var cameras = cameraVR.cameras;
  14404. updateCamera(cameraVR, parent);
  14405. for (var i = 0; i < cameras.length; i++) {
  14406. updateCamera(cameras[i], parent);
  14407. } // update camera and its children
  14408. camera.matrixWorld.copy(cameraVR.matrixWorld);
  14409. var children = camera.children;
  14410. for (var i = 0, l = children.length; i < l; i++) {
  14411. children[i].updateMatrixWorld(true);
  14412. }
  14413. setProjectionFromUnion(cameraVR, cameraL, cameraR);
  14414. return cameraVR;
  14415. }
  14416. return camera;
  14417. };
  14418. this.isPresenting = isPresenting; // Animation Loop
  14419. var onAnimationFrameCallback = null;
  14420. function onAnimationFrame(time, frame) {
  14421. pose = frame.getViewerPose(referenceSpace);
  14422. if (pose !== null) {
  14423. var views = pose.views;
  14424. var baseLayer = session.renderState.baseLayer;
  14425. renderer.setFramebuffer(baseLayer.framebuffer);
  14426. for (var i = 0; i < views.length; i++) {
  14427. var view = views[i];
  14428. var viewport = baseLayer.getViewport(view);
  14429. var viewMatrix = view.transform.inverse.matrix;
  14430. var camera = cameraVR.cameras[i];
  14431. camera.matrix.fromArray(viewMatrix).getInverse(camera.matrix);
  14432. camera.projectionMatrix.fromArray(view.projectionMatrix);
  14433. camera.viewport.set(viewport.x, viewport.y, viewport.width, viewport.height);
  14434. if (i === 0) {
  14435. cameraVR.matrix.copy(camera.matrix);
  14436. }
  14437. }
  14438. } //
  14439. for (var i = 0; i < controllers.length; i++) {
  14440. var controller = controllers[i];
  14441. var inputSource = inputSources[i];
  14442. if (inputSource) {
  14443. var inputPose = frame.getPose(inputSource.targetRaySpace, referenceSpace);
  14444. if (inputPose !== null) {
  14445. controller.matrix.fromArray(inputPose.transform.matrix);
  14446. controller.matrix.decompose(controller.position, controller.rotation, controller.scale);
  14447. controller.visible = true;
  14448. continue;
  14449. }
  14450. }
  14451. controller.visible = false;
  14452. }
  14453. if (onAnimationFrameCallback) onAnimationFrameCallback(time);
  14454. }
  14455. var animation = new WebGLAnimation();
  14456. animation.setAnimationLoop(onAnimationFrame);
  14457. this.setAnimationLoop = function (callback) {
  14458. onAnimationFrameCallback = callback;
  14459. };
  14460. this.dispose = function () {}; // DEPRECATED
  14461. this.getStandingMatrix = function () {
  14462. console.warn('THREE.WebXRManager: getStandingMatrix() is no longer needed.');
  14463. return new Matrix4();
  14464. };
  14465. this.getDevice = function () {
  14466. console.warn('THREE.WebXRManager: getDevice() has been deprecated.');
  14467. };
  14468. this.setDevice = function () {
  14469. console.warn('THREE.WebXRManager: setDevice() has been deprecated.');
  14470. };
  14471. this.setFrameOfReferenceType = function () {
  14472. console.warn('THREE.WebXRManager: setFrameOfReferenceType() has been deprecated.');
  14473. };
  14474. this.submitFrame = function () {};
  14475. }
  14476. Object.assign(WebXRManager.prototype, EventDispatcher.prototype);
  14477. /**
  14478. * @author supereggbert / http://www.paulbrunt.co.uk/
  14479. * @author mrdoob / http://mrdoob.com/
  14480. * @author alteredq / http://alteredqualia.com/
  14481. * @author szimek / https://github.com/szimek/
  14482. * @author tschw
  14483. */
  14484. function WebGLRenderer(parameters) {
  14485. parameters = parameters || {};
  14486. var _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElementNS('http://www.w3.org/1999/xhtml', 'canvas'),
  14487. _context = parameters.context !== undefined ? parameters.context : null,
  14488. _alpha = parameters.alpha !== undefined ? parameters.alpha : false,
  14489. _depth = parameters.depth !== undefined ? parameters.depth : true,
  14490. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  14491. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  14492. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  14493. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false,
  14494. _powerPreference = parameters.powerPreference !== undefined ? parameters.powerPreference : 'default',
  14495. _failIfMajorPerformanceCaveat = parameters.failIfMajorPerformanceCaveat !== undefined ? parameters.failIfMajorPerformanceCaveat : false;
  14496. var currentRenderList = null;
  14497. var currentRenderState = null; // public properties
  14498. this.domElement = _canvas; // Debug configuration container
  14499. this.debug = {
  14500. /**
  14501. * Enables error checking and reporting when shader programs are being compiled
  14502. * @type {boolean}
  14503. */
  14504. checkShaderErrors: true
  14505. }; // clearing
  14506. this.autoClear = true;
  14507. this.autoClearColor = true;
  14508. this.autoClearDepth = true;
  14509. this.autoClearStencil = true; // scene graph
  14510. this.sortObjects = true; // user-defined clipping
  14511. this.clippingPlanes = [];
  14512. this.localClippingEnabled = false; // physically based shading
  14513. this.gammaFactor = 2.0; // for backwards compatibility
  14514. this.gammaInput = false;
  14515. this.gammaOutput = false; // physical lights
  14516. this.physicallyCorrectLights = false; // tone mapping
  14517. this.toneMapping = LinearToneMapping;
  14518. this.toneMappingExposure = 1.0;
  14519. this.toneMappingWhitePoint = 1.0; // morphs
  14520. this.maxMorphTargets = 8;
  14521. this.maxMorphNormals = 4; // internal properties
  14522. var _this = this,
  14523. _isContextLost = false,
  14524. // internal state cache
  14525. _framebuffer = null,
  14526. _currentActiveCubeFace = 0,
  14527. _currentActiveMipmapLevel = 0,
  14528. _currentRenderTarget = null,
  14529. _currentFramebuffer = null,
  14530. _currentMaterialId = -1,
  14531. // geometry and program caching
  14532. _currentGeometryProgram = {
  14533. geometry: null,
  14534. program: null,
  14535. wireframe: false
  14536. },
  14537. _currentCamera = null,
  14538. _currentArrayCamera = null,
  14539. _currentViewport = new Vector4(),
  14540. _currentScissor = new Vector4(),
  14541. _currentScissorTest = null,
  14542. //
  14543. _width = _canvas.width,
  14544. _height = _canvas.height,
  14545. _pixelRatio = 1,
  14546. _viewport = new Vector4(0, 0, _width, _height),
  14547. _scissor = new Vector4(0, 0, _width, _height),
  14548. _scissorTest = false,
  14549. // frustum
  14550. _frustum = new Frustum(),
  14551. // clipping
  14552. _clipping = new WebGLClipping(),
  14553. _clippingEnabled = false,
  14554. _localClippingEnabled = false,
  14555. // camera matrices cache
  14556. _projScreenMatrix = new Matrix4(),
  14557. _vector3 = new Vector3();
  14558. function getTargetPixelRatio() {
  14559. return _currentRenderTarget === null ? _pixelRatio : 1;
  14560. } // initialize
  14561. var _gl;
  14562. try {
  14563. var contextAttributes = {
  14564. alpha: _alpha,
  14565. depth: _depth,
  14566. stencil: _stencil,
  14567. antialias: _antialias,
  14568. premultipliedAlpha: _premultipliedAlpha,
  14569. preserveDrawingBuffer: _preserveDrawingBuffer,
  14570. powerPreference: _powerPreference,
  14571. failIfMajorPerformanceCaveat: _failIfMajorPerformanceCaveat,
  14572. xrCompatible: true
  14573. }; // event listeners must be registered before WebGL context is created, see #12753
  14574. _canvas.addEventListener('webglcontextlost', onContextLost, false);
  14575. _canvas.addEventListener('webglcontextrestored', onContextRestore, false);
  14576. _gl = _context || _canvas.getContext('webgl', contextAttributes) || _canvas.getContext('experimental-webgl', contextAttributes);
  14577. if (_gl === null) {
  14578. if (_canvas.getContext('webgl') !== null) {
  14579. throw new Error('Error creating WebGL context with your selected attributes.');
  14580. } else {
  14581. throw new Error('Error creating WebGL context.');
  14582. }
  14583. } // Some experimental-webgl implementations do not have getShaderPrecisionFormat
  14584. if (_gl.getShaderPrecisionFormat === undefined) {
  14585. _gl.getShaderPrecisionFormat = function () {
  14586. return {
  14587. 'rangeMin': 1,
  14588. 'rangeMax': 1,
  14589. 'precision': 1
  14590. };
  14591. };
  14592. }
  14593. } catch (error) {
  14594. console.error('THREE.WebGLRenderer: ' + error.message);
  14595. throw error;
  14596. }
  14597. var extensions, capabilities, state, info;
  14598. var properties, textures, attributes, geometries, objects;
  14599. var programCache, renderLists, renderStates;
  14600. var background, morphtargets, bufferRenderer, indexedBufferRenderer;
  14601. var utils;
  14602. function initGLContext() {
  14603. extensions = new WebGLExtensions(_gl);
  14604. capabilities = new WebGLCapabilities(_gl, extensions, parameters);
  14605. if (capabilities.isWebGL2 === false) {
  14606. extensions.get('WEBGL_depth_texture');
  14607. extensions.get('OES_texture_float');
  14608. extensions.get('OES_texture_half_float');
  14609. extensions.get('OES_texture_half_float_linear');
  14610. extensions.get('OES_standard_derivatives');
  14611. extensions.get('OES_element_index_uint');
  14612. extensions.get('ANGLE_instanced_arrays');
  14613. }
  14614. extensions.get('OES_texture_float_linear');
  14615. utils = new WebGLUtils(_gl, extensions, capabilities);
  14616. state = new WebGLState(_gl, extensions, utils, capabilities);
  14617. state.scissor(_currentScissor.copy(_scissor).multiplyScalar(_pixelRatio).floor());
  14618. state.viewport(_currentViewport.copy(_viewport).multiplyScalar(_pixelRatio).floor());
  14619. info = new WebGLInfo(_gl);
  14620. properties = new WebGLProperties();
  14621. textures = new WebGLTextures(_gl, extensions, state, properties, capabilities, utils, info);
  14622. attributes = new WebGLAttributes(_gl);
  14623. geometries = new WebGLGeometries(_gl, attributes, info);
  14624. objects = new WebGLObjects(_gl, geometries, attributes, info);
  14625. morphtargets = new WebGLMorphtargets(_gl);
  14626. programCache = new WebGLPrograms(_this, extensions, capabilities);
  14627. renderLists = new WebGLRenderLists();
  14628. renderStates = new WebGLRenderStates();
  14629. background = new WebGLBackground(_this, state, objects, _premultipliedAlpha);
  14630. bufferRenderer = new WebGLBufferRenderer(_gl, extensions, info, capabilities);
  14631. indexedBufferRenderer = new WebGLIndexedBufferRenderer(_gl, extensions, info, capabilities);
  14632. info.programs = programCache.programs;
  14633. _this.capabilities = capabilities;
  14634. _this.extensions = extensions;
  14635. _this.properties = properties;
  14636. _this.renderLists = renderLists;
  14637. _this.state = state;
  14638. _this.info = info;
  14639. }
  14640. initGLContext(); // vr
  14641. var vr = typeof navigator !== 'undefined' && 'xr' in navigator && 'supportsSession' in navigator.xr ? new WebXRManager(_this, _gl) : new WebVRManager(_this);
  14642. this.vr = vr; // Multiview
  14643. var multiview = new WebGLMultiview(_this, _gl); // shadow map
  14644. var shadowMap = new WebGLShadowMap(_this, objects, capabilities.maxTextureSize);
  14645. this.shadowMap = shadowMap; // API
  14646. this.getContext = function () {
  14647. return _gl;
  14648. };
  14649. this.getContextAttributes = function () {
  14650. return _gl.getContextAttributes();
  14651. };
  14652. this.forceContextLoss = function () {
  14653. var extension = extensions.get('WEBGL_lose_context');
  14654. if (extension) extension.loseContext();
  14655. };
  14656. this.forceContextRestore = function () {
  14657. var extension = extensions.get('WEBGL_lose_context');
  14658. if (extension) extension.restoreContext();
  14659. };
  14660. this.getPixelRatio = function () {
  14661. return _pixelRatio;
  14662. };
  14663. this.setPixelRatio = function (value) {
  14664. if (value === undefined) return;
  14665. _pixelRatio = value;
  14666. this.setSize(_width, _height, false);
  14667. };
  14668. this.getSize = function (target) {
  14669. if (target === undefined) {
  14670. console.warn('WebGLRenderer: .getsize() now requires a Vector2 as an argument');
  14671. target = new Vector2();
  14672. }
  14673. return target.set(_width, _height);
  14674. };
  14675. this.setSize = function (width, height, updateStyle) {
  14676. if (vr.isPresenting()) {
  14677. console.warn('THREE.WebGLRenderer: Can\'t change size while VR device is presenting.');
  14678. return;
  14679. }
  14680. _width = width;
  14681. _height = height;
  14682. _canvas.width = Math.floor(width * _pixelRatio);
  14683. _canvas.height = Math.floor(height * _pixelRatio);
  14684. if (updateStyle !== false) {
  14685. _canvas.style.width = width + 'px';
  14686. _canvas.style.height = height + 'px';
  14687. }
  14688. this.setViewport(0, 0, width, height);
  14689. };
  14690. this.getDrawingBufferSize = function (target) {
  14691. if (target === undefined) {
  14692. console.warn('WebGLRenderer: .getdrawingBufferSize() now requires a Vector2 as an argument');
  14693. target = new Vector2();
  14694. }
  14695. return target.set(_width * _pixelRatio, _height * _pixelRatio).floor();
  14696. };
  14697. this.setDrawingBufferSize = function (width, height, pixelRatio) {
  14698. _width = width;
  14699. _height = height;
  14700. _pixelRatio = pixelRatio;
  14701. _canvas.width = Math.floor(width * pixelRatio);
  14702. _canvas.height = Math.floor(height * pixelRatio);
  14703. this.setViewport(0, 0, width, height);
  14704. };
  14705. this.getCurrentViewport = function (target) {
  14706. if (target === undefined) {
  14707. console.warn('WebGLRenderer: .getCurrentViewport() now requires a Vector4 as an argument');
  14708. target = new Vector4();
  14709. }
  14710. return target.copy(_currentViewport);
  14711. };
  14712. this.getViewport = function (target) {
  14713. return target.copy(_viewport);
  14714. };
  14715. this.setViewport = function (x, y, width, height) {
  14716. if (x.isVector4) {
  14717. _viewport.set(x.x, x.y, x.z, x.w);
  14718. } else {
  14719. _viewport.set(x, y, width, height);
  14720. }
  14721. state.viewport(_currentViewport.copy(_viewport).multiplyScalar(_pixelRatio).floor());
  14722. };
  14723. this.getScissor = function (target) {
  14724. return target.copy(_scissor);
  14725. };
  14726. this.setScissor = function (x, y, width, height) {
  14727. if (x.isVector4) {
  14728. _scissor.set(x.x, x.y, x.z, x.w);
  14729. } else {
  14730. _scissor.set(x, y, width, height);
  14731. }
  14732. state.scissor(_currentScissor.copy(_scissor).multiplyScalar(_pixelRatio).floor());
  14733. };
  14734. this.getScissorTest = function () {
  14735. return _scissorTest;
  14736. };
  14737. this.setScissorTest = function (boolean) {
  14738. state.setScissorTest(_scissorTest = boolean);
  14739. }; // Clearing
  14740. this.getClearColor = function () {
  14741. return background.getClearColor();
  14742. };
  14743. this.setClearColor = function () {
  14744. background.setClearColor.apply(background, arguments);
  14745. };
  14746. this.getClearAlpha = function () {
  14747. return background.getClearAlpha();
  14748. };
  14749. this.setClearAlpha = function () {
  14750. background.setClearAlpha.apply(background, arguments);
  14751. };
  14752. this.clear = function (color, depth, stencil) {
  14753. var bits = 0;
  14754. if (color === undefined || color) bits |= 16384;
  14755. if (depth === undefined || depth) bits |= 256;
  14756. if (stencil === undefined || stencil) bits |= 1024;
  14757. _gl.clear(bits);
  14758. };
  14759. this.clearColor = function () {
  14760. this.clear(true, false, false);
  14761. };
  14762. this.clearDepth = function () {
  14763. this.clear(false, true, false);
  14764. };
  14765. this.clearStencil = function () {
  14766. this.clear(false, false, true);
  14767. }; //
  14768. this.dispose = function () {
  14769. _canvas.removeEventListener('webglcontextlost', onContextLost, false);
  14770. _canvas.removeEventListener('webglcontextrestored', onContextRestore, false);
  14771. renderLists.dispose();
  14772. renderStates.dispose();
  14773. properties.dispose();
  14774. objects.dispose();
  14775. vr.dispose();
  14776. animation.stop();
  14777. }; // Events
  14778. function onContextLost(event) {
  14779. event.preventDefault();
  14780. console.log('THREE.WebGLRenderer: Context Lost.');
  14781. _isContextLost = true;
  14782. }
  14783. function onContextRestore()
  14784. /* event */
  14785. {
  14786. console.log('THREE.WebGLRenderer: Context Restored.');
  14787. _isContextLost = false;
  14788. initGLContext();
  14789. }
  14790. function onMaterialDispose(event) {
  14791. var material = event.target;
  14792. material.removeEventListener('dispose', onMaterialDispose);
  14793. deallocateMaterial(material);
  14794. } // Buffer deallocation
  14795. function deallocateMaterial(material) {
  14796. releaseMaterialProgramReference(material);
  14797. properties.remove(material);
  14798. }
  14799. function releaseMaterialProgramReference(material) {
  14800. var programInfo = properties.get(material).program;
  14801. material.program = undefined;
  14802. if (programInfo !== undefined) {
  14803. programCache.releaseProgram(programInfo);
  14804. }
  14805. } // Buffer rendering
  14806. function renderObjectImmediate(object, program) {
  14807. object.render(function (object) {
  14808. _this.renderBufferImmediate(object, program);
  14809. });
  14810. }
  14811. this.renderBufferImmediate = function (object, program) {
  14812. state.initAttributes();
  14813. var buffers = properties.get(object);
  14814. if (object.hasPositions && !buffers.position) buffers.position = _gl.createBuffer();
  14815. if (object.hasNormals && !buffers.normal) buffers.normal = _gl.createBuffer();
  14816. if (object.hasUvs && !buffers.uv) buffers.uv = _gl.createBuffer();
  14817. if (object.hasColors && !buffers.color) buffers.color = _gl.createBuffer();
  14818. var programAttributes = program.getAttributes();
  14819. if (object.hasPositions) {
  14820. _gl.bindBuffer(34962, buffers.position);
  14821. _gl.bufferData(34962, object.positionArray, 35048);
  14822. state.enableAttribute(programAttributes.position);
  14823. _gl.vertexAttribPointer(programAttributes.position, 3, 5126, false, 0, 0);
  14824. }
  14825. if (object.hasNormals) {
  14826. _gl.bindBuffer(34962, buffers.normal);
  14827. _gl.bufferData(34962, object.normalArray, 35048);
  14828. state.enableAttribute(programAttributes.normal);
  14829. _gl.vertexAttribPointer(programAttributes.normal, 3, 5126, false, 0, 0);
  14830. }
  14831. if (object.hasUvs) {
  14832. _gl.bindBuffer(34962, buffers.uv);
  14833. _gl.bufferData(34962, object.uvArray, 35048);
  14834. state.enableAttribute(programAttributes.uv);
  14835. _gl.vertexAttribPointer(programAttributes.uv, 2, 5126, false, 0, 0);
  14836. }
  14837. if (object.hasColors) {
  14838. _gl.bindBuffer(34962, buffers.color);
  14839. _gl.bufferData(34962, object.colorArray, 35048);
  14840. state.enableAttribute(programAttributes.color);
  14841. _gl.vertexAttribPointer(programAttributes.color, 3, 5126, false, 0, 0);
  14842. }
  14843. state.disableUnusedAttributes();
  14844. _gl.drawArrays(4, 0, object.count);
  14845. object.count = 0;
  14846. };
  14847. this.renderBufferDirect = function (camera, fog, geometry, material, object, group) {
  14848. var frontFaceCW = object.isMesh && object.matrixWorld.determinant() < 0;
  14849. state.setMaterial(material, frontFaceCW);
  14850. var program = setProgram(camera, fog, material, object);
  14851. var updateBuffers = false;
  14852. if (_currentGeometryProgram.geometry !== geometry.id || _currentGeometryProgram.program !== program.id || _currentGeometryProgram.wireframe !== (material.wireframe === true)) {
  14853. _currentGeometryProgram.geometry = geometry.id;
  14854. _currentGeometryProgram.program = program.id;
  14855. _currentGeometryProgram.wireframe = material.wireframe === true;
  14856. updateBuffers = true;
  14857. }
  14858. if (object.morphTargetInfluences) {
  14859. morphtargets.update(object, geometry, material, program);
  14860. updateBuffers = true;
  14861. } //
  14862. var index = geometry.index;
  14863. var position = geometry.attributes.position;
  14864. var rangeFactor = 1;
  14865. if (material.wireframe === true) {
  14866. index = geometries.getWireframeAttribute(geometry);
  14867. rangeFactor = 2;
  14868. }
  14869. var attribute;
  14870. var renderer = bufferRenderer;
  14871. if (index !== null) {
  14872. attribute = attributes.get(index);
  14873. renderer = indexedBufferRenderer;
  14874. renderer.setIndex(attribute);
  14875. }
  14876. if (updateBuffers) {
  14877. setupVertexAttributes(object, geometry, material, program);
  14878. if (index !== null) {
  14879. _gl.bindBuffer(34963, attribute.buffer);
  14880. }
  14881. } //
  14882. var dataCount = Infinity;
  14883. if (index !== null) {
  14884. dataCount = index.count;
  14885. } else if (position !== undefined) {
  14886. dataCount = position.count;
  14887. }
  14888. var rangeStart = geometry.drawRange.start * rangeFactor;
  14889. var rangeCount = geometry.drawRange.count * rangeFactor;
  14890. var groupStart = group !== null ? group.start * rangeFactor : 0;
  14891. var groupCount = group !== null ? group.count * rangeFactor : Infinity;
  14892. var drawStart = Math.max(rangeStart, groupStart);
  14893. var drawEnd = Math.min(dataCount, rangeStart + rangeCount, groupStart + groupCount) - 1;
  14894. var drawCount = Math.max(0, drawEnd - drawStart + 1);
  14895. if (drawCount === 0) return; //
  14896. if (object.isMesh) {
  14897. if (material.wireframe === true) {
  14898. state.setLineWidth(material.wireframeLinewidth * getTargetPixelRatio());
  14899. renderer.setMode(1);
  14900. } else {
  14901. switch (object.drawMode) {
  14902. case TrianglesDrawMode:
  14903. renderer.setMode(4);
  14904. break;
  14905. case TriangleStripDrawMode:
  14906. renderer.setMode(5);
  14907. break;
  14908. case TriangleFanDrawMode:
  14909. renderer.setMode(6);
  14910. break;
  14911. }
  14912. }
  14913. } else if (object.isLine) {
  14914. var lineWidth = material.linewidth;
  14915. if (lineWidth === undefined) lineWidth = 1; // Not using Line*Material
  14916. state.setLineWidth(lineWidth * getTargetPixelRatio());
  14917. if (object.isLineSegments) {
  14918. renderer.setMode(1);
  14919. } else if (object.isLineLoop) {
  14920. renderer.setMode(2);
  14921. } else {
  14922. renderer.setMode(3);
  14923. }
  14924. } else if (object.isPoints) {
  14925. renderer.setMode(0);
  14926. } else if (object.isSprite) {
  14927. renderer.setMode(4);
  14928. }
  14929. if (object.isInstancedMesh) {
  14930. renderer.renderInstances(geometry, drawStart, drawCount, object.count);
  14931. } else if (geometry.isInstancedBufferGeometry) {
  14932. renderer.renderInstances(geometry, drawStart, drawCount, geometry.maxInstancedCount);
  14933. } else {
  14934. renderer.render(drawStart, drawCount);
  14935. }
  14936. };
  14937. function setupVertexAttributes(object, geometry, material, program) {
  14938. if (capabilities.isWebGL2 === false && (object.isInstancedMesh || geometry.isInstancedBufferGeometry)) {
  14939. if (extensions.get('ANGLE_instanced_arrays') === null) return;
  14940. }
  14941. state.initAttributes();
  14942. var geometryAttributes = geometry.attributes;
  14943. var programAttributes = program.getAttributes();
  14944. var materialDefaultAttributeValues = material.defaultAttributeValues;
  14945. for (var name in programAttributes) {
  14946. var programAttribute = programAttributes[name];
  14947. if (programAttribute >= 0) {
  14948. var geometryAttribute = geometryAttributes[name];
  14949. if (geometryAttribute !== undefined) {
  14950. var normalized = geometryAttribute.normalized;
  14951. var size = geometryAttribute.itemSize;
  14952. var attribute = attributes.get(geometryAttribute); // TODO Attribute may not be available on context restore
  14953. if (attribute === undefined) continue;
  14954. var buffer = attribute.buffer;
  14955. var type = attribute.type;
  14956. var bytesPerElement = attribute.bytesPerElement;
  14957. if (geometryAttribute.isInterleavedBufferAttribute) {
  14958. var data = geometryAttribute.data;
  14959. var stride = data.stride;
  14960. var offset = geometryAttribute.offset;
  14961. if (data && data.isInstancedInterleavedBuffer) {
  14962. state.enableAttributeAndDivisor(programAttribute, data.meshPerAttribute);
  14963. if (geometry.maxInstancedCount === undefined) {
  14964. geometry.maxInstancedCount = data.meshPerAttribute * data.count;
  14965. }
  14966. } else {
  14967. state.enableAttribute(programAttribute);
  14968. }
  14969. _gl.bindBuffer(34962, buffer);
  14970. _gl.vertexAttribPointer(programAttribute, size, type, normalized, stride * bytesPerElement, offset * bytesPerElement);
  14971. } else {
  14972. if (geometryAttribute.isInstancedBufferAttribute) {
  14973. state.enableAttributeAndDivisor(programAttribute, geometryAttribute.meshPerAttribute);
  14974. if (geometry.maxInstancedCount === undefined) {
  14975. geometry.maxInstancedCount = geometryAttribute.meshPerAttribute * geometryAttribute.count;
  14976. }
  14977. } else {
  14978. state.enableAttribute(programAttribute);
  14979. }
  14980. _gl.bindBuffer(34962, buffer);
  14981. _gl.vertexAttribPointer(programAttribute, size, type, normalized, 0, 0);
  14982. }
  14983. } else if (name === 'instanceMatrix') {
  14984. var attribute = attributes.get(object.instanceMatrix); // TODO Attribute may not be available on context restore
  14985. if (attribute === undefined) continue;
  14986. var buffer = attribute.buffer;
  14987. var type = attribute.type;
  14988. state.enableAttributeAndDivisor(programAttribute + 0, 1);
  14989. state.enableAttributeAndDivisor(programAttribute + 1, 1);
  14990. state.enableAttributeAndDivisor(programAttribute + 2, 1);
  14991. state.enableAttributeAndDivisor(programAttribute + 3, 1);
  14992. _gl.bindBuffer(34962, buffer);
  14993. _gl.vertexAttribPointer(programAttribute + 0, 4, type, false, 64, 0);
  14994. _gl.vertexAttribPointer(programAttribute + 1, 4, type, false, 64, 16);
  14995. _gl.vertexAttribPointer(programAttribute + 2, 4, type, false, 64, 32);
  14996. _gl.vertexAttribPointer(programAttribute + 3, 4, type, false, 64, 48);
  14997. } else if (materialDefaultAttributeValues !== undefined) {
  14998. var value = materialDefaultAttributeValues[name];
  14999. if (value !== undefined) {
  15000. switch (value.length) {
  15001. case 2:
  15002. _gl.vertexAttrib2fv(programAttribute, value);
  15003. break;
  15004. case 3:
  15005. _gl.vertexAttrib3fv(programAttribute, value);
  15006. break;
  15007. case 4:
  15008. _gl.vertexAttrib4fv(programAttribute, value);
  15009. break;
  15010. default:
  15011. _gl.vertexAttrib1fv(programAttribute, value);
  15012. }
  15013. }
  15014. }
  15015. }
  15016. }
  15017. state.disableUnusedAttributes();
  15018. } // Compile
  15019. this.compile = function (scene, camera) {
  15020. currentRenderState = renderStates.get(scene, camera);
  15021. currentRenderState.init();
  15022. scene.traverse(function (object) {
  15023. if (object.isLight) {
  15024. currentRenderState.pushLight(object);
  15025. if (object.castShadow) {
  15026. currentRenderState.pushShadow(object);
  15027. }
  15028. }
  15029. });
  15030. currentRenderState.setupLights(camera);
  15031. scene.traverse(function (object) {
  15032. if (object.material) {
  15033. if (Array.isArray(object.material)) {
  15034. for (var i = 0; i < object.material.length; i++) {
  15035. initMaterial(object.material[i], scene.fog, object);
  15036. }
  15037. } else {
  15038. initMaterial(object.material, scene.fog, object);
  15039. }
  15040. }
  15041. });
  15042. }; // Animation Loop
  15043. var onAnimationFrameCallback = null;
  15044. function onAnimationFrame(time) {
  15045. if (vr.isPresenting()) return;
  15046. if (onAnimationFrameCallback) onAnimationFrameCallback(time);
  15047. }
  15048. var animation = new WebGLAnimation();
  15049. animation.setAnimationLoop(onAnimationFrame);
  15050. if (typeof window !== 'undefined') animation.setContext(window);
  15051. this.setAnimationLoop = function (callback) {
  15052. onAnimationFrameCallback = callback;
  15053. vr.setAnimationLoop(callback);
  15054. animation.start();
  15055. }; // Rendering
  15056. this.render = function (scene, camera) {
  15057. var renderTarget, forceClear;
  15058. if (arguments[2] !== undefined) {
  15059. console.warn('THREE.WebGLRenderer.render(): the renderTarget argument has been removed. Use .setRenderTarget() instead.');
  15060. renderTarget = arguments[2];
  15061. }
  15062. if (arguments[3] !== undefined) {
  15063. console.warn('THREE.WebGLRenderer.render(): the forceClear argument has been removed. Use .clear() instead.');
  15064. forceClear = arguments[3];
  15065. }
  15066. if (!(camera && camera.isCamera)) {
  15067. console.error('THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.');
  15068. return;
  15069. }
  15070. if (_isContextLost) return; // reset caching for this frame
  15071. _currentGeometryProgram.geometry = null;
  15072. _currentGeometryProgram.program = null;
  15073. _currentGeometryProgram.wireframe = false;
  15074. _currentMaterialId = -1;
  15075. _currentCamera = null; // update scene graph
  15076. if (scene.autoUpdate === true) scene.updateMatrixWorld(); // update camera matrices and frustum
  15077. if (camera.parent === null) camera.updateMatrixWorld();
  15078. if (vr.enabled) {
  15079. camera = vr.getCamera(camera);
  15080. } //
  15081. currentRenderState = renderStates.get(scene, camera);
  15082. currentRenderState.init();
  15083. scene.onBeforeRender(_this, scene, camera, renderTarget || _currentRenderTarget);
  15084. _projScreenMatrix.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse);
  15085. _frustum.setFromMatrix(_projScreenMatrix);
  15086. _localClippingEnabled = this.localClippingEnabled;
  15087. _clippingEnabled = _clipping.init(this.clippingPlanes, _localClippingEnabled, camera);
  15088. currentRenderList = renderLists.get(scene, camera);
  15089. currentRenderList.init();
  15090. projectObject(scene, camera, 0, _this.sortObjects);
  15091. if (_this.sortObjects === true) {
  15092. currentRenderList.sort();
  15093. } //
  15094. if (_clippingEnabled) _clipping.beginShadows();
  15095. var shadowsArray = currentRenderState.state.shadowsArray;
  15096. shadowMap.render(shadowsArray, scene, camera);
  15097. currentRenderState.setupLights(camera);
  15098. if (_clippingEnabled) _clipping.endShadows(); //
  15099. if (this.info.autoReset) this.info.reset();
  15100. if (renderTarget !== undefined) {
  15101. this.setRenderTarget(renderTarget);
  15102. }
  15103. if (vr.enabled && multiview.isAvailable()) {
  15104. multiview.attachCamera(camera);
  15105. } //
  15106. background.render(currentRenderList, scene, camera, forceClear); // render scene
  15107. var opaqueObjects = currentRenderList.opaque;
  15108. var transparentObjects = currentRenderList.transparent;
  15109. if (scene.overrideMaterial) {
  15110. var overrideMaterial = scene.overrideMaterial;
  15111. if (opaqueObjects.length) renderObjects(opaqueObjects, scene, camera, overrideMaterial);
  15112. if (transparentObjects.length) renderObjects(transparentObjects, scene, camera, overrideMaterial);
  15113. } else {
  15114. // opaque pass (front-to-back order)
  15115. if (opaqueObjects.length) renderObjects(opaqueObjects, scene, camera); // transparent pass (back-to-front order)
  15116. if (transparentObjects.length) renderObjects(transparentObjects, scene, camera);
  15117. } //
  15118. scene.onAfterRender(_this, scene, camera); //
  15119. if (_currentRenderTarget !== null) {
  15120. // Generate mipmap if we're using any kind of mipmap filtering
  15121. textures.updateRenderTargetMipmap(_currentRenderTarget); // resolve multisample renderbuffers to a single-sample texture if necessary
  15122. textures.updateMultisampleRenderTarget(_currentRenderTarget);
  15123. } // Ensure depth buffer writing is enabled so it can be cleared on next render
  15124. state.buffers.depth.setTest(true);
  15125. state.buffers.depth.setMask(true);
  15126. state.buffers.color.setMask(true);
  15127. state.setPolygonOffset(false);
  15128. if (vr.enabled) {
  15129. if (multiview.isAvailable()) {
  15130. multiview.detachCamera(camera);
  15131. }
  15132. vr.submitFrame();
  15133. } // _gl.finish();
  15134. currentRenderList = null;
  15135. currentRenderState = null;
  15136. };
  15137. function projectObject(object, camera, groupOrder, sortObjects) {
  15138. if (object.visible === false) return;
  15139. var visible = object.layers.test(camera.layers);
  15140. if (visible) {
  15141. if (object.isGroup) {
  15142. groupOrder = object.renderOrder;
  15143. } else if (object.isLOD) {
  15144. if (object.autoUpdate === true) object.update(camera);
  15145. } else if (object.isLight) {
  15146. currentRenderState.pushLight(object);
  15147. if (object.castShadow) {
  15148. currentRenderState.pushShadow(object);
  15149. }
  15150. } else if (object.isSprite) {
  15151. if (!object.frustumCulled || _frustum.intersectsSprite(object)) {
  15152. if (sortObjects) {
  15153. _vector3.setFromMatrixPosition(object.matrixWorld).applyMatrix4(_projScreenMatrix);
  15154. }
  15155. var geometry = objects.update(object);
  15156. var material = object.material;
  15157. if (material.visible) {
  15158. currentRenderList.push(object, geometry, material, groupOrder, _vector3.z, null);
  15159. }
  15160. }
  15161. } else if (object.isImmediateRenderObject) {
  15162. if (sortObjects) {
  15163. _vector3.setFromMatrixPosition(object.matrixWorld).applyMatrix4(_projScreenMatrix);
  15164. }
  15165. currentRenderList.push(object, null, object.material, groupOrder, _vector3.z, null);
  15166. } else if (object.isMesh || object.isLine || object.isPoints) {
  15167. if (object.isSkinnedMesh) {
  15168. // update skeleton only once in a frame
  15169. if (object.skeleton.frame !== info.render.frame) {
  15170. object.skeleton.update();
  15171. object.skeleton.frame = info.render.frame;
  15172. }
  15173. }
  15174. if (!object.frustumCulled || _frustum.intersectsObject(object)) {
  15175. if (sortObjects) {
  15176. _vector3.setFromMatrixPosition(object.matrixWorld).applyMatrix4(_projScreenMatrix);
  15177. }
  15178. var geometry = objects.update(object);
  15179. var material = object.material;
  15180. if (Array.isArray(material)) {
  15181. var groups = geometry.groups;
  15182. for (var i = 0, l = groups.length; i < l; i++) {
  15183. var group = groups[i];
  15184. var groupMaterial = material[group.materialIndex];
  15185. if (groupMaterial && groupMaterial.visible) {
  15186. currentRenderList.push(object, geometry, groupMaterial, groupOrder, _vector3.z, group);
  15187. }
  15188. }
  15189. } else if (material.visible) {
  15190. currentRenderList.push(object, geometry, material, groupOrder, _vector3.z, null);
  15191. }
  15192. }
  15193. }
  15194. }
  15195. var children = object.children;
  15196. for (var i = 0, l = children.length; i < l; i++) {
  15197. projectObject(children[i], camera, groupOrder, sortObjects);
  15198. }
  15199. }
  15200. function renderObjects(renderList, scene, camera, overrideMaterial) {
  15201. for (var i = 0, l = renderList.length; i < l; i++) {
  15202. var renderItem = renderList[i];
  15203. var object = renderItem.object;
  15204. var geometry = renderItem.geometry;
  15205. var material = overrideMaterial === undefined ? renderItem.material : overrideMaterial;
  15206. var group = renderItem.group;
  15207. if (camera.isArrayCamera) {
  15208. _currentArrayCamera = camera;
  15209. if (vr.enabled && multiview.isAvailable()) {
  15210. renderObject(object, scene, camera, geometry, material, group);
  15211. } else {
  15212. var cameras = camera.cameras;
  15213. for (var j = 0, jl = cameras.length; j < jl; j++) {
  15214. var camera2 = cameras[j];
  15215. if (object.layers.test(camera2.layers)) {
  15216. state.viewport(_currentViewport.copy(camera2.viewport));
  15217. currentRenderState.setupLights(camera2);
  15218. renderObject(object, scene, camera2, geometry, material, group);
  15219. }
  15220. }
  15221. }
  15222. } else {
  15223. _currentArrayCamera = null;
  15224. renderObject(object, scene, camera, geometry, material, group);
  15225. }
  15226. }
  15227. }
  15228. function renderObject(object, scene, camera, geometry, material, group) {
  15229. object.onBeforeRender(_this, scene, camera, geometry, material, group);
  15230. currentRenderState = renderStates.get(scene, _currentArrayCamera || camera);
  15231. object.modelViewMatrix.multiplyMatrices(camera.matrixWorldInverse, object.matrixWorld);
  15232. object.normalMatrix.getNormalMatrix(object.modelViewMatrix);
  15233. if (object.isImmediateRenderObject) {
  15234. state.setMaterial(material);
  15235. var program = setProgram(camera, scene.fog, material, object);
  15236. _currentGeometryProgram.geometry = null;
  15237. _currentGeometryProgram.program = null;
  15238. _currentGeometryProgram.wireframe = false;
  15239. renderObjectImmediate(object, program);
  15240. } else {
  15241. _this.renderBufferDirect(camera, scene.fog, geometry, material, object, group);
  15242. }
  15243. object.onAfterRender(_this, scene, camera, geometry, material, group);
  15244. currentRenderState = renderStates.get(scene, _currentArrayCamera || camera);
  15245. }
  15246. function initMaterial(material, fog, object) {
  15247. var materialProperties = properties.get(material);
  15248. var lights = currentRenderState.state.lights;
  15249. var shadowsArray = currentRenderState.state.shadowsArray;
  15250. var lightsStateVersion = lights.state.version;
  15251. var parameters = programCache.getParameters(material, lights.state, shadowsArray, fog, _clipping.numPlanes, _clipping.numIntersection, object);
  15252. var code = programCache.getProgramCode(material, parameters);
  15253. var program = materialProperties.program;
  15254. var programChange = true;
  15255. if (program === undefined) {
  15256. // new material
  15257. material.addEventListener('dispose', onMaterialDispose);
  15258. } else if (program.code !== code) {
  15259. // changed glsl or parameters
  15260. releaseMaterialProgramReference(material);
  15261. } else if (materialProperties.lightsStateVersion !== lightsStateVersion) {
  15262. materialProperties.lightsStateVersion = lightsStateVersion;
  15263. programChange = false;
  15264. } else if (parameters.shaderID !== undefined) {
  15265. // same glsl and uniform list
  15266. return;
  15267. } else {
  15268. // only rebuild uniform list
  15269. programChange = false;
  15270. }
  15271. if (programChange) {
  15272. if (parameters.shaderID) {
  15273. var shader = ShaderLib[parameters.shaderID];
  15274. materialProperties.shader = {
  15275. name: material.type,
  15276. uniforms: cloneUniforms(shader.uniforms),
  15277. vertexShader: shader.vertexShader,
  15278. fragmentShader: shader.fragmentShader
  15279. };
  15280. } else {
  15281. materialProperties.shader = {
  15282. name: material.type,
  15283. uniforms: material.uniforms,
  15284. vertexShader: material.vertexShader,
  15285. fragmentShader: material.fragmentShader
  15286. };
  15287. }
  15288. material.onBeforeCompile(materialProperties.shader, _this); // Computing code again as onBeforeCompile may have changed the shaders
  15289. code = programCache.getProgramCode(material, parameters);
  15290. program = programCache.acquireProgram(material, materialProperties.shader, parameters, code);
  15291. materialProperties.program = program;
  15292. material.program = program;
  15293. }
  15294. var programAttributes = program.getAttributes();
  15295. if (material.morphTargets) {
  15296. material.numSupportedMorphTargets = 0;
  15297. for (var i = 0; i < _this.maxMorphTargets; i++) {
  15298. if (programAttributes['morphTarget' + i] >= 0) {
  15299. material.numSupportedMorphTargets++;
  15300. }
  15301. }
  15302. }
  15303. if (material.morphNormals) {
  15304. material.numSupportedMorphNormals = 0;
  15305. for (var i = 0; i < _this.maxMorphNormals; i++) {
  15306. if (programAttributes['morphNormal' + i] >= 0) {
  15307. material.numSupportedMorphNormals++;
  15308. }
  15309. }
  15310. }
  15311. var uniforms = materialProperties.shader.uniforms;
  15312. if (!material.isShaderMaterial && !material.isRawShaderMaterial || material.clipping === true) {
  15313. materialProperties.numClippingPlanes = _clipping.numPlanes;
  15314. materialProperties.numIntersection = _clipping.numIntersection;
  15315. uniforms.clippingPlanes = _clipping.uniform;
  15316. }
  15317. materialProperties.fog = fog; // store the light setup it was created for
  15318. materialProperties.needsLights = materialNeedsLights(material);
  15319. materialProperties.lightsStateVersion = lightsStateVersion;
  15320. if (materialProperties.needsLights) {
  15321. // wire up the material to this renderer's lighting state
  15322. uniforms.ambientLightColor.value = lights.state.ambient;
  15323. uniforms.lightProbe.value = lights.state.probe;
  15324. uniforms.directionalLights.value = lights.state.directional;
  15325. uniforms.spotLights.value = lights.state.spot;
  15326. uniforms.rectAreaLights.value = lights.state.rectArea;
  15327. uniforms.pointLights.value = lights.state.point;
  15328. uniforms.hemisphereLights.value = lights.state.hemi;
  15329. uniforms.directionalShadowMap.value = lights.state.directionalShadowMap;
  15330. uniforms.directionalShadowMatrix.value = lights.state.directionalShadowMatrix;
  15331. uniforms.spotShadowMap.value = lights.state.spotShadowMap;
  15332. uniforms.spotShadowMatrix.value = lights.state.spotShadowMatrix;
  15333. uniforms.pointShadowMap.value = lights.state.pointShadowMap;
  15334. uniforms.pointShadowMatrix.value = lights.state.pointShadowMatrix; // TODO (abelnation): add area lights shadow info to uniforms
  15335. }
  15336. var progUniforms = materialProperties.program.getUniforms(),
  15337. uniformsList = WebGLUniforms.seqWithValue(progUniforms.seq, uniforms);
  15338. materialProperties.uniformsList = uniformsList;
  15339. }
  15340. function setProgram(camera, fog, material, object) {
  15341. textures.resetTextureUnits();
  15342. var materialProperties = properties.get(material);
  15343. var lights = currentRenderState.state.lights;
  15344. if (_clippingEnabled) {
  15345. if (_localClippingEnabled || camera !== _currentCamera) {
  15346. var useCache = camera === _currentCamera && material.id === _currentMaterialId; // we might want to call this function with some ClippingGroup
  15347. // object instead of the material, once it becomes feasible
  15348. // (#8465, #8379)
  15349. _clipping.setState(material.clippingPlanes, material.clipIntersection, material.clipShadows, camera, materialProperties, useCache);
  15350. }
  15351. }
  15352. if (material.needsUpdate === false) {
  15353. if (materialProperties.program === undefined) {
  15354. material.needsUpdate = true;
  15355. } else if (material.fog && materialProperties.fog !== fog) {
  15356. material.needsUpdate = true;
  15357. } else if (materialProperties.needsLights && materialProperties.lightsStateVersion !== lights.state.version) {
  15358. material.needsUpdate = true;
  15359. } else if (materialProperties.numClippingPlanes !== undefined && (materialProperties.numClippingPlanes !== _clipping.numPlanes || materialProperties.numIntersection !== _clipping.numIntersection)) {
  15360. material.needsUpdate = true;
  15361. }
  15362. }
  15363. if (material.needsUpdate) {
  15364. initMaterial(material, fog, object);
  15365. material.needsUpdate = false;
  15366. }
  15367. var refreshProgram = false;
  15368. var refreshMaterial = false;
  15369. var refreshLights = false;
  15370. var program = materialProperties.program,
  15371. p_uniforms = program.getUniforms(),
  15372. m_uniforms = materialProperties.shader.uniforms;
  15373. if (state.useProgram(program.program)) {
  15374. refreshProgram = true;
  15375. refreshMaterial = true;
  15376. refreshLights = true;
  15377. }
  15378. if (material.id !== _currentMaterialId) {
  15379. _currentMaterialId = material.id;
  15380. refreshMaterial = true;
  15381. }
  15382. if (refreshProgram || _currentCamera !== camera) {
  15383. if (program.numMultiviewViews > 0) {
  15384. multiview.updateCameraProjectionMatricesUniform(camera, p_uniforms);
  15385. } else {
  15386. p_uniforms.setValue(_gl, 'projectionMatrix', camera.projectionMatrix);
  15387. }
  15388. if (capabilities.logarithmicDepthBuffer) {
  15389. p_uniforms.setValue(_gl, 'logDepthBufFC', 2.0 / (Math.log(camera.far + 1.0) / Math.LN2));
  15390. }
  15391. if (_currentCamera !== camera) {
  15392. _currentCamera = camera; // lighting uniforms depend on the camera so enforce an update
  15393. // now, in case this material supports lights - or later, when
  15394. // the next material that does gets activated:
  15395. refreshMaterial = true; // set to true on material change
  15396. refreshLights = true; // remains set until update done
  15397. } // load material specific uniforms
  15398. // (shader material also gets them for the sake of genericity)
  15399. if (material.isShaderMaterial || material.isMeshPhongMaterial || material.isMeshStandardMaterial || material.envMap) {
  15400. var uCamPos = p_uniforms.map.cameraPosition;
  15401. if (uCamPos !== undefined) {
  15402. uCamPos.setValue(_gl, _vector3.setFromMatrixPosition(camera.matrixWorld));
  15403. }
  15404. }
  15405. if (material.isMeshPhongMaterial || material.isMeshLambertMaterial || material.isMeshBasicMaterial || material.isMeshStandardMaterial || material.isShaderMaterial || material.skinning) {
  15406. if (program.numMultiviewViews > 0) {
  15407. multiview.updateCameraViewMatricesUniform(camera, p_uniforms);
  15408. } else {
  15409. p_uniforms.setValue(_gl, 'viewMatrix', camera.matrixWorldInverse);
  15410. }
  15411. }
  15412. } // skinning uniforms must be set even if material didn't change
  15413. // auto-setting of texture unit for bone texture must go before other textures
  15414. // not sure why, but otherwise weird things happen
  15415. if (material.skinning) {
  15416. p_uniforms.setOptional(_gl, object, 'bindMatrix');
  15417. p_uniforms.setOptional(_gl, object, 'bindMatrixInverse');
  15418. var skeleton = object.skeleton;
  15419. if (skeleton) {
  15420. var bones = skeleton.bones;
  15421. if (capabilities.floatVertexTextures) {
  15422. if (skeleton.boneTexture === undefined) {
  15423. // layout (1 matrix = 4 pixels)
  15424. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  15425. // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8)
  15426. // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16)
  15427. // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32)
  15428. // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64)
  15429. var size = Math.sqrt(bones.length * 4); // 4 pixels needed for 1 matrix
  15430. size = _Math.ceilPowerOfTwo(size);
  15431. size = Math.max(size, 4);
  15432. var boneMatrices = new Float32Array(size * size * 4); // 4 floats per RGBA pixel
  15433. boneMatrices.set(skeleton.boneMatrices); // copy current values
  15434. var boneTexture = new DataTexture(boneMatrices, size, size, RGBAFormat, FloatType);
  15435. skeleton.boneMatrices = boneMatrices;
  15436. skeleton.boneTexture = boneTexture;
  15437. skeleton.boneTextureSize = size;
  15438. }
  15439. p_uniforms.setValue(_gl, 'boneTexture', skeleton.boneTexture, textures);
  15440. p_uniforms.setValue(_gl, 'boneTextureSize', skeleton.boneTextureSize);
  15441. } else {
  15442. p_uniforms.setOptional(_gl, skeleton, 'boneMatrices');
  15443. }
  15444. }
  15445. }
  15446. if (refreshMaterial || materialProperties.receiveShadow !== object.receiveShadow) {
  15447. materialProperties.receiveShadow = object.receiveShadow;
  15448. p_uniforms.setValue(_gl, 'receiveShadow', object.receiveShadow);
  15449. }
  15450. if (refreshMaterial) {
  15451. p_uniforms.setValue(_gl, 'toneMappingExposure', _this.toneMappingExposure);
  15452. p_uniforms.setValue(_gl, 'toneMappingWhitePoint', _this.toneMappingWhitePoint);
  15453. if (materialProperties.needsLights) {
  15454. // the current material requires lighting info
  15455. // note: all lighting uniforms are always set correctly
  15456. // they simply reference the renderer's state for their
  15457. // values
  15458. //
  15459. // use the current material's .needsUpdate flags to set
  15460. // the GL state when required
  15461. markUniformsLightsNeedsUpdate(m_uniforms, refreshLights);
  15462. } // refresh uniforms common to several materials
  15463. if (fog && material.fog) {
  15464. refreshUniformsFog(m_uniforms, fog);
  15465. }
  15466. if (material.isMeshBasicMaterial) {
  15467. refreshUniformsCommon(m_uniforms, material);
  15468. } else if (material.isMeshLambertMaterial) {
  15469. refreshUniformsCommon(m_uniforms, material);
  15470. refreshUniformsLambert(m_uniforms, material);
  15471. } else if (material.isMeshPhongMaterial) {
  15472. refreshUniformsCommon(m_uniforms, material);
  15473. if (material.isMeshToonMaterial) {
  15474. refreshUniformsToon(m_uniforms, material);
  15475. } else {
  15476. refreshUniformsPhong(m_uniforms, material);
  15477. }
  15478. } else if (material.isMeshStandardMaterial) {
  15479. refreshUniformsCommon(m_uniforms, material);
  15480. if (material.isMeshPhysicalMaterial) {
  15481. refreshUniformsPhysical(m_uniforms, material);
  15482. } else {
  15483. refreshUniformsStandard(m_uniforms, material);
  15484. }
  15485. } else if (material.isMeshMatcapMaterial) {
  15486. refreshUniformsCommon(m_uniforms, material);
  15487. refreshUniformsMatcap(m_uniforms, material);
  15488. } else if (material.isMeshDepthMaterial) {
  15489. refreshUniformsCommon(m_uniforms, material);
  15490. refreshUniformsDepth(m_uniforms, material);
  15491. } else if (material.isMeshDistanceMaterial) {
  15492. refreshUniformsCommon(m_uniforms, material);
  15493. refreshUniformsDistance(m_uniforms, material);
  15494. } else if (material.isMeshNormalMaterial) {
  15495. refreshUniformsCommon(m_uniforms, material);
  15496. refreshUniformsNormal(m_uniforms, material);
  15497. } else if (material.isLineBasicMaterial) {
  15498. refreshUniformsLine(m_uniforms, material);
  15499. if (material.isLineDashedMaterial) {
  15500. refreshUniformsDash(m_uniforms, material);
  15501. }
  15502. } else if (material.isPointsMaterial) {
  15503. refreshUniformsPoints(m_uniforms, material);
  15504. } else if (material.isSpriteMaterial) {
  15505. refreshUniformsSprites(m_uniforms, material);
  15506. } else if (material.isShadowMaterial) {
  15507. m_uniforms.color.value.copy(material.color);
  15508. m_uniforms.opacity.value = material.opacity;
  15509. } // RectAreaLight Texture
  15510. // TODO (mrdoob): Find a nicer implementation
  15511. if (m_uniforms.ltc_1 !== undefined) m_uniforms.ltc_1.value = UniformsLib.LTC_1;
  15512. if (m_uniforms.ltc_2 !== undefined) m_uniforms.ltc_2.value = UniformsLib.LTC_2;
  15513. WebGLUniforms.upload(_gl, materialProperties.uniformsList, m_uniforms, textures);
  15514. }
  15515. if (material.isShaderMaterial && material.uniformsNeedUpdate === true) {
  15516. WebGLUniforms.upload(_gl, materialProperties.uniformsList, m_uniforms, textures);
  15517. material.uniformsNeedUpdate = false;
  15518. }
  15519. if (material.isSpriteMaterial) {
  15520. p_uniforms.setValue(_gl, 'center', object.center);
  15521. } // common matrices
  15522. if (program.numMultiviewViews > 0) {
  15523. multiview.updateObjectMatricesUniforms(object, camera, p_uniforms);
  15524. } else {
  15525. p_uniforms.setValue(_gl, 'modelViewMatrix', object.modelViewMatrix);
  15526. p_uniforms.setValue(_gl, 'normalMatrix', object.normalMatrix);
  15527. }
  15528. p_uniforms.setValue(_gl, 'modelMatrix', object.matrixWorld);
  15529. return program;
  15530. } // Uniforms (refresh uniforms objects)
  15531. function refreshUniformsCommon(uniforms, material) {
  15532. uniforms.opacity.value = material.opacity;
  15533. if (material.color) {
  15534. uniforms.diffuse.value.copy(material.color);
  15535. }
  15536. if (material.emissive) {
  15537. uniforms.emissive.value.copy(material.emissive).multiplyScalar(material.emissiveIntensity);
  15538. }
  15539. if (material.map) {
  15540. uniforms.map.value = material.map;
  15541. }
  15542. if (material.alphaMap) {
  15543. uniforms.alphaMap.value = material.alphaMap;
  15544. }
  15545. if (material.specularMap) {
  15546. uniforms.specularMap.value = material.specularMap;
  15547. }
  15548. if (material.envMap) {
  15549. uniforms.envMap.value = material.envMap; // don't flip CubeTexture envMaps, flip everything else:
  15550. // WebGLRenderTargetCube will be flipped for backwards compatibility
  15551. // WebGLRenderTargetCube.texture will be flipped because it's a Texture and NOT a CubeTexture
  15552. // this check must be handled differently, or removed entirely, if WebGLRenderTargetCube uses a CubeTexture in the future
  15553. uniforms.flipEnvMap.value = material.envMap.isCubeTexture ? -1 : 1;
  15554. uniforms.reflectivity.value = material.reflectivity;
  15555. uniforms.refractionRatio.value = material.refractionRatio;
  15556. uniforms.maxMipLevel.value = properties.get(material.envMap).__maxMipLevel;
  15557. }
  15558. if (material.lightMap) {
  15559. uniforms.lightMap.value = material.lightMap;
  15560. uniforms.lightMapIntensity.value = material.lightMapIntensity;
  15561. }
  15562. if (material.aoMap) {
  15563. uniforms.aoMap.value = material.aoMap;
  15564. uniforms.aoMapIntensity.value = material.aoMapIntensity;
  15565. } // uv repeat and offset setting priorities
  15566. // 1. color map
  15567. // 2. specular map
  15568. // 3. normal map
  15569. // 4. bump map
  15570. // 5. alpha map
  15571. // 6. emissive map
  15572. var uvScaleMap;
  15573. if (material.map) {
  15574. uvScaleMap = material.map;
  15575. } else if (material.specularMap) {
  15576. uvScaleMap = material.specularMap;
  15577. } else if (material.displacementMap) {
  15578. uvScaleMap = material.displacementMap;
  15579. } else if (material.normalMap) {
  15580. uvScaleMap = material.normalMap;
  15581. } else if (material.bumpMap) {
  15582. uvScaleMap = material.bumpMap;
  15583. } else if (material.roughnessMap) {
  15584. uvScaleMap = material.roughnessMap;
  15585. } else if (material.metalnessMap) {
  15586. uvScaleMap = material.metalnessMap;
  15587. } else if (material.alphaMap) {
  15588. uvScaleMap = material.alphaMap;
  15589. } else if (material.emissiveMap) {
  15590. uvScaleMap = material.emissiveMap;
  15591. }
  15592. if (uvScaleMap !== undefined) {
  15593. // backwards compatibility
  15594. if (uvScaleMap.isWebGLRenderTarget) {
  15595. uvScaleMap = uvScaleMap.texture;
  15596. }
  15597. if (uvScaleMap.matrixAutoUpdate === true) {
  15598. uvScaleMap.updateMatrix();
  15599. }
  15600. uniforms.uvTransform.value.copy(uvScaleMap.matrix);
  15601. }
  15602. }
  15603. function refreshUniformsLine(uniforms, material) {
  15604. uniforms.diffuse.value.copy(material.color);
  15605. uniforms.opacity.value = material.opacity;
  15606. }
  15607. function refreshUniformsDash(uniforms, material) {
  15608. uniforms.dashSize.value = material.dashSize;
  15609. uniforms.totalSize.value = material.dashSize + material.gapSize;
  15610. uniforms.scale.value = material.scale;
  15611. }
  15612. function refreshUniformsPoints(uniforms, material) {
  15613. uniforms.diffuse.value.copy(material.color);
  15614. uniforms.opacity.value = material.opacity;
  15615. uniforms.size.value = material.size * _pixelRatio;
  15616. uniforms.scale.value = _height * 0.5;
  15617. uniforms.map.value = material.map;
  15618. if (material.map !== null) {
  15619. if (material.map.matrixAutoUpdate === true) {
  15620. material.map.updateMatrix();
  15621. }
  15622. uniforms.uvTransform.value.copy(material.map.matrix);
  15623. }
  15624. }
  15625. function refreshUniformsSprites(uniforms, material) {
  15626. uniforms.diffuse.value.copy(material.color);
  15627. uniforms.opacity.value = material.opacity;
  15628. uniforms.rotation.value = material.rotation;
  15629. uniforms.map.value = material.map;
  15630. if (material.map !== null) {
  15631. if (material.map.matrixAutoUpdate === true) {
  15632. material.map.updateMatrix();
  15633. }
  15634. uniforms.uvTransform.value.copy(material.map.matrix);
  15635. }
  15636. }
  15637. function refreshUniformsFog(uniforms, fog) {
  15638. uniforms.fogColor.value.copy(fog.color);
  15639. if (fog.isFog) {
  15640. uniforms.fogNear.value = fog.near;
  15641. uniforms.fogFar.value = fog.far;
  15642. } else if (fog.isFogExp2) {
  15643. uniforms.fogDensity.value = fog.density;
  15644. }
  15645. }
  15646. function refreshUniformsLambert(uniforms, material) {
  15647. if (material.emissiveMap) {
  15648. uniforms.emissiveMap.value = material.emissiveMap;
  15649. }
  15650. }
  15651. function refreshUniformsPhong(uniforms, material) {
  15652. uniforms.specular.value.copy(material.specular);
  15653. uniforms.shininess.value = Math.max(material.shininess, 1e-4); // to prevent pow( 0.0, 0.0 )
  15654. if (material.emissiveMap) {
  15655. uniforms.emissiveMap.value = material.emissiveMap;
  15656. }
  15657. if (material.bumpMap) {
  15658. uniforms.bumpMap.value = material.bumpMap;
  15659. uniforms.bumpScale.value = material.bumpScale;
  15660. if (material.side === BackSide) uniforms.bumpScale.value *= -1;
  15661. }
  15662. if (material.normalMap) {
  15663. uniforms.normalMap.value = material.normalMap;
  15664. uniforms.normalScale.value.copy(material.normalScale);
  15665. if (material.side === BackSide) uniforms.normalScale.value.negate();
  15666. }
  15667. if (material.displacementMap) {
  15668. uniforms.displacementMap.value = material.displacementMap;
  15669. uniforms.displacementScale.value = material.displacementScale;
  15670. uniforms.displacementBias.value = material.displacementBias;
  15671. }
  15672. }
  15673. function refreshUniformsToon(uniforms, material) {
  15674. refreshUniformsPhong(uniforms, material);
  15675. if (material.gradientMap) {
  15676. uniforms.gradientMap.value = material.gradientMap;
  15677. }
  15678. }
  15679. function refreshUniformsStandard(uniforms, material) {
  15680. uniforms.roughness.value = material.roughness;
  15681. uniforms.metalness.value = material.metalness;
  15682. if (material.roughnessMap) {
  15683. uniforms.roughnessMap.value = material.roughnessMap;
  15684. }
  15685. if (material.metalnessMap) {
  15686. uniforms.metalnessMap.value = material.metalnessMap;
  15687. }
  15688. if (material.emissiveMap) {
  15689. uniforms.emissiveMap.value = material.emissiveMap;
  15690. }
  15691. if (material.bumpMap) {
  15692. uniforms.bumpMap.value = material.bumpMap;
  15693. uniforms.bumpScale.value = material.bumpScale;
  15694. if (material.side === BackSide) uniforms.bumpScale.value *= -1;
  15695. }
  15696. if (material.normalMap) {
  15697. uniforms.normalMap.value = material.normalMap;
  15698. uniforms.normalScale.value.copy(material.normalScale);
  15699. if (material.side === BackSide) uniforms.normalScale.value.negate();
  15700. }
  15701. if (material.displacementMap) {
  15702. uniforms.displacementMap.value = material.displacementMap;
  15703. uniforms.displacementScale.value = material.displacementScale;
  15704. uniforms.displacementBias.value = material.displacementBias;
  15705. }
  15706. if (material.envMap) {
  15707. //uniforms.envMap.value = material.envMap; // part of uniforms common
  15708. uniforms.envMapIntensity.value = material.envMapIntensity;
  15709. }
  15710. }
  15711. function refreshUniformsPhysical(uniforms, material) {
  15712. refreshUniformsStandard(uniforms, material);
  15713. uniforms.reflectivity.value = material.reflectivity; // also part of uniforms common
  15714. uniforms.clearcoat.value = material.clearcoat;
  15715. uniforms.clearcoatRoughness.value = material.clearcoatRoughness;
  15716. if (material.sheen) uniforms.sheen.value.copy(material.sheen);
  15717. if (material.clearcoatNormalMap) {
  15718. uniforms.clearcoatNormalScale.value.copy(material.clearcoatNormalScale);
  15719. uniforms.clearcoatNormalMap.value = material.clearcoatNormalMap;
  15720. if (material.side === BackSide) {
  15721. uniforms.clearcoatNormalScale.value.negate();
  15722. }
  15723. }
  15724. uniforms.transparency.value = material.transparency;
  15725. }
  15726. function refreshUniformsMatcap(uniforms, material) {
  15727. if (material.matcap) {
  15728. uniforms.matcap.value = material.matcap;
  15729. }
  15730. if (material.bumpMap) {
  15731. uniforms.bumpMap.value = material.bumpMap;
  15732. uniforms.bumpScale.value = material.bumpScale;
  15733. if (material.side === BackSide) uniforms.bumpScale.value *= -1;
  15734. }
  15735. if (material.normalMap) {
  15736. uniforms.normalMap.value = material.normalMap;
  15737. uniforms.normalScale.value.copy(material.normalScale);
  15738. if (material.side === BackSide) uniforms.normalScale.value.negate();
  15739. }
  15740. if (material.displacementMap) {
  15741. uniforms.displacementMap.value = material.displacementMap;
  15742. uniforms.displacementScale.value = material.displacementScale;
  15743. uniforms.displacementBias.value = material.displacementBias;
  15744. }
  15745. }
  15746. function refreshUniformsDepth(uniforms, material) {
  15747. if (material.displacementMap) {
  15748. uniforms.displacementMap.value = material.displacementMap;
  15749. uniforms.displacementScale.value = material.displacementScale;
  15750. uniforms.displacementBias.value = material.displacementBias;
  15751. }
  15752. }
  15753. function refreshUniformsDistance(uniforms, material) {
  15754. if (material.displacementMap) {
  15755. uniforms.displacementMap.value = material.displacementMap;
  15756. uniforms.displacementScale.value = material.displacementScale;
  15757. uniforms.displacementBias.value = material.displacementBias;
  15758. }
  15759. uniforms.referencePosition.value.copy(material.referencePosition);
  15760. uniforms.nearDistance.value = material.nearDistance;
  15761. uniforms.farDistance.value = material.farDistance;
  15762. }
  15763. function refreshUniformsNormal(uniforms, material) {
  15764. if (material.bumpMap) {
  15765. uniforms.bumpMap.value = material.bumpMap;
  15766. uniforms.bumpScale.value = material.bumpScale;
  15767. if (material.side === BackSide) uniforms.bumpScale.value *= -1;
  15768. }
  15769. if (material.normalMap) {
  15770. uniforms.normalMap.value = material.normalMap;
  15771. uniforms.normalScale.value.copy(material.normalScale);
  15772. if (material.side === BackSide) uniforms.normalScale.value.negate();
  15773. }
  15774. if (material.displacementMap) {
  15775. uniforms.displacementMap.value = material.displacementMap;
  15776. uniforms.displacementScale.value = material.displacementScale;
  15777. uniforms.displacementBias.value = material.displacementBias;
  15778. }
  15779. } // If uniforms are marked as clean, they don't need to be loaded to the GPU.
  15780. function markUniformsLightsNeedsUpdate(uniforms, value) {
  15781. uniforms.ambientLightColor.needsUpdate = value;
  15782. uniforms.lightProbe.needsUpdate = value;
  15783. uniforms.directionalLights.needsUpdate = value;
  15784. uniforms.pointLights.needsUpdate = value;
  15785. uniforms.spotLights.needsUpdate = value;
  15786. uniforms.rectAreaLights.needsUpdate = value;
  15787. uniforms.hemisphereLights.needsUpdate = value;
  15788. }
  15789. function materialNeedsLights(material) {
  15790. return material.isMeshLambertMaterial || material.isMeshPhongMaterial || material.isMeshStandardMaterial || material.isShadowMaterial || material.isShaderMaterial && material.lights === true;
  15791. } //
  15792. this.setFramebuffer = function (value) {
  15793. if (_framebuffer !== value) _gl.bindFramebuffer(36160, value);
  15794. _framebuffer = value;
  15795. };
  15796. this.getActiveCubeFace = function () {
  15797. return _currentActiveCubeFace;
  15798. };
  15799. this.getActiveMipmapLevel = function () {
  15800. return _currentActiveMipmapLevel;
  15801. };
  15802. this.getRenderTarget = function () {
  15803. return _currentRenderTarget;
  15804. };
  15805. this.setRenderTarget = function (renderTarget, activeCubeFace, activeMipmapLevel) {
  15806. _currentRenderTarget = renderTarget;
  15807. _currentActiveCubeFace = activeCubeFace;
  15808. _currentActiveMipmapLevel = activeMipmapLevel;
  15809. if (renderTarget && properties.get(renderTarget).__webglFramebuffer === undefined) {
  15810. textures.setupRenderTarget(renderTarget);
  15811. }
  15812. var framebuffer = _framebuffer;
  15813. var isCube = false;
  15814. if (renderTarget) {
  15815. var __webglFramebuffer = properties.get(renderTarget).__webglFramebuffer;
  15816. if (renderTarget.isWebGLRenderTargetCube) {
  15817. framebuffer = __webglFramebuffer[activeCubeFace || 0];
  15818. isCube = true;
  15819. } else if (renderTarget.isWebGLMultisampleRenderTarget) {
  15820. framebuffer = properties.get(renderTarget).__webglMultisampledFramebuffer;
  15821. } else {
  15822. framebuffer = __webglFramebuffer;
  15823. }
  15824. _currentViewport.copy(renderTarget.viewport);
  15825. _currentScissor.copy(renderTarget.scissor);
  15826. _currentScissorTest = renderTarget.scissorTest;
  15827. } else {
  15828. _currentViewport.copy(_viewport).multiplyScalar(_pixelRatio).floor();
  15829. _currentScissor.copy(_scissor).multiplyScalar(_pixelRatio).floor();
  15830. _currentScissorTest = _scissorTest;
  15831. }
  15832. if (_currentFramebuffer !== framebuffer) {
  15833. _gl.bindFramebuffer(36160, framebuffer);
  15834. _currentFramebuffer = framebuffer;
  15835. }
  15836. state.viewport(_currentViewport);
  15837. state.scissor(_currentScissor);
  15838. state.setScissorTest(_currentScissorTest);
  15839. if (isCube) {
  15840. var textureProperties = properties.get(renderTarget.texture);
  15841. _gl.framebufferTexture2D(36160, 36064, 34069 + (activeCubeFace || 0), textureProperties.__webglTexture, activeMipmapLevel || 0);
  15842. }
  15843. };
  15844. this.readRenderTargetPixels = function (renderTarget, x, y, width, height, buffer, activeCubeFaceIndex) {
  15845. if (!(renderTarget && renderTarget.isWebGLRenderTarget)) {
  15846. console.error('THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.');
  15847. return;
  15848. }
  15849. var framebuffer = properties.get(renderTarget).__webglFramebuffer;
  15850. if (renderTarget.isWebGLRenderTargetCube && activeCubeFaceIndex !== undefined) {
  15851. framebuffer = framebuffer[activeCubeFaceIndex];
  15852. }
  15853. if (framebuffer) {
  15854. var restore = false;
  15855. if (framebuffer !== _currentFramebuffer) {
  15856. _gl.bindFramebuffer(36160, framebuffer);
  15857. restore = true;
  15858. }
  15859. try {
  15860. var texture = renderTarget.texture;
  15861. var textureFormat = texture.format;
  15862. var textureType = texture.type;
  15863. if (textureFormat !== RGBAFormat && utils.convert(textureFormat) !== _gl.getParameter(35739)) {
  15864. console.error('THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.');
  15865. return;
  15866. }
  15867. if (textureType !== UnsignedByteType && utils.convert(textureType) !== _gl.getParameter(35738) && // IE11, Edge and Chrome Mac < 52 (#9513)
  15868. !(textureType === FloatType && (capabilities.isWebGL2 || extensions.get('OES_texture_float') || extensions.get('WEBGL_color_buffer_float'))) && // Chrome Mac >= 52 and Firefox
  15869. !(textureType === HalfFloatType && (capabilities.isWebGL2 ? extensions.get('EXT_color_buffer_float') : extensions.get('EXT_color_buffer_half_float')))) {
  15870. console.error('THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.');
  15871. return;
  15872. }
  15873. if (_gl.checkFramebufferStatus(36160) === 36053) {
  15874. // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604)
  15875. if (x >= 0 && x <= renderTarget.width - width && y >= 0 && y <= renderTarget.height - height) {
  15876. _gl.readPixels(x, y, width, height, utils.convert(textureFormat), utils.convert(textureType), buffer);
  15877. }
  15878. } else {
  15879. console.error('THREE.WebGLRenderer.readRenderTargetPixels: readPixels from renderTarget failed. Framebuffer not complete.');
  15880. }
  15881. } finally {
  15882. if (restore) {
  15883. _gl.bindFramebuffer(36160, _currentFramebuffer);
  15884. }
  15885. }
  15886. }
  15887. };
  15888. this.copyFramebufferToTexture = function (position, texture, level) {
  15889. var width = texture.image.width;
  15890. var height = texture.image.height;
  15891. var glFormat = utils.convert(texture.format);
  15892. textures.setTexture2D(texture, 0);
  15893. _gl.copyTexImage2D(3553, level || 0, glFormat, position.x, position.y, width, height, 0);
  15894. };
  15895. this.copyTextureToTexture = function (position, srcTexture, dstTexture, level) {
  15896. var width = srcTexture.image.width;
  15897. var height = srcTexture.image.height;
  15898. var glFormat = utils.convert(dstTexture.format);
  15899. var glType = utils.convert(dstTexture.type);
  15900. textures.setTexture2D(dstTexture, 0);
  15901. if (srcTexture.isDataTexture) {
  15902. _gl.texSubImage2D(3553, level || 0, position.x, position.y, width, height, glFormat, glType, srcTexture.image.data);
  15903. } else {
  15904. _gl.texSubImage2D(3553, level || 0, position.x, position.y, glFormat, glType, srcTexture.image);
  15905. }
  15906. };
  15907. if (typeof __THREE_DEVTOOLS__ !== 'undefined') {
  15908. __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent('observe', {
  15909. detail: this
  15910. })); // eslint-disable-line no-undef
  15911. }
  15912. }
  15913. /**
  15914. * @author mrdoob / http://mrdoob.com/
  15915. * @author alteredq / http://alteredqualia.com/
  15916. */
  15917. function FogExp2(color, density) {
  15918. this.name = '';
  15919. this.color = new Color(color);
  15920. this.density = density !== undefined ? density : 0.00025;
  15921. }
  15922. Object.assign(FogExp2.prototype, {
  15923. isFogExp2: true,
  15924. clone: function () {
  15925. return new FogExp2(this.color, this.density);
  15926. },
  15927. toJSON: function ()
  15928. /* meta */
  15929. {
  15930. return {
  15931. type: 'FogExp2',
  15932. color: this.color.getHex(),
  15933. density: this.density
  15934. };
  15935. }
  15936. });
  15937. /**
  15938. * @author mrdoob / http://mrdoob.com/
  15939. * @author alteredq / http://alteredqualia.com/
  15940. */
  15941. function Fog(color, near, far) {
  15942. this.name = '';
  15943. this.color = new Color(color);
  15944. this.near = near !== undefined ? near : 1;
  15945. this.far = far !== undefined ? far : 1000;
  15946. }
  15947. Object.assign(Fog.prototype, {
  15948. isFog: true,
  15949. clone: function () {
  15950. return new Fog(this.color, this.near, this.far);
  15951. },
  15952. toJSON: function ()
  15953. /* meta */
  15954. {
  15955. return {
  15956. type: 'Fog',
  15957. color: this.color.getHex(),
  15958. near: this.near,
  15959. far: this.far
  15960. };
  15961. }
  15962. });
  15963. /**
  15964. * @author benaadams / https://twitter.com/ben_a_adams
  15965. */
  15966. function InterleavedBuffer(array, stride) {
  15967. this.array = array;
  15968. this.stride = stride;
  15969. this.count = array !== undefined ? array.length / stride : 0;
  15970. this.dynamic = false;
  15971. this.updateRange = {
  15972. offset: 0,
  15973. count: -1
  15974. };
  15975. this.version = 0;
  15976. }
  15977. Object.defineProperty(InterleavedBuffer.prototype, 'needsUpdate', {
  15978. set: function (value) {
  15979. if (value === true) this.version++;
  15980. }
  15981. });
  15982. Object.assign(InterleavedBuffer.prototype, {
  15983. isInterleavedBuffer: true,
  15984. onUploadCallback: function () {},
  15985. setDynamic: function (value) {
  15986. this.dynamic = value;
  15987. return this;
  15988. },
  15989. copy: function (source) {
  15990. this.array = new source.array.constructor(source.array);
  15991. this.count = source.count;
  15992. this.stride = source.stride;
  15993. this.dynamic = source.dynamic;
  15994. return this;
  15995. },
  15996. copyAt: function (index1, attribute, index2) {
  15997. index1 *= this.stride;
  15998. index2 *= attribute.stride;
  15999. for (var i = 0, l = this.stride; i < l; i++) {
  16000. this.array[index1 + i] = attribute.array[index2 + i];
  16001. }
  16002. return this;
  16003. },
  16004. set: function (value, offset) {
  16005. if (offset === undefined) offset = 0;
  16006. this.array.set(value, offset);
  16007. return this;
  16008. },
  16009. clone: function () {
  16010. return new this.constructor().copy(this);
  16011. },
  16012. onUpload: function (callback) {
  16013. this.onUploadCallback = callback;
  16014. return this;
  16015. }
  16016. });
  16017. /**
  16018. * @author benaadams / https://twitter.com/ben_a_adams
  16019. */
  16020. function InterleavedBufferAttribute(interleavedBuffer, itemSize, offset, normalized) {
  16021. this.data = interleavedBuffer;
  16022. this.itemSize = itemSize;
  16023. this.offset = offset;
  16024. this.normalized = normalized === true;
  16025. }
  16026. Object.defineProperties(InterleavedBufferAttribute.prototype, {
  16027. count: {
  16028. get: function () {
  16029. return this.data.count;
  16030. }
  16031. },
  16032. array: {
  16033. get: function () {
  16034. return this.data.array;
  16035. }
  16036. }
  16037. });
  16038. Object.assign(InterleavedBufferAttribute.prototype, {
  16039. isInterleavedBufferAttribute: true,
  16040. setX: function (index, x) {
  16041. this.data.array[index * this.data.stride + this.offset] = x;
  16042. return this;
  16043. },
  16044. setY: function (index, y) {
  16045. this.data.array[index * this.data.stride + this.offset + 1] = y;
  16046. return this;
  16047. },
  16048. setZ: function (index, z) {
  16049. this.data.array[index * this.data.stride + this.offset + 2] = z;
  16050. return this;
  16051. },
  16052. setW: function (index, w) {
  16053. this.data.array[index * this.data.stride + this.offset + 3] = w;
  16054. return this;
  16055. },
  16056. getX: function (index) {
  16057. return this.data.array[index * this.data.stride + this.offset];
  16058. },
  16059. getY: function (index) {
  16060. return this.data.array[index * this.data.stride + this.offset + 1];
  16061. },
  16062. getZ: function (index) {
  16063. return this.data.array[index * this.data.stride + this.offset + 2];
  16064. },
  16065. getW: function (index) {
  16066. return this.data.array[index * this.data.stride + this.offset + 3];
  16067. },
  16068. setXY: function (index, x, y) {
  16069. index = index * this.data.stride + this.offset;
  16070. this.data.array[index + 0] = x;
  16071. this.data.array[index + 1] = y;
  16072. return this;
  16073. },
  16074. setXYZ: function (index, x, y, z) {
  16075. index = index * this.data.stride + this.offset;
  16076. this.data.array[index + 0] = x;
  16077. this.data.array[index + 1] = y;
  16078. this.data.array[index + 2] = z;
  16079. return this;
  16080. },
  16081. setXYZW: function (index, x, y, z, w) {
  16082. index = index * this.data.stride + this.offset;
  16083. this.data.array[index + 0] = x;
  16084. this.data.array[index + 1] = y;
  16085. this.data.array[index + 2] = z;
  16086. this.data.array[index + 3] = w;
  16087. return this;
  16088. }
  16089. });
  16090. /**
  16091. * @author alteredq / http://alteredqualia.com/
  16092. *
  16093. * parameters = {
  16094. * color: <hex>,
  16095. * map: new THREE.Texture( <Image> ),
  16096. * rotation: <float>,
  16097. * sizeAttenuation: <bool>
  16098. * }
  16099. */
  16100. function SpriteMaterial(parameters) {
  16101. Material.call(this);
  16102. this.type = 'SpriteMaterial';
  16103. this.color = new Color(0xffffff);
  16104. this.map = null;
  16105. this.rotation = 0;
  16106. this.sizeAttenuation = true;
  16107. this.transparent = true;
  16108. this.setValues(parameters);
  16109. }
  16110. SpriteMaterial.prototype = Object.create(Material.prototype);
  16111. SpriteMaterial.prototype.constructor = SpriteMaterial;
  16112. SpriteMaterial.prototype.isSpriteMaterial = true;
  16113. SpriteMaterial.prototype.copy = function (source) {
  16114. Material.prototype.copy.call(this, source);
  16115. this.color.copy(source.color);
  16116. this.map = source.map;
  16117. this.rotation = source.rotation;
  16118. this.sizeAttenuation = source.sizeAttenuation;
  16119. return this;
  16120. };
  16121. /**
  16122. * @author mikael emtinger / http://gomo.se/
  16123. * @author alteredq / http://alteredqualia.com/
  16124. */
  16125. var _geometry;
  16126. var _intersectPoint = new Vector3();
  16127. var _worldScale = new Vector3();
  16128. var _mvPosition = new Vector3();
  16129. var _alignedPosition = new Vector2();
  16130. var _rotatedPosition = new Vector2();
  16131. var _viewWorldMatrix = new Matrix4();
  16132. var _vA$1 = new Vector3();
  16133. var _vB$1 = new Vector3();
  16134. var _vC$1 = new Vector3();
  16135. var _uvA$1 = new Vector2();
  16136. var _uvB$1 = new Vector2();
  16137. var _uvC$1 = new Vector2();
  16138. function Sprite(material) {
  16139. Object3D.call(this);
  16140. this.type = 'Sprite';
  16141. if (_geometry === undefined) {
  16142. _geometry = new BufferGeometry();
  16143. 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]);
  16144. var interleavedBuffer = new InterleavedBuffer(float32Array, 5);
  16145. _geometry.setIndex([0, 1, 2, 0, 2, 3]);
  16146. _geometry.addAttribute('position', new InterleavedBufferAttribute(interleavedBuffer, 3, 0, false));
  16147. _geometry.addAttribute('uv', new InterleavedBufferAttribute(interleavedBuffer, 2, 3, false));
  16148. }
  16149. this.geometry = _geometry;
  16150. this.material = material !== undefined ? material : new SpriteMaterial();
  16151. this.center = new Vector2(0.5, 0.5);
  16152. }
  16153. Sprite.prototype = Object.assign(Object.create(Object3D.prototype), {
  16154. constructor: Sprite,
  16155. isSprite: true,
  16156. raycast: function (raycaster, intersects) {
  16157. if (raycaster.camera === null) {
  16158. console.error('THREE.Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.');
  16159. }
  16160. _worldScale.setFromMatrixScale(this.matrixWorld);
  16161. _viewWorldMatrix.copy(raycaster.camera.matrixWorld);
  16162. this.modelViewMatrix.multiplyMatrices(raycaster.camera.matrixWorldInverse, this.matrixWorld);
  16163. _mvPosition.setFromMatrixPosition(this.modelViewMatrix);
  16164. if (raycaster.camera.isPerspectiveCamera && this.material.sizeAttenuation === false) {
  16165. _worldScale.multiplyScalar(-_mvPosition.z);
  16166. }
  16167. var rotation = this.material.rotation;
  16168. var sin, cos;
  16169. if (rotation !== 0) {
  16170. cos = Math.cos(rotation);
  16171. sin = Math.sin(rotation);
  16172. }
  16173. var center = this.center;
  16174. transformVertex(_vA$1.set(-0.5, -0.5, 0), _mvPosition, center, _worldScale, sin, cos);
  16175. transformVertex(_vB$1.set(0.5, -0.5, 0), _mvPosition, center, _worldScale, sin, cos);
  16176. transformVertex(_vC$1.set(0.5, 0.5, 0), _mvPosition, center, _worldScale, sin, cos);
  16177. _uvA$1.set(0, 0);
  16178. _uvB$1.set(1, 0);
  16179. _uvC$1.set(1, 1); // check first triangle
  16180. var intersect = raycaster.ray.intersectTriangle(_vA$1, _vB$1, _vC$1, false, _intersectPoint);
  16181. if (intersect === null) {
  16182. // check second triangle
  16183. transformVertex(_vB$1.set(-0.5, 0.5, 0), _mvPosition, center, _worldScale, sin, cos);
  16184. _uvB$1.set(0, 1);
  16185. intersect = raycaster.ray.intersectTriangle(_vA$1, _vC$1, _vB$1, false, _intersectPoint);
  16186. if (intersect === null) {
  16187. return;
  16188. }
  16189. }
  16190. var distance = raycaster.ray.origin.distanceTo(_intersectPoint);
  16191. if (distance < raycaster.near || distance > raycaster.far) return;
  16192. intersects.push({
  16193. distance: distance,
  16194. point: _intersectPoint.clone(),
  16195. uv: Triangle.getUV(_intersectPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2()),
  16196. face: null,
  16197. object: this
  16198. });
  16199. },
  16200. clone: function () {
  16201. return new this.constructor(this.material).copy(this);
  16202. },
  16203. copy: function (source) {
  16204. Object3D.prototype.copy.call(this, source);
  16205. if (source.center !== undefined) this.center.copy(source.center);
  16206. return this;
  16207. }
  16208. });
  16209. function transformVertex(vertexPosition, mvPosition, center, scale, sin, cos) {
  16210. // compute position in camera space
  16211. _alignedPosition.subVectors(vertexPosition, center).addScalar(0.5).multiply(scale); // to check if rotation is not zero
  16212. if (sin !== undefined) {
  16213. _rotatedPosition.x = cos * _alignedPosition.x - sin * _alignedPosition.y;
  16214. _rotatedPosition.y = sin * _alignedPosition.x + cos * _alignedPosition.y;
  16215. } else {
  16216. _rotatedPosition.copy(_alignedPosition);
  16217. }
  16218. vertexPosition.copy(mvPosition);
  16219. vertexPosition.x += _rotatedPosition.x;
  16220. vertexPosition.y += _rotatedPosition.y; // transform to world space
  16221. vertexPosition.applyMatrix4(_viewWorldMatrix);
  16222. }
  16223. /**
  16224. * @author mikael emtinger / http://gomo.se/
  16225. * @author alteredq / http://alteredqualia.com/
  16226. * @author mrdoob / http://mrdoob.com/
  16227. */
  16228. var _v1$4 = new Vector3();
  16229. var _v2$2 = new Vector3();
  16230. function LOD() {
  16231. Object3D.call(this);
  16232. this.type = 'LOD';
  16233. Object.defineProperties(this, {
  16234. levels: {
  16235. enumerable: true,
  16236. value: []
  16237. }
  16238. });
  16239. this.autoUpdate = true;
  16240. }
  16241. LOD.prototype = Object.assign(Object.create(Object3D.prototype), {
  16242. constructor: LOD,
  16243. isLOD: true,
  16244. copy: function (source) {
  16245. Object3D.prototype.copy.call(this, source, false);
  16246. var levels = source.levels;
  16247. for (var i = 0, l = levels.length; i < l; i++) {
  16248. var level = levels[i];
  16249. this.addLevel(level.object.clone(), level.distance);
  16250. }
  16251. return this;
  16252. },
  16253. addLevel: function (object, distance) {
  16254. if (distance === undefined) distance = 0;
  16255. distance = Math.abs(distance);
  16256. var levels = this.levels;
  16257. for (var l = 0; l < levels.length; l++) {
  16258. if (distance < levels[l].distance) {
  16259. break;
  16260. }
  16261. }
  16262. levels.splice(l, 0, {
  16263. distance: distance,
  16264. object: object
  16265. });
  16266. this.add(object);
  16267. return this;
  16268. },
  16269. getObjectForDistance: function (distance) {
  16270. var levels = this.levels;
  16271. for (var i = 1, l = levels.length; i < l; i++) {
  16272. if (distance < levels[i].distance) {
  16273. break;
  16274. }
  16275. }
  16276. return levels[i - 1].object;
  16277. },
  16278. raycast: function (raycaster, intersects) {
  16279. _v1$4.setFromMatrixPosition(this.matrixWorld);
  16280. var distance = raycaster.ray.origin.distanceTo(_v1$4);
  16281. this.getObjectForDistance(distance).raycast(raycaster, intersects);
  16282. },
  16283. update: function (camera) {
  16284. var levels = this.levels;
  16285. if (levels.length > 1) {
  16286. _v1$4.setFromMatrixPosition(camera.matrixWorld);
  16287. _v2$2.setFromMatrixPosition(this.matrixWorld);
  16288. var distance = _v1$4.distanceTo(_v2$2);
  16289. levels[0].object.visible = true;
  16290. for (var i = 1, l = levels.length; i < l; i++) {
  16291. if (distance >= levels[i].distance) {
  16292. levels[i - 1].object.visible = false;
  16293. levels[i].object.visible = true;
  16294. } else {
  16295. break;
  16296. }
  16297. }
  16298. for (; i < l; i++) {
  16299. levels[i].object.visible = false;
  16300. }
  16301. }
  16302. },
  16303. toJSON: function (meta) {
  16304. var data = Object3D.prototype.toJSON.call(this, meta);
  16305. data.object.levels = [];
  16306. var levels = this.levels;
  16307. for (var i = 0, l = levels.length; i < l; i++) {
  16308. var level = levels[i];
  16309. data.object.levels.push({
  16310. object: level.object.uuid,
  16311. distance: level.distance
  16312. });
  16313. }
  16314. return data;
  16315. }
  16316. });
  16317. /**
  16318. * @author mikael emtinger / http://gomo.se/
  16319. * @author alteredq / http://alteredqualia.com/
  16320. * @author ikerr / http://verold.com
  16321. */
  16322. function SkinnedMesh(geometry, material) {
  16323. if (geometry && geometry.isGeometry) {
  16324. console.error('THREE.SkinnedMesh no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');
  16325. }
  16326. Mesh.call(this, geometry, material);
  16327. this.type = 'SkinnedMesh';
  16328. this.bindMode = 'attached';
  16329. this.bindMatrix = new Matrix4();
  16330. this.bindMatrixInverse = new Matrix4();
  16331. }
  16332. SkinnedMesh.prototype = Object.assign(Object.create(Mesh.prototype), {
  16333. constructor: SkinnedMesh,
  16334. isSkinnedMesh: true,
  16335. bind: function (skeleton, bindMatrix) {
  16336. this.skeleton = skeleton;
  16337. if (bindMatrix === undefined) {
  16338. this.updateMatrixWorld(true);
  16339. this.skeleton.calculateInverses();
  16340. bindMatrix = this.matrixWorld;
  16341. }
  16342. this.bindMatrix.copy(bindMatrix);
  16343. this.bindMatrixInverse.getInverse(bindMatrix);
  16344. },
  16345. pose: function () {
  16346. this.skeleton.pose();
  16347. },
  16348. normalizeSkinWeights: function () {
  16349. var vector = new Vector4();
  16350. var skinWeight = this.geometry.attributes.skinWeight;
  16351. for (var i = 0, l = skinWeight.count; i < l; i++) {
  16352. vector.x = skinWeight.getX(i);
  16353. vector.y = skinWeight.getY(i);
  16354. vector.z = skinWeight.getZ(i);
  16355. vector.w = skinWeight.getW(i);
  16356. var scale = 1.0 / vector.manhattanLength();
  16357. if (scale !== Infinity) {
  16358. vector.multiplyScalar(scale);
  16359. } else {
  16360. vector.set(1, 0, 0, 0); // do something reasonable
  16361. }
  16362. skinWeight.setXYZW(i, vector.x, vector.y, vector.z, vector.w);
  16363. }
  16364. },
  16365. updateMatrixWorld: function (force) {
  16366. Mesh.prototype.updateMatrixWorld.call(this, force);
  16367. if (this.bindMode === 'attached') {
  16368. this.bindMatrixInverse.getInverse(this.matrixWorld);
  16369. } else if (this.bindMode === 'detached') {
  16370. this.bindMatrixInverse.getInverse(this.bindMatrix);
  16371. } else {
  16372. console.warn('THREE.SkinnedMesh: Unrecognized bindMode: ' + this.bindMode);
  16373. }
  16374. },
  16375. clone: function () {
  16376. return new this.constructor(this.geometry, this.material).copy(this);
  16377. }
  16378. });
  16379. /**
  16380. * @author mikael emtinger / http://gomo.se/
  16381. * @author alteredq / http://alteredqualia.com/
  16382. * @author michael guerrero / http://realitymeltdown.com
  16383. * @author ikerr / http://verold.com
  16384. */
  16385. var _offsetMatrix = new Matrix4();
  16386. var _identityMatrix = new Matrix4();
  16387. function Skeleton(bones, boneInverses) {
  16388. // copy the bone array
  16389. bones = bones || [];
  16390. this.bones = bones.slice(0);
  16391. this.boneMatrices = new Float32Array(this.bones.length * 16);
  16392. this.frame = -1; // use the supplied bone inverses or calculate the inverses
  16393. if (boneInverses === undefined) {
  16394. this.calculateInverses();
  16395. } else {
  16396. if (this.bones.length === boneInverses.length) {
  16397. this.boneInverses = boneInverses.slice(0);
  16398. } else {
  16399. console.warn('THREE.Skeleton boneInverses is the wrong length.');
  16400. this.boneInverses = [];
  16401. for (var i = 0, il = this.bones.length; i < il; i++) {
  16402. this.boneInverses.push(new Matrix4());
  16403. }
  16404. }
  16405. }
  16406. }
  16407. Object.assign(Skeleton.prototype, {
  16408. calculateInverses: function () {
  16409. this.boneInverses = [];
  16410. for (var i = 0, il = this.bones.length; i < il; i++) {
  16411. var inverse = new Matrix4();
  16412. if (this.bones[i]) {
  16413. inverse.getInverse(this.bones[i].matrixWorld);
  16414. }
  16415. this.boneInverses.push(inverse);
  16416. }
  16417. },
  16418. pose: function () {
  16419. var bone, i, il; // recover the bind-time world matrices
  16420. for (i = 0, il = this.bones.length; i < il; i++) {
  16421. bone = this.bones[i];
  16422. if (bone) {
  16423. bone.matrixWorld.getInverse(this.boneInverses[i]);
  16424. }
  16425. } // compute the local matrices, positions, rotations and scales
  16426. for (i = 0, il = this.bones.length; i < il; i++) {
  16427. bone = this.bones[i];
  16428. if (bone) {
  16429. if (bone.parent && bone.parent.isBone) {
  16430. bone.matrix.getInverse(bone.parent.matrixWorld);
  16431. bone.matrix.multiply(bone.matrixWorld);
  16432. } else {
  16433. bone.matrix.copy(bone.matrixWorld);
  16434. }
  16435. bone.matrix.decompose(bone.position, bone.quaternion, bone.scale);
  16436. }
  16437. }
  16438. },
  16439. update: function () {
  16440. var bones = this.bones;
  16441. var boneInverses = this.boneInverses;
  16442. var boneMatrices = this.boneMatrices;
  16443. var boneTexture = this.boneTexture; // flatten bone matrices to array
  16444. for (var i = 0, il = bones.length; i < il; i++) {
  16445. // compute the offset between the current and the original transform
  16446. var matrix = bones[i] ? bones[i].matrixWorld : _identityMatrix;
  16447. _offsetMatrix.multiplyMatrices(matrix, boneInverses[i]);
  16448. _offsetMatrix.toArray(boneMatrices, i * 16);
  16449. }
  16450. if (boneTexture !== undefined) {
  16451. boneTexture.needsUpdate = true;
  16452. }
  16453. },
  16454. clone: function () {
  16455. return new Skeleton(this.bones, this.boneInverses);
  16456. },
  16457. getBoneByName: function (name) {
  16458. for (var i = 0, il = this.bones.length; i < il; i++) {
  16459. var bone = this.bones[i];
  16460. if (bone.name === name) {
  16461. return bone;
  16462. }
  16463. }
  16464. return undefined;
  16465. }
  16466. });
  16467. /**
  16468. * @author mikael emtinger / http://gomo.se/
  16469. * @author alteredq / http://alteredqualia.com/
  16470. * @author ikerr / http://verold.com
  16471. */
  16472. function Bone() {
  16473. Object3D.call(this);
  16474. this.type = 'Bone';
  16475. }
  16476. Bone.prototype = Object.assign(Object.create(Object3D.prototype), {
  16477. constructor: Bone,
  16478. isBone: true
  16479. });
  16480. /**
  16481. * @author mrdoob / http://mrdoob.com/
  16482. */
  16483. function InstancedMesh(geometry, material, count) {
  16484. Mesh.call(this, geometry, material);
  16485. this.instanceMatrix = new BufferAttribute(new Float32Array(count * 16), 16);
  16486. this.count = count;
  16487. }
  16488. InstancedMesh.prototype = Object.assign(Object.create(Mesh.prototype), {
  16489. constructor: InstancedMesh,
  16490. isInstancedMesh: true,
  16491. raycast: function () {},
  16492. setMatrixAt: function (index, matrix) {
  16493. matrix.toArray(this.instanceMatrix.array, index * 16);
  16494. },
  16495. updateMorphTargets: function () {}
  16496. });
  16497. /**
  16498. * @author mrdoob / http://mrdoob.com/
  16499. * @author alteredq / http://alteredqualia.com/
  16500. *
  16501. * parameters = {
  16502. * color: <hex>,
  16503. * opacity: <float>,
  16504. *
  16505. * linewidth: <float>,
  16506. * linecap: "round",
  16507. * linejoin: "round"
  16508. * }
  16509. */
  16510. function LineBasicMaterial(parameters) {
  16511. Material.call(this);
  16512. this.type = 'LineBasicMaterial';
  16513. this.color = new Color(0xffffff);
  16514. this.linewidth = 1;
  16515. this.linecap = 'round';
  16516. this.linejoin = 'round';
  16517. this.setValues(parameters);
  16518. }
  16519. LineBasicMaterial.prototype = Object.create(Material.prototype);
  16520. LineBasicMaterial.prototype.constructor = LineBasicMaterial;
  16521. LineBasicMaterial.prototype.isLineBasicMaterial = true;
  16522. LineBasicMaterial.prototype.copy = function (source) {
  16523. Material.prototype.copy.call(this, source);
  16524. this.color.copy(source.color);
  16525. this.linewidth = source.linewidth;
  16526. this.linecap = source.linecap;
  16527. this.linejoin = source.linejoin;
  16528. return this;
  16529. };
  16530. /**
  16531. * @author mrdoob / http://mrdoob.com/
  16532. */
  16533. var _start = new Vector3();
  16534. var _end = new Vector3();
  16535. var _inverseMatrix$1 = new Matrix4();
  16536. var _ray$1 = new Ray();
  16537. var _sphere$2 = new Sphere();
  16538. function Line(geometry, material, mode) {
  16539. if (mode === 1) {
  16540. console.error('THREE.Line: parameter THREE.LinePieces no longer supported. Use THREE.LineSegments instead.');
  16541. }
  16542. Object3D.call(this);
  16543. this.type = 'Line';
  16544. this.geometry = geometry !== undefined ? geometry : new BufferGeometry();
  16545. this.material = material !== undefined ? material : new LineBasicMaterial({
  16546. color: Math.random() * 0xffffff
  16547. });
  16548. }
  16549. Line.prototype = Object.assign(Object.create(Object3D.prototype), {
  16550. constructor: Line,
  16551. isLine: true,
  16552. computeLineDistances: function () {
  16553. var geometry = this.geometry;
  16554. if (geometry.isBufferGeometry) {
  16555. // we assume non-indexed geometry
  16556. if (geometry.index === null) {
  16557. var positionAttribute = geometry.attributes.position;
  16558. var lineDistances = [0];
  16559. for (var i = 1, l = positionAttribute.count; i < l; i++) {
  16560. _start.fromBufferAttribute(positionAttribute, i - 1);
  16561. _end.fromBufferAttribute(positionAttribute, i);
  16562. lineDistances[i] = lineDistances[i - 1];
  16563. lineDistances[i] += _start.distanceTo(_end);
  16564. }
  16565. geometry.addAttribute('lineDistance', new Float32BufferAttribute(lineDistances, 1));
  16566. } else {
  16567. console.warn('THREE.Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.');
  16568. }
  16569. } else if (geometry.isGeometry) {
  16570. var vertices = geometry.vertices;
  16571. var lineDistances = geometry.lineDistances;
  16572. lineDistances[0] = 0;
  16573. for (var i = 1, l = vertices.length; i < l; i++) {
  16574. lineDistances[i] = lineDistances[i - 1];
  16575. lineDistances[i] += vertices[i - 1].distanceTo(vertices[i]);
  16576. }
  16577. }
  16578. return this;
  16579. },
  16580. raycast: function (raycaster, intersects) {
  16581. var precision = raycaster.linePrecision;
  16582. var geometry = this.geometry;
  16583. var matrixWorld = this.matrixWorld; // Checking boundingSphere distance to ray
  16584. if (geometry.boundingSphere === null) geometry.computeBoundingSphere();
  16585. _sphere$2.copy(geometry.boundingSphere);
  16586. _sphere$2.applyMatrix4(matrixWorld);
  16587. _sphere$2.radius += precision;
  16588. if (raycaster.ray.intersectsSphere(_sphere$2) === false) return; //
  16589. _inverseMatrix$1.getInverse(matrixWorld);
  16590. _ray$1.copy(raycaster.ray).applyMatrix4(_inverseMatrix$1);
  16591. var localPrecision = precision / ((this.scale.x + this.scale.y + this.scale.z) / 3);
  16592. var localPrecisionSq = localPrecision * localPrecision;
  16593. var vStart = new Vector3();
  16594. var vEnd = new Vector3();
  16595. var interSegment = new Vector3();
  16596. var interRay = new Vector3();
  16597. var step = this && this.isLineSegments ? 2 : 1;
  16598. if (geometry.isBufferGeometry) {
  16599. var index = geometry.index;
  16600. var attributes = geometry.attributes;
  16601. var positions = attributes.position.array;
  16602. if (index !== null) {
  16603. var indices = index.array;
  16604. for (var i = 0, l = indices.length - 1; i < l; i += step) {
  16605. var a = indices[i];
  16606. var b = indices[i + 1];
  16607. vStart.fromArray(positions, a * 3);
  16608. vEnd.fromArray(positions, b * 3);
  16609. var distSq = _ray$1.distanceSqToSegment(vStart, vEnd, interRay, interSegment);
  16610. if (distSq > localPrecisionSq) continue;
  16611. interRay.applyMatrix4(this.matrixWorld); //Move back to world space for distance calculation
  16612. var distance = raycaster.ray.origin.distanceTo(interRay);
  16613. if (distance < raycaster.near || distance > raycaster.far) continue;
  16614. intersects.push({
  16615. distance: distance,
  16616. // What do we want? intersection point on the ray or on the segment??
  16617. // point: raycaster.ray.at( distance ),
  16618. point: interSegment.clone().applyMatrix4(this.matrixWorld),
  16619. index: i,
  16620. face: null,
  16621. faceIndex: null,
  16622. object: this
  16623. });
  16624. }
  16625. } else {
  16626. for (var i = 0, l = positions.length / 3 - 1; i < l; i += step) {
  16627. vStart.fromArray(positions, 3 * i);
  16628. vEnd.fromArray(positions, 3 * i + 3);
  16629. var distSq = _ray$1.distanceSqToSegment(vStart, vEnd, interRay, interSegment);
  16630. if (distSq > localPrecisionSq) continue;
  16631. interRay.applyMatrix4(this.matrixWorld); //Move back to world space for distance calculation
  16632. var distance = raycaster.ray.origin.distanceTo(interRay);
  16633. if (distance < raycaster.near || distance > raycaster.far) continue;
  16634. intersects.push({
  16635. distance: distance,
  16636. // What do we want? intersection point on the ray or on the segment??
  16637. // point: raycaster.ray.at( distance ),
  16638. point: interSegment.clone().applyMatrix4(this.matrixWorld),
  16639. index: i,
  16640. face: null,
  16641. faceIndex: null,
  16642. object: this
  16643. });
  16644. }
  16645. }
  16646. } else if (geometry.isGeometry) {
  16647. var vertices = geometry.vertices;
  16648. var nbVertices = vertices.length;
  16649. for (var i = 0; i < nbVertices - 1; i += step) {
  16650. var distSq = _ray$1.distanceSqToSegment(vertices[i], vertices[i + 1], interRay, interSegment);
  16651. if (distSq > localPrecisionSq) continue;
  16652. interRay.applyMatrix4(this.matrixWorld); //Move back to world space for distance calculation
  16653. var distance = raycaster.ray.origin.distanceTo(interRay);
  16654. if (distance < raycaster.near || distance > raycaster.far) continue;
  16655. intersects.push({
  16656. distance: distance,
  16657. // What do we want? intersection point on the ray or on the segment??
  16658. // point: raycaster.ray.at( distance ),
  16659. point: interSegment.clone().applyMatrix4(this.matrixWorld),
  16660. index: i,
  16661. face: null,
  16662. faceIndex: null,
  16663. object: this
  16664. });
  16665. }
  16666. }
  16667. },
  16668. clone: function () {
  16669. return new this.constructor(this.geometry, this.material).copy(this);
  16670. }
  16671. });
  16672. /**
  16673. * @author mrdoob / http://mrdoob.com/
  16674. */
  16675. var _start$1 = new Vector3();
  16676. var _end$1 = new Vector3();
  16677. function LineSegments(geometry, material) {
  16678. Line.call(this, geometry, material);
  16679. this.type = 'LineSegments';
  16680. }
  16681. LineSegments.prototype = Object.assign(Object.create(Line.prototype), {
  16682. constructor: LineSegments,
  16683. isLineSegments: true,
  16684. computeLineDistances: function () {
  16685. var geometry = this.geometry;
  16686. if (geometry.isBufferGeometry) {
  16687. // we assume non-indexed geometry
  16688. if (geometry.index === null) {
  16689. var positionAttribute = geometry.attributes.position;
  16690. var lineDistances = [];
  16691. for (var i = 0, l = positionAttribute.count; i < l; i += 2) {
  16692. _start$1.fromBufferAttribute(positionAttribute, i);
  16693. _end$1.fromBufferAttribute(positionAttribute, i + 1);
  16694. lineDistances[i] = i === 0 ? 0 : lineDistances[i - 1];
  16695. lineDistances[i + 1] = lineDistances[i] + _start$1.distanceTo(_end$1);
  16696. }
  16697. geometry.addAttribute('lineDistance', new Float32BufferAttribute(lineDistances, 1));
  16698. } else {
  16699. console.warn('THREE.LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.');
  16700. }
  16701. } else if (geometry.isGeometry) {
  16702. var vertices = geometry.vertices;
  16703. var lineDistances = geometry.lineDistances;
  16704. for (var i = 0, l = vertices.length; i < l; i += 2) {
  16705. _start$1.copy(vertices[i]);
  16706. _end$1.copy(vertices[i + 1]);
  16707. lineDistances[i] = i === 0 ? 0 : lineDistances[i - 1];
  16708. lineDistances[i + 1] = lineDistances[i] + _start$1.distanceTo(_end$1);
  16709. }
  16710. }
  16711. return this;
  16712. }
  16713. });
  16714. /**
  16715. * @author mgreter / http://github.com/mgreter
  16716. */
  16717. function LineLoop(geometry, material) {
  16718. Line.call(this, geometry, material);
  16719. this.type = 'LineLoop';
  16720. }
  16721. LineLoop.prototype = Object.assign(Object.create(Line.prototype), {
  16722. constructor: LineLoop,
  16723. isLineLoop: true
  16724. });
  16725. /**
  16726. * @author mrdoob / http://mrdoob.com/
  16727. * @author alteredq / http://alteredqualia.com/
  16728. *
  16729. * parameters = {
  16730. * color: <hex>,
  16731. * opacity: <float>,
  16732. * map: new THREE.Texture( <Image> ),
  16733. *
  16734. * size: <float>,
  16735. * sizeAttenuation: <bool>
  16736. *
  16737. * morphTargets: <bool>
  16738. * }
  16739. */
  16740. function PointsMaterial(parameters) {
  16741. Material.call(this);
  16742. this.type = 'PointsMaterial';
  16743. this.color = new Color(0xffffff);
  16744. this.map = null;
  16745. this.size = 1;
  16746. this.sizeAttenuation = true;
  16747. this.morphTargets = false;
  16748. this.setValues(parameters);
  16749. }
  16750. PointsMaterial.prototype = Object.create(Material.prototype);
  16751. PointsMaterial.prototype.constructor = PointsMaterial;
  16752. PointsMaterial.prototype.isPointsMaterial = true;
  16753. PointsMaterial.prototype.copy = function (source) {
  16754. Material.prototype.copy.call(this, source);
  16755. this.color.copy(source.color);
  16756. this.map = source.map;
  16757. this.size = source.size;
  16758. this.sizeAttenuation = source.sizeAttenuation;
  16759. this.morphTargets = source.morphTargets;
  16760. return this;
  16761. };
  16762. /**
  16763. * @author alteredq / http://alteredqualia.com/
  16764. */
  16765. var _inverseMatrix$2 = new Matrix4();
  16766. var _ray$2 = new Ray();
  16767. var _sphere$3 = new Sphere();
  16768. var _position$1 = new Vector3();
  16769. function Points(geometry, material) {
  16770. Object3D.call(this);
  16771. this.type = 'Points';
  16772. this.geometry = geometry !== undefined ? geometry : new BufferGeometry();
  16773. this.material = material !== undefined ? material : new PointsMaterial({
  16774. color: Math.random() * 0xffffff
  16775. });
  16776. this.updateMorphTargets();
  16777. }
  16778. Points.prototype = Object.assign(Object.create(Object3D.prototype), {
  16779. constructor: Points,
  16780. isPoints: true,
  16781. raycast: function (raycaster, intersects) {
  16782. var geometry = this.geometry;
  16783. var matrixWorld = this.matrixWorld;
  16784. var threshold = raycaster.params.Points.threshold; // Checking boundingSphere distance to ray
  16785. if (geometry.boundingSphere === null) geometry.computeBoundingSphere();
  16786. _sphere$3.copy(geometry.boundingSphere);
  16787. _sphere$3.applyMatrix4(matrixWorld);
  16788. _sphere$3.radius += threshold;
  16789. if (raycaster.ray.intersectsSphere(_sphere$3) === false) return; //
  16790. _inverseMatrix$2.getInverse(matrixWorld);
  16791. _ray$2.copy(raycaster.ray).applyMatrix4(_inverseMatrix$2);
  16792. var localThreshold = threshold / ((this.scale.x + this.scale.y + this.scale.z) / 3);
  16793. var localThresholdSq = localThreshold * localThreshold;
  16794. if (geometry.isBufferGeometry) {
  16795. var index = geometry.index;
  16796. var attributes = geometry.attributes;
  16797. var positions = attributes.position.array;
  16798. if (index !== null) {
  16799. var indices = index.array;
  16800. for (var i = 0, il = indices.length; i < il; i++) {
  16801. var a = indices[i];
  16802. _position$1.fromArray(positions, a * 3);
  16803. testPoint(_position$1, a, localThresholdSq, matrixWorld, raycaster, intersects, this);
  16804. }
  16805. } else {
  16806. for (var i = 0, l = positions.length / 3; i < l; i++) {
  16807. _position$1.fromArray(positions, i * 3);
  16808. testPoint(_position$1, i, localThresholdSq, matrixWorld, raycaster, intersects, this);
  16809. }
  16810. }
  16811. } else {
  16812. var vertices = geometry.vertices;
  16813. for (var i = 0, l = vertices.length; i < l; i++) {
  16814. testPoint(vertices[i], i, localThresholdSq, matrixWorld, raycaster, intersects, this);
  16815. }
  16816. }
  16817. },
  16818. updateMorphTargets: function () {
  16819. var geometry = this.geometry;
  16820. var m, ml, name;
  16821. if (geometry.isBufferGeometry) {
  16822. var morphAttributes = geometry.morphAttributes;
  16823. var keys = Object.keys(morphAttributes);
  16824. if (keys.length > 0) {
  16825. var morphAttribute = morphAttributes[keys[0]];
  16826. if (morphAttribute !== undefined) {
  16827. this.morphTargetInfluences = [];
  16828. this.morphTargetDictionary = {};
  16829. for (m = 0, ml = morphAttribute.length; m < ml; m++) {
  16830. name = morphAttribute[m].name || String(m);
  16831. this.morphTargetInfluences.push(0);
  16832. this.morphTargetDictionary[name] = m;
  16833. }
  16834. }
  16835. }
  16836. } else {
  16837. var morphTargets = geometry.morphTargets;
  16838. if (morphTargets !== undefined && morphTargets.length > 0) {
  16839. console.error('THREE.Points.updateMorphTargets() does not support THREE.Geometry. Use THREE.BufferGeometry instead.');
  16840. }
  16841. }
  16842. },
  16843. clone: function () {
  16844. return new this.constructor(this.geometry, this.material).copy(this);
  16845. }
  16846. });
  16847. function testPoint(point, index, localThresholdSq, matrixWorld, raycaster, intersects, object) {
  16848. var rayPointDistanceSq = _ray$2.distanceSqToPoint(point);
  16849. if (rayPointDistanceSq < localThresholdSq) {
  16850. var intersectPoint = new Vector3();
  16851. _ray$2.closestPointToPoint(point, intersectPoint);
  16852. intersectPoint.applyMatrix4(matrixWorld);
  16853. var distance = raycaster.ray.origin.distanceTo(intersectPoint);
  16854. if (distance < raycaster.near || distance > raycaster.far) return;
  16855. intersects.push({
  16856. distance: distance,
  16857. distanceToRay: Math.sqrt(rayPointDistanceSq),
  16858. point: intersectPoint,
  16859. index: index,
  16860. face: null,
  16861. object: object
  16862. });
  16863. }
  16864. }
  16865. /**
  16866. * @author mrdoob / http://mrdoob.com/
  16867. */
  16868. function VideoTexture(video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy) {
  16869. Texture.call(this, video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy);
  16870. this.format = format !== undefined ? format : RGBFormat;
  16871. this.minFilter = minFilter !== undefined ? minFilter : LinearFilter;
  16872. this.magFilter = magFilter !== undefined ? magFilter : LinearFilter;
  16873. this.generateMipmaps = false;
  16874. }
  16875. VideoTexture.prototype = Object.assign(Object.create(Texture.prototype), {
  16876. constructor: VideoTexture,
  16877. isVideoTexture: true,
  16878. update: function () {
  16879. var video = this.image;
  16880. if (video.readyState >= video.HAVE_CURRENT_DATA) {
  16881. this.needsUpdate = true;
  16882. }
  16883. }
  16884. });
  16885. /**
  16886. * @author alteredq / http://alteredqualia.com/
  16887. */
  16888. function CompressedTexture(mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding) {
  16889. Texture.call(this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding);
  16890. this.image = {
  16891. width: width,
  16892. height: height
  16893. };
  16894. this.mipmaps = mipmaps; // no flipping for cube textures
  16895. // (also flipping doesn't work for compressed textures )
  16896. this.flipY = false; // can't generate mipmaps for compressed textures
  16897. // mips must be embedded in DDS files
  16898. this.generateMipmaps = false;
  16899. }
  16900. CompressedTexture.prototype = Object.create(Texture.prototype);
  16901. CompressedTexture.prototype.constructor = CompressedTexture;
  16902. CompressedTexture.prototype.isCompressedTexture = true;
  16903. /**
  16904. * @author mrdoob / http://mrdoob.com/
  16905. */
  16906. function CanvasTexture(canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy) {
  16907. Texture.call(this, canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy);
  16908. this.needsUpdate = true;
  16909. }
  16910. CanvasTexture.prototype = Object.create(Texture.prototype);
  16911. CanvasTexture.prototype.constructor = CanvasTexture;
  16912. CanvasTexture.prototype.isCanvasTexture = true;
  16913. /**
  16914. * @author Matt DesLauriers / @mattdesl
  16915. * @author atix / arthursilber.de
  16916. */
  16917. function DepthTexture(width, height, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, format) {
  16918. format = format !== undefined ? format : DepthFormat;
  16919. if (format !== DepthFormat && format !== DepthStencilFormat) {
  16920. throw new Error('DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat');
  16921. }
  16922. if (type === undefined && format === DepthFormat) type = UnsignedShortType;
  16923. if (type === undefined && format === DepthStencilFormat) type = UnsignedInt248Type;
  16924. Texture.call(this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy);
  16925. this.image = {
  16926. width: width,
  16927. height: height
  16928. };
  16929. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  16930. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  16931. this.flipY = false;
  16932. this.generateMipmaps = false;
  16933. }
  16934. DepthTexture.prototype = Object.create(Texture.prototype);
  16935. DepthTexture.prototype.constructor = DepthTexture;
  16936. DepthTexture.prototype.isDepthTexture = true;
  16937. /**
  16938. * @author mrdoob / http://mrdoob.com/
  16939. * @author Mugen87 / https://github.com/Mugen87
  16940. */
  16941. function WireframeGeometry(geometry) {
  16942. BufferGeometry.call(this);
  16943. this.type = 'WireframeGeometry'; // buffer
  16944. var vertices = []; // helper variables
  16945. var i, j, l, o, ol;
  16946. var edge = [0, 0],
  16947. edges = {},
  16948. e,
  16949. edge1,
  16950. edge2;
  16951. var key,
  16952. keys = ['a', 'b', 'c'];
  16953. var vertex; // different logic for Geometry and BufferGeometry
  16954. if (geometry && geometry.isGeometry) {
  16955. // create a data structure that contains all edges without duplicates
  16956. var faces = geometry.faces;
  16957. for (i = 0, l = faces.length; i < l; i++) {
  16958. var face = faces[i];
  16959. for (j = 0; j < 3; j++) {
  16960. edge1 = face[keys[j]];
  16961. edge2 = face[keys[(j + 1) % 3]];
  16962. edge[0] = Math.min(edge1, edge2); // sorting prevents duplicates
  16963. edge[1] = Math.max(edge1, edge2);
  16964. key = edge[0] + ',' + edge[1];
  16965. if (edges[key] === undefined) {
  16966. edges[key] = {
  16967. index1: edge[0],
  16968. index2: edge[1]
  16969. };
  16970. }
  16971. }
  16972. } // generate vertices
  16973. for (key in edges) {
  16974. e = edges[key];
  16975. vertex = geometry.vertices[e.index1];
  16976. vertices.push(vertex.x, vertex.y, vertex.z);
  16977. vertex = geometry.vertices[e.index2];
  16978. vertices.push(vertex.x, vertex.y, vertex.z);
  16979. }
  16980. } else if (geometry && geometry.isBufferGeometry) {
  16981. var position, indices, groups;
  16982. var group, start, count;
  16983. var index1, index2;
  16984. vertex = new Vector3();
  16985. if (geometry.index !== null) {
  16986. // indexed BufferGeometry
  16987. position = geometry.attributes.position;
  16988. indices = geometry.index;
  16989. groups = geometry.groups;
  16990. if (groups.length === 0) {
  16991. groups = [{
  16992. start: 0,
  16993. count: indices.count,
  16994. materialIndex: 0
  16995. }];
  16996. } // create a data structure that contains all eges without duplicates
  16997. for (o = 0, ol = groups.length; o < ol; ++o) {
  16998. group = groups[o];
  16999. start = group.start;
  17000. count = group.count;
  17001. for (i = start, l = start + count; i < l; i += 3) {
  17002. for (j = 0; j < 3; j++) {
  17003. edge1 = indices.getX(i + j);
  17004. edge2 = indices.getX(i + (j + 1) % 3);
  17005. edge[0] = Math.min(edge1, edge2); // sorting prevents duplicates
  17006. edge[1] = Math.max(edge1, edge2);
  17007. key = edge[0] + ',' + edge[1];
  17008. if (edges[key] === undefined) {
  17009. edges[key] = {
  17010. index1: edge[0],
  17011. index2: edge[1]
  17012. };
  17013. }
  17014. }
  17015. }
  17016. } // generate vertices
  17017. for (key in edges) {
  17018. e = edges[key];
  17019. vertex.fromBufferAttribute(position, e.index1);
  17020. vertices.push(vertex.x, vertex.y, vertex.z);
  17021. vertex.fromBufferAttribute(position, e.index2);
  17022. vertices.push(vertex.x, vertex.y, vertex.z);
  17023. }
  17024. } else {
  17025. // non-indexed BufferGeometry
  17026. position = geometry.attributes.position;
  17027. for (i = 0, l = position.count / 3; i < l; i++) {
  17028. for (j = 0; j < 3; j++) {
  17029. // three edges per triangle, an edge is represented as (index1, index2)
  17030. // e.g. the first triangle has the following edges: (0,1),(1,2),(2,0)
  17031. index1 = 3 * i + j;
  17032. vertex.fromBufferAttribute(position, index1);
  17033. vertices.push(vertex.x, vertex.y, vertex.z);
  17034. index2 = 3 * i + (j + 1) % 3;
  17035. vertex.fromBufferAttribute(position, index2);
  17036. vertices.push(vertex.x, vertex.y, vertex.z);
  17037. }
  17038. }
  17039. }
  17040. } // build geometry
  17041. this.addAttribute('position', new Float32BufferAttribute(vertices, 3));
  17042. }
  17043. WireframeGeometry.prototype = Object.create(BufferGeometry.prototype);
  17044. WireframeGeometry.prototype.constructor = WireframeGeometry;
  17045. /**
  17046. * @author zz85 / https://github.com/zz85
  17047. * @author Mugen87 / https://github.com/Mugen87
  17048. *
  17049. * Parametric Surfaces Geometry
  17050. * based on the brilliant article by @prideout http://prideout.net/blog/?p=44
  17051. */
  17052. // ParametricGeometry
  17053. function ParametricGeometry(func, slices, stacks) {
  17054. Geometry.call(this);
  17055. this.type = 'ParametricGeometry';
  17056. this.parameters = {
  17057. func: func,
  17058. slices: slices,
  17059. stacks: stacks
  17060. };
  17061. this.fromBufferGeometry(new ParametricBufferGeometry(func, slices, stacks));
  17062. this.mergeVertices();
  17063. }
  17064. ParametricGeometry.prototype = Object.create(Geometry.prototype);
  17065. ParametricGeometry.prototype.constructor = ParametricGeometry; // ParametricBufferGeometry
  17066. function ParametricBufferGeometry(func, slices, stacks) {
  17067. BufferGeometry.call(this);
  17068. this.type = 'ParametricBufferGeometry';
  17069. this.parameters = {
  17070. func: func,
  17071. slices: slices,
  17072. stacks: stacks
  17073. }; // buffers
  17074. var indices = [];
  17075. var vertices = [];
  17076. var normals = [];
  17077. var uvs = [];
  17078. var EPS = 0.00001;
  17079. var normal = new Vector3();
  17080. var p0 = new Vector3(),
  17081. p1 = new Vector3();
  17082. var pu = new Vector3(),
  17083. pv = new Vector3();
  17084. var i, j;
  17085. if (func.length < 3) {
  17086. console.error('THREE.ParametricGeometry: Function must now modify a Vector3 as third parameter.');
  17087. } // generate vertices, normals and uvs
  17088. var sliceCount = slices + 1;
  17089. for (i = 0; i <= stacks; i++) {
  17090. var v = i / stacks;
  17091. for (j = 0; j <= slices; j++) {
  17092. var u = j / slices; // vertex
  17093. func(u, v, p0);
  17094. vertices.push(p0.x, p0.y, p0.z); // normal
  17095. // approximate tangent vectors via finite differences
  17096. if (u - EPS >= 0) {
  17097. func(u - EPS, v, p1);
  17098. pu.subVectors(p0, p1);
  17099. } else {
  17100. func(u + EPS, v, p1);
  17101. pu.subVectors(p1, p0);
  17102. }
  17103. if (v - EPS >= 0) {
  17104. func(u, v - EPS, p1);
  17105. pv.subVectors(p0, p1);
  17106. } else {
  17107. func(u, v + EPS, p1);
  17108. pv.subVectors(p1, p0);
  17109. } // cross product of tangent vectors returns surface normal
  17110. normal.crossVectors(pu, pv).normalize();
  17111. normals.push(normal.x, normal.y, normal.z); // uv
  17112. uvs.push(u, v);
  17113. }
  17114. } // generate indices
  17115. for (i = 0; i < stacks; i++) {
  17116. for (j = 0; j < slices; j++) {
  17117. var a = i * sliceCount + j;
  17118. var b = i * sliceCount + j + 1;
  17119. var c = (i + 1) * sliceCount + j + 1;
  17120. var d = (i + 1) * sliceCount + j; // faces one and two
  17121. indices.push(a, b, d);
  17122. indices.push(b, c, d);
  17123. }
  17124. } // build geometry
  17125. this.setIndex(indices);
  17126. this.addAttribute('position', new Float32BufferAttribute(vertices, 3));
  17127. this.addAttribute('normal', new Float32BufferAttribute(normals, 3));
  17128. this.addAttribute('uv', new Float32BufferAttribute(uvs, 2));
  17129. }
  17130. ParametricBufferGeometry.prototype = Object.create(BufferGeometry.prototype);
  17131. ParametricBufferGeometry.prototype.constructor = ParametricBufferGeometry;
  17132. /**
  17133. * @author clockworkgeek / https://github.com/clockworkgeek
  17134. * @author timothypratley / https://github.com/timothypratley
  17135. * @author WestLangley / http://github.com/WestLangley
  17136. * @author Mugen87 / https://github.com/Mugen87
  17137. */
  17138. // PolyhedronGeometry
  17139. function PolyhedronGeometry(vertices, indices, radius, detail) {
  17140. Geometry.call(this);
  17141. this.type = 'PolyhedronGeometry';
  17142. this.parameters = {
  17143. vertices: vertices,
  17144. indices: indices,
  17145. radius: radius,
  17146. detail: detail
  17147. };
  17148. this.fromBufferGeometry(new PolyhedronBufferGeometry(vertices, indices, radius, detail));
  17149. this.mergeVertices();
  17150. }
  17151. PolyhedronGeometry.prototype = Object.create(Geometry.prototype);
  17152. PolyhedronGeometry.prototype.constructor = PolyhedronGeometry; // PolyhedronBufferGeometry
  17153. function PolyhedronBufferGeometry(vertices, indices, radius, detail) {
  17154. BufferGeometry.call(this);
  17155. this.type = 'PolyhedronBufferGeometry';
  17156. this.parameters = {
  17157. vertices: vertices,
  17158. indices: indices,
  17159. radius: radius,
  17160. detail: detail
  17161. };
  17162. radius = radius || 1;
  17163. detail = detail || 0; // default buffer data
  17164. var vertexBuffer = [];
  17165. var uvBuffer = []; // the subdivision creates the vertex buffer data
  17166. subdivide(detail); // all vertices should lie on a conceptual sphere with a given radius
  17167. applyRadius(radius); // finally, create the uv data
  17168. generateUVs(); // build non-indexed geometry
  17169. this.addAttribute('position', new Float32BufferAttribute(vertexBuffer, 3));
  17170. this.addAttribute('normal', new Float32BufferAttribute(vertexBuffer.slice(), 3));
  17171. this.addAttribute('uv', new Float32BufferAttribute(uvBuffer, 2));
  17172. if (detail === 0) {
  17173. this.computeVertexNormals(); // flat normals
  17174. } else {
  17175. this.normalizeNormals(); // smooth normals
  17176. } // helper functions
  17177. function subdivide(detail) {
  17178. var a = new Vector3();
  17179. var b = new Vector3();
  17180. var c = new Vector3(); // iterate over all faces and apply a subdivison with the given detail value
  17181. for (var i = 0; i < indices.length; i += 3) {
  17182. // get the vertices of the face
  17183. getVertexByIndex(indices[i + 0], a);
  17184. getVertexByIndex(indices[i + 1], b);
  17185. getVertexByIndex(indices[i + 2], c); // perform subdivision
  17186. subdivideFace(a, b, c, detail);
  17187. }
  17188. }
  17189. function subdivideFace(a, b, c, detail) {
  17190. var cols = Math.pow(2, detail); // we use this multidimensional array as a data structure for creating the subdivision
  17191. var v = [];
  17192. var i, j; // construct all of the vertices for this subdivision
  17193. for (i = 0; i <= cols; i++) {
  17194. v[i] = [];
  17195. var aj = a.clone().lerp(c, i / cols);
  17196. var bj = b.clone().lerp(c, i / cols);
  17197. var rows = cols - i;
  17198. for (j = 0; j <= rows; j++) {
  17199. if (j === 0 && i === cols) {
  17200. v[i][j] = aj;
  17201. } else {
  17202. v[i][j] = aj.clone().lerp(bj, j / rows);
  17203. }
  17204. }
  17205. } // construct all of the faces
  17206. for (i = 0; i < cols; i++) {
  17207. for (j = 0; j < 2 * (cols - i) - 1; j++) {
  17208. var k = Math.floor(j / 2);
  17209. if (j % 2 === 0) {
  17210. pushVertex(v[i][k + 1]);
  17211. pushVertex(v[i + 1][k]);
  17212. pushVertex(v[i][k]);
  17213. } else {
  17214. pushVertex(v[i][k + 1]);
  17215. pushVertex(v[i + 1][k + 1]);
  17216. pushVertex(v[i + 1][k]);
  17217. }
  17218. }
  17219. }
  17220. }
  17221. function applyRadius(radius) {
  17222. var vertex = new Vector3(); // iterate over the entire buffer and apply the radius to each vertex
  17223. for (var i = 0; i < vertexBuffer.length; i += 3) {
  17224. vertex.x = vertexBuffer[i + 0];
  17225. vertex.y = vertexBuffer[i + 1];
  17226. vertex.z = vertexBuffer[i + 2];
  17227. vertex.normalize().multiplyScalar(radius);
  17228. vertexBuffer[i + 0] = vertex.x;
  17229. vertexBuffer[i + 1] = vertex.y;
  17230. vertexBuffer[i + 2] = vertex.z;
  17231. }
  17232. }
  17233. function generateUVs() {
  17234. var vertex = new Vector3();
  17235. for (var i = 0; i < vertexBuffer.length; i += 3) {
  17236. vertex.x = vertexBuffer[i + 0];
  17237. vertex.y = vertexBuffer[i + 1];
  17238. vertex.z = vertexBuffer[i + 2];
  17239. var u = azimuth(vertex) / 2 / Math.PI + 0.5;
  17240. var v = inclination(vertex) / Math.PI + 0.5;
  17241. uvBuffer.push(u, 1 - v);
  17242. }
  17243. correctUVs();
  17244. correctSeam();
  17245. }
  17246. function correctSeam() {
  17247. // handle case when face straddles the seam, see #3269
  17248. for (var i = 0; i < uvBuffer.length; i += 6) {
  17249. // uv data of a single face
  17250. var x0 = uvBuffer[i + 0];
  17251. var x1 = uvBuffer[i + 2];
  17252. var x2 = uvBuffer[i + 4];
  17253. var max = Math.max(x0, x1, x2);
  17254. var min = Math.min(x0, x1, x2); // 0.9 is somewhat arbitrary
  17255. if (max > 0.9 && min < 0.1) {
  17256. if (x0 < 0.2) uvBuffer[i + 0] += 1;
  17257. if (x1 < 0.2) uvBuffer[i + 2] += 1;
  17258. if (x2 < 0.2) uvBuffer[i + 4] += 1;
  17259. }
  17260. }
  17261. }
  17262. function pushVertex(vertex) {
  17263. vertexBuffer.push(vertex.x, vertex.y, vertex.z);
  17264. }
  17265. function getVertexByIndex(index, vertex) {
  17266. var stride = index * 3;
  17267. vertex.x = vertices[stride + 0];
  17268. vertex.y = vertices[stride + 1];
  17269. vertex.z = vertices[stride + 2];
  17270. }
  17271. function correctUVs() {
  17272. var a = new Vector3();
  17273. var b = new Vector3();
  17274. var c = new Vector3();
  17275. var centroid = new Vector3();
  17276. var uvA = new Vector2();
  17277. var uvB = new Vector2();
  17278. var uvC = new Vector2();
  17279. for (var i = 0, j = 0; i < vertexBuffer.length; i += 9, j += 6) {
  17280. a.set(vertexBuffer[i + 0], vertexBuffer[i + 1], vertexBuffer[i + 2]);
  17281. b.set(vertexBuffer[i + 3], vertexBuffer[i + 4], vertexBuffer[i + 5]);
  17282. c.set(vertexBuffer[i + 6], vertexBuffer[i + 7], vertexBuffer[i + 8]);
  17283. uvA.set(uvBuffer[j + 0], uvBuffer[j + 1]);
  17284. uvB.set(uvBuffer[j + 2], uvBuffer[j + 3]);
  17285. uvC.set(uvBuffer[j + 4], uvBuffer[j + 5]);
  17286. centroid.copy(a).add(b).add(c).divideScalar(3);
  17287. var azi = azimuth(centroid);
  17288. correctUV(uvA, j + 0, a, azi);
  17289. correctUV(uvB, j + 2, b, azi);
  17290. correctUV(uvC, j + 4, c, azi);
  17291. }
  17292. }
  17293. function correctUV(uv, stride, vector, azimuth) {
  17294. if (azimuth < 0 && uv.x === 1) {
  17295. uvBuffer[stride] = uv.x - 1;
  17296. }
  17297. if (vector.x === 0 && vector.z === 0) {
  17298. uvBuffer[stride] = azimuth / 2 / Math.PI + 0.5;
  17299. }
  17300. } // Angle around the Y axis, counter-clockwise when looking from above.
  17301. function azimuth(vector) {
  17302. return Math.atan2(vector.z, -vector.x);
  17303. } // Angle above the XZ plane.
  17304. function inclination(vector) {
  17305. return Math.atan2(-vector.y, Math.sqrt(vector.x * vector.x + vector.z * vector.z));
  17306. }
  17307. }
  17308. PolyhedronBufferGeometry.prototype = Object.create(BufferGeometry.prototype);
  17309. PolyhedronBufferGeometry.prototype.constructor = PolyhedronBufferGeometry;
  17310. /**
  17311. * @author timothypratley / https://github.com/timothypratley
  17312. * @author Mugen87 / https://github.com/Mugen87
  17313. */
  17314. // TetrahedronGeometry
  17315. function TetrahedronGeometry(radius, detail) {
  17316. Geometry.call(this);
  17317. this.type = 'TetrahedronGeometry';
  17318. this.parameters = {
  17319. radius: radius,
  17320. detail: detail
  17321. };
  17322. this.fromBufferGeometry(new TetrahedronBufferGeometry(radius, detail));
  17323. this.mergeVertices();
  17324. }
  17325. TetrahedronGeometry.prototype = Object.create(Geometry.prototype);
  17326. TetrahedronGeometry.prototype.constructor = TetrahedronGeometry; // TetrahedronBufferGeometry
  17327. function TetrahedronBufferGeometry(radius, detail) {
  17328. var vertices = [1, 1, 1, -1, -1, 1, -1, 1, -1, 1, -1, -1];
  17329. var indices = [2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1];
  17330. PolyhedronBufferGeometry.call(this, vertices, indices, radius, detail);
  17331. this.type = 'TetrahedronBufferGeometry';
  17332. this.parameters = {
  17333. radius: radius,
  17334. detail: detail
  17335. };
  17336. }
  17337. TetrahedronBufferGeometry.prototype = Object.create(PolyhedronBufferGeometry.prototype);
  17338. TetrahedronBufferGeometry.prototype.constructor = TetrahedronBufferGeometry;
  17339. /**
  17340. * @author timothypratley / https://github.com/timothypratley
  17341. * @author Mugen87 / https://github.com/Mugen87
  17342. */
  17343. // OctahedronGeometry
  17344. function OctahedronGeometry(radius, detail) {
  17345. Geometry.call(this);
  17346. this.type = 'OctahedronGeometry';
  17347. this.parameters = {
  17348. radius: radius,
  17349. detail: detail
  17350. };
  17351. this.fromBufferGeometry(new OctahedronBufferGeometry(radius, detail));
  17352. this.mergeVertices();
  17353. }
  17354. OctahedronGeometry.prototype = Object.create(Geometry.prototype);
  17355. OctahedronGeometry.prototype.constructor = OctahedronGeometry; // OctahedronBufferGeometry
  17356. function OctahedronBufferGeometry(radius, detail) {
  17357. var vertices = [1, 0, 0, -1, 0, 0, 0, 1, 0, 0, -1, 0, 0, 0, 1, 0, 0, -1];
  17358. 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];
  17359. PolyhedronBufferGeometry.call(this, vertices, indices, radius, detail);
  17360. this.type = 'OctahedronBufferGeometry';
  17361. this.parameters = {
  17362. radius: radius,
  17363. detail: detail
  17364. };
  17365. }
  17366. OctahedronBufferGeometry.prototype = Object.create(PolyhedronBufferGeometry.prototype);
  17367. OctahedronBufferGeometry.prototype.constructor = OctahedronBufferGeometry;
  17368. /**
  17369. * @author timothypratley / https://github.com/timothypratley
  17370. * @author Mugen87 / https://github.com/Mugen87
  17371. */
  17372. // IcosahedronGeometry
  17373. function IcosahedronGeometry(radius, detail) {
  17374. Geometry.call(this);
  17375. this.type = 'IcosahedronGeometry';
  17376. this.parameters = {
  17377. radius: radius,
  17378. detail: detail
  17379. };
  17380. this.fromBufferGeometry(new IcosahedronBufferGeometry(radius, detail));
  17381. this.mergeVertices();
  17382. }
  17383. IcosahedronGeometry.prototype = Object.create(Geometry.prototype);
  17384. IcosahedronGeometry.prototype.constructor = IcosahedronGeometry; // IcosahedronBufferGeometry
  17385. function IcosahedronBufferGeometry(radius, detail) {
  17386. var t = (1 + Math.sqrt(5)) / 2;
  17387. 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];
  17388. 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];
  17389. PolyhedronBufferGeometry.call(this, vertices, indices, radius, detail);
  17390. this.type = 'IcosahedronBufferGeometry';
  17391. this.parameters = {
  17392. radius: radius,
  17393. detail: detail
  17394. };
  17395. }
  17396. IcosahedronBufferGeometry.prototype = Object.create(PolyhedronBufferGeometry.prototype);
  17397. IcosahedronBufferGeometry.prototype.constructor = IcosahedronBufferGeometry;
  17398. /**
  17399. * @author Abe Pazos / https://hamoid.com
  17400. * @author Mugen87 / https://github.com/Mugen87
  17401. */
  17402. // DodecahedronGeometry
  17403. function DodecahedronGeometry(radius, detail) {
  17404. Geometry.call(this);
  17405. this.type = 'DodecahedronGeometry';
  17406. this.parameters = {
  17407. radius: radius,
  17408. detail: detail
  17409. };
  17410. this.fromBufferGeometry(new DodecahedronBufferGeometry(radius, detail));
  17411. this.mergeVertices();
  17412. }
  17413. DodecahedronGeometry.prototype = Object.create(Geometry.prototype);
  17414. DodecahedronGeometry.prototype.constructor = DodecahedronGeometry; // DodecahedronBufferGeometry
  17415. function DodecahedronBufferGeometry(radius, detail) {
  17416. var t = (1 + Math.sqrt(5)) / 2;
  17417. var r = 1 / t;
  17418. var vertices = [// (±1, ±1, ±1)
  17419. -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/φ, ±φ)
  17420. 0, -r, -t, 0, -r, t, 0, r, -t, 0, r, t, // (±1/φ, ±φ, 0)
  17421. -r, -t, 0, -r, t, 0, r, -t, 0, r, t, 0, // (±φ, 0, ±1/φ)
  17422. -t, 0, -r, t, 0, -r, -t, 0, r, t, 0, r];
  17423. 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];
  17424. PolyhedronBufferGeometry.call(this, vertices, indices, radius, detail);
  17425. this.type = 'DodecahedronBufferGeometry';
  17426. this.parameters = {
  17427. radius: radius,
  17428. detail: detail
  17429. };
  17430. }
  17431. DodecahedronBufferGeometry.prototype = Object.create(PolyhedronBufferGeometry.prototype);
  17432. DodecahedronBufferGeometry.prototype.constructor = DodecahedronBufferGeometry;
  17433. /**
  17434. * @author oosmoxiecode / https://github.com/oosmoxiecode
  17435. * @author WestLangley / https://github.com/WestLangley
  17436. * @author zz85 / https://github.com/zz85
  17437. * @author miningold / https://github.com/miningold
  17438. * @author jonobr1 / https://github.com/jonobr1
  17439. * @author Mugen87 / https://github.com/Mugen87
  17440. *
  17441. */
  17442. // TubeGeometry
  17443. function TubeGeometry(path, tubularSegments, radius, radialSegments, closed, taper) {
  17444. Geometry.call(this);
  17445. this.type = 'TubeGeometry';
  17446. this.parameters = {
  17447. path: path,
  17448. tubularSegments: tubularSegments,
  17449. radius: radius,
  17450. radialSegments: radialSegments,
  17451. closed: closed
  17452. };
  17453. if (taper !== undefined) console.warn('THREE.TubeGeometry: taper has been removed.');
  17454. var bufferGeometry = new TubeBufferGeometry(path, tubularSegments, radius, radialSegments, closed); // expose internals
  17455. this.tangents = bufferGeometry.tangents;
  17456. this.normals = bufferGeometry.normals;
  17457. this.binormals = bufferGeometry.binormals; // create geometry
  17458. this.fromBufferGeometry(bufferGeometry);
  17459. this.mergeVertices();
  17460. }
  17461. TubeGeometry.prototype = Object.create(Geometry.prototype);
  17462. TubeGeometry.prototype.constructor = TubeGeometry; // TubeBufferGeometry
  17463. function TubeBufferGeometry(path, tubularSegments, radius, radialSegments, closed) {
  17464. BufferGeometry.call(this);
  17465. this.type = 'TubeBufferGeometry';
  17466. this.parameters = {
  17467. path: path,
  17468. tubularSegments: tubularSegments,
  17469. radius: radius,
  17470. radialSegments: radialSegments,
  17471. closed: closed
  17472. };
  17473. tubularSegments = tubularSegments || 64;
  17474. radius = radius || 1;
  17475. radialSegments = radialSegments || 8;
  17476. closed = closed || false;
  17477. var frames = path.computeFrenetFrames(tubularSegments, closed); // expose internals
  17478. this.tangents = frames.tangents;
  17479. this.normals = frames.normals;
  17480. this.binormals = frames.binormals; // helper variables
  17481. var vertex = new Vector3();
  17482. var normal = new Vector3();
  17483. var uv = new Vector2();
  17484. var P = new Vector3();
  17485. var i, j; // buffer
  17486. var vertices = [];
  17487. var normals = [];
  17488. var uvs = [];
  17489. var indices = []; // create buffer data
  17490. generateBufferData(); // build geometry
  17491. this.setIndex(indices);
  17492. this.addAttribute('position', new Float32BufferAttribute(vertices, 3));
  17493. this.addAttribute('normal', new Float32BufferAttribute(normals, 3));
  17494. this.addAttribute('uv', new Float32BufferAttribute(uvs, 2)); // functions
  17495. function generateBufferData() {
  17496. for (i = 0; i < tubularSegments; i++) {
  17497. generateSegment(i);
  17498. } // if the geometry is not closed, generate the last row of vertices and normals
  17499. // at the regular position on the given path
  17500. //
  17501. // if the geometry is closed, duplicate the first row of vertices and normals (uvs will differ)
  17502. generateSegment(closed === false ? tubularSegments : 0); // uvs are generated in a separate function.
  17503. // this makes it easy compute correct values for closed geometries
  17504. generateUVs(); // finally create faces
  17505. generateIndices();
  17506. }
  17507. function generateSegment(i) {
  17508. // we use getPointAt to sample evenly distributed points from the given path
  17509. P = path.getPointAt(i / tubularSegments, P); // retrieve corresponding normal and binormal
  17510. var N = frames.normals[i];
  17511. var B = frames.binormals[i]; // generate normals and vertices for the current segment
  17512. for (j = 0; j <= radialSegments; j++) {
  17513. var v = j / radialSegments * Math.PI * 2;
  17514. var sin = Math.sin(v);
  17515. var cos = -Math.cos(v); // normal
  17516. normal.x = cos * N.x + sin * B.x;
  17517. normal.y = cos * N.y + sin * B.y;
  17518. normal.z = cos * N.z + sin * B.z;
  17519. normal.normalize();
  17520. normals.push(normal.x, normal.y, normal.z); // vertex
  17521. vertex.x = P.x + radius * normal.x;
  17522. vertex.y = P.y + radius * normal.y;
  17523. vertex.z = P.z + radius * normal.z;
  17524. vertices.push(vertex.x, vertex.y, vertex.z);
  17525. }
  17526. }
  17527. function generateIndices() {
  17528. for (j = 1; j <= tubularSegments; j++) {
  17529. for (i = 1; i <= radialSegments; i++) {
  17530. var a = (radialSegments + 1) * (j - 1) + (i - 1);
  17531. var b = (radialSegments + 1) * j + (i - 1);
  17532. var c = (radialSegments + 1) * j + i;
  17533. var d = (radialSegments + 1) * (j - 1) + i; // faces
  17534. indices.push(a, b, d);
  17535. indices.push(b, c, d);
  17536. }
  17537. }
  17538. }
  17539. function generateUVs() {
  17540. for (i = 0; i <= tubularSegments; i++) {
  17541. for (j = 0; j <= radialSegments; j++) {
  17542. uv.x = i / tubularSegments;
  17543. uv.y = j / radialSegments;
  17544. uvs.push(uv.x, uv.y);
  17545. }
  17546. }
  17547. }
  17548. }
  17549. TubeBufferGeometry.prototype = Object.create(BufferGeometry.prototype);
  17550. TubeBufferGeometry.prototype.constructor = TubeBufferGeometry;
  17551. TubeBufferGeometry.prototype.toJSON = function () {
  17552. var data = BufferGeometry.prototype.toJSON.call(this);
  17553. data.path = this.parameters.path.toJSON();
  17554. return data;
  17555. };
  17556. /**
  17557. * @author oosmoxiecode
  17558. * @author Mugen87 / https://github.com/Mugen87
  17559. *
  17560. * based on http://www.blackpawn.com/texts/pqtorus/
  17561. */
  17562. // TorusKnotGeometry
  17563. function TorusKnotGeometry(radius, tube, tubularSegments, radialSegments, p, q, heightScale) {
  17564. Geometry.call(this);
  17565. this.type = 'TorusKnotGeometry';
  17566. this.parameters = {
  17567. radius: radius,
  17568. tube: tube,
  17569. tubularSegments: tubularSegments,
  17570. radialSegments: radialSegments,
  17571. p: p,
  17572. q: q
  17573. };
  17574. if (heightScale !== undefined) console.warn('THREE.TorusKnotGeometry: heightScale has been deprecated. Use .scale( x, y, z ) instead.');
  17575. this.fromBufferGeometry(new TorusKnotBufferGeometry(radius, tube, tubularSegments, radialSegments, p, q));
  17576. this.mergeVertices();
  17577. }
  17578. TorusKnotGeometry.prototype = Object.create(Geometry.prototype);
  17579. TorusKnotGeometry.prototype.constructor = TorusKnotGeometry; // TorusKnotBufferGeometry
  17580. function TorusKnotBufferGeometry(radius, tube, tubularSegments, radialSegments, p, q) {
  17581. BufferGeometry.call(this);
  17582. this.type = 'TorusKnotBufferGeometry';
  17583. this.parameters = {
  17584. radius: radius,
  17585. tube: tube,
  17586. tubularSegments: tubularSegments,
  17587. radialSegments: radialSegments,
  17588. p: p,
  17589. q: q
  17590. };
  17591. radius = radius || 1;
  17592. tube = tube || 0.4;
  17593. tubularSegments = Math.floor(tubularSegments) || 64;
  17594. radialSegments = Math.floor(radialSegments) || 8;
  17595. p = p || 2;
  17596. q = q || 3; // buffers
  17597. var indices = [];
  17598. var vertices = [];
  17599. var normals = [];
  17600. var uvs = []; // helper variables
  17601. var i, j;
  17602. var vertex = new Vector3();
  17603. var normal = new Vector3();
  17604. var P1 = new Vector3();
  17605. var P2 = new Vector3();
  17606. var B = new Vector3();
  17607. var T = new Vector3();
  17608. var N = new Vector3(); // generate vertices, normals and uvs
  17609. for (i = 0; i <= tubularSegments; ++i) {
  17610. // the radian "u" is used to calculate the position on the torus curve of the current tubular segement
  17611. 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.
  17612. // these points are used to create a special "coordinate space", which is necessary to calculate the correct vertex positions
  17613. calculatePositionOnCurve(u, p, q, radius, P1);
  17614. calculatePositionOnCurve(u + 0.01, p, q, radius, P2); // calculate orthonormal basis
  17615. T.subVectors(P2, P1);
  17616. N.addVectors(P2, P1);
  17617. B.crossVectors(T, N);
  17618. N.crossVectors(B, T); // normalize B, N. T can be ignored, we don't use it
  17619. B.normalize();
  17620. N.normalize();
  17621. for (j = 0; j <= radialSegments; ++j) {
  17622. // now calculate the vertices. they are nothing more than an extrusion of the torus curve.
  17623. // because we extrude a shape in the xy-plane, there is no need to calculate a z-value.
  17624. var v = j / radialSegments * Math.PI * 2;
  17625. var cx = -tube * Math.cos(v);
  17626. var cy = tube * Math.sin(v); // now calculate the final vertex position.
  17627. // first we orient the extrusion with our basis vectos, then we add it to the current position on the curve
  17628. vertex.x = P1.x + (cx * N.x + cy * B.x);
  17629. vertex.y = P1.y + (cx * N.y + cy * B.y);
  17630. vertex.z = P1.z + (cx * N.z + cy * B.z);
  17631. 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)
  17632. normal.subVectors(vertex, P1).normalize();
  17633. normals.push(normal.x, normal.y, normal.z); // uv
  17634. uvs.push(i / tubularSegments);
  17635. uvs.push(j / radialSegments);
  17636. }
  17637. } // generate indices
  17638. for (j = 1; j <= tubularSegments; j++) {
  17639. for (i = 1; i <= radialSegments; i++) {
  17640. // indices
  17641. var a = (radialSegments + 1) * (j - 1) + (i - 1);
  17642. var b = (radialSegments + 1) * j + (i - 1);
  17643. var c = (radialSegments + 1) * j + i;
  17644. var d = (radialSegments + 1) * (j - 1) + i; // faces
  17645. indices.push(a, b, d);
  17646. indices.push(b, c, d);
  17647. }
  17648. } // build geometry
  17649. this.setIndex(indices);
  17650. this.addAttribute('position', new Float32BufferAttribute(vertices, 3));
  17651. this.addAttribute('normal', new Float32BufferAttribute(normals, 3));
  17652. this.addAttribute('uv', new Float32BufferAttribute(uvs, 2)); // this function calculates the current position on the torus curve
  17653. function calculatePositionOnCurve(u, p, q, radius, position) {
  17654. var cu = Math.cos(u);
  17655. var su = Math.sin(u);
  17656. var quOverP = q / p * u;
  17657. var cs = Math.cos(quOverP);
  17658. position.x = radius * (2 + cs) * 0.5 * cu;
  17659. position.y = radius * (2 + cs) * su * 0.5;
  17660. position.z = radius * Math.sin(quOverP) * 0.5;
  17661. }
  17662. }
  17663. TorusKnotBufferGeometry.prototype = Object.create(BufferGeometry.prototype);
  17664. TorusKnotBufferGeometry.prototype.constructor = TorusKnotBufferGeometry;
  17665. /**
  17666. * @author oosmoxiecode
  17667. * @author mrdoob / http://mrdoob.com/
  17668. * @author Mugen87 / https://github.com/Mugen87
  17669. */
  17670. // TorusGeometry
  17671. function TorusGeometry(radius, tube, radialSegments, tubularSegments, arc) {
  17672. Geometry.call(this);
  17673. this.type = 'TorusGeometry';
  17674. this.parameters = {
  17675. radius: radius,
  17676. tube: tube,
  17677. radialSegments: radialSegments,
  17678. tubularSegments: tubularSegments,
  17679. arc: arc
  17680. };
  17681. this.fromBufferGeometry(new TorusBufferGeometry(radius, tube, radialSegments, tubularSegments, arc));
  17682. this.mergeVertices();
  17683. }
  17684. TorusGeometry.prototype = Object.create(Geometry.prototype);
  17685. TorusGeometry.prototype.constructor = TorusGeometry; // TorusBufferGeometry
  17686. function TorusBufferGeometry(radius, tube, radialSegments, tubularSegments, arc) {
  17687. BufferGeometry.call(this);
  17688. this.type = 'TorusBufferGeometry';
  17689. this.parameters = {
  17690. radius: radius,
  17691. tube: tube,
  17692. radialSegments: radialSegments,
  17693. tubularSegments: tubularSegments,
  17694. arc: arc
  17695. };
  17696. radius = radius || 1;
  17697. tube = tube || 0.4;
  17698. radialSegments = Math.floor(radialSegments) || 8;
  17699. tubularSegments = Math.floor(tubularSegments) || 6;
  17700. arc = arc || Math.PI * 2; // buffers
  17701. var indices = [];
  17702. var vertices = [];
  17703. var normals = [];
  17704. var uvs = []; // helper variables
  17705. var center = new Vector3();
  17706. var vertex = new Vector3();
  17707. var normal = new Vector3();
  17708. var j, i; // generate vertices, normals and uvs
  17709. for (j = 0; j <= radialSegments; j++) {
  17710. for (i = 0; i <= tubularSegments; i++) {
  17711. var u = i / tubularSegments * arc;
  17712. var v = j / radialSegments * Math.PI * 2; // vertex
  17713. vertex.x = (radius + tube * Math.cos(v)) * Math.cos(u);
  17714. vertex.y = (radius + tube * Math.cos(v)) * Math.sin(u);
  17715. vertex.z = tube * Math.sin(v);
  17716. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  17717. center.x = radius * Math.cos(u);
  17718. center.y = radius * Math.sin(u);
  17719. normal.subVectors(vertex, center).normalize();
  17720. normals.push(normal.x, normal.y, normal.z); // uv
  17721. uvs.push(i / tubularSegments);
  17722. uvs.push(j / radialSegments);
  17723. }
  17724. } // generate indices
  17725. for (j = 1; j <= radialSegments; j++) {
  17726. for (i = 1; i <= tubularSegments; i++) {
  17727. // indices
  17728. var a = (tubularSegments + 1) * j + i - 1;
  17729. var b = (tubularSegments + 1) * (j - 1) + i - 1;
  17730. var c = (tubularSegments + 1) * (j - 1) + i;
  17731. var d = (tubularSegments + 1) * j + i; // faces
  17732. indices.push(a, b, d);
  17733. indices.push(b, c, d);
  17734. }
  17735. } // build geometry
  17736. this.setIndex(indices);
  17737. this.addAttribute('position', new Float32BufferAttribute(vertices, 3));
  17738. this.addAttribute('normal', new Float32BufferAttribute(normals, 3));
  17739. this.addAttribute('uv', new Float32BufferAttribute(uvs, 2));
  17740. }
  17741. TorusBufferGeometry.prototype = Object.create(BufferGeometry.prototype);
  17742. TorusBufferGeometry.prototype.constructor = TorusBufferGeometry;
  17743. /**
  17744. * @author Mugen87 / https://github.com/Mugen87
  17745. * Port from https://github.com/mapbox/earcut (v2.1.5)
  17746. */
  17747. var Earcut = {
  17748. triangulate: function (data, holeIndices, dim) {
  17749. dim = dim || 2;
  17750. var hasHoles = holeIndices && holeIndices.length,
  17751. outerLen = hasHoles ? holeIndices[0] * dim : data.length,
  17752. outerNode = linkedList(data, 0, outerLen, dim, true),
  17753. triangles = [];
  17754. if (!outerNode || outerNode.next === outerNode.prev) return triangles;
  17755. var minX, minY, maxX, maxY, x, y, invSize;
  17756. 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
  17757. if (data.length > 80 * dim) {
  17758. minX = maxX = data[0];
  17759. minY = maxY = data[1];
  17760. for (var i = dim; i < outerLen; i += dim) {
  17761. x = data[i];
  17762. y = data[i + 1];
  17763. if (x < minX) minX = x;
  17764. if (y < minY) minY = y;
  17765. if (x > maxX) maxX = x;
  17766. if (y > maxY) maxY = y;
  17767. } // minX, minY and invSize are later used to transform coords into integers for z-order calculation
  17768. invSize = Math.max(maxX - minX, maxY - minY);
  17769. invSize = invSize !== 0 ? 1 / invSize : 0;
  17770. }
  17771. earcutLinked(outerNode, triangles, dim, minX, minY, invSize);
  17772. return triangles;
  17773. }
  17774. }; // create a circular doubly linked list from polygon points in the specified winding order
  17775. function linkedList(data, start, end, dim, clockwise) {
  17776. var i, last;
  17777. if (clockwise === signedArea(data, start, end, dim) > 0) {
  17778. for (i = start; i < end; i += dim) last = insertNode(i, data[i], data[i + 1], last);
  17779. } else {
  17780. for (i = end - dim; i >= start; i -= dim) last = insertNode(i, data[i], data[i + 1], last);
  17781. }
  17782. if (last && equals(last, last.next)) {
  17783. removeNode(last);
  17784. last = last.next;
  17785. }
  17786. return last;
  17787. } // eliminate colinear or duplicate points
  17788. function filterPoints(start, end) {
  17789. if (!start) return start;
  17790. if (!end) end = start;
  17791. var p = start,
  17792. again;
  17793. do {
  17794. again = false;
  17795. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  17796. removeNode(p);
  17797. p = end = p.prev;
  17798. if (p === p.next) break;
  17799. again = true;
  17800. } else {
  17801. p = p.next;
  17802. }
  17803. } while (again || p !== end);
  17804. return end;
  17805. } // main ear slicing loop which triangulates a polygon (given as a linked list)
  17806. function earcutLinked(ear, triangles, dim, minX, minY, invSize, pass) {
  17807. if (!ear) return; // interlink polygon nodes in z-order
  17808. if (!pass && invSize) indexCurve(ear, minX, minY, invSize);
  17809. var stop = ear,
  17810. prev,
  17811. next; // iterate through ears, slicing them one by one
  17812. while (ear.prev !== ear.next) {
  17813. prev = ear.prev;
  17814. next = ear.next;
  17815. if (invSize ? isEarHashed(ear, minX, minY, invSize) : isEar(ear)) {
  17816. // cut off the triangle
  17817. triangles.push(prev.i / dim);
  17818. triangles.push(ear.i / dim);
  17819. triangles.push(next.i / dim);
  17820. removeNode(ear); // skipping the next vertex leads to less sliver triangles
  17821. ear = next.next;
  17822. stop = next.next;
  17823. continue;
  17824. }
  17825. ear = next; // if we looped through the whole remaining polygon and can't find any more ears
  17826. if (ear === stop) {
  17827. // try filtering points and slicing again
  17828. if (!pass) {
  17829. earcutLinked(filterPoints(ear), triangles, dim, minX, minY, invSize, 1); // if this didn't work, try curing all small self-intersections locally
  17830. } else if (pass === 1) {
  17831. ear = cureLocalIntersections(ear, triangles, dim);
  17832. earcutLinked(ear, triangles, dim, minX, minY, invSize, 2); // as a last resort, try splitting the remaining polygon into two
  17833. } else if (pass === 2) {
  17834. splitEarcut(ear, triangles, dim, minX, minY, invSize);
  17835. }
  17836. break;
  17837. }
  17838. }
  17839. } // check whether a polygon node forms a valid ear with adjacent nodes
  17840. function isEar(ear) {
  17841. var a = ear.prev,
  17842. b = ear,
  17843. c = ear.next;
  17844. if (area(a, b, c) >= 0) return false; // reflex, can't be an ear
  17845. // now make sure we don't have other points inside the potential ear
  17846. var p = ear.next.next;
  17847. while (p !== ear.prev) {
  17848. 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;
  17849. p = p.next;
  17850. }
  17851. return true;
  17852. }
  17853. function isEarHashed(ear, minX, minY, invSize) {
  17854. var a = ear.prev,
  17855. b = ear,
  17856. c = ear.next;
  17857. if (area(a, b, c) >= 0) return false; // reflex, can't be an ear
  17858. // triangle bbox; min & max are calculated like this for speed
  17859. var minTX = a.x < b.x ? a.x < c.x ? a.x : c.x : b.x < c.x ? b.x : c.x,
  17860. minTY = a.y < b.y ? a.y < c.y ? a.y : c.y : b.y < c.y ? b.y : c.y,
  17861. maxTX = a.x > b.x ? a.x > c.x ? a.x : c.x : b.x > c.x ? b.x : c.x,
  17862. 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;
  17863. var minZ = zOrder(minTX, minTY, minX, minY, invSize),
  17864. maxZ = zOrder(maxTX, maxTY, minX, minY, invSize);
  17865. var p = ear.prevZ,
  17866. n = ear.nextZ; // look for points inside the triangle in both directions
  17867. while (p && p.z >= minZ && n && n.z <= maxZ) {
  17868. 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;
  17869. p = p.prevZ;
  17870. 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;
  17871. n = n.nextZ;
  17872. } // look for remaining points in decreasing z-order
  17873. while (p && p.z >= minZ) {
  17874. 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;
  17875. p = p.prevZ;
  17876. } // look for remaining points in increasing z-order
  17877. while (n && n.z <= maxZ) {
  17878. 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;
  17879. n = n.nextZ;
  17880. }
  17881. return true;
  17882. } // go through all polygon nodes and cure small local self-intersections
  17883. function cureLocalIntersections(start, triangles, dim) {
  17884. var p = start;
  17885. do {
  17886. var a = p.prev,
  17887. b = p.next.next;
  17888. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  17889. triangles.push(a.i / dim);
  17890. triangles.push(p.i / dim);
  17891. triangles.push(b.i / dim); // remove two nodes involved
  17892. removeNode(p);
  17893. removeNode(p.next);
  17894. p = start = b;
  17895. }
  17896. p = p.next;
  17897. } while (p !== start);
  17898. return p;
  17899. } // try splitting polygon into two and triangulate them independently
  17900. function splitEarcut(start, triangles, dim, minX, minY, invSize) {
  17901. // look for a valid diagonal that divides the polygon into two
  17902. var a = start;
  17903. do {
  17904. var b = a.next.next;
  17905. while (b !== a.prev) {
  17906. if (a.i !== b.i && isValidDiagonal(a, b)) {
  17907. // split the polygon in two by the diagonal
  17908. var c = splitPolygon(a, b); // filter colinear points around the cuts
  17909. a = filterPoints(a, a.next);
  17910. c = filterPoints(c, c.next); // run earcut on each half
  17911. earcutLinked(a, triangles, dim, minX, minY, invSize);
  17912. earcutLinked(c, triangles, dim, minX, minY, invSize);
  17913. return;
  17914. }
  17915. b = b.next;
  17916. }
  17917. a = a.next;
  17918. } while (a !== start);
  17919. } // link every hole into the outer loop, producing a single-ring polygon without holes
  17920. function eliminateHoles(data, holeIndices, outerNode, dim) {
  17921. var queue = [],
  17922. i,
  17923. len,
  17924. start,
  17925. end,
  17926. list;
  17927. for (i = 0, len = holeIndices.length; i < len; i++) {
  17928. start = holeIndices[i] * dim;
  17929. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  17930. list = linkedList(data, start, end, dim, false);
  17931. if (list === list.next) list.steiner = true;
  17932. queue.push(getLeftmost(list));
  17933. }
  17934. queue.sort(compareX); // process holes from left to right
  17935. for (i = 0; i < queue.length; i++) {
  17936. eliminateHole(queue[i], outerNode);
  17937. outerNode = filterPoints(outerNode, outerNode.next);
  17938. }
  17939. return outerNode;
  17940. }
  17941. function compareX(a, b) {
  17942. return a.x - b.x;
  17943. } // find a bridge between vertices that connects hole with an outer ring and and link it
  17944. function eliminateHole(hole, outerNode) {
  17945. outerNode = findHoleBridge(hole, outerNode);
  17946. if (outerNode) {
  17947. var b = splitPolygon(outerNode, hole);
  17948. filterPoints(b, b.next);
  17949. }
  17950. } // David Eberly's algorithm for finding a bridge between hole and outer polygon
  17951. function findHoleBridge(hole, outerNode) {
  17952. var p = outerNode,
  17953. hx = hole.x,
  17954. hy = hole.y,
  17955. qx = -Infinity,
  17956. m; // find a segment intersected by a ray from the hole's leftmost point to the left;
  17957. // segment's endpoint with lesser x will be potential connection point
  17958. do {
  17959. if (hy <= p.y && hy >= p.next.y && p.next.y !== p.y) {
  17960. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  17961. if (x <= hx && x > qx) {
  17962. qx = x;
  17963. if (x === hx) {
  17964. if (hy === p.y) return p;
  17965. if (hy === p.next.y) return p.next;
  17966. }
  17967. m = p.x < p.next.x ? p : p.next;
  17968. }
  17969. }
  17970. p = p.next;
  17971. } while (p !== outerNode);
  17972. if (!m) return null;
  17973. if (hx === qx) return m.prev; // hole touches outer segment; pick lower endpoint
  17974. // look for points inside the triangle of hole point, segment intersection and endpoint;
  17975. // if there are no points found, we have a valid connection;
  17976. // otherwise choose the point of the minimum angle with the ray as connection point
  17977. var stop = m,
  17978. mx = m.x,
  17979. my = m.y,
  17980. tanMin = Infinity,
  17981. tan;
  17982. p = m.next;
  17983. while (p !== stop) {
  17984. 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)) {
  17985. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  17986. if ((tan < tanMin || tan === tanMin && p.x > m.x) && locallyInside(p, hole)) {
  17987. m = p;
  17988. tanMin = tan;
  17989. }
  17990. }
  17991. p = p.next;
  17992. }
  17993. return m;
  17994. } // interlink polygon nodes in z-order
  17995. function indexCurve(start, minX, minY, invSize) {
  17996. var p = start;
  17997. do {
  17998. if (p.z === null) p.z = zOrder(p.x, p.y, minX, minY, invSize);
  17999. p.prevZ = p.prev;
  18000. p.nextZ = p.next;
  18001. p = p.next;
  18002. } while (p !== start);
  18003. p.prevZ.nextZ = null;
  18004. p.prevZ = null;
  18005. sortLinked(p);
  18006. } // Simon Tatham's linked list merge sort algorithm
  18007. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  18008. function sortLinked(list) {
  18009. var i,
  18010. p,
  18011. q,
  18012. e,
  18013. tail,
  18014. numMerges,
  18015. pSize,
  18016. qSize,
  18017. inSize = 1;
  18018. do {
  18019. p = list;
  18020. list = null;
  18021. tail = null;
  18022. numMerges = 0;
  18023. while (p) {
  18024. numMerges++;
  18025. q = p;
  18026. pSize = 0;
  18027. for (i = 0; i < inSize; i++) {
  18028. pSize++;
  18029. q = q.nextZ;
  18030. if (!q) break;
  18031. }
  18032. qSize = inSize;
  18033. while (pSize > 0 || qSize > 0 && q) {
  18034. if (pSize !== 0 && (qSize === 0 || !q || p.z <= q.z)) {
  18035. e = p;
  18036. p = p.nextZ;
  18037. pSize--;
  18038. } else {
  18039. e = q;
  18040. q = q.nextZ;
  18041. qSize--;
  18042. }
  18043. if (tail) tail.nextZ = e;else list = e;
  18044. e.prevZ = tail;
  18045. tail = e;
  18046. }
  18047. p = q;
  18048. }
  18049. tail.nextZ = null;
  18050. inSize *= 2;
  18051. } while (numMerges > 1);
  18052. return list;
  18053. } // z-order of a point given coords and inverse of the longer side of data bbox
  18054. function zOrder(x, y, minX, minY, invSize) {
  18055. // coords are transformed into non-negative 15-bit integer range
  18056. x = 32767 * (x - minX) * invSize;
  18057. y = 32767 * (y - minY) * invSize;
  18058. x = (x | x << 8) & 0x00FF00FF;
  18059. x = (x | x << 4) & 0x0F0F0F0F;
  18060. x = (x | x << 2) & 0x33333333;
  18061. x = (x | x << 1) & 0x55555555;
  18062. y = (y | y << 8) & 0x00FF00FF;
  18063. y = (y | y << 4) & 0x0F0F0F0F;
  18064. y = (y | y << 2) & 0x33333333;
  18065. y = (y | y << 1) & 0x55555555;
  18066. return x | y << 1;
  18067. } // find the leftmost node of a polygon ring
  18068. function getLeftmost(start) {
  18069. var p = start,
  18070. leftmost = start;
  18071. do {
  18072. if (p.x < leftmost.x || p.x === leftmost.x && p.y < leftmost.y) leftmost = p;
  18073. p = p.next;
  18074. } while (p !== start);
  18075. return leftmost;
  18076. } // check if a point lies within a convex triangle
  18077. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  18078. 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;
  18079. } // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  18080. function isValidDiagonal(a, b) {
  18081. return a.next.i !== b.i && a.prev.i !== b.i && !intersectsPolygon(a, b) && locallyInside(a, b) && locallyInside(b, a) && middleInside(a, b);
  18082. } // signed area of a triangle
  18083. function area(p, q, r) {
  18084. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  18085. } // check if two points are equal
  18086. function equals(p1, p2) {
  18087. return p1.x === p2.x && p1.y === p2.y;
  18088. } // check if two segments intersect
  18089. function intersects(p1, q1, p2, q2) {
  18090. if (equals(p1, p2) && equals(q1, q2) || equals(p1, q2) && equals(p2, q1)) return true;
  18091. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 && area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  18092. } // check if a polygon diagonal intersects any polygon segments
  18093. function intersectsPolygon(a, b) {
  18094. var p = a;
  18095. do {
  18096. 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;
  18097. p = p.next;
  18098. } while (p !== a);
  18099. return false;
  18100. } // check if a polygon diagonal is locally inside the polygon
  18101. function locallyInside(a, b) {
  18102. 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;
  18103. } // check if the middle point of a polygon diagonal is inside the polygon
  18104. function middleInside(a, b) {
  18105. var p = a,
  18106. inside = false,
  18107. px = (a.x + b.x) / 2,
  18108. py = (a.y + b.y) / 2;
  18109. do {
  18110. 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;
  18111. p = p.next;
  18112. } while (p !== a);
  18113. return inside;
  18114. } // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  18115. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  18116. function splitPolygon(a, b) {
  18117. var a2 = new Node(a.i, a.x, a.y),
  18118. b2 = new Node(b.i, b.x, b.y),
  18119. an = a.next,
  18120. bp = b.prev;
  18121. a.next = b;
  18122. b.prev = a;
  18123. a2.next = an;
  18124. an.prev = a2;
  18125. b2.next = a2;
  18126. a2.prev = b2;
  18127. bp.next = b2;
  18128. b2.prev = bp;
  18129. return b2;
  18130. } // create a node and optionally link it with previous one (in a circular doubly linked list)
  18131. function insertNode(i, x, y, last) {
  18132. var p = new Node(i, x, y);
  18133. if (!last) {
  18134. p.prev = p;
  18135. p.next = p;
  18136. } else {
  18137. p.next = last.next;
  18138. p.prev = last;
  18139. last.next.prev = p;
  18140. last.next = p;
  18141. }
  18142. return p;
  18143. }
  18144. function removeNode(p) {
  18145. p.next.prev = p.prev;
  18146. p.prev.next = p.next;
  18147. if (p.prevZ) p.prevZ.nextZ = p.nextZ;
  18148. if (p.nextZ) p.nextZ.prevZ = p.prevZ;
  18149. }
  18150. function Node(i, x, y) {
  18151. // vertex index in coordinates array
  18152. this.i = i; // vertex coordinates
  18153. this.x = x;
  18154. this.y = y; // previous and next vertex nodes in a polygon ring
  18155. this.prev = null;
  18156. this.next = null; // z-order curve value
  18157. this.z = null; // previous and next nodes in z-order
  18158. this.prevZ = null;
  18159. this.nextZ = null; // indicates whether this is a steiner point
  18160. this.steiner = false;
  18161. }
  18162. function signedArea(data, start, end, dim) {
  18163. var sum = 0;
  18164. for (var i = start, j = end - dim; i < end; i += dim) {
  18165. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  18166. j = i;
  18167. }
  18168. return sum;
  18169. }
  18170. /**
  18171. * @author zz85 / http://www.lab4games.net/zz85/blog
  18172. */
  18173. var ShapeUtils = {
  18174. // calculate area of the contour polygon
  18175. area: function (contour) {
  18176. var n = contour.length;
  18177. var a = 0.0;
  18178. for (var p = n - 1, q = 0; q < n; p = q++) {
  18179. a += contour[p].x * contour[q].y - contour[q].x * contour[p].y;
  18180. }
  18181. return a * 0.5;
  18182. },
  18183. isClockWise: function (pts) {
  18184. return ShapeUtils.area(pts) < 0;
  18185. },
  18186. triangulateShape: function (contour, holes) {
  18187. var vertices = []; // flat array of vertices like [ x0,y0, x1,y1, x2,y2, ... ]
  18188. var holeIndices = []; // array of hole indices
  18189. var faces = []; // final array of vertex indices like [ [ a,b,d ], [ b,c,d ] ]
  18190. removeDupEndPts(contour);
  18191. addContour(vertices, contour); //
  18192. var holeIndex = contour.length;
  18193. holes.forEach(removeDupEndPts);
  18194. for (var i = 0; i < holes.length; i++) {
  18195. holeIndices.push(holeIndex);
  18196. holeIndex += holes[i].length;
  18197. addContour(vertices, holes[i]);
  18198. } //
  18199. var triangles = Earcut.triangulate(vertices, holeIndices); //
  18200. for (var i = 0; i < triangles.length; i += 3) {
  18201. faces.push(triangles.slice(i, i + 3));
  18202. }
  18203. return faces;
  18204. }
  18205. };
  18206. exports.ShapeUtils = ShapeUtils;
  18207. function removeDupEndPts(points) {
  18208. var l = points.length;
  18209. if (l > 2 && points[l - 1].equals(points[0])) {
  18210. points.pop();
  18211. }
  18212. }
  18213. function addContour(vertices, contour) {
  18214. for (var i = 0; i < contour.length; i++) {
  18215. vertices.push(contour[i].x);
  18216. vertices.push(contour[i].y);
  18217. }
  18218. }
  18219. /**
  18220. * @author zz85 / http://www.lab4games.net/zz85/blog
  18221. *
  18222. * Creates extruded geometry from a path shape.
  18223. *
  18224. * parameters = {
  18225. *
  18226. * curveSegments: <int>, // number of points on the curves
  18227. * steps: <int>, // number of points for z-side extrusions / used for subdividing segments of extrude spline too
  18228. * depth: <float>, // Depth to extrude the shape
  18229. *
  18230. * bevelEnabled: <bool>, // turn on bevel
  18231. * bevelThickness: <float>, // how deep into the original shape bevel goes
  18232. * bevelSize: <float>, // how far from shape outline (including bevelOffset) is bevel
  18233. * bevelOffset: <float>, // how far from shape outline does bevel start
  18234. * bevelSegments: <int>, // number of bevel layers
  18235. *
  18236. * extrudePath: <THREE.Curve> // curve to extrude shape along
  18237. *
  18238. * UVGenerator: <Object> // object that provides UV generator functions
  18239. *
  18240. * }
  18241. */
  18242. // ExtrudeGeometry
  18243. function ExtrudeGeometry(shapes, options) {
  18244. Geometry.call(this);
  18245. this.type = 'ExtrudeGeometry';
  18246. this.parameters = {
  18247. shapes: shapes,
  18248. options: options
  18249. };
  18250. this.fromBufferGeometry(new ExtrudeBufferGeometry(shapes, options));
  18251. this.mergeVertices();
  18252. }
  18253. ExtrudeGeometry.prototype = Object.create(Geometry.prototype);
  18254. ExtrudeGeometry.prototype.constructor = ExtrudeGeometry;
  18255. ExtrudeGeometry.prototype.toJSON = function () {
  18256. var data = Geometry.prototype.toJSON.call(this);
  18257. var shapes = this.parameters.shapes;
  18258. var options = this.parameters.options;
  18259. return toJSON(shapes, options, data);
  18260. }; // ExtrudeBufferGeometry
  18261. function ExtrudeBufferGeometry(shapes, options) {
  18262. BufferGeometry.call(this);
  18263. this.type = 'ExtrudeBufferGeometry';
  18264. this.parameters = {
  18265. shapes: shapes,
  18266. options: options
  18267. };
  18268. shapes = Array.isArray(shapes) ? shapes : [shapes];
  18269. var scope = this;
  18270. var verticesArray = [];
  18271. var uvArray = [];
  18272. for (var i = 0, l = shapes.length; i < l; i++) {
  18273. var shape = shapes[i];
  18274. addShape(shape);
  18275. } // build geometry
  18276. this.addAttribute('position', new Float32BufferAttribute(verticesArray, 3));
  18277. this.addAttribute('uv', new Float32BufferAttribute(uvArray, 2));
  18278. this.computeVertexNormals(); // functions
  18279. function addShape(shape) {
  18280. var placeholder = []; // options
  18281. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  18282. var steps = options.steps !== undefined ? options.steps : 1;
  18283. var depth = options.depth !== undefined ? options.depth : 100;
  18284. var bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true;
  18285. var bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 6;
  18286. var bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 2;
  18287. var bevelOffset = options.bevelOffset !== undefined ? options.bevelOffset : 0;
  18288. var bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  18289. var extrudePath = options.extrudePath;
  18290. var uvgen = options.UVGenerator !== undefined ? options.UVGenerator : WorldUVGenerator; // deprecated options
  18291. if (options.amount !== undefined) {
  18292. console.warn('THREE.ExtrudeBufferGeometry: amount has been renamed to depth.');
  18293. depth = options.amount;
  18294. } //
  18295. var extrudePts,
  18296. extrudeByPath = false;
  18297. var splineTube, binormal, normal, position2;
  18298. if (extrudePath) {
  18299. extrudePts = extrudePath.getSpacedPoints(steps);
  18300. extrudeByPath = true;
  18301. bevelEnabled = false; // bevels not supported for path extrusion
  18302. // SETUP TNB variables
  18303. // TODO1 - have a .isClosed in spline?
  18304. splineTube = extrudePath.computeFrenetFrames(steps, false); // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  18305. binormal = new Vector3();
  18306. normal = new Vector3();
  18307. position2 = new Vector3();
  18308. } // Safeguards if bevels are not enabled
  18309. if (!bevelEnabled) {
  18310. bevelSegments = 0;
  18311. bevelThickness = 0;
  18312. bevelSize = 0;
  18313. bevelOffset = 0;
  18314. } // Variables initialization
  18315. var ahole, h, hl; // looping of holes
  18316. var shapePoints = shape.extractPoints(curveSegments);
  18317. var vertices = shapePoints.shape;
  18318. var holes = shapePoints.holes;
  18319. var reverse = !ShapeUtils.isClockWise(vertices);
  18320. if (reverse) {
  18321. vertices = vertices.reverse(); // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  18322. for (h = 0, hl = holes.length; h < hl; h++) {
  18323. ahole = holes[h];
  18324. if (ShapeUtils.isClockWise(ahole)) {
  18325. holes[h] = ahole.reverse();
  18326. }
  18327. }
  18328. }
  18329. var faces = ShapeUtils.triangulateShape(vertices, holes);
  18330. /* Vertices */
  18331. var contour = vertices; // vertices has all points but contour has only points of circumference
  18332. for (h = 0, hl = holes.length; h < hl; h++) {
  18333. ahole = holes[h];
  18334. vertices = vertices.concat(ahole);
  18335. }
  18336. function scalePt2(pt, vec, size) {
  18337. if (!vec) console.error("THREE.ExtrudeGeometry: vec does not exist");
  18338. return vec.clone().multiplyScalar(size).add(pt);
  18339. }
  18340. var b,
  18341. bs,
  18342. t,
  18343. z,
  18344. vert,
  18345. vlen = vertices.length,
  18346. face,
  18347. flen = faces.length; // Find directions for point movement
  18348. function getBevelVec(inPt, inPrev, inNext) {
  18349. // computes for inPt the corresponding point inPt' on a new contour
  18350. // shifted by 1 unit (length of normalized vector) to the left
  18351. // if we walk along contour clockwise, this new contour is outside the old one
  18352. //
  18353. // inPt' is the intersection of the two lines parallel to the two
  18354. // adjacent edges of inPt at a distance of 1 unit on the left side.
  18355. var v_trans_x, v_trans_y, shrink_by; // resulting translation vector for inPt
  18356. // good reading for geometry algorithms (here: line-line intersection)
  18357. // http://geomalgorithms.com/a05-_intersect-1.html
  18358. var v_prev_x = inPt.x - inPrev.x,
  18359. v_prev_y = inPt.y - inPrev.y;
  18360. var v_next_x = inNext.x - inPt.x,
  18361. v_next_y = inNext.y - inPt.y;
  18362. var v_prev_lensq = v_prev_x * v_prev_x + v_prev_y * v_prev_y; // check for collinear edges
  18363. var collinear0 = v_prev_x * v_next_y - v_prev_y * v_next_x;
  18364. if (Math.abs(collinear0) > Number.EPSILON) {
  18365. // not collinear
  18366. // length of vectors for normalizing
  18367. var v_prev_len = Math.sqrt(v_prev_lensq);
  18368. 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
  18369. var ptPrevShift_x = inPrev.x - v_prev_y / v_prev_len;
  18370. var ptPrevShift_y = inPrev.y + v_prev_x / v_prev_len;
  18371. var ptNextShift_x = inNext.x - v_next_y / v_next_len;
  18372. var ptNextShift_y = inNext.y + v_next_x / v_next_len; // scaling factor for v_prev to intersection point
  18373. 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
  18374. v_trans_x = ptPrevShift_x + v_prev_x * sf - inPt.x;
  18375. v_trans_y = ptPrevShift_y + v_prev_y * sf - inPt.y; // Don't normalize!, otherwise sharp corners become ugly
  18376. // but prevent crazy spikes
  18377. var v_trans_lensq = v_trans_x * v_trans_x + v_trans_y * v_trans_y;
  18378. if (v_trans_lensq <= 2) {
  18379. return new Vector2(v_trans_x, v_trans_y);
  18380. } else {
  18381. shrink_by = Math.sqrt(v_trans_lensq / 2);
  18382. }
  18383. } else {
  18384. // handle special case of collinear edges
  18385. var direction_eq = false; // assumes: opposite
  18386. if (v_prev_x > Number.EPSILON) {
  18387. if (v_next_x > Number.EPSILON) {
  18388. direction_eq = true;
  18389. }
  18390. } else {
  18391. if (v_prev_x < -Number.EPSILON) {
  18392. if (v_next_x < -Number.EPSILON) {
  18393. direction_eq = true;
  18394. }
  18395. } else {
  18396. if (Math.sign(v_prev_y) === Math.sign(v_next_y)) {
  18397. direction_eq = true;
  18398. }
  18399. }
  18400. }
  18401. if (direction_eq) {
  18402. // console.log("Warning: lines are a straight sequence");
  18403. v_trans_x = -v_prev_y;
  18404. v_trans_y = v_prev_x;
  18405. shrink_by = Math.sqrt(v_prev_lensq);
  18406. } else {
  18407. // console.log("Warning: lines are a straight spike");
  18408. v_trans_x = v_prev_x;
  18409. v_trans_y = v_prev_y;
  18410. shrink_by = Math.sqrt(v_prev_lensq / 2);
  18411. }
  18412. }
  18413. return new Vector2(v_trans_x / shrink_by, v_trans_y / shrink_by);
  18414. }
  18415. var contourMovements = [];
  18416. for (var i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i++, j++, k++) {
  18417. if (j === il) j = 0;
  18418. if (k === il) k = 0; // (j)---(i)---(k)
  18419. // console.log('i,j,k', i, j , k)
  18420. contourMovements[i] = getBevelVec(contour[i], contour[j], contour[k]);
  18421. }
  18422. var holesMovements = [],
  18423. oneHoleMovements,
  18424. verticesMovements = contourMovements.concat();
  18425. for (h = 0, hl = holes.length; h < hl; h++) {
  18426. ahole = holes[h];
  18427. oneHoleMovements = [];
  18428. for (i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i++, j++, k++) {
  18429. if (j === il) j = 0;
  18430. if (k === il) k = 0; // (j)---(i)---(k)
  18431. oneHoleMovements[i] = getBevelVec(ahole[i], ahole[j], ahole[k]);
  18432. }
  18433. holesMovements.push(oneHoleMovements);
  18434. verticesMovements = verticesMovements.concat(oneHoleMovements);
  18435. } // Loop bevelSegments, 1 for the front, 1 for the back
  18436. for (b = 0; b < bevelSegments; b++) {
  18437. //for ( b = bevelSegments; b > 0; b -- ) {
  18438. t = b / bevelSegments;
  18439. z = bevelThickness * Math.cos(t * Math.PI / 2);
  18440. bs = bevelSize * Math.sin(t * Math.PI / 2) + bevelOffset; // contract shape
  18441. for (i = 0, il = contour.length; i < il; i++) {
  18442. vert = scalePt2(contour[i], contourMovements[i], bs);
  18443. v(vert.x, vert.y, -z);
  18444. } // expand holes
  18445. for (h = 0, hl = holes.length; h < hl; h++) {
  18446. ahole = holes[h];
  18447. oneHoleMovements = holesMovements[h];
  18448. for (i = 0, il = ahole.length; i < il; i++) {
  18449. vert = scalePt2(ahole[i], oneHoleMovements[i], bs);
  18450. v(vert.x, vert.y, -z);
  18451. }
  18452. }
  18453. }
  18454. bs = bevelSize + bevelOffset; // Back facing vertices
  18455. for (i = 0; i < vlen; i++) {
  18456. vert = bevelEnabled ? scalePt2(vertices[i], verticesMovements[i], bs) : vertices[i];
  18457. if (!extrudeByPath) {
  18458. v(vert.x, vert.y, 0);
  18459. } else {
  18460. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  18461. normal.copy(splineTube.normals[0]).multiplyScalar(vert.x);
  18462. binormal.copy(splineTube.binormals[0]).multiplyScalar(vert.y);
  18463. position2.copy(extrudePts[0]).add(normal).add(binormal);
  18464. v(position2.x, position2.y, position2.z);
  18465. }
  18466. } // Add stepped vertices...
  18467. // Including front facing vertices
  18468. var s;
  18469. for (s = 1; s <= steps; s++) {
  18470. for (i = 0; i < vlen; i++) {
  18471. vert = bevelEnabled ? scalePt2(vertices[i], verticesMovements[i], bs) : vertices[i];
  18472. if (!extrudeByPath) {
  18473. v(vert.x, vert.y, depth / steps * s);
  18474. } else {
  18475. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  18476. normal.copy(splineTube.normals[s]).multiplyScalar(vert.x);
  18477. binormal.copy(splineTube.binormals[s]).multiplyScalar(vert.y);
  18478. position2.copy(extrudePts[s]).add(normal).add(binormal);
  18479. v(position2.x, position2.y, position2.z);
  18480. }
  18481. }
  18482. } // Add bevel segments planes
  18483. //for ( b = 1; b <= bevelSegments; b ++ ) {
  18484. for (b = bevelSegments - 1; b >= 0; b--) {
  18485. t = b / bevelSegments;
  18486. z = bevelThickness * Math.cos(t * Math.PI / 2);
  18487. bs = bevelSize * Math.sin(t * Math.PI / 2) + bevelOffset; // contract shape
  18488. for (i = 0, il = contour.length; i < il; i++) {
  18489. vert = scalePt2(contour[i], contourMovements[i], bs);
  18490. v(vert.x, vert.y, depth + z);
  18491. } // expand holes
  18492. for (h = 0, hl = holes.length; h < hl; h++) {
  18493. ahole = holes[h];
  18494. oneHoleMovements = holesMovements[h];
  18495. for (i = 0, il = ahole.length; i < il; i++) {
  18496. vert = scalePt2(ahole[i], oneHoleMovements[i], bs);
  18497. if (!extrudeByPath) {
  18498. v(vert.x, vert.y, depth + z);
  18499. } else {
  18500. v(vert.x, vert.y + extrudePts[steps - 1].y, extrudePts[steps - 1].x + z);
  18501. }
  18502. }
  18503. }
  18504. }
  18505. /* Faces */
  18506. // Top and bottom faces
  18507. buildLidFaces(); // Sides faces
  18508. buildSideFaces(); ///// Internal functions
  18509. function buildLidFaces() {
  18510. var start = verticesArray.length / 3;
  18511. if (bevelEnabled) {
  18512. var layer = 0; // steps + 1
  18513. var offset = vlen * layer; // Bottom faces
  18514. for (i = 0; i < flen; i++) {
  18515. face = faces[i];
  18516. f3(face[2] + offset, face[1] + offset, face[0] + offset);
  18517. }
  18518. layer = steps + bevelSegments * 2;
  18519. offset = vlen * layer; // Top faces
  18520. for (i = 0; i < flen; i++) {
  18521. face = faces[i];
  18522. f3(face[0] + offset, face[1] + offset, face[2] + offset);
  18523. }
  18524. } else {
  18525. // Bottom faces
  18526. for (i = 0; i < flen; i++) {
  18527. face = faces[i];
  18528. f3(face[2], face[1], face[0]);
  18529. } // Top faces
  18530. for (i = 0; i < flen; i++) {
  18531. face = faces[i];
  18532. f3(face[0] + vlen * steps, face[1] + vlen * steps, face[2] + vlen * steps);
  18533. }
  18534. }
  18535. scope.addGroup(start, verticesArray.length / 3 - start, 0);
  18536. } // Create faces for the z-sides of the shape
  18537. function buildSideFaces() {
  18538. var start = verticesArray.length / 3;
  18539. var layeroffset = 0;
  18540. sidewalls(contour, layeroffset);
  18541. layeroffset += contour.length;
  18542. for (h = 0, hl = holes.length; h < hl; h++) {
  18543. ahole = holes[h];
  18544. sidewalls(ahole, layeroffset); //, true
  18545. layeroffset += ahole.length;
  18546. }
  18547. scope.addGroup(start, verticesArray.length / 3 - start, 1);
  18548. }
  18549. function sidewalls(contour, layeroffset) {
  18550. var j, k;
  18551. i = contour.length;
  18552. while (--i >= 0) {
  18553. j = i;
  18554. k = i - 1;
  18555. if (k < 0) k = contour.length - 1; //console.log('b', i,j, i-1, k,vertices.length);
  18556. var s = 0,
  18557. sl = steps + bevelSegments * 2;
  18558. for (s = 0; s < sl; s++) {
  18559. var slen1 = vlen * s;
  18560. var slen2 = vlen * (s + 1);
  18561. var a = layeroffset + j + slen1,
  18562. b = layeroffset + k + slen1,
  18563. c = layeroffset + k + slen2,
  18564. d = layeroffset + j + slen2;
  18565. f4(a, b, c, d);
  18566. }
  18567. }
  18568. }
  18569. function v(x, y, z) {
  18570. placeholder.push(x);
  18571. placeholder.push(y);
  18572. placeholder.push(z);
  18573. }
  18574. function f3(a, b, c) {
  18575. addVertex(a);
  18576. addVertex(b);
  18577. addVertex(c);
  18578. var nextIndex = verticesArray.length / 3;
  18579. var uvs = uvgen.generateTopUV(scope, verticesArray, nextIndex - 3, nextIndex - 2, nextIndex - 1);
  18580. addUV(uvs[0]);
  18581. addUV(uvs[1]);
  18582. addUV(uvs[2]);
  18583. }
  18584. function f4(a, b, c, d) {
  18585. addVertex(a);
  18586. addVertex(b);
  18587. addVertex(d);
  18588. addVertex(b);
  18589. addVertex(c);
  18590. addVertex(d);
  18591. var nextIndex = verticesArray.length / 3;
  18592. var uvs = uvgen.generateSideWallUV(scope, verticesArray, nextIndex - 6, nextIndex - 3, nextIndex - 2, nextIndex - 1);
  18593. addUV(uvs[0]);
  18594. addUV(uvs[1]);
  18595. addUV(uvs[3]);
  18596. addUV(uvs[1]);
  18597. addUV(uvs[2]);
  18598. addUV(uvs[3]);
  18599. }
  18600. function addVertex(index) {
  18601. verticesArray.push(placeholder[index * 3 + 0]);
  18602. verticesArray.push(placeholder[index * 3 + 1]);
  18603. verticesArray.push(placeholder[index * 3 + 2]);
  18604. }
  18605. function addUV(vector2) {
  18606. uvArray.push(vector2.x);
  18607. uvArray.push(vector2.y);
  18608. }
  18609. }
  18610. }
  18611. ExtrudeBufferGeometry.prototype = Object.create(BufferGeometry.prototype);
  18612. ExtrudeBufferGeometry.prototype.constructor = ExtrudeBufferGeometry;
  18613. ExtrudeBufferGeometry.prototype.toJSON = function () {
  18614. var data = BufferGeometry.prototype.toJSON.call(this);
  18615. var shapes = this.parameters.shapes;
  18616. var options = this.parameters.options;
  18617. return toJSON(shapes, options, data);
  18618. }; //
  18619. var WorldUVGenerator = {
  18620. generateTopUV: function (geometry, vertices, indexA, indexB, indexC) {
  18621. var a_x = vertices[indexA * 3];
  18622. var a_y = vertices[indexA * 3 + 1];
  18623. var b_x = vertices[indexB * 3];
  18624. var b_y = vertices[indexB * 3 + 1];
  18625. var c_x = vertices[indexC * 3];
  18626. var c_y = vertices[indexC * 3 + 1];
  18627. return [new Vector2(a_x, a_y), new Vector2(b_x, b_y), new Vector2(c_x, c_y)];
  18628. },
  18629. generateSideWallUV: function (geometry, vertices, indexA, indexB, indexC, indexD) {
  18630. var a_x = vertices[indexA * 3];
  18631. var a_y = vertices[indexA * 3 + 1];
  18632. var a_z = vertices[indexA * 3 + 2];
  18633. var b_x = vertices[indexB * 3];
  18634. var b_y = vertices[indexB * 3 + 1];
  18635. var b_z = vertices[indexB * 3 + 2];
  18636. var c_x = vertices[indexC * 3];
  18637. var c_y = vertices[indexC * 3 + 1];
  18638. var c_z = vertices[indexC * 3 + 2];
  18639. var d_x = vertices[indexD * 3];
  18640. var d_y = vertices[indexD * 3 + 1];
  18641. var d_z = vertices[indexD * 3 + 2];
  18642. if (Math.abs(a_y - b_y) < 0.01) {
  18643. 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)];
  18644. } else {
  18645. 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)];
  18646. }
  18647. }
  18648. };
  18649. function toJSON(shapes, options, data) {
  18650. //
  18651. data.shapes = [];
  18652. if (Array.isArray(shapes)) {
  18653. for (var i = 0, l = shapes.length; i < l; i++) {
  18654. var shape = shapes[i];
  18655. data.shapes.push(shape.uuid);
  18656. }
  18657. } else {
  18658. data.shapes.push(shapes.uuid);
  18659. } //
  18660. if (options.extrudePath !== undefined) data.options.extrudePath = options.extrudePath.toJSON();
  18661. return data;
  18662. }
  18663. /**
  18664. * @author zz85 / http://www.lab4games.net/zz85/blog
  18665. * @author alteredq / http://alteredqualia.com/
  18666. *
  18667. * Text = 3D Text
  18668. *
  18669. * parameters = {
  18670. * font: <THREE.Font>, // font
  18671. *
  18672. * size: <float>, // size of the text
  18673. * height: <float>, // thickness to extrude text
  18674. * curveSegments: <int>, // number of points on the curves
  18675. *
  18676. * bevelEnabled: <bool>, // turn on bevel
  18677. * bevelThickness: <float>, // how deep into text bevel goes
  18678. * bevelSize: <float>, // how far from text outline (including bevelOffset) is bevel
  18679. * bevelOffset: <float> // how far from text outline does bevel start
  18680. * }
  18681. */
  18682. // TextGeometry
  18683. function TextGeometry(text, parameters) {
  18684. Geometry.call(this);
  18685. this.type = 'TextGeometry';
  18686. this.parameters = {
  18687. text: text,
  18688. parameters: parameters
  18689. };
  18690. this.fromBufferGeometry(new TextBufferGeometry(text, parameters));
  18691. this.mergeVertices();
  18692. }
  18693. TextGeometry.prototype = Object.create(Geometry.prototype);
  18694. TextGeometry.prototype.constructor = TextGeometry; // TextBufferGeometry
  18695. function TextBufferGeometry(text, parameters) {
  18696. parameters = parameters || {};
  18697. var font = parameters.font;
  18698. if (!(font && font.isFont)) {
  18699. console.error('THREE.TextGeometry: font parameter is not an instance of THREE.Font.');
  18700. return new Geometry();
  18701. }
  18702. var shapes = font.generateShapes(text, parameters.size); // translate parameters to ExtrudeGeometry API
  18703. parameters.depth = parameters.height !== undefined ? parameters.height : 50; // defaults
  18704. if (parameters.bevelThickness === undefined) parameters.bevelThickness = 10;
  18705. if (parameters.bevelSize === undefined) parameters.bevelSize = 8;
  18706. if (parameters.bevelEnabled === undefined) parameters.bevelEnabled = false;
  18707. ExtrudeBufferGeometry.call(this, shapes, parameters);
  18708. this.type = 'TextBufferGeometry';
  18709. }
  18710. TextBufferGeometry.prototype = Object.create(ExtrudeBufferGeometry.prototype);
  18711. TextBufferGeometry.prototype.constructor = TextBufferGeometry;
  18712. /**
  18713. * @author mrdoob / http://mrdoob.com/
  18714. * @author benaadams / https://twitter.com/ben_a_adams
  18715. * @author Mugen87 / https://github.com/Mugen87
  18716. */
  18717. // SphereGeometry
  18718. function SphereGeometry(radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength) {
  18719. Geometry.call(this);
  18720. this.type = 'SphereGeometry';
  18721. this.parameters = {
  18722. radius: radius,
  18723. widthSegments: widthSegments,
  18724. heightSegments: heightSegments,
  18725. phiStart: phiStart,
  18726. phiLength: phiLength,
  18727. thetaStart: thetaStart,
  18728. thetaLength: thetaLength
  18729. };
  18730. this.fromBufferGeometry(new SphereBufferGeometry(radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength));
  18731. this.mergeVertices();
  18732. }
  18733. SphereGeometry.prototype = Object.create(Geometry.prototype);
  18734. SphereGeometry.prototype.constructor = SphereGeometry; // SphereBufferGeometry
  18735. function SphereBufferGeometry(radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength) {
  18736. BufferGeometry.call(this);
  18737. this.type = 'SphereBufferGeometry';
  18738. this.parameters = {
  18739. radius: radius,
  18740. widthSegments: widthSegments,
  18741. heightSegments: heightSegments,
  18742. phiStart: phiStart,
  18743. phiLength: phiLength,
  18744. thetaStart: thetaStart,
  18745. thetaLength: thetaLength
  18746. };
  18747. radius = radius || 1;
  18748. widthSegments = Math.max(3, Math.floor(widthSegments) || 8);
  18749. heightSegments = Math.max(2, Math.floor(heightSegments) || 6);
  18750. phiStart = phiStart !== undefined ? phiStart : 0;
  18751. phiLength = phiLength !== undefined ? phiLength : Math.PI * 2;
  18752. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  18753. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI;
  18754. var thetaEnd = Math.min(thetaStart + thetaLength, Math.PI);
  18755. var ix, iy;
  18756. var index = 0;
  18757. var grid = [];
  18758. var vertex = new Vector3();
  18759. var normal = new Vector3(); // buffers
  18760. var indices = [];
  18761. var vertices = [];
  18762. var normals = [];
  18763. var uvs = []; // generate vertices, normals and uvs
  18764. for (iy = 0; iy <= heightSegments; iy++) {
  18765. var verticesRow = [];
  18766. var v = iy / heightSegments; // special case for the poles
  18767. var uOffset = 0;
  18768. if (iy == 0 && thetaStart == 0) {
  18769. uOffset = 0.5 / widthSegments;
  18770. } else if (iy == heightSegments && thetaEnd == Math.PI) {
  18771. uOffset = -0.5 / widthSegments;
  18772. }
  18773. for (ix = 0; ix <= widthSegments; ix++) {
  18774. var u = ix / widthSegments; // vertex
  18775. vertex.x = -radius * Math.cos(phiStart + u * phiLength) * Math.sin(thetaStart + v * thetaLength);
  18776. vertex.y = radius * Math.cos(thetaStart + v * thetaLength);
  18777. vertex.z = radius * Math.sin(phiStart + u * phiLength) * Math.sin(thetaStart + v * thetaLength);
  18778. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  18779. normal.copy(vertex).normalize();
  18780. normals.push(normal.x, normal.y, normal.z); // uv
  18781. uvs.push(u + uOffset, 1 - v);
  18782. verticesRow.push(index++);
  18783. }
  18784. grid.push(verticesRow);
  18785. } // indices
  18786. for (iy = 0; iy < heightSegments; iy++) {
  18787. for (ix = 0; ix < widthSegments; ix++) {
  18788. var a = grid[iy][ix + 1];
  18789. var b = grid[iy][ix];
  18790. var c = grid[iy + 1][ix];
  18791. var d = grid[iy + 1][ix + 1];
  18792. if (iy !== 0 || thetaStart > 0) indices.push(a, b, d);
  18793. if (iy !== heightSegments - 1 || thetaEnd < Math.PI) indices.push(b, c, d);
  18794. }
  18795. } // build geometry
  18796. this.setIndex(indices);
  18797. this.addAttribute('position', new Float32BufferAttribute(vertices, 3));
  18798. this.addAttribute('normal', new Float32BufferAttribute(normals, 3));
  18799. this.addAttribute('uv', new Float32BufferAttribute(uvs, 2));
  18800. }
  18801. SphereBufferGeometry.prototype = Object.create(BufferGeometry.prototype);
  18802. SphereBufferGeometry.prototype.constructor = SphereBufferGeometry;
  18803. /**
  18804. * @author Kaleb Murphy
  18805. * @author Mugen87 / https://github.com/Mugen87
  18806. */
  18807. // RingGeometry
  18808. function RingGeometry(innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength) {
  18809. Geometry.call(this);
  18810. this.type = 'RingGeometry';
  18811. this.parameters = {
  18812. innerRadius: innerRadius,
  18813. outerRadius: outerRadius,
  18814. thetaSegments: thetaSegments,
  18815. phiSegments: phiSegments,
  18816. thetaStart: thetaStart,
  18817. thetaLength: thetaLength
  18818. };
  18819. this.fromBufferGeometry(new RingBufferGeometry(innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength));
  18820. this.mergeVertices();
  18821. }
  18822. RingGeometry.prototype = Object.create(Geometry.prototype);
  18823. RingGeometry.prototype.constructor = RingGeometry; // RingBufferGeometry
  18824. function RingBufferGeometry(innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength) {
  18825. BufferGeometry.call(this);
  18826. this.type = 'RingBufferGeometry';
  18827. this.parameters = {
  18828. innerRadius: innerRadius,
  18829. outerRadius: outerRadius,
  18830. thetaSegments: thetaSegments,
  18831. phiSegments: phiSegments,
  18832. thetaStart: thetaStart,
  18833. thetaLength: thetaLength
  18834. };
  18835. innerRadius = innerRadius || 0.5;
  18836. outerRadius = outerRadius || 1;
  18837. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  18838. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  18839. thetaSegments = thetaSegments !== undefined ? Math.max(3, thetaSegments) : 8;
  18840. phiSegments = phiSegments !== undefined ? Math.max(1, phiSegments) : 1; // buffers
  18841. var indices = [];
  18842. var vertices = [];
  18843. var normals = [];
  18844. var uvs = []; // some helper variables
  18845. var segment;
  18846. var radius = innerRadius;
  18847. var radiusStep = (outerRadius - innerRadius) / phiSegments;
  18848. var vertex = new Vector3();
  18849. var uv = new Vector2();
  18850. var j, i; // generate vertices, normals and uvs
  18851. for (j = 0; j <= phiSegments; j++) {
  18852. for (i = 0; i <= thetaSegments; i++) {
  18853. // values are generate from the inside of the ring to the outside
  18854. segment = thetaStart + i / thetaSegments * thetaLength; // vertex
  18855. vertex.x = radius * Math.cos(segment);
  18856. vertex.y = radius * Math.sin(segment);
  18857. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  18858. normals.push(0, 0, 1); // uv
  18859. uv.x = (vertex.x / outerRadius + 1) / 2;
  18860. uv.y = (vertex.y / outerRadius + 1) / 2;
  18861. uvs.push(uv.x, uv.y);
  18862. } // increase the radius for next row of vertices
  18863. radius += radiusStep;
  18864. } // indices
  18865. for (j = 0; j < phiSegments; j++) {
  18866. var thetaSegmentLevel = j * (thetaSegments + 1);
  18867. for (i = 0; i < thetaSegments; i++) {
  18868. segment = i + thetaSegmentLevel;
  18869. var a = segment;
  18870. var b = segment + thetaSegments + 1;
  18871. var c = segment + thetaSegments + 2;
  18872. var d = segment + 1; // faces
  18873. indices.push(a, b, d);
  18874. indices.push(b, c, d);
  18875. }
  18876. } // build geometry
  18877. this.setIndex(indices);
  18878. this.addAttribute('position', new Float32BufferAttribute(vertices, 3));
  18879. this.addAttribute('normal', new Float32BufferAttribute(normals, 3));
  18880. this.addAttribute('uv', new Float32BufferAttribute(uvs, 2));
  18881. }
  18882. RingBufferGeometry.prototype = Object.create(BufferGeometry.prototype);
  18883. RingBufferGeometry.prototype.constructor = RingBufferGeometry;
  18884. /**
  18885. * @author zz85 / https://github.com/zz85
  18886. * @author bhouston / http://clara.io
  18887. * @author Mugen87 / https://github.com/Mugen87
  18888. */
  18889. // LatheGeometry
  18890. function LatheGeometry(points, segments, phiStart, phiLength) {
  18891. Geometry.call(this);
  18892. this.type = 'LatheGeometry';
  18893. this.parameters = {
  18894. points: points,
  18895. segments: segments,
  18896. phiStart: phiStart,
  18897. phiLength: phiLength
  18898. };
  18899. this.fromBufferGeometry(new LatheBufferGeometry(points, segments, phiStart, phiLength));
  18900. this.mergeVertices();
  18901. }
  18902. LatheGeometry.prototype = Object.create(Geometry.prototype);
  18903. LatheGeometry.prototype.constructor = LatheGeometry; // LatheBufferGeometry
  18904. function LatheBufferGeometry(points, segments, phiStart, phiLength) {
  18905. BufferGeometry.call(this);
  18906. this.type = 'LatheBufferGeometry';
  18907. this.parameters = {
  18908. points: points,
  18909. segments: segments,
  18910. phiStart: phiStart,
  18911. phiLength: phiLength
  18912. };
  18913. segments = Math.floor(segments) || 12;
  18914. phiStart = phiStart || 0;
  18915. phiLength = phiLength || Math.PI * 2; // clamp phiLength so it's in range of [ 0, 2PI ]
  18916. phiLength = _Math.clamp(phiLength, 0, Math.PI * 2); // buffers
  18917. var indices = [];
  18918. var vertices = [];
  18919. var uvs = []; // helper variables
  18920. var base;
  18921. var inverseSegments = 1.0 / segments;
  18922. var vertex = new Vector3();
  18923. var uv = new Vector2();
  18924. var i, j; // generate vertices and uvs
  18925. for (i = 0; i <= segments; i++) {
  18926. var phi = phiStart + i * inverseSegments * phiLength;
  18927. var sin = Math.sin(phi);
  18928. var cos = Math.cos(phi);
  18929. for (j = 0; j <= points.length - 1; j++) {
  18930. // vertex
  18931. vertex.x = points[j].x * sin;
  18932. vertex.y = points[j].y;
  18933. vertex.z = points[j].x * cos;
  18934. vertices.push(vertex.x, vertex.y, vertex.z); // uv
  18935. uv.x = i / segments;
  18936. uv.y = j / (points.length - 1);
  18937. uvs.push(uv.x, uv.y);
  18938. }
  18939. } // indices
  18940. for (i = 0; i < segments; i++) {
  18941. for (j = 0; j < points.length - 1; j++) {
  18942. base = j + i * points.length;
  18943. var a = base;
  18944. var b = base + points.length;
  18945. var c = base + points.length + 1;
  18946. var d = base + 1; // faces
  18947. indices.push(a, b, d);
  18948. indices.push(b, c, d);
  18949. }
  18950. } // build geometry
  18951. this.setIndex(indices);
  18952. this.addAttribute('position', new Float32BufferAttribute(vertices, 3));
  18953. this.addAttribute('uv', new Float32BufferAttribute(uvs, 2)); // generate normals
  18954. this.computeVertexNormals(); // if the geometry is closed, we need to average the normals along the seam.
  18955. // because the corresponding vertices are identical (but still have different UVs).
  18956. if (phiLength === Math.PI * 2) {
  18957. var normals = this.attributes.normal.array;
  18958. var n1 = new Vector3();
  18959. var n2 = new Vector3();
  18960. var n = new Vector3(); // this is the buffer offset for the last line of vertices
  18961. base = segments * points.length * 3;
  18962. for (i = 0, j = 0; i < points.length; i++, j += 3) {
  18963. // select the normal of the vertex in the first line
  18964. n1.x = normals[j + 0];
  18965. n1.y = normals[j + 1];
  18966. n1.z = normals[j + 2]; // select the normal of the vertex in the last line
  18967. n2.x = normals[base + j + 0];
  18968. n2.y = normals[base + j + 1];
  18969. n2.z = normals[base + j + 2]; // average normals
  18970. n.addVectors(n1, n2).normalize(); // assign the new values to both normals
  18971. normals[j + 0] = normals[base + j + 0] = n.x;
  18972. normals[j + 1] = normals[base + j + 1] = n.y;
  18973. normals[j + 2] = normals[base + j + 2] = n.z;
  18974. }
  18975. }
  18976. }
  18977. LatheBufferGeometry.prototype = Object.create(BufferGeometry.prototype);
  18978. LatheBufferGeometry.prototype.constructor = LatheBufferGeometry;
  18979. /**
  18980. * @author jonobr1 / http://jonobr1.com
  18981. * @author Mugen87 / https://github.com/Mugen87
  18982. */
  18983. // ShapeGeometry
  18984. function ShapeGeometry(shapes, curveSegments) {
  18985. Geometry.call(this);
  18986. this.type = 'ShapeGeometry';
  18987. if (typeof curveSegments === 'object') {
  18988. console.warn('THREE.ShapeGeometry: Options parameter has been removed.');
  18989. curveSegments = curveSegments.curveSegments;
  18990. }
  18991. this.parameters = {
  18992. shapes: shapes,
  18993. curveSegments: curveSegments
  18994. };
  18995. this.fromBufferGeometry(new ShapeBufferGeometry(shapes, curveSegments));
  18996. this.mergeVertices();
  18997. }
  18998. ShapeGeometry.prototype = Object.create(Geometry.prototype);
  18999. ShapeGeometry.prototype.constructor = ShapeGeometry;
  19000. ShapeGeometry.prototype.toJSON = function () {
  19001. var data = Geometry.prototype.toJSON.call(this);
  19002. var shapes = this.parameters.shapes;
  19003. return toJSON$1(shapes, data);
  19004. }; // ShapeBufferGeometry
  19005. function ShapeBufferGeometry(shapes, curveSegments) {
  19006. BufferGeometry.call(this);
  19007. this.type = 'ShapeBufferGeometry';
  19008. this.parameters = {
  19009. shapes: shapes,
  19010. curveSegments: curveSegments
  19011. };
  19012. curveSegments = curveSegments || 12; // buffers
  19013. var indices = [];
  19014. var vertices = [];
  19015. var normals = [];
  19016. var uvs = []; // helper variables
  19017. var groupStart = 0;
  19018. var groupCount = 0; // allow single and array values for "shapes" parameter
  19019. if (Array.isArray(shapes) === false) {
  19020. addShape(shapes);
  19021. } else {
  19022. for (var i = 0; i < shapes.length; i++) {
  19023. addShape(shapes[i]);
  19024. this.addGroup(groupStart, groupCount, i); // enables MultiMaterial support
  19025. groupStart += groupCount;
  19026. groupCount = 0;
  19027. }
  19028. } // build geometry
  19029. this.setIndex(indices);
  19030. this.addAttribute('position', new Float32BufferAttribute(vertices, 3));
  19031. this.addAttribute('normal', new Float32BufferAttribute(normals, 3));
  19032. this.addAttribute('uv', new Float32BufferAttribute(uvs, 2)); // helper functions
  19033. function addShape(shape) {
  19034. var i, l, shapeHole;
  19035. var indexOffset = vertices.length / 3;
  19036. var points = shape.extractPoints(curveSegments);
  19037. var shapeVertices = points.shape;
  19038. var shapeHoles = points.holes; // check direction of vertices
  19039. if (ShapeUtils.isClockWise(shapeVertices) === false) {
  19040. shapeVertices = shapeVertices.reverse();
  19041. }
  19042. for (i = 0, l = shapeHoles.length; i < l; i++) {
  19043. shapeHole = shapeHoles[i];
  19044. if (ShapeUtils.isClockWise(shapeHole) === true) {
  19045. shapeHoles[i] = shapeHole.reverse();
  19046. }
  19047. }
  19048. var faces = ShapeUtils.triangulateShape(shapeVertices, shapeHoles); // join vertices of inner and outer paths to a single array
  19049. for (i = 0, l = shapeHoles.length; i < l; i++) {
  19050. shapeHole = shapeHoles[i];
  19051. shapeVertices = shapeVertices.concat(shapeHole);
  19052. } // vertices, normals, uvs
  19053. for (i = 0, l = shapeVertices.length; i < l; i++) {
  19054. var vertex = shapeVertices[i];
  19055. vertices.push(vertex.x, vertex.y, 0);
  19056. normals.push(0, 0, 1);
  19057. uvs.push(vertex.x, vertex.y); // world uvs
  19058. } // incides
  19059. for (i = 0, l = faces.length; i < l; i++) {
  19060. var face = faces[i];
  19061. var a = face[0] + indexOffset;
  19062. var b = face[1] + indexOffset;
  19063. var c = face[2] + indexOffset;
  19064. indices.push(a, b, c);
  19065. groupCount += 3;
  19066. }
  19067. }
  19068. }
  19069. ShapeBufferGeometry.prototype = Object.create(BufferGeometry.prototype);
  19070. ShapeBufferGeometry.prototype.constructor = ShapeBufferGeometry;
  19071. ShapeBufferGeometry.prototype.toJSON = function () {
  19072. var data = BufferGeometry.prototype.toJSON.call(this);
  19073. var shapes = this.parameters.shapes;
  19074. return toJSON$1(shapes, data);
  19075. }; //
  19076. function toJSON$1(shapes, data) {
  19077. data.shapes = [];
  19078. if (Array.isArray(shapes)) {
  19079. for (var i = 0, l = shapes.length; i < l; i++) {
  19080. var shape = shapes[i];
  19081. data.shapes.push(shape.uuid);
  19082. }
  19083. } else {
  19084. data.shapes.push(shapes.uuid);
  19085. }
  19086. return data;
  19087. }
  19088. /**
  19089. * @author WestLangley / http://github.com/WestLangley
  19090. * @author Mugen87 / https://github.com/Mugen87
  19091. */
  19092. function EdgesGeometry(geometry, thresholdAngle) {
  19093. BufferGeometry.call(this);
  19094. this.type = 'EdgesGeometry';
  19095. this.parameters = {
  19096. thresholdAngle: thresholdAngle
  19097. };
  19098. thresholdAngle = thresholdAngle !== undefined ? thresholdAngle : 1; // buffer
  19099. var vertices = []; // helper variables
  19100. var thresholdDot = Math.cos(_Math.DEG2RAD * thresholdAngle);
  19101. var edge = [0, 0],
  19102. edges = {},
  19103. edge1,
  19104. edge2;
  19105. var key,
  19106. keys = ['a', 'b', 'c']; // prepare source geometry
  19107. var geometry2;
  19108. if (geometry.isBufferGeometry) {
  19109. geometry2 = new Geometry();
  19110. geometry2.fromBufferGeometry(geometry);
  19111. } else {
  19112. geometry2 = geometry.clone();
  19113. }
  19114. geometry2.mergeVertices();
  19115. geometry2.computeFaceNormals();
  19116. var sourceVertices = geometry2.vertices;
  19117. var faces = geometry2.faces; // now create a data structure where each entry represents an edge with its adjoining faces
  19118. for (var i = 0, l = faces.length; i < l; i++) {
  19119. var face = faces[i];
  19120. for (var j = 0; j < 3; j++) {
  19121. edge1 = face[keys[j]];
  19122. edge2 = face[keys[(j + 1) % 3]];
  19123. edge[0] = Math.min(edge1, edge2);
  19124. edge[1] = Math.max(edge1, edge2);
  19125. key = edge[0] + ',' + edge[1];
  19126. if (edges[key] === undefined) {
  19127. edges[key] = {
  19128. index1: edge[0],
  19129. index2: edge[1],
  19130. face1: i,
  19131. face2: undefined
  19132. };
  19133. } else {
  19134. edges[key].face2 = i;
  19135. }
  19136. }
  19137. } // generate vertices
  19138. for (key in edges) {
  19139. 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.
  19140. if (e.face2 === undefined || faces[e.face1].normal.dot(faces[e.face2].normal) <= thresholdDot) {
  19141. var vertex = sourceVertices[e.index1];
  19142. vertices.push(vertex.x, vertex.y, vertex.z);
  19143. vertex = sourceVertices[e.index2];
  19144. vertices.push(vertex.x, vertex.y, vertex.z);
  19145. }
  19146. } // build geometry
  19147. this.addAttribute('position', new Float32BufferAttribute(vertices, 3));
  19148. }
  19149. EdgesGeometry.prototype = Object.create(BufferGeometry.prototype);
  19150. EdgesGeometry.prototype.constructor = EdgesGeometry;
  19151. /**
  19152. * @author mrdoob / http://mrdoob.com/
  19153. * @author Mugen87 / https://github.com/Mugen87
  19154. */
  19155. // CylinderGeometry
  19156. function CylinderGeometry(radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength) {
  19157. Geometry.call(this);
  19158. this.type = 'CylinderGeometry';
  19159. this.parameters = {
  19160. radiusTop: radiusTop,
  19161. radiusBottom: radiusBottom,
  19162. height: height,
  19163. radialSegments: radialSegments,
  19164. heightSegments: heightSegments,
  19165. openEnded: openEnded,
  19166. thetaStart: thetaStart,
  19167. thetaLength: thetaLength
  19168. };
  19169. this.fromBufferGeometry(new CylinderBufferGeometry(radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength));
  19170. this.mergeVertices();
  19171. }
  19172. CylinderGeometry.prototype = Object.create(Geometry.prototype);
  19173. CylinderGeometry.prototype.constructor = CylinderGeometry; // CylinderBufferGeometry
  19174. function CylinderBufferGeometry(radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength) {
  19175. BufferGeometry.call(this);
  19176. this.type = 'CylinderBufferGeometry';
  19177. this.parameters = {
  19178. radiusTop: radiusTop,
  19179. radiusBottom: radiusBottom,
  19180. height: height,
  19181. radialSegments: radialSegments,
  19182. heightSegments: heightSegments,
  19183. openEnded: openEnded,
  19184. thetaStart: thetaStart,
  19185. thetaLength: thetaLength
  19186. };
  19187. var scope = this;
  19188. radiusTop = radiusTop !== undefined ? radiusTop : 1;
  19189. radiusBottom = radiusBottom !== undefined ? radiusBottom : 1;
  19190. height = height || 1;
  19191. radialSegments = Math.floor(radialSegments) || 8;
  19192. heightSegments = Math.floor(heightSegments) || 1;
  19193. openEnded = openEnded !== undefined ? openEnded : false;
  19194. thetaStart = thetaStart !== undefined ? thetaStart : 0.0;
  19195. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2; // buffers
  19196. var indices = [];
  19197. var vertices = [];
  19198. var normals = [];
  19199. var uvs = []; // helper variables
  19200. var index = 0;
  19201. var indexArray = [];
  19202. var halfHeight = height / 2;
  19203. var groupStart = 0; // generate geometry
  19204. generateTorso();
  19205. if (openEnded === false) {
  19206. if (radiusTop > 0) generateCap(true);
  19207. if (radiusBottom > 0) generateCap(false);
  19208. } // build geometry
  19209. this.setIndex(indices);
  19210. this.addAttribute('position', new Float32BufferAttribute(vertices, 3));
  19211. this.addAttribute('normal', new Float32BufferAttribute(normals, 3));
  19212. this.addAttribute('uv', new Float32BufferAttribute(uvs, 2));
  19213. function generateTorso() {
  19214. var x, y;
  19215. var normal = new Vector3();
  19216. var vertex = new Vector3();
  19217. var groupCount = 0; // this will be used to calculate the normal
  19218. var slope = (radiusBottom - radiusTop) / height; // generate vertices, normals and uvs
  19219. for (y = 0; y <= heightSegments; y++) {
  19220. var indexRow = [];
  19221. var v = y / heightSegments; // calculate the radius of the current row
  19222. var radius = v * (radiusBottom - radiusTop) + radiusTop;
  19223. for (x = 0; x <= radialSegments; x++) {
  19224. var u = x / radialSegments;
  19225. var theta = u * thetaLength + thetaStart;
  19226. var sinTheta = Math.sin(theta);
  19227. var cosTheta = Math.cos(theta); // vertex
  19228. vertex.x = radius * sinTheta;
  19229. vertex.y = -v * height + halfHeight;
  19230. vertex.z = radius * cosTheta;
  19231. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  19232. normal.set(sinTheta, slope, cosTheta).normalize();
  19233. normals.push(normal.x, normal.y, normal.z); // uv
  19234. uvs.push(u, 1 - v); // save index of vertex in respective row
  19235. indexRow.push(index++);
  19236. } // now save vertices of the row in our index array
  19237. indexArray.push(indexRow);
  19238. } // generate indices
  19239. for (x = 0; x < radialSegments; x++) {
  19240. for (y = 0; y < heightSegments; y++) {
  19241. // we use the index array to access the correct indices
  19242. var a = indexArray[y][x];
  19243. var b = indexArray[y + 1][x];
  19244. var c = indexArray[y + 1][x + 1];
  19245. var d = indexArray[y][x + 1]; // faces
  19246. indices.push(a, b, d);
  19247. indices.push(b, c, d); // update group counter
  19248. groupCount += 6;
  19249. }
  19250. } // add a group to the geometry. this will ensure multi material support
  19251. scope.addGroup(groupStart, groupCount, 0); // calculate new start value for groups
  19252. groupStart += groupCount;
  19253. }
  19254. function generateCap(top) {
  19255. var x, centerIndexStart, centerIndexEnd;
  19256. var uv = new Vector2();
  19257. var vertex = new Vector3();
  19258. var groupCount = 0;
  19259. var radius = top === true ? radiusTop : radiusBottom;
  19260. var sign = top === true ? 1 : -1; // save the index of the first center vertex
  19261. centerIndexStart = index; // first we generate the center vertex data of the cap.
  19262. // because the geometry needs one set of uvs per face,
  19263. // we must generate a center vertex per face/segment
  19264. for (x = 1; x <= radialSegments; x++) {
  19265. // vertex
  19266. vertices.push(0, halfHeight * sign, 0); // normal
  19267. normals.push(0, sign, 0); // uv
  19268. uvs.push(0.5, 0.5); // increase index
  19269. index++;
  19270. } // save the index of the last center vertex
  19271. centerIndexEnd = index; // now we generate the surrounding vertices, normals and uvs
  19272. for (x = 0; x <= radialSegments; x++) {
  19273. var u = x / radialSegments;
  19274. var theta = u * thetaLength + thetaStart;
  19275. var cosTheta = Math.cos(theta);
  19276. var sinTheta = Math.sin(theta); // vertex
  19277. vertex.x = radius * sinTheta;
  19278. vertex.y = halfHeight * sign;
  19279. vertex.z = radius * cosTheta;
  19280. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  19281. normals.push(0, sign, 0); // uv
  19282. uv.x = cosTheta * 0.5 + 0.5;
  19283. uv.y = sinTheta * 0.5 * sign + 0.5;
  19284. uvs.push(uv.x, uv.y); // increase index
  19285. index++;
  19286. } // generate indices
  19287. for (x = 0; x < radialSegments; x++) {
  19288. var c = centerIndexStart + x;
  19289. var i = centerIndexEnd + x;
  19290. if (top === true) {
  19291. // face top
  19292. indices.push(i, i + 1, c);
  19293. } else {
  19294. // face bottom
  19295. indices.push(i + 1, i, c);
  19296. }
  19297. groupCount += 3;
  19298. } // add a group to the geometry. this will ensure multi material support
  19299. scope.addGroup(groupStart, groupCount, top === true ? 1 : 2); // calculate new start value for groups
  19300. groupStart += groupCount;
  19301. }
  19302. }
  19303. CylinderBufferGeometry.prototype = Object.create(BufferGeometry.prototype);
  19304. CylinderBufferGeometry.prototype.constructor = CylinderBufferGeometry;
  19305. /**
  19306. * @author abelnation / http://github.com/abelnation
  19307. */
  19308. // ConeGeometry
  19309. function ConeGeometry(radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength) {
  19310. CylinderGeometry.call(this, 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength);
  19311. this.type = 'ConeGeometry';
  19312. this.parameters = {
  19313. radius: radius,
  19314. height: height,
  19315. radialSegments: radialSegments,
  19316. heightSegments: heightSegments,
  19317. openEnded: openEnded,
  19318. thetaStart: thetaStart,
  19319. thetaLength: thetaLength
  19320. };
  19321. }
  19322. ConeGeometry.prototype = Object.create(CylinderGeometry.prototype);
  19323. ConeGeometry.prototype.constructor = ConeGeometry; // ConeBufferGeometry
  19324. function ConeBufferGeometry(radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength) {
  19325. CylinderBufferGeometry.call(this, 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength);
  19326. this.type = 'ConeBufferGeometry';
  19327. this.parameters = {
  19328. radius: radius,
  19329. height: height,
  19330. radialSegments: radialSegments,
  19331. heightSegments: heightSegments,
  19332. openEnded: openEnded,
  19333. thetaStart: thetaStart,
  19334. thetaLength: thetaLength
  19335. };
  19336. }
  19337. ConeBufferGeometry.prototype = Object.create(CylinderBufferGeometry.prototype);
  19338. ConeBufferGeometry.prototype.constructor = ConeBufferGeometry;
  19339. /**
  19340. * @author benaadams / https://twitter.com/ben_a_adams
  19341. * @author Mugen87 / https://github.com/Mugen87
  19342. * @author hughes
  19343. */
  19344. // CircleGeometry
  19345. function CircleGeometry(radius, segments, thetaStart, thetaLength) {
  19346. Geometry.call(this);
  19347. this.type = 'CircleGeometry';
  19348. this.parameters = {
  19349. radius: radius,
  19350. segments: segments,
  19351. thetaStart: thetaStart,
  19352. thetaLength: thetaLength
  19353. };
  19354. this.fromBufferGeometry(new CircleBufferGeometry(radius, segments, thetaStart, thetaLength));
  19355. this.mergeVertices();
  19356. }
  19357. CircleGeometry.prototype = Object.create(Geometry.prototype);
  19358. CircleGeometry.prototype.constructor = CircleGeometry; // CircleBufferGeometry
  19359. function CircleBufferGeometry(radius, segments, thetaStart, thetaLength) {
  19360. BufferGeometry.call(this);
  19361. this.type = 'CircleBufferGeometry';
  19362. this.parameters = {
  19363. radius: radius,
  19364. segments: segments,
  19365. thetaStart: thetaStart,
  19366. thetaLength: thetaLength
  19367. };
  19368. radius = radius || 1;
  19369. segments = segments !== undefined ? Math.max(3, segments) : 8;
  19370. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  19371. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2; // buffers
  19372. var indices = [];
  19373. var vertices = [];
  19374. var normals = [];
  19375. var uvs = []; // helper variables
  19376. var i, s;
  19377. var vertex = new Vector3();
  19378. var uv = new Vector2(); // center point
  19379. vertices.push(0, 0, 0);
  19380. normals.push(0, 0, 1);
  19381. uvs.push(0.5, 0.5);
  19382. for (s = 0, i = 3; s <= segments; s++, i += 3) {
  19383. var segment = thetaStart + s / segments * thetaLength; // vertex
  19384. vertex.x = radius * Math.cos(segment);
  19385. vertex.y = radius * Math.sin(segment);
  19386. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  19387. normals.push(0, 0, 1); // uvs
  19388. uv.x = (vertices[i] / radius + 1) / 2;
  19389. uv.y = (vertices[i + 1] / radius + 1) / 2;
  19390. uvs.push(uv.x, uv.y);
  19391. } // indices
  19392. for (i = 1; i <= segments; i++) {
  19393. indices.push(i, i + 1, 0);
  19394. } // build geometry
  19395. this.setIndex(indices);
  19396. this.addAttribute('position', new Float32BufferAttribute(vertices, 3));
  19397. this.addAttribute('normal', new Float32BufferAttribute(normals, 3));
  19398. this.addAttribute('uv', new Float32BufferAttribute(uvs, 2));
  19399. }
  19400. CircleBufferGeometry.prototype = Object.create(BufferGeometry.prototype);
  19401. CircleBufferGeometry.prototype.constructor = CircleBufferGeometry;
  19402. var Geometries =
  19403. /*#__PURE__*/
  19404. Object.freeze({
  19405. WireframeGeometry: WireframeGeometry,
  19406. ParametricGeometry: ParametricGeometry,
  19407. ParametricBufferGeometry: ParametricBufferGeometry,
  19408. TetrahedronGeometry: TetrahedronGeometry,
  19409. TetrahedronBufferGeometry: TetrahedronBufferGeometry,
  19410. OctahedronGeometry: OctahedronGeometry,
  19411. OctahedronBufferGeometry: OctahedronBufferGeometry,
  19412. IcosahedronGeometry: IcosahedronGeometry,
  19413. IcosahedronBufferGeometry: IcosahedronBufferGeometry,
  19414. DodecahedronGeometry: DodecahedronGeometry,
  19415. DodecahedronBufferGeometry: DodecahedronBufferGeometry,
  19416. PolyhedronGeometry: PolyhedronGeometry,
  19417. PolyhedronBufferGeometry: PolyhedronBufferGeometry,
  19418. TubeGeometry: TubeGeometry,
  19419. TubeBufferGeometry: TubeBufferGeometry,
  19420. TorusKnotGeometry: TorusKnotGeometry,
  19421. TorusKnotBufferGeometry: TorusKnotBufferGeometry,
  19422. TorusGeometry: TorusGeometry,
  19423. TorusBufferGeometry: TorusBufferGeometry,
  19424. TextGeometry: TextGeometry,
  19425. TextBufferGeometry: TextBufferGeometry,
  19426. SphereGeometry: SphereGeometry,
  19427. SphereBufferGeometry: SphereBufferGeometry,
  19428. RingGeometry: RingGeometry,
  19429. RingBufferGeometry: RingBufferGeometry,
  19430. PlaneGeometry: PlaneGeometry,
  19431. PlaneBufferGeometry: PlaneBufferGeometry,
  19432. LatheGeometry: LatheGeometry,
  19433. LatheBufferGeometry: LatheBufferGeometry,
  19434. ShapeGeometry: ShapeGeometry,
  19435. ShapeBufferGeometry: ShapeBufferGeometry,
  19436. ExtrudeGeometry: ExtrudeGeometry,
  19437. ExtrudeBufferGeometry: ExtrudeBufferGeometry,
  19438. EdgesGeometry: EdgesGeometry,
  19439. ConeGeometry: ConeGeometry,
  19440. ConeBufferGeometry: ConeBufferGeometry,
  19441. CylinderGeometry: CylinderGeometry,
  19442. CylinderBufferGeometry: CylinderBufferGeometry,
  19443. CircleGeometry: CircleGeometry,
  19444. CircleBufferGeometry: CircleBufferGeometry,
  19445. BoxGeometry: BoxGeometry,
  19446. BoxBufferGeometry: BoxBufferGeometry
  19447. });
  19448. /**
  19449. * @author mrdoob / http://mrdoob.com/
  19450. *
  19451. * parameters = {
  19452. * color: <THREE.Color>
  19453. * }
  19454. */
  19455. function ShadowMaterial(parameters) {
  19456. Material.call(this);
  19457. this.type = 'ShadowMaterial';
  19458. this.color = new Color(0x000000);
  19459. this.transparent = true;
  19460. this.setValues(parameters);
  19461. }
  19462. ShadowMaterial.prototype = Object.create(Material.prototype);
  19463. ShadowMaterial.prototype.constructor = ShadowMaterial;
  19464. ShadowMaterial.prototype.isShadowMaterial = true;
  19465. ShadowMaterial.prototype.copy = function (source) {
  19466. Material.prototype.copy.call(this, source);
  19467. this.color.copy(source.color);
  19468. return this;
  19469. };
  19470. /**
  19471. * @author mrdoob / http://mrdoob.com/
  19472. */
  19473. function RawShaderMaterial(parameters) {
  19474. ShaderMaterial.call(this, parameters);
  19475. this.type = 'RawShaderMaterial';
  19476. }
  19477. RawShaderMaterial.prototype = Object.create(ShaderMaterial.prototype);
  19478. RawShaderMaterial.prototype.constructor = RawShaderMaterial;
  19479. RawShaderMaterial.prototype.isRawShaderMaterial = true;
  19480. /**
  19481. * @author WestLangley / http://github.com/WestLangley
  19482. *
  19483. * parameters = {
  19484. * color: <hex>,
  19485. * roughness: <float>,
  19486. * metalness: <float>,
  19487. * opacity: <float>,
  19488. *
  19489. * map: new THREE.Texture( <Image> ),
  19490. *
  19491. * lightMap: new THREE.Texture( <Image> ),
  19492. * lightMapIntensity: <float>
  19493. *
  19494. * aoMap: new THREE.Texture( <Image> ),
  19495. * aoMapIntensity: <float>
  19496. *
  19497. * emissive: <hex>,
  19498. * emissiveIntensity: <float>
  19499. * emissiveMap: new THREE.Texture( <Image> ),
  19500. *
  19501. * bumpMap: new THREE.Texture( <Image> ),
  19502. * bumpScale: <float>,
  19503. *
  19504. * normalMap: new THREE.Texture( <Image> ),
  19505. * normalMapType: THREE.TangentSpaceNormalMap,
  19506. * normalScale: <Vector2>,
  19507. *
  19508. * displacementMap: new THREE.Texture( <Image> ),
  19509. * displacementScale: <float>,
  19510. * displacementBias: <float>,
  19511. *
  19512. * roughnessMap: new THREE.Texture( <Image> ),
  19513. *
  19514. * metalnessMap: new THREE.Texture( <Image> ),
  19515. *
  19516. * alphaMap: new THREE.Texture( <Image> ),
  19517. *
  19518. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  19519. * envMapIntensity: <float>
  19520. *
  19521. * refractionRatio: <float>,
  19522. *
  19523. * wireframe: <boolean>,
  19524. * wireframeLinewidth: <float>,
  19525. *
  19526. * skinning: <bool>,
  19527. * morphTargets: <bool>,
  19528. * morphNormals: <bool>
  19529. * }
  19530. */
  19531. function MeshStandardMaterial(parameters) {
  19532. Material.call(this);
  19533. this.defines = {
  19534. 'STANDARD': ''
  19535. };
  19536. this.type = 'MeshStandardMaterial';
  19537. this.color = new Color(0xffffff); // diffuse
  19538. this.roughness = 0.5;
  19539. this.metalness = 0.5;
  19540. this.map = null;
  19541. this.lightMap = null;
  19542. this.lightMapIntensity = 1.0;
  19543. this.aoMap = null;
  19544. this.aoMapIntensity = 1.0;
  19545. this.emissive = new Color(0x000000);
  19546. this.emissiveIntensity = 1.0;
  19547. this.emissiveMap = null;
  19548. this.bumpMap = null;
  19549. this.bumpScale = 1;
  19550. this.normalMap = null;
  19551. this.normalMapType = TangentSpaceNormalMap;
  19552. this.normalScale = new Vector2(1, 1);
  19553. this.displacementMap = null;
  19554. this.displacementScale = 1;
  19555. this.displacementBias = 0;
  19556. this.roughnessMap = null;
  19557. this.metalnessMap = null;
  19558. this.alphaMap = null;
  19559. this.envMap = null;
  19560. this.envMapIntensity = 1.0;
  19561. this.refractionRatio = 0.98;
  19562. this.wireframe = false;
  19563. this.wireframeLinewidth = 1;
  19564. this.wireframeLinecap = 'round';
  19565. this.wireframeLinejoin = 'round';
  19566. this.skinning = false;
  19567. this.morphTargets = false;
  19568. this.morphNormals = false;
  19569. this.setValues(parameters);
  19570. }
  19571. MeshStandardMaterial.prototype = Object.create(Material.prototype);
  19572. MeshStandardMaterial.prototype.constructor = MeshStandardMaterial;
  19573. MeshStandardMaterial.prototype.isMeshStandardMaterial = true;
  19574. MeshStandardMaterial.prototype.copy = function (source) {
  19575. Material.prototype.copy.call(this, source);
  19576. this.defines = {
  19577. 'STANDARD': ''
  19578. };
  19579. this.color.copy(source.color);
  19580. this.roughness = source.roughness;
  19581. this.metalness = source.metalness;
  19582. this.map = source.map;
  19583. this.lightMap = source.lightMap;
  19584. this.lightMapIntensity = source.lightMapIntensity;
  19585. this.aoMap = source.aoMap;
  19586. this.aoMapIntensity = source.aoMapIntensity;
  19587. this.emissive.copy(source.emissive);
  19588. this.emissiveMap = source.emissiveMap;
  19589. this.emissiveIntensity = source.emissiveIntensity;
  19590. this.bumpMap = source.bumpMap;
  19591. this.bumpScale = source.bumpScale;
  19592. this.normalMap = source.normalMap;
  19593. this.normalMapType = source.normalMapType;
  19594. this.normalScale.copy(source.normalScale);
  19595. this.displacementMap = source.displacementMap;
  19596. this.displacementScale = source.displacementScale;
  19597. this.displacementBias = source.displacementBias;
  19598. this.roughnessMap = source.roughnessMap;
  19599. this.metalnessMap = source.metalnessMap;
  19600. this.alphaMap = source.alphaMap;
  19601. this.envMap = source.envMap;
  19602. this.envMapIntensity = source.envMapIntensity;
  19603. this.refractionRatio = source.refractionRatio;
  19604. this.wireframe = source.wireframe;
  19605. this.wireframeLinewidth = source.wireframeLinewidth;
  19606. this.wireframeLinecap = source.wireframeLinecap;
  19607. this.wireframeLinejoin = source.wireframeLinejoin;
  19608. this.skinning = source.skinning;
  19609. this.morphTargets = source.morphTargets;
  19610. this.morphNormals = source.morphNormals;
  19611. return this;
  19612. };
  19613. /**
  19614. * @author WestLangley / http://github.com/WestLangley
  19615. *
  19616. * parameters = {
  19617. * reflectivity: <float>
  19618. * clearcoat: <float>
  19619. * clearcoatRoughness: <float>
  19620. *
  19621. * sheen: <Color>
  19622. *
  19623. * clearcoatNormalScale: <Vector2>,
  19624. * clearcoatNormalMap: new THREE.Texture( <Image> ),
  19625. * }
  19626. */
  19627. function MeshPhysicalMaterial(parameters) {
  19628. MeshStandardMaterial.call(this);
  19629. this.defines = {
  19630. 'STANDARD': '',
  19631. 'PHYSICAL': ''
  19632. };
  19633. this.type = 'MeshPhysicalMaterial';
  19634. this.reflectivity = 0.5; // maps to F0 = 0.04
  19635. this.clearcoat = 0.0;
  19636. this.clearcoatRoughness = 0.0;
  19637. this.sheen = null; // null will disable sheen bsdf
  19638. this.clearcoatNormalScale = new Vector2(1, 1);
  19639. this.clearcoatNormalMap = null;
  19640. this.transparency = 0.0;
  19641. this.setValues(parameters);
  19642. }
  19643. MeshPhysicalMaterial.prototype = Object.create(MeshStandardMaterial.prototype);
  19644. MeshPhysicalMaterial.prototype.constructor = MeshPhysicalMaterial;
  19645. MeshPhysicalMaterial.prototype.isMeshPhysicalMaterial = true;
  19646. MeshPhysicalMaterial.prototype.copy = function (source) {
  19647. MeshStandardMaterial.prototype.copy.call(this, source);
  19648. this.defines = {
  19649. 'STANDARD': '',
  19650. 'PHYSICAL': ''
  19651. };
  19652. this.reflectivity = source.reflectivity;
  19653. this.clearcoat = source.clearcoat;
  19654. this.clearcoatRoughness = source.clearcoatRoughness;
  19655. if (source.sheen) this.sheen = (this.sheen || new Color()).copy(source.sheen);else this.sheen = null;
  19656. this.clearcoatNormalMap = source.clearcoatNormalMap;
  19657. this.clearcoatNormalScale.copy(source.clearcoatNormalScale);
  19658. this.transparency = source.transparency;
  19659. return this;
  19660. };
  19661. /**
  19662. * @author mrdoob / http://mrdoob.com/
  19663. * @author alteredq / http://alteredqualia.com/
  19664. *
  19665. * parameters = {
  19666. * color: <hex>,
  19667. * specular: <hex>,
  19668. * shininess: <float>,
  19669. * opacity: <float>,
  19670. *
  19671. * map: new THREE.Texture( <Image> ),
  19672. *
  19673. * lightMap: new THREE.Texture( <Image> ),
  19674. * lightMapIntensity: <float>
  19675. *
  19676. * aoMap: new THREE.Texture( <Image> ),
  19677. * aoMapIntensity: <float>
  19678. *
  19679. * emissive: <hex>,
  19680. * emissiveIntensity: <float>
  19681. * emissiveMap: new THREE.Texture( <Image> ),
  19682. *
  19683. * bumpMap: new THREE.Texture( <Image> ),
  19684. * bumpScale: <float>,
  19685. *
  19686. * normalMap: new THREE.Texture( <Image> ),
  19687. * normalMapType: THREE.TangentSpaceNormalMap,
  19688. * normalScale: <Vector2>,
  19689. *
  19690. * displacementMap: new THREE.Texture( <Image> ),
  19691. * displacementScale: <float>,
  19692. * displacementBias: <float>,
  19693. *
  19694. * specularMap: new THREE.Texture( <Image> ),
  19695. *
  19696. * alphaMap: new THREE.Texture( <Image> ),
  19697. *
  19698. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  19699. * combine: THREE.Multiply,
  19700. * reflectivity: <float>,
  19701. * refractionRatio: <float>,
  19702. *
  19703. * wireframe: <boolean>,
  19704. * wireframeLinewidth: <float>,
  19705. *
  19706. * skinning: <bool>,
  19707. * morphTargets: <bool>,
  19708. * morphNormals: <bool>
  19709. * }
  19710. */
  19711. function MeshPhongMaterial(parameters) {
  19712. Material.call(this);
  19713. this.type = 'MeshPhongMaterial';
  19714. this.color = new Color(0xffffff); // diffuse
  19715. this.specular = new Color(0x111111);
  19716. this.shininess = 30;
  19717. this.map = null;
  19718. this.lightMap = null;
  19719. this.lightMapIntensity = 1.0;
  19720. this.aoMap = null;
  19721. this.aoMapIntensity = 1.0;
  19722. this.emissive = new Color(0x000000);
  19723. this.emissiveIntensity = 1.0;
  19724. this.emissiveMap = null;
  19725. this.bumpMap = null;
  19726. this.bumpScale = 1;
  19727. this.normalMap = null;
  19728. this.normalMapType = TangentSpaceNormalMap;
  19729. this.normalScale = new Vector2(1, 1);
  19730. this.displacementMap = null;
  19731. this.displacementScale = 1;
  19732. this.displacementBias = 0;
  19733. this.specularMap = null;
  19734. this.alphaMap = null;
  19735. this.envMap = null;
  19736. this.combine = MultiplyOperation;
  19737. this.reflectivity = 1;
  19738. this.refractionRatio = 0.98;
  19739. this.wireframe = false;
  19740. this.wireframeLinewidth = 1;
  19741. this.wireframeLinecap = 'round';
  19742. this.wireframeLinejoin = 'round';
  19743. this.skinning = false;
  19744. this.morphTargets = false;
  19745. this.morphNormals = false;
  19746. this.setValues(parameters);
  19747. }
  19748. MeshPhongMaterial.prototype = Object.create(Material.prototype);
  19749. MeshPhongMaterial.prototype.constructor = MeshPhongMaterial;
  19750. MeshPhongMaterial.prototype.isMeshPhongMaterial = true;
  19751. MeshPhongMaterial.prototype.copy = function (source) {
  19752. Material.prototype.copy.call(this, source);
  19753. this.color.copy(source.color);
  19754. this.specular.copy(source.specular);
  19755. this.shininess = source.shininess;
  19756. this.map = source.map;
  19757. this.lightMap = source.lightMap;
  19758. this.lightMapIntensity = source.lightMapIntensity;
  19759. this.aoMap = source.aoMap;
  19760. this.aoMapIntensity = source.aoMapIntensity;
  19761. this.emissive.copy(source.emissive);
  19762. this.emissiveMap = source.emissiveMap;
  19763. this.emissiveIntensity = source.emissiveIntensity;
  19764. this.bumpMap = source.bumpMap;
  19765. this.bumpScale = source.bumpScale;
  19766. this.normalMap = source.normalMap;
  19767. this.normalMapType = source.normalMapType;
  19768. this.normalScale.copy(source.normalScale);
  19769. this.displacementMap = source.displacementMap;
  19770. this.displacementScale = source.displacementScale;
  19771. this.displacementBias = source.displacementBias;
  19772. this.specularMap = source.specularMap;
  19773. this.alphaMap = source.alphaMap;
  19774. this.envMap = source.envMap;
  19775. this.combine = source.combine;
  19776. this.reflectivity = source.reflectivity;
  19777. this.refractionRatio = source.refractionRatio;
  19778. this.wireframe = source.wireframe;
  19779. this.wireframeLinewidth = source.wireframeLinewidth;
  19780. this.wireframeLinecap = source.wireframeLinecap;
  19781. this.wireframeLinejoin = source.wireframeLinejoin;
  19782. this.skinning = source.skinning;
  19783. this.morphTargets = source.morphTargets;
  19784. this.morphNormals = source.morphNormals;
  19785. return this;
  19786. };
  19787. /**
  19788. * @author takahirox / http://github.com/takahirox
  19789. *
  19790. * parameters = {
  19791. * gradientMap: new THREE.Texture( <Image> )
  19792. * }
  19793. */
  19794. function MeshToonMaterial(parameters) {
  19795. MeshPhongMaterial.call(this);
  19796. this.defines = {
  19797. 'TOON': ''
  19798. };
  19799. this.type = 'MeshToonMaterial';
  19800. this.gradientMap = null;
  19801. this.setValues(parameters);
  19802. }
  19803. MeshToonMaterial.prototype = Object.create(MeshPhongMaterial.prototype);
  19804. MeshToonMaterial.prototype.constructor = MeshToonMaterial;
  19805. MeshToonMaterial.prototype.isMeshToonMaterial = true;
  19806. MeshToonMaterial.prototype.copy = function (source) {
  19807. MeshPhongMaterial.prototype.copy.call(this, source);
  19808. this.gradientMap = source.gradientMap;
  19809. return this;
  19810. };
  19811. /**
  19812. * @author mrdoob / http://mrdoob.com/
  19813. * @author WestLangley / http://github.com/WestLangley
  19814. *
  19815. * parameters = {
  19816. * opacity: <float>,
  19817. *
  19818. * bumpMap: new THREE.Texture( <Image> ),
  19819. * bumpScale: <float>,
  19820. *
  19821. * normalMap: new THREE.Texture( <Image> ),
  19822. * normalMapType: THREE.TangentSpaceNormalMap,
  19823. * normalScale: <Vector2>,
  19824. *
  19825. * displacementMap: new THREE.Texture( <Image> ),
  19826. * displacementScale: <float>,
  19827. * displacementBias: <float>,
  19828. *
  19829. * wireframe: <boolean>,
  19830. * wireframeLinewidth: <float>
  19831. *
  19832. * skinning: <bool>,
  19833. * morphTargets: <bool>,
  19834. * morphNormals: <bool>
  19835. * }
  19836. */
  19837. function MeshNormalMaterial(parameters) {
  19838. Material.call(this);
  19839. this.type = 'MeshNormalMaterial';
  19840. this.bumpMap = null;
  19841. this.bumpScale = 1;
  19842. this.normalMap = null;
  19843. this.normalMapType = TangentSpaceNormalMap;
  19844. this.normalScale = new Vector2(1, 1);
  19845. this.displacementMap = null;
  19846. this.displacementScale = 1;
  19847. this.displacementBias = 0;
  19848. this.wireframe = false;
  19849. this.wireframeLinewidth = 1;
  19850. this.fog = false;
  19851. this.skinning = false;
  19852. this.morphTargets = false;
  19853. this.morphNormals = false;
  19854. this.setValues(parameters);
  19855. }
  19856. MeshNormalMaterial.prototype = Object.create(Material.prototype);
  19857. MeshNormalMaterial.prototype.constructor = MeshNormalMaterial;
  19858. MeshNormalMaterial.prototype.isMeshNormalMaterial = true;
  19859. MeshNormalMaterial.prototype.copy = function (source) {
  19860. Material.prototype.copy.call(this, source);
  19861. this.bumpMap = source.bumpMap;
  19862. this.bumpScale = source.bumpScale;
  19863. this.normalMap = source.normalMap;
  19864. this.normalMapType = source.normalMapType;
  19865. this.normalScale.copy(source.normalScale);
  19866. this.displacementMap = source.displacementMap;
  19867. this.displacementScale = source.displacementScale;
  19868. this.displacementBias = source.displacementBias;
  19869. this.wireframe = source.wireframe;
  19870. this.wireframeLinewidth = source.wireframeLinewidth;
  19871. this.skinning = source.skinning;
  19872. this.morphTargets = source.morphTargets;
  19873. this.morphNormals = source.morphNormals;
  19874. return this;
  19875. };
  19876. /**
  19877. * @author mrdoob / http://mrdoob.com/
  19878. * @author alteredq / http://alteredqualia.com/
  19879. *
  19880. * parameters = {
  19881. * color: <hex>,
  19882. * opacity: <float>,
  19883. *
  19884. * map: new THREE.Texture( <Image> ),
  19885. *
  19886. * lightMap: new THREE.Texture( <Image> ),
  19887. * lightMapIntensity: <float>
  19888. *
  19889. * aoMap: new THREE.Texture( <Image> ),
  19890. * aoMapIntensity: <float>
  19891. *
  19892. * emissive: <hex>,
  19893. * emissiveIntensity: <float>
  19894. * emissiveMap: new THREE.Texture( <Image> ),
  19895. *
  19896. * specularMap: new THREE.Texture( <Image> ),
  19897. *
  19898. * alphaMap: new THREE.Texture( <Image> ),
  19899. *
  19900. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  19901. * combine: THREE.Multiply,
  19902. * reflectivity: <float>,
  19903. * refractionRatio: <float>,
  19904. *
  19905. * wireframe: <boolean>,
  19906. * wireframeLinewidth: <float>,
  19907. *
  19908. * skinning: <bool>,
  19909. * morphTargets: <bool>,
  19910. * morphNormals: <bool>
  19911. * }
  19912. */
  19913. function MeshLambertMaterial(parameters) {
  19914. Material.call(this);
  19915. this.type = 'MeshLambertMaterial';
  19916. this.color = new Color(0xffffff); // diffuse
  19917. this.map = null;
  19918. this.lightMap = null;
  19919. this.lightMapIntensity = 1.0;
  19920. this.aoMap = null;
  19921. this.aoMapIntensity = 1.0;
  19922. this.emissive = new Color(0x000000);
  19923. this.emissiveIntensity = 1.0;
  19924. this.emissiveMap = null;
  19925. this.specularMap = null;
  19926. this.alphaMap = null;
  19927. this.envMap = null;
  19928. this.combine = MultiplyOperation;
  19929. this.reflectivity = 1;
  19930. this.refractionRatio = 0.98;
  19931. this.wireframe = false;
  19932. this.wireframeLinewidth = 1;
  19933. this.wireframeLinecap = 'round';
  19934. this.wireframeLinejoin = 'round';
  19935. this.skinning = false;
  19936. this.morphTargets = false;
  19937. this.morphNormals = false;
  19938. this.setValues(parameters);
  19939. }
  19940. MeshLambertMaterial.prototype = Object.create(Material.prototype);
  19941. MeshLambertMaterial.prototype.constructor = MeshLambertMaterial;
  19942. MeshLambertMaterial.prototype.isMeshLambertMaterial = true;
  19943. MeshLambertMaterial.prototype.copy = function (source) {
  19944. Material.prototype.copy.call(this, source);
  19945. this.color.copy(source.color);
  19946. this.map = source.map;
  19947. this.lightMap = source.lightMap;
  19948. this.lightMapIntensity = source.lightMapIntensity;
  19949. this.aoMap = source.aoMap;
  19950. this.aoMapIntensity = source.aoMapIntensity;
  19951. this.emissive.copy(source.emissive);
  19952. this.emissiveMap = source.emissiveMap;
  19953. this.emissiveIntensity = source.emissiveIntensity;
  19954. this.specularMap = source.specularMap;
  19955. this.alphaMap = source.alphaMap;
  19956. this.envMap = source.envMap;
  19957. this.combine = source.combine;
  19958. this.reflectivity = source.reflectivity;
  19959. this.refractionRatio = source.refractionRatio;
  19960. this.wireframe = source.wireframe;
  19961. this.wireframeLinewidth = source.wireframeLinewidth;
  19962. this.wireframeLinecap = source.wireframeLinecap;
  19963. this.wireframeLinejoin = source.wireframeLinejoin;
  19964. this.skinning = source.skinning;
  19965. this.morphTargets = source.morphTargets;
  19966. this.morphNormals = source.morphNormals;
  19967. return this;
  19968. };
  19969. /**
  19970. * @author WestLangley / http://github.com/WestLangley
  19971. *
  19972. * parameters = {
  19973. * color: <hex>,
  19974. * opacity: <float>,
  19975. *
  19976. * matcap: new THREE.Texture( <Image> ),
  19977. *
  19978. * map: new THREE.Texture( <Image> ),
  19979. *
  19980. * bumpMap: new THREE.Texture( <Image> ),
  19981. * bumpScale: <float>,
  19982. *
  19983. * normalMap: new THREE.Texture( <Image> ),
  19984. * normalMapType: THREE.TangentSpaceNormalMap,
  19985. * normalScale: <Vector2>,
  19986. *
  19987. * displacementMap: new THREE.Texture( <Image> ),
  19988. * displacementScale: <float>,
  19989. * displacementBias: <float>,
  19990. *
  19991. * alphaMap: new THREE.Texture( <Image> ),
  19992. *
  19993. * skinning: <bool>,
  19994. * morphTargets: <bool>,
  19995. * morphNormals: <bool>
  19996. * }
  19997. */
  19998. function MeshMatcapMaterial(parameters) {
  19999. Material.call(this);
  20000. this.defines = {
  20001. 'MATCAP': ''
  20002. };
  20003. this.type = 'MeshMatcapMaterial';
  20004. this.color = new Color(0xffffff); // diffuse
  20005. this.matcap = null;
  20006. this.map = null;
  20007. this.bumpMap = null;
  20008. this.bumpScale = 1;
  20009. this.normalMap = null;
  20010. this.normalMapType = TangentSpaceNormalMap;
  20011. this.normalScale = new Vector2(1, 1);
  20012. this.displacementMap = null;
  20013. this.displacementScale = 1;
  20014. this.displacementBias = 0;
  20015. this.alphaMap = null;
  20016. this.skinning = false;
  20017. this.morphTargets = false;
  20018. this.morphNormals = false;
  20019. this.setValues(parameters);
  20020. }
  20021. MeshMatcapMaterial.prototype = Object.create(Material.prototype);
  20022. MeshMatcapMaterial.prototype.constructor = MeshMatcapMaterial;
  20023. MeshMatcapMaterial.prototype.isMeshMatcapMaterial = true;
  20024. MeshMatcapMaterial.prototype.copy = function (source) {
  20025. Material.prototype.copy.call(this, source);
  20026. this.defines = {
  20027. 'MATCAP': ''
  20028. };
  20029. this.color.copy(source.color);
  20030. this.matcap = source.matcap;
  20031. this.map = source.map;
  20032. this.bumpMap = source.bumpMap;
  20033. this.bumpScale = source.bumpScale;
  20034. this.normalMap = source.normalMap;
  20035. this.normalMapType = source.normalMapType;
  20036. this.normalScale.copy(source.normalScale);
  20037. this.displacementMap = source.displacementMap;
  20038. this.displacementScale = source.displacementScale;
  20039. this.displacementBias = source.displacementBias;
  20040. this.alphaMap = source.alphaMap;
  20041. this.skinning = source.skinning;
  20042. this.morphTargets = source.morphTargets;
  20043. this.morphNormals = source.morphNormals;
  20044. return this;
  20045. };
  20046. /**
  20047. * @author alteredq / http://alteredqualia.com/
  20048. *
  20049. * parameters = {
  20050. * color: <hex>,
  20051. * opacity: <float>,
  20052. *
  20053. * linewidth: <float>,
  20054. *
  20055. * scale: <float>,
  20056. * dashSize: <float>,
  20057. * gapSize: <float>
  20058. * }
  20059. */
  20060. function LineDashedMaterial(parameters) {
  20061. LineBasicMaterial.call(this);
  20062. this.type = 'LineDashedMaterial';
  20063. this.scale = 1;
  20064. this.dashSize = 3;
  20065. this.gapSize = 1;
  20066. this.setValues(parameters);
  20067. }
  20068. LineDashedMaterial.prototype = Object.create(LineBasicMaterial.prototype);
  20069. LineDashedMaterial.prototype.constructor = LineDashedMaterial;
  20070. LineDashedMaterial.prototype.isLineDashedMaterial = true;
  20071. LineDashedMaterial.prototype.copy = function (source) {
  20072. LineBasicMaterial.prototype.copy.call(this, source);
  20073. this.scale = source.scale;
  20074. this.dashSize = source.dashSize;
  20075. this.gapSize = source.gapSize;
  20076. return this;
  20077. };
  20078. var Materials =
  20079. /*#__PURE__*/
  20080. Object.freeze({
  20081. ShadowMaterial: ShadowMaterial,
  20082. SpriteMaterial: SpriteMaterial,
  20083. RawShaderMaterial: RawShaderMaterial,
  20084. ShaderMaterial: ShaderMaterial,
  20085. PointsMaterial: PointsMaterial,
  20086. MeshPhysicalMaterial: MeshPhysicalMaterial,
  20087. MeshStandardMaterial: MeshStandardMaterial,
  20088. MeshPhongMaterial: MeshPhongMaterial,
  20089. MeshToonMaterial: MeshToonMaterial,
  20090. MeshNormalMaterial: MeshNormalMaterial,
  20091. MeshLambertMaterial: MeshLambertMaterial,
  20092. MeshDepthMaterial: MeshDepthMaterial,
  20093. MeshDistanceMaterial: MeshDistanceMaterial,
  20094. MeshBasicMaterial: MeshBasicMaterial,
  20095. MeshMatcapMaterial: MeshMatcapMaterial,
  20096. LineDashedMaterial: LineDashedMaterial,
  20097. LineBasicMaterial: LineBasicMaterial,
  20098. Material: Material
  20099. });
  20100. /**
  20101. * @author tschw
  20102. * @author Ben Houston / http://clara.io/
  20103. * @author David Sarno / http://lighthaus.us/
  20104. */
  20105. var AnimationUtils = {
  20106. // same as Array.prototype.slice, but also works on typed arrays
  20107. arraySlice: function (array, from, to) {
  20108. if (AnimationUtils.isTypedArray(array)) {
  20109. // in ios9 array.subarray(from, undefined) will return empty array
  20110. // but array.subarray(from) or array.subarray(from, len) is correct
  20111. return new array.constructor(array.subarray(from, to !== undefined ? to : array.length));
  20112. }
  20113. return array.slice(from, to);
  20114. },
  20115. // converts an array to a specific type
  20116. convertArray: function (array, type, forceClone) {
  20117. if (!array || // let 'undefined' and 'null' pass
  20118. !forceClone && array.constructor === type) return array;
  20119. if (typeof type.BYTES_PER_ELEMENT === 'number') {
  20120. return new type(array); // create typed array
  20121. }
  20122. return Array.prototype.slice.call(array); // create Array
  20123. },
  20124. isTypedArray: function (object) {
  20125. return ArrayBuffer.isView(object) && !(object instanceof DataView);
  20126. },
  20127. // returns an array by which times and values can be sorted
  20128. getKeyframeOrder: function (times) {
  20129. function compareTime(i, j) {
  20130. return times[i] - times[j];
  20131. }
  20132. var n = times.length;
  20133. var result = new Array(n);
  20134. for (var i = 0; i !== n; ++i) result[i] = i;
  20135. result.sort(compareTime);
  20136. return result;
  20137. },
  20138. // uses the array previously returned by 'getKeyframeOrder' to sort data
  20139. sortedArray: function (values, stride, order) {
  20140. var nValues = values.length;
  20141. var result = new values.constructor(nValues);
  20142. for (var i = 0, dstOffset = 0; dstOffset !== nValues; ++i) {
  20143. var srcOffset = order[i] * stride;
  20144. for (var j = 0; j !== stride; ++j) {
  20145. result[dstOffset++] = values[srcOffset + j];
  20146. }
  20147. }
  20148. return result;
  20149. },
  20150. // function for parsing AOS keyframe formats
  20151. flattenJSON: function (jsonKeys, times, values, valuePropertyName) {
  20152. var i = 1,
  20153. key = jsonKeys[0];
  20154. while (key !== undefined && key[valuePropertyName] === undefined) {
  20155. key = jsonKeys[i++];
  20156. }
  20157. if (key === undefined) return; // no data
  20158. var value = key[valuePropertyName];
  20159. if (value === undefined) return; // no data
  20160. if (Array.isArray(value)) {
  20161. do {
  20162. value = key[valuePropertyName];
  20163. if (value !== undefined) {
  20164. times.push(key.time);
  20165. values.push.apply(values, value); // push all elements
  20166. }
  20167. key = jsonKeys[i++];
  20168. } while (key !== undefined);
  20169. } else if (value.toArray !== undefined) {
  20170. // ...assume THREE.Math-ish
  20171. do {
  20172. value = key[valuePropertyName];
  20173. if (value !== undefined) {
  20174. times.push(key.time);
  20175. value.toArray(values, values.length);
  20176. }
  20177. key = jsonKeys[i++];
  20178. } while (key !== undefined);
  20179. } else {
  20180. // otherwise push as-is
  20181. do {
  20182. value = key[valuePropertyName];
  20183. if (value !== undefined) {
  20184. times.push(key.time);
  20185. values.push(value);
  20186. }
  20187. key = jsonKeys[i++];
  20188. } while (key !== undefined);
  20189. }
  20190. }
  20191. };
  20192. /**
  20193. * Abstract base class of interpolants over parametric samples.
  20194. *
  20195. * The parameter domain is one dimensional, typically the time or a path
  20196. * along a curve defined by the data.
  20197. *
  20198. * The sample values can have any dimensionality and derived classes may
  20199. * apply special interpretations to the data.
  20200. *
  20201. * This class provides the interval seek in a Template Method, deferring
  20202. * the actual interpolation to derived classes.
  20203. *
  20204. * Time complexity is O(1) for linear access crossing at most two points
  20205. * and O(log N) for random access, where N is the number of positions.
  20206. *
  20207. * References:
  20208. *
  20209. * http://www.oodesign.com/template-method-pattern.html
  20210. *
  20211. * @author tschw
  20212. */
  20213. exports.AnimationUtils = AnimationUtils;
  20214. function Interpolant(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  20215. this.parameterPositions = parameterPositions;
  20216. this._cachedIndex = 0;
  20217. this.resultBuffer = resultBuffer !== undefined ? resultBuffer : new sampleValues.constructor(sampleSize);
  20218. this.sampleValues = sampleValues;
  20219. this.valueSize = sampleSize;
  20220. }
  20221. Object.assign(Interpolant.prototype, {
  20222. evaluate: function (t) {
  20223. var pp = this.parameterPositions,
  20224. i1 = this._cachedIndex,
  20225. t1 = pp[i1],
  20226. t0 = pp[i1 - 1];
  20227. validate_interval: {
  20228. seek: {
  20229. var right;
  20230. linear_scan: {
  20231. //- See http://jsperf.com/comparison-to-undefined/3
  20232. //- slower code:
  20233. //-
  20234. //- if ( t >= t1 || t1 === undefined ) {
  20235. forward_scan: if (!(t < t1)) {
  20236. for (var giveUpAt = i1 + 2;;) {
  20237. if (t1 === undefined) {
  20238. if (t < t0) break forward_scan; // after end
  20239. i1 = pp.length;
  20240. this._cachedIndex = i1;
  20241. return this.afterEnd_(i1 - 1, t, t0);
  20242. }
  20243. if (i1 === giveUpAt) break; // this loop
  20244. t0 = t1;
  20245. t1 = pp[++i1];
  20246. if (t < t1) {
  20247. // we have arrived at the sought interval
  20248. break seek;
  20249. }
  20250. } // prepare binary search on the right side of the index
  20251. right = pp.length;
  20252. break linear_scan;
  20253. } //- slower code:
  20254. //- if ( t < t0 || t0 === undefined ) {
  20255. if (!(t >= t0)) {
  20256. // looping?
  20257. var t1global = pp[1];
  20258. if (t < t1global) {
  20259. i1 = 2; // + 1, using the scan for the details
  20260. t0 = t1global;
  20261. } // linear reverse scan
  20262. for (var giveUpAt = i1 - 2;;) {
  20263. if (t0 === undefined) {
  20264. // before start
  20265. this._cachedIndex = 0;
  20266. return this.beforeStart_(0, t, t1);
  20267. }
  20268. if (i1 === giveUpAt) break; // this loop
  20269. t1 = t0;
  20270. t0 = pp[--i1 - 1];
  20271. if (t >= t0) {
  20272. // we have arrived at the sought interval
  20273. break seek;
  20274. }
  20275. } // prepare binary search on the left side of the index
  20276. right = i1;
  20277. i1 = 0;
  20278. break linear_scan;
  20279. } // the interval is valid
  20280. break validate_interval;
  20281. } // linear scan
  20282. // binary search
  20283. while (i1 < right) {
  20284. var mid = i1 + right >>> 1;
  20285. if (t < pp[mid]) {
  20286. right = mid;
  20287. } else {
  20288. i1 = mid + 1;
  20289. }
  20290. }
  20291. t1 = pp[i1];
  20292. t0 = pp[i1 - 1]; // check boundary cases, again
  20293. if (t0 === undefined) {
  20294. this._cachedIndex = 0;
  20295. return this.beforeStart_(0, t, t1);
  20296. }
  20297. if (t1 === undefined) {
  20298. i1 = pp.length;
  20299. this._cachedIndex = i1;
  20300. return this.afterEnd_(i1 - 1, t0, t);
  20301. }
  20302. } // seek
  20303. this._cachedIndex = i1;
  20304. this.intervalChanged_(i1, t0, t1);
  20305. } // validate_interval
  20306. return this.interpolate_(i1, t0, t, t1);
  20307. },
  20308. settings: null,
  20309. // optional, subclass-specific settings structure
  20310. // Note: The indirection allows central control of many interpolants.
  20311. // --- Protected interface
  20312. DefaultSettings_: {},
  20313. getSettings_: function () {
  20314. return this.settings || this.DefaultSettings_;
  20315. },
  20316. copySampleValue_: function (index) {
  20317. // copies a sample value to the result buffer
  20318. var result = this.resultBuffer,
  20319. values = this.sampleValues,
  20320. stride = this.valueSize,
  20321. offset = index * stride;
  20322. for (var i = 0; i !== stride; ++i) {
  20323. result[i] = values[offset + i];
  20324. }
  20325. return result;
  20326. },
  20327. // Template methods for derived classes:
  20328. interpolate_: function ()
  20329. /* i1, t0, t, t1 */
  20330. {
  20331. throw new Error('call to abstract method'); // implementations shall return this.resultBuffer
  20332. },
  20333. intervalChanged_: function ()
  20334. /* i1, t0, t1 */
  20335. {// empty
  20336. }
  20337. }); //!\ DECLARE ALIAS AFTER assign prototype !
  20338. Object.assign(Interpolant.prototype, {
  20339. //( 0, t, t0 ), returns this.resultBuffer
  20340. beforeStart_: Interpolant.prototype.copySampleValue_,
  20341. //( N-1, tN-1, t ), returns this.resultBuffer
  20342. afterEnd_: Interpolant.prototype.copySampleValue_
  20343. });
  20344. /**
  20345. * Fast and simple cubic spline interpolant.
  20346. *
  20347. * It was derived from a Hermitian construction setting the first derivative
  20348. * at each sample position to the linear slope between neighboring positions
  20349. * over their parameter interval.
  20350. *
  20351. * @author tschw
  20352. */
  20353. function CubicInterpolant(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  20354. Interpolant.call(this, parameterPositions, sampleValues, sampleSize, resultBuffer);
  20355. this._weightPrev = -0;
  20356. this._offsetPrev = -0;
  20357. this._weightNext = -0;
  20358. this._offsetNext = -0;
  20359. }
  20360. CubicInterpolant.prototype = Object.assign(Object.create(Interpolant.prototype), {
  20361. constructor: CubicInterpolant,
  20362. DefaultSettings_: {
  20363. endingStart: ZeroCurvatureEnding,
  20364. endingEnd: ZeroCurvatureEnding
  20365. },
  20366. intervalChanged_: function (i1, t0, t1) {
  20367. var pp = this.parameterPositions,
  20368. iPrev = i1 - 2,
  20369. iNext = i1 + 1,
  20370. tPrev = pp[iPrev],
  20371. tNext = pp[iNext];
  20372. if (tPrev === undefined) {
  20373. switch (this.getSettings_().endingStart) {
  20374. case ZeroSlopeEnding:
  20375. // f'(t0) = 0
  20376. iPrev = i1;
  20377. tPrev = 2 * t0 - t1;
  20378. break;
  20379. case WrapAroundEnding:
  20380. // use the other end of the curve
  20381. iPrev = pp.length - 2;
  20382. tPrev = t0 + pp[iPrev] - pp[iPrev + 1];
  20383. break;
  20384. default:
  20385. // ZeroCurvatureEnding
  20386. // f''(t0) = 0 a.k.a. Natural Spline
  20387. iPrev = i1;
  20388. tPrev = t1;
  20389. }
  20390. }
  20391. if (tNext === undefined) {
  20392. switch (this.getSettings_().endingEnd) {
  20393. case ZeroSlopeEnding:
  20394. // f'(tN) = 0
  20395. iNext = i1;
  20396. tNext = 2 * t1 - t0;
  20397. break;
  20398. case WrapAroundEnding:
  20399. // use the other end of the curve
  20400. iNext = 1;
  20401. tNext = t1 + pp[1] - pp[0];
  20402. break;
  20403. default:
  20404. // ZeroCurvatureEnding
  20405. // f''(tN) = 0, a.k.a. Natural Spline
  20406. iNext = i1 - 1;
  20407. tNext = t0;
  20408. }
  20409. }
  20410. var halfDt = (t1 - t0) * 0.5,
  20411. stride = this.valueSize;
  20412. this._weightPrev = halfDt / (t0 - tPrev);
  20413. this._weightNext = halfDt / (tNext - t1);
  20414. this._offsetPrev = iPrev * stride;
  20415. this._offsetNext = iNext * stride;
  20416. },
  20417. interpolate_: function (i1, t0, t, t1) {
  20418. var result = this.resultBuffer,
  20419. values = this.sampleValues,
  20420. stride = this.valueSize,
  20421. o1 = i1 * stride,
  20422. o0 = o1 - stride,
  20423. oP = this._offsetPrev,
  20424. oN = this._offsetNext,
  20425. wP = this._weightPrev,
  20426. wN = this._weightNext,
  20427. p = (t - t0) / (t1 - t0),
  20428. pp = p * p,
  20429. ppp = pp * p; // evaluate polynomials
  20430. var sP = -wP * ppp + 2 * wP * pp - wP * p;
  20431. var s0 = (1 + wP) * ppp + (-1.5 - 2 * wP) * pp + (-0.5 + wP) * p + 1;
  20432. var s1 = (-1 - wN) * ppp + (1.5 + wN) * pp + 0.5 * p;
  20433. var sN = wN * ppp - wN * pp; // combine data linearly
  20434. for (var i = 0; i !== stride; ++i) {
  20435. result[i] = sP * values[oP + i] + s0 * values[o0 + i] + s1 * values[o1 + i] + sN * values[oN + i];
  20436. }
  20437. return result;
  20438. }
  20439. });
  20440. /**
  20441. * @author tschw
  20442. */
  20443. function LinearInterpolant(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  20444. Interpolant.call(this, parameterPositions, sampleValues, sampleSize, resultBuffer);
  20445. }
  20446. LinearInterpolant.prototype = Object.assign(Object.create(Interpolant.prototype), {
  20447. constructor: LinearInterpolant,
  20448. interpolate_: function (i1, t0, t, t1) {
  20449. var result = this.resultBuffer,
  20450. values = this.sampleValues,
  20451. stride = this.valueSize,
  20452. offset1 = i1 * stride,
  20453. offset0 = offset1 - stride,
  20454. weight1 = (t - t0) / (t1 - t0),
  20455. weight0 = 1 - weight1;
  20456. for (var i = 0; i !== stride; ++i) {
  20457. result[i] = values[offset0 + i] * weight0 + values[offset1 + i] * weight1;
  20458. }
  20459. return result;
  20460. }
  20461. });
  20462. /**
  20463. *
  20464. * Interpolant that evaluates to the sample value at the position preceeding
  20465. * the parameter.
  20466. *
  20467. * @author tschw
  20468. */
  20469. function DiscreteInterpolant(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  20470. Interpolant.call(this, parameterPositions, sampleValues, sampleSize, resultBuffer);
  20471. }
  20472. DiscreteInterpolant.prototype = Object.assign(Object.create(Interpolant.prototype), {
  20473. constructor: DiscreteInterpolant,
  20474. interpolate_: function (i1
  20475. /*, t0, t, t1 */
  20476. ) {
  20477. return this.copySampleValue_(i1 - 1);
  20478. }
  20479. });
  20480. /**
  20481. *
  20482. * A timed sequence of keyframes for a specific property.
  20483. *
  20484. *
  20485. * @author Ben Houston / http://clara.io/
  20486. * @author David Sarno / http://lighthaus.us/
  20487. * @author tschw
  20488. */
  20489. function KeyframeTrack(name, times, values, interpolation) {
  20490. if (name === undefined) throw new Error('THREE.KeyframeTrack: track name is undefined');
  20491. if (times === undefined || times.length === 0) throw new Error('THREE.KeyframeTrack: no keyframes in track named ' + name);
  20492. this.name = name;
  20493. this.times = AnimationUtils.convertArray(times, this.TimeBufferType);
  20494. this.values = AnimationUtils.convertArray(values, this.ValueBufferType);
  20495. this.setInterpolation(interpolation || this.DefaultInterpolation);
  20496. } // Static methods
  20497. Object.assign(KeyframeTrack, {
  20498. // Serialization (in static context, because of constructor invocation
  20499. // and automatic invocation of .toJSON):
  20500. toJSON: function (track) {
  20501. var trackType = track.constructor;
  20502. var json; // derived classes can define a static toJSON method
  20503. if (trackType.toJSON !== undefined) {
  20504. json = trackType.toJSON(track);
  20505. } else {
  20506. // by default, we assume the data can be serialized as-is
  20507. json = {
  20508. 'name': track.name,
  20509. 'times': AnimationUtils.convertArray(track.times, Array),
  20510. 'values': AnimationUtils.convertArray(track.values, Array)
  20511. };
  20512. var interpolation = track.getInterpolation();
  20513. if (interpolation !== track.DefaultInterpolation) {
  20514. json.interpolation = interpolation;
  20515. }
  20516. }
  20517. json.type = track.ValueTypeName; // mandatory
  20518. return json;
  20519. }
  20520. });
  20521. Object.assign(KeyframeTrack.prototype, {
  20522. constructor: KeyframeTrack,
  20523. TimeBufferType: Float32Array,
  20524. ValueBufferType: Float32Array,
  20525. DefaultInterpolation: InterpolateLinear,
  20526. InterpolantFactoryMethodDiscrete: function (result) {
  20527. return new DiscreteInterpolant(this.times, this.values, this.getValueSize(), result);
  20528. },
  20529. InterpolantFactoryMethodLinear: function (result) {
  20530. return new LinearInterpolant(this.times, this.values, this.getValueSize(), result);
  20531. },
  20532. InterpolantFactoryMethodSmooth: function (result) {
  20533. return new CubicInterpolant(this.times, this.values, this.getValueSize(), result);
  20534. },
  20535. setInterpolation: function (interpolation) {
  20536. var factoryMethod;
  20537. switch (interpolation) {
  20538. case InterpolateDiscrete:
  20539. factoryMethod = this.InterpolantFactoryMethodDiscrete;
  20540. break;
  20541. case InterpolateLinear:
  20542. factoryMethod = this.InterpolantFactoryMethodLinear;
  20543. break;
  20544. case InterpolateSmooth:
  20545. factoryMethod = this.InterpolantFactoryMethodSmooth;
  20546. break;
  20547. }
  20548. if (factoryMethod === undefined) {
  20549. var message = "unsupported interpolation for " + this.ValueTypeName + " keyframe track named " + this.name;
  20550. if (this.createInterpolant === undefined) {
  20551. // fall back to default, unless the default itself is messed up
  20552. if (interpolation !== this.DefaultInterpolation) {
  20553. this.setInterpolation(this.DefaultInterpolation);
  20554. } else {
  20555. throw new Error(message); // fatal, in this case
  20556. }
  20557. }
  20558. console.warn('THREE.KeyframeTrack:', message);
  20559. return this;
  20560. }
  20561. this.createInterpolant = factoryMethod;
  20562. return this;
  20563. },
  20564. getInterpolation: function () {
  20565. switch (this.createInterpolant) {
  20566. case this.InterpolantFactoryMethodDiscrete:
  20567. return InterpolateDiscrete;
  20568. case this.InterpolantFactoryMethodLinear:
  20569. return InterpolateLinear;
  20570. case this.InterpolantFactoryMethodSmooth:
  20571. return InterpolateSmooth;
  20572. }
  20573. },
  20574. getValueSize: function () {
  20575. return this.values.length / this.times.length;
  20576. },
  20577. // move all keyframes either forwards or backwards in time
  20578. shift: function (timeOffset) {
  20579. if (timeOffset !== 0.0) {
  20580. var times = this.times;
  20581. for (var i = 0, n = times.length; i !== n; ++i) {
  20582. times[i] += timeOffset;
  20583. }
  20584. }
  20585. return this;
  20586. },
  20587. // scale all keyframe times by a factor (useful for frame <-> seconds conversions)
  20588. scale: function (timeScale) {
  20589. if (timeScale !== 1.0) {
  20590. var times = this.times;
  20591. for (var i = 0, n = times.length; i !== n; ++i) {
  20592. times[i] *= timeScale;
  20593. }
  20594. }
  20595. return this;
  20596. },
  20597. // removes keyframes before and after animation without changing any values within the range [startTime, endTime].
  20598. // IMPORTANT: We do not shift around keys to the start of the track time, because for interpolated keys this will change their values
  20599. trim: function (startTime, endTime) {
  20600. var times = this.times,
  20601. nKeys = times.length,
  20602. from = 0,
  20603. to = nKeys - 1;
  20604. while (from !== nKeys && times[from] < startTime) {
  20605. ++from;
  20606. }
  20607. while (to !== -1 && times[to] > endTime) {
  20608. --to;
  20609. }
  20610. ++to; // inclusive -> exclusive bound
  20611. if (from !== 0 || to !== nKeys) {
  20612. // empty tracks are forbidden, so keep at least one keyframe
  20613. if (from >= to) to = Math.max(to, 1), from = to - 1;
  20614. var stride = this.getValueSize();
  20615. this.times = AnimationUtils.arraySlice(times, from, to);
  20616. this.values = AnimationUtils.arraySlice(this.values, from * stride, to * stride);
  20617. }
  20618. return this;
  20619. },
  20620. // ensure we do not get a GarbageInGarbageOut situation, make sure tracks are at least minimally viable
  20621. validate: function () {
  20622. var valid = true;
  20623. var valueSize = this.getValueSize();
  20624. if (valueSize - Math.floor(valueSize) !== 0) {
  20625. console.error('THREE.KeyframeTrack: Invalid value size in track.', this);
  20626. valid = false;
  20627. }
  20628. var times = this.times,
  20629. values = this.values,
  20630. nKeys = times.length;
  20631. if (nKeys === 0) {
  20632. console.error('THREE.KeyframeTrack: Track is empty.', this);
  20633. valid = false;
  20634. }
  20635. var prevTime = null;
  20636. for (var i = 0; i !== nKeys; i++) {
  20637. var currTime = times[i];
  20638. if (typeof currTime === 'number' && isNaN(currTime)) {
  20639. console.error('THREE.KeyframeTrack: Time is not a valid number.', this, i, currTime);
  20640. valid = false;
  20641. break;
  20642. }
  20643. if (prevTime !== null && prevTime > currTime) {
  20644. console.error('THREE.KeyframeTrack: Out of order keys.', this, i, currTime, prevTime);
  20645. valid = false;
  20646. break;
  20647. }
  20648. prevTime = currTime;
  20649. }
  20650. if (values !== undefined) {
  20651. if (AnimationUtils.isTypedArray(values)) {
  20652. for (var i = 0, n = values.length; i !== n; ++i) {
  20653. var value = values[i];
  20654. if (isNaN(value)) {
  20655. console.error('THREE.KeyframeTrack: Value is not a valid number.', this, i, value);
  20656. valid = false;
  20657. break;
  20658. }
  20659. }
  20660. }
  20661. }
  20662. return valid;
  20663. },
  20664. // removes equivalent sequential keys as common in morph target sequences
  20665. // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0)
  20666. optimize: function () {
  20667. var times = this.times,
  20668. values = this.values,
  20669. stride = this.getValueSize(),
  20670. smoothInterpolation = this.getInterpolation() === InterpolateSmooth,
  20671. writeIndex = 1,
  20672. lastIndex = times.length - 1;
  20673. for (var i = 1; i < lastIndex; ++i) {
  20674. var keep = false;
  20675. var time = times[i];
  20676. var timeNext = times[i + 1]; // remove adjacent keyframes scheduled at the same time
  20677. if (time !== timeNext && (i !== 1 || time !== time[0])) {
  20678. if (!smoothInterpolation) {
  20679. // remove unnecessary keyframes same as their neighbors
  20680. var offset = i * stride,
  20681. offsetP = offset - stride,
  20682. offsetN = offset + stride;
  20683. for (var j = 0; j !== stride; ++j) {
  20684. var value = values[offset + j];
  20685. if (value !== values[offsetP + j] || value !== values[offsetN + j]) {
  20686. keep = true;
  20687. break;
  20688. }
  20689. }
  20690. } else {
  20691. keep = true;
  20692. }
  20693. } // in-place compaction
  20694. if (keep) {
  20695. if (i !== writeIndex) {
  20696. times[writeIndex] = times[i];
  20697. var readOffset = i * stride,
  20698. writeOffset = writeIndex * stride;
  20699. for (var j = 0; j !== stride; ++j) {
  20700. values[writeOffset + j] = values[readOffset + j];
  20701. }
  20702. }
  20703. ++writeIndex;
  20704. }
  20705. } // flush last keyframe (compaction looks ahead)
  20706. if (lastIndex > 0) {
  20707. times[writeIndex] = times[lastIndex];
  20708. for (var readOffset = lastIndex * stride, writeOffset = writeIndex * stride, j = 0; j !== stride; ++j) {
  20709. values[writeOffset + j] = values[readOffset + j];
  20710. }
  20711. ++writeIndex;
  20712. }
  20713. if (writeIndex !== times.length) {
  20714. this.times = AnimationUtils.arraySlice(times, 0, writeIndex);
  20715. this.values = AnimationUtils.arraySlice(values, 0, writeIndex * stride);
  20716. }
  20717. return this;
  20718. },
  20719. clone: function () {
  20720. var times = AnimationUtils.arraySlice(this.times, 0);
  20721. var values = AnimationUtils.arraySlice(this.values, 0);
  20722. var TypedKeyframeTrack = this.constructor;
  20723. var track = new TypedKeyframeTrack(this.name, times, values); // Interpolant argument to constructor is not saved, so copy the factory method directly.
  20724. track.createInterpolant = this.createInterpolant;
  20725. return track;
  20726. }
  20727. });
  20728. /**
  20729. *
  20730. * A Track of Boolean keyframe values.
  20731. *
  20732. *
  20733. * @author Ben Houston / http://clara.io/
  20734. * @author David Sarno / http://lighthaus.us/
  20735. * @author tschw
  20736. */
  20737. function BooleanKeyframeTrack(name, times, values) {
  20738. KeyframeTrack.call(this, name, times, values);
  20739. }
  20740. BooleanKeyframeTrack.prototype = Object.assign(Object.create(KeyframeTrack.prototype), {
  20741. constructor: BooleanKeyframeTrack,
  20742. ValueTypeName: 'bool',
  20743. ValueBufferType: Array,
  20744. DefaultInterpolation: InterpolateDiscrete,
  20745. InterpolantFactoryMethodLinear: undefined,
  20746. InterpolantFactoryMethodSmooth: undefined // Note: Actually this track could have a optimized / compressed
  20747. // representation of a single value and a custom interpolant that
  20748. // computes "firstValue ^ isOdd( index )".
  20749. });
  20750. /**
  20751. *
  20752. * A Track of keyframe values that represent color.
  20753. *
  20754. *
  20755. * @author Ben Houston / http://clara.io/
  20756. * @author David Sarno / http://lighthaus.us/
  20757. * @author tschw
  20758. */
  20759. function ColorKeyframeTrack(name, times, values, interpolation) {
  20760. KeyframeTrack.call(this, name, times, values, interpolation);
  20761. }
  20762. ColorKeyframeTrack.prototype = Object.assign(Object.create(KeyframeTrack.prototype), {
  20763. constructor: ColorKeyframeTrack,
  20764. ValueTypeName: 'color' // ValueBufferType is inherited
  20765. // DefaultInterpolation is inherited
  20766. // Note: Very basic implementation and nothing special yet.
  20767. // However, this is the place for color space parameterization.
  20768. });
  20769. /**
  20770. *
  20771. * A Track of numeric keyframe values.
  20772. *
  20773. * @author Ben Houston / http://clara.io/
  20774. * @author David Sarno / http://lighthaus.us/
  20775. * @author tschw
  20776. */
  20777. function NumberKeyframeTrack(name, times, values, interpolation) {
  20778. KeyframeTrack.call(this, name, times, values, interpolation);
  20779. }
  20780. NumberKeyframeTrack.prototype = Object.assign(Object.create(KeyframeTrack.prototype), {
  20781. constructor: NumberKeyframeTrack,
  20782. ValueTypeName: 'number' // ValueBufferType is inherited
  20783. // DefaultInterpolation is inherited
  20784. });
  20785. /**
  20786. * Spherical linear unit quaternion interpolant.
  20787. *
  20788. * @author tschw
  20789. */
  20790. function QuaternionLinearInterpolant(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  20791. Interpolant.call(this, parameterPositions, sampleValues, sampleSize, resultBuffer);
  20792. }
  20793. QuaternionLinearInterpolant.prototype = Object.assign(Object.create(Interpolant.prototype), {
  20794. constructor: QuaternionLinearInterpolant,
  20795. interpolate_: function (i1, t0, t, t1) {
  20796. var result = this.resultBuffer,
  20797. values = this.sampleValues,
  20798. stride = this.valueSize,
  20799. offset = i1 * stride,
  20800. alpha = (t - t0) / (t1 - t0);
  20801. for (var end = offset + stride; offset !== end; offset += 4) {
  20802. Quaternion.slerpFlat(result, 0, values, offset - stride, values, offset, alpha);
  20803. }
  20804. return result;
  20805. }
  20806. });
  20807. /**
  20808. *
  20809. * A Track of quaternion keyframe values.
  20810. *
  20811. * @author Ben Houston / http://clara.io/
  20812. * @author David Sarno / http://lighthaus.us/
  20813. * @author tschw
  20814. */
  20815. function QuaternionKeyframeTrack(name, times, values, interpolation) {
  20816. KeyframeTrack.call(this, name, times, values, interpolation);
  20817. }
  20818. QuaternionKeyframeTrack.prototype = Object.assign(Object.create(KeyframeTrack.prototype), {
  20819. constructor: QuaternionKeyframeTrack,
  20820. ValueTypeName: 'quaternion',
  20821. // ValueBufferType is inherited
  20822. DefaultInterpolation: InterpolateLinear,
  20823. InterpolantFactoryMethodLinear: function (result) {
  20824. return new QuaternionLinearInterpolant(this.times, this.values, this.getValueSize(), result);
  20825. },
  20826. InterpolantFactoryMethodSmooth: undefined // not yet implemented
  20827. });
  20828. /**
  20829. *
  20830. * A Track that interpolates Strings
  20831. *
  20832. *
  20833. * @author Ben Houston / http://clara.io/
  20834. * @author David Sarno / http://lighthaus.us/
  20835. * @author tschw
  20836. */
  20837. function StringKeyframeTrack(name, times, values, interpolation) {
  20838. KeyframeTrack.call(this, name, times, values, interpolation);
  20839. }
  20840. StringKeyframeTrack.prototype = Object.assign(Object.create(KeyframeTrack.prototype), {
  20841. constructor: StringKeyframeTrack,
  20842. ValueTypeName: 'string',
  20843. ValueBufferType: Array,
  20844. DefaultInterpolation: InterpolateDiscrete,
  20845. InterpolantFactoryMethodLinear: undefined,
  20846. InterpolantFactoryMethodSmooth: undefined
  20847. });
  20848. /**
  20849. *
  20850. * A Track of vectored keyframe values.
  20851. *
  20852. *
  20853. * @author Ben Houston / http://clara.io/
  20854. * @author David Sarno / http://lighthaus.us/
  20855. * @author tschw
  20856. */
  20857. function VectorKeyframeTrack(name, times, values, interpolation) {
  20858. KeyframeTrack.call(this, name, times, values, interpolation);
  20859. }
  20860. VectorKeyframeTrack.prototype = Object.assign(Object.create(KeyframeTrack.prototype), {
  20861. constructor: VectorKeyframeTrack,
  20862. ValueTypeName: 'vector' // ValueBufferType is inherited
  20863. // DefaultInterpolation is inherited
  20864. });
  20865. /**
  20866. *
  20867. * Reusable set of Tracks that represent an animation.
  20868. *
  20869. * @author Ben Houston / http://clara.io/
  20870. * @author David Sarno / http://lighthaus.us/
  20871. */
  20872. function AnimationClip(name, duration, tracks) {
  20873. this.name = name;
  20874. this.tracks = tracks;
  20875. this.duration = duration !== undefined ? duration : -1;
  20876. this.uuid = _Math.generateUUID(); // this means it should figure out its duration by scanning the tracks
  20877. if (this.duration < 0) {
  20878. this.resetDuration();
  20879. }
  20880. }
  20881. function getTrackTypeForValueTypeName(typeName) {
  20882. switch (typeName.toLowerCase()) {
  20883. case 'scalar':
  20884. case 'double':
  20885. case 'float':
  20886. case 'number':
  20887. case 'integer':
  20888. return NumberKeyframeTrack;
  20889. case 'vector':
  20890. case 'vector2':
  20891. case 'vector3':
  20892. case 'vector4':
  20893. return VectorKeyframeTrack;
  20894. case 'color':
  20895. return ColorKeyframeTrack;
  20896. case 'quaternion':
  20897. return QuaternionKeyframeTrack;
  20898. case 'bool':
  20899. case 'boolean':
  20900. return BooleanKeyframeTrack;
  20901. case 'string':
  20902. return StringKeyframeTrack;
  20903. }
  20904. throw new Error('THREE.KeyframeTrack: Unsupported typeName: ' + typeName);
  20905. }
  20906. function parseKeyframeTrack(json) {
  20907. if (json.type === undefined) {
  20908. throw new Error('THREE.KeyframeTrack: track type undefined, can not parse');
  20909. }
  20910. var trackType = getTrackTypeForValueTypeName(json.type);
  20911. if (json.times === undefined) {
  20912. var times = [],
  20913. values = [];
  20914. AnimationUtils.flattenJSON(json.keys, times, values, 'value');
  20915. json.times = times;
  20916. json.values = values;
  20917. } // derived classes can define a static parse method
  20918. if (trackType.parse !== undefined) {
  20919. return trackType.parse(json);
  20920. } else {
  20921. // by default, we assume a constructor compatible with the base
  20922. return new trackType(json.name, json.times, json.values, json.interpolation);
  20923. }
  20924. }
  20925. Object.assign(AnimationClip, {
  20926. parse: function (json) {
  20927. var tracks = [],
  20928. jsonTracks = json.tracks,
  20929. frameTime = 1.0 / (json.fps || 1.0);
  20930. for (var i = 0, n = jsonTracks.length; i !== n; ++i) {
  20931. tracks.push(parseKeyframeTrack(jsonTracks[i]).scale(frameTime));
  20932. }
  20933. return new AnimationClip(json.name, json.duration, tracks);
  20934. },
  20935. toJSON: function (clip) {
  20936. var tracks = [],
  20937. clipTracks = clip.tracks;
  20938. var json = {
  20939. 'name': clip.name,
  20940. 'duration': clip.duration,
  20941. 'tracks': tracks,
  20942. 'uuid': clip.uuid
  20943. };
  20944. for (var i = 0, n = clipTracks.length; i !== n; ++i) {
  20945. tracks.push(KeyframeTrack.toJSON(clipTracks[i]));
  20946. }
  20947. return json;
  20948. },
  20949. CreateFromMorphTargetSequence: function (name, morphTargetSequence, fps, noLoop) {
  20950. var numMorphTargets = morphTargetSequence.length;
  20951. var tracks = [];
  20952. for (var i = 0; i < numMorphTargets; i++) {
  20953. var times = [];
  20954. var values = [];
  20955. times.push((i + numMorphTargets - 1) % numMorphTargets, i, (i + 1) % numMorphTargets);
  20956. values.push(0, 1, 0);
  20957. var order = AnimationUtils.getKeyframeOrder(times);
  20958. times = AnimationUtils.sortedArray(times, 1, order);
  20959. values = AnimationUtils.sortedArray(values, 1, order); // if there is a key at the first frame, duplicate it as the
  20960. // last frame as well for perfect loop.
  20961. if (!noLoop && times[0] === 0) {
  20962. times.push(numMorphTargets);
  20963. values.push(values[0]);
  20964. }
  20965. tracks.push(new NumberKeyframeTrack('.morphTargetInfluences[' + morphTargetSequence[i].name + ']', times, values).scale(1.0 / fps));
  20966. }
  20967. return new AnimationClip(name, -1, tracks);
  20968. },
  20969. findByName: function (objectOrClipArray, name) {
  20970. var clipArray = objectOrClipArray;
  20971. if (!Array.isArray(objectOrClipArray)) {
  20972. var o = objectOrClipArray;
  20973. clipArray = o.geometry && o.geometry.animations || o.animations;
  20974. }
  20975. for (var i = 0; i < clipArray.length; i++) {
  20976. if (clipArray[i].name === name) {
  20977. return clipArray[i];
  20978. }
  20979. }
  20980. return null;
  20981. },
  20982. CreateClipsFromMorphTargetSequences: function (morphTargets, fps, noLoop) {
  20983. var animationToMorphTargets = {}; // tested with https://regex101.com/ on trick sequences
  20984. // such flamingo_flyA_003, flamingo_run1_003, crdeath0059
  20985. var pattern = /^([\w-]*?)([\d]+)$/; // sort morph target names into animation groups based
  20986. // patterns like Walk_001, Walk_002, Run_001, Run_002
  20987. for (var i = 0, il = morphTargets.length; i < il; i++) {
  20988. var morphTarget = morphTargets[i];
  20989. var parts = morphTarget.name.match(pattern);
  20990. if (parts && parts.length > 1) {
  20991. var name = parts[1];
  20992. var animationMorphTargets = animationToMorphTargets[name];
  20993. if (!animationMorphTargets) {
  20994. animationToMorphTargets[name] = animationMorphTargets = [];
  20995. }
  20996. animationMorphTargets.push(morphTarget);
  20997. }
  20998. }
  20999. var clips = [];
  21000. for (var name in animationToMorphTargets) {
  21001. clips.push(AnimationClip.CreateFromMorphTargetSequence(name, animationToMorphTargets[name], fps, noLoop));
  21002. }
  21003. return clips;
  21004. },
  21005. // parse the animation.hierarchy format
  21006. parseAnimation: function (animation, bones) {
  21007. if (!animation) {
  21008. console.error('THREE.AnimationClip: No animation in JSONLoader data.');
  21009. return null;
  21010. }
  21011. var addNonemptyTrack = function (trackType, trackName, animationKeys, propertyName, destTracks) {
  21012. // only return track if there are actually keys.
  21013. if (animationKeys.length !== 0) {
  21014. var times = [];
  21015. var values = [];
  21016. AnimationUtils.flattenJSON(animationKeys, times, values, propertyName); // empty keys are filtered out, so check again
  21017. if (times.length !== 0) {
  21018. destTracks.push(new trackType(trackName, times, values));
  21019. }
  21020. }
  21021. };
  21022. var tracks = [];
  21023. var clipName = animation.name || 'default'; // automatic length determination in AnimationClip.
  21024. var duration = animation.length || -1;
  21025. var fps = animation.fps || 30;
  21026. var hierarchyTracks = animation.hierarchy || [];
  21027. for (var h = 0; h < hierarchyTracks.length; h++) {
  21028. var animationKeys = hierarchyTracks[h].keys; // skip empty tracks
  21029. if (!animationKeys || animationKeys.length === 0) continue; // process morph targets
  21030. if (animationKeys[0].morphTargets) {
  21031. // figure out all morph targets used in this track
  21032. var morphTargetNames = {};
  21033. for (var k = 0; k < animationKeys.length; k++) {
  21034. if (animationKeys[k].morphTargets) {
  21035. for (var m = 0; m < animationKeys[k].morphTargets.length; m++) {
  21036. morphTargetNames[animationKeys[k].morphTargets[m]] = -1;
  21037. }
  21038. }
  21039. } // create a track for each morph target with all zero
  21040. // morphTargetInfluences except for the keys in which
  21041. // the morphTarget is named.
  21042. for (var morphTargetName in morphTargetNames) {
  21043. var times = [];
  21044. var values = [];
  21045. for (var m = 0; m !== animationKeys[k].morphTargets.length; ++m) {
  21046. var animationKey = animationKeys[k];
  21047. times.push(animationKey.time);
  21048. values.push(animationKey.morphTarget === morphTargetName ? 1 : 0);
  21049. }
  21050. tracks.push(new NumberKeyframeTrack('.morphTargetInfluence[' + morphTargetName + ']', times, values));
  21051. }
  21052. duration = morphTargetNames.length * (fps || 1.0);
  21053. } else {
  21054. // ...assume skeletal animation
  21055. var boneName = '.bones[' + bones[h].name + ']';
  21056. addNonemptyTrack(VectorKeyframeTrack, boneName + '.position', animationKeys, 'pos', tracks);
  21057. addNonemptyTrack(QuaternionKeyframeTrack, boneName + '.quaternion', animationKeys, 'rot', tracks);
  21058. addNonemptyTrack(VectorKeyframeTrack, boneName + '.scale', animationKeys, 'scl', tracks);
  21059. }
  21060. }
  21061. if (tracks.length === 0) {
  21062. return null;
  21063. }
  21064. var clip = new AnimationClip(clipName, duration, tracks);
  21065. return clip;
  21066. }
  21067. });
  21068. Object.assign(AnimationClip.prototype, {
  21069. resetDuration: function () {
  21070. var tracks = this.tracks,
  21071. duration = 0;
  21072. for (var i = 0, n = tracks.length; i !== n; ++i) {
  21073. var track = this.tracks[i];
  21074. duration = Math.max(duration, track.times[track.times.length - 1]);
  21075. }
  21076. this.duration = duration;
  21077. return this;
  21078. },
  21079. trim: function () {
  21080. for (var i = 0; i < this.tracks.length; i++) {
  21081. this.tracks[i].trim(0, this.duration);
  21082. }
  21083. return this;
  21084. },
  21085. validate: function () {
  21086. var valid = true;
  21087. for (var i = 0; i < this.tracks.length; i++) {
  21088. valid = valid && this.tracks[i].validate();
  21089. }
  21090. return valid;
  21091. },
  21092. optimize: function () {
  21093. for (var i = 0; i < this.tracks.length; i++) {
  21094. this.tracks[i].optimize();
  21095. }
  21096. return this;
  21097. },
  21098. clone: function () {
  21099. var tracks = [];
  21100. for (var i = 0; i < this.tracks.length; i++) {
  21101. tracks.push(this.tracks[i].clone());
  21102. }
  21103. return new AnimationClip(this.name, this.duration, tracks);
  21104. }
  21105. });
  21106. /**
  21107. * @author mrdoob / http://mrdoob.com/
  21108. */
  21109. var Cache = {
  21110. enabled: false,
  21111. files: {},
  21112. add: function (key, file) {
  21113. if (this.enabled === false) return; // console.log( 'THREE.Cache', 'Adding key:', key );
  21114. this.files[key] = file;
  21115. },
  21116. get: function (key) {
  21117. if (this.enabled === false) return; // console.log( 'THREE.Cache', 'Checking key:', key );
  21118. return this.files[key];
  21119. },
  21120. remove: function (key) {
  21121. delete this.files[key];
  21122. },
  21123. clear: function () {
  21124. this.files = {};
  21125. }
  21126. };
  21127. /**
  21128. * @author mrdoob / http://mrdoob.com/
  21129. */
  21130. exports.Cache = Cache;
  21131. function LoadingManager(onLoad, onProgress, onError) {
  21132. var scope = this;
  21133. var isLoading = false;
  21134. var itemsLoaded = 0;
  21135. var itemsTotal = 0;
  21136. var urlModifier = undefined;
  21137. var handlers = []; // Refer to #5689 for the reason why we don't set .onStart
  21138. // in the constructor
  21139. this.onStart = undefined;
  21140. this.onLoad = onLoad;
  21141. this.onProgress = onProgress;
  21142. this.onError = onError;
  21143. this.itemStart = function (url) {
  21144. itemsTotal++;
  21145. if (isLoading === false) {
  21146. if (scope.onStart !== undefined) {
  21147. scope.onStart(url, itemsLoaded, itemsTotal);
  21148. }
  21149. }
  21150. isLoading = true;
  21151. };
  21152. this.itemEnd = function (url) {
  21153. itemsLoaded++;
  21154. if (scope.onProgress !== undefined) {
  21155. scope.onProgress(url, itemsLoaded, itemsTotal);
  21156. }
  21157. if (itemsLoaded === itemsTotal) {
  21158. isLoading = false;
  21159. if (scope.onLoad !== undefined) {
  21160. scope.onLoad();
  21161. }
  21162. }
  21163. };
  21164. this.itemError = function (url) {
  21165. if (scope.onError !== undefined) {
  21166. scope.onError(url);
  21167. }
  21168. };
  21169. this.resolveURL = function (url) {
  21170. if (urlModifier) {
  21171. return urlModifier(url);
  21172. }
  21173. return url;
  21174. };
  21175. this.setURLModifier = function (transform) {
  21176. urlModifier = transform;
  21177. return this;
  21178. };
  21179. this.addHandler = function (regex, loader) {
  21180. handlers.push(regex, loader);
  21181. return this;
  21182. };
  21183. this.removeHandler = function (regex) {
  21184. var index = handlers.indexOf(regex);
  21185. if (index !== -1) {
  21186. handlers.splice(index, 2);
  21187. }
  21188. return this;
  21189. };
  21190. this.getHandler = function (file) {
  21191. for (var i = 0, l = handlers.length; i < l; i += 2) {
  21192. var regex = handlers[i];
  21193. var loader = handlers[i + 1];
  21194. if (regex.test(file)) {
  21195. return loader;
  21196. }
  21197. }
  21198. return null;
  21199. };
  21200. }
  21201. var DefaultLoadingManager = new LoadingManager();
  21202. /**
  21203. * @author alteredq / http://alteredqualia.com/
  21204. */
  21205. exports.DefaultLoadingManager = DefaultLoadingManager;
  21206. function Loader(manager) {
  21207. this.manager = manager !== undefined ? manager : DefaultLoadingManager;
  21208. this.crossOrigin = 'anonymous';
  21209. this.path = '';
  21210. this.resourcePath = '';
  21211. }
  21212. Object.assign(Loader.prototype, {
  21213. load: function ()
  21214. /* url, onLoad, onProgress, onError */
  21215. {},
  21216. parse: function ()
  21217. /* data */
  21218. {},
  21219. setCrossOrigin: function (crossOrigin) {
  21220. this.crossOrigin = crossOrigin;
  21221. return this;
  21222. },
  21223. setPath: function (path) {
  21224. this.path = path;
  21225. return this;
  21226. },
  21227. setResourcePath: function (resourcePath) {
  21228. this.resourcePath = resourcePath;
  21229. return this;
  21230. }
  21231. });
  21232. /**
  21233. * @author mrdoob / http://mrdoob.com/
  21234. */
  21235. var loading = {};
  21236. function FileLoader(manager) {
  21237. Loader.call(this, manager);
  21238. }
  21239. FileLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  21240. constructor: FileLoader,
  21241. load: function (url, onLoad, onProgress, onError) {
  21242. if (url === undefined) url = '';
  21243. if (this.path !== undefined) url = this.path + url;
  21244. url = this.manager.resolveURL(url);
  21245. var scope = this;
  21246. var cached = Cache.get(url);
  21247. if (cached !== undefined) {
  21248. scope.manager.itemStart(url);
  21249. setTimeout(function () {
  21250. if (onLoad) onLoad(cached);
  21251. scope.manager.itemEnd(url);
  21252. }, 0);
  21253. return cached;
  21254. } // Check if request is duplicate
  21255. if (loading[url] !== undefined) {
  21256. loading[url].push({
  21257. onLoad: onLoad,
  21258. onProgress: onProgress,
  21259. onError: onError
  21260. });
  21261. return;
  21262. } // Check for data: URI
  21263. var dataUriRegex = /^data:(.*?)(;base64)?,(.*)$/;
  21264. var dataUriRegexResult = url.match(dataUriRegex); // Safari can not handle Data URIs through XMLHttpRequest so process manually
  21265. if (dataUriRegexResult) {
  21266. var mimeType = dataUriRegexResult[1];
  21267. var isBase64 = !!dataUriRegexResult[2];
  21268. var data = dataUriRegexResult[3];
  21269. data = decodeURIComponent(data);
  21270. if (isBase64) data = atob(data);
  21271. try {
  21272. var response;
  21273. var responseType = (this.responseType || '').toLowerCase();
  21274. switch (responseType) {
  21275. case 'arraybuffer':
  21276. case 'blob':
  21277. var view = new Uint8Array(data.length);
  21278. for (var i = 0; i < data.length; i++) {
  21279. view[i] = data.charCodeAt(i);
  21280. }
  21281. if (responseType === 'blob') {
  21282. response = new Blob([view.buffer], {
  21283. type: mimeType
  21284. });
  21285. } else {
  21286. response = view.buffer;
  21287. }
  21288. break;
  21289. case 'document':
  21290. var parser = new DOMParser();
  21291. response = parser.parseFromString(data, mimeType);
  21292. break;
  21293. case 'json':
  21294. response = JSON.parse(data);
  21295. break;
  21296. default:
  21297. // 'text' or other
  21298. response = data;
  21299. break;
  21300. } // Wait for next browser tick like standard XMLHttpRequest event dispatching does
  21301. setTimeout(function () {
  21302. if (onLoad) onLoad(response);
  21303. scope.manager.itemEnd(url);
  21304. }, 0);
  21305. } catch (error) {
  21306. // Wait for next browser tick like standard XMLHttpRequest event dispatching does
  21307. setTimeout(function () {
  21308. if (onError) onError(error);
  21309. scope.manager.itemError(url);
  21310. scope.manager.itemEnd(url);
  21311. }, 0);
  21312. }
  21313. } else {
  21314. // Initialise array for duplicate requests
  21315. loading[url] = [];
  21316. loading[url].push({
  21317. onLoad: onLoad,
  21318. onProgress: onProgress,
  21319. onError: onError
  21320. });
  21321. var request = new XMLHttpRequest();
  21322. request.open('GET', url, true);
  21323. request.addEventListener('load', function (event) {
  21324. var response = this.response;
  21325. Cache.add(url, response);
  21326. var callbacks = loading[url];
  21327. delete loading[url];
  21328. if (this.status === 200 || this.status === 0) {
  21329. // Some browsers return HTTP Status 0 when using non-http protocol
  21330. // e.g. 'file://' or 'data://'. Handle as success.
  21331. if (this.status === 0) console.warn('THREE.FileLoader: HTTP Status 0 received.');
  21332. for (var i = 0, il = callbacks.length; i < il; i++) {
  21333. var callback = callbacks[i];
  21334. if (callback.onLoad) callback.onLoad(response);
  21335. }
  21336. scope.manager.itemEnd(url);
  21337. } else {
  21338. for (var i = 0, il = callbacks.length; i < il; i++) {
  21339. var callback = callbacks[i];
  21340. if (callback.onError) callback.onError(event);
  21341. }
  21342. scope.manager.itemError(url);
  21343. scope.manager.itemEnd(url);
  21344. }
  21345. }, false);
  21346. request.addEventListener('progress', function (event) {
  21347. var callbacks = loading[url];
  21348. for (var i = 0, il = callbacks.length; i < il; i++) {
  21349. var callback = callbacks[i];
  21350. if (callback.onProgress) callback.onProgress(event);
  21351. }
  21352. }, false);
  21353. request.addEventListener('error', function (event) {
  21354. var callbacks = loading[url];
  21355. delete loading[url];
  21356. for (var i = 0, il = callbacks.length; i < il; i++) {
  21357. var callback = callbacks[i];
  21358. if (callback.onError) callback.onError(event);
  21359. }
  21360. scope.manager.itemError(url);
  21361. scope.manager.itemEnd(url);
  21362. }, false);
  21363. request.addEventListener('abort', function (event) {
  21364. var callbacks = loading[url];
  21365. delete loading[url];
  21366. for (var i = 0, il = callbacks.length; i < il; i++) {
  21367. var callback = callbacks[i];
  21368. if (callback.onError) callback.onError(event);
  21369. }
  21370. scope.manager.itemError(url);
  21371. scope.manager.itemEnd(url);
  21372. }, false);
  21373. if (this.responseType !== undefined) request.responseType = this.responseType;
  21374. if (this.withCredentials !== undefined) request.withCredentials = this.withCredentials;
  21375. if (request.overrideMimeType) request.overrideMimeType(this.mimeType !== undefined ? this.mimeType : 'text/plain');
  21376. for (var header in this.requestHeader) {
  21377. request.setRequestHeader(header, this.requestHeader[header]);
  21378. }
  21379. request.send(null);
  21380. }
  21381. scope.manager.itemStart(url);
  21382. return request;
  21383. },
  21384. setResponseType: function (value) {
  21385. this.responseType = value;
  21386. return this;
  21387. },
  21388. setWithCredentials: function (value) {
  21389. this.withCredentials = value;
  21390. return this;
  21391. },
  21392. setMimeType: function (value) {
  21393. this.mimeType = value;
  21394. return this;
  21395. },
  21396. setRequestHeader: function (value) {
  21397. this.requestHeader = value;
  21398. return this;
  21399. }
  21400. });
  21401. /**
  21402. * @author bhouston / http://clara.io/
  21403. */
  21404. function AnimationLoader(manager) {
  21405. Loader.call(this, manager);
  21406. }
  21407. AnimationLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  21408. constructor: AnimationLoader,
  21409. load: function (url, onLoad, onProgress, onError) {
  21410. var scope = this;
  21411. var loader = new FileLoader(scope.manager);
  21412. loader.setPath(scope.path);
  21413. loader.load(url, function (text) {
  21414. onLoad(scope.parse(JSON.parse(text)));
  21415. }, onProgress, onError);
  21416. },
  21417. parse: function (json) {
  21418. var animations = [];
  21419. for (var i = 0; i < json.length; i++) {
  21420. var clip = AnimationClip.parse(json[i]);
  21421. animations.push(clip);
  21422. }
  21423. return animations;
  21424. }
  21425. });
  21426. /**
  21427. * @author mrdoob / http://mrdoob.com/
  21428. *
  21429. * Abstract Base class to block based textures loader (dds, pvr, ...)
  21430. *
  21431. * Sub classes have to implement the parse() method which will be used in load().
  21432. */
  21433. function CompressedTextureLoader(manager) {
  21434. Loader.call(this, manager);
  21435. }
  21436. CompressedTextureLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  21437. constructor: CompressedTextureLoader,
  21438. load: function (url, onLoad, onProgress, onError) {
  21439. var scope = this;
  21440. var images = [];
  21441. var texture = new CompressedTexture();
  21442. texture.image = images;
  21443. var loader = new FileLoader(this.manager);
  21444. loader.setPath(this.path);
  21445. loader.setResponseType('arraybuffer');
  21446. function loadTexture(i) {
  21447. loader.load(url[i], function (buffer) {
  21448. var texDatas = scope.parse(buffer, true);
  21449. images[i] = {
  21450. width: texDatas.width,
  21451. height: texDatas.height,
  21452. format: texDatas.format,
  21453. mipmaps: texDatas.mipmaps
  21454. };
  21455. loaded += 1;
  21456. if (loaded === 6) {
  21457. if (texDatas.mipmapCount === 1) texture.minFilter = LinearFilter;
  21458. texture.format = texDatas.format;
  21459. texture.needsUpdate = true;
  21460. if (onLoad) onLoad(texture);
  21461. }
  21462. }, onProgress, onError);
  21463. }
  21464. if (Array.isArray(url)) {
  21465. var loaded = 0;
  21466. for (var i = 0, il = url.length; i < il; ++i) {
  21467. loadTexture(i);
  21468. }
  21469. } else {
  21470. // compressed cubemap texture stored in a single DDS file
  21471. loader.load(url, function (buffer) {
  21472. var texDatas = scope.parse(buffer, true);
  21473. if (texDatas.isCubemap) {
  21474. var faces = texDatas.mipmaps.length / texDatas.mipmapCount;
  21475. for (var f = 0; f < faces; f++) {
  21476. images[f] = {
  21477. mipmaps: []
  21478. };
  21479. for (var i = 0; i < texDatas.mipmapCount; i++) {
  21480. images[f].mipmaps.push(texDatas.mipmaps[f * texDatas.mipmapCount + i]);
  21481. images[f].format = texDatas.format;
  21482. images[f].width = texDatas.width;
  21483. images[f].height = texDatas.height;
  21484. }
  21485. }
  21486. } else {
  21487. texture.image.width = texDatas.width;
  21488. texture.image.height = texDatas.height;
  21489. texture.mipmaps = texDatas.mipmaps;
  21490. }
  21491. if (texDatas.mipmapCount === 1) {
  21492. texture.minFilter = LinearFilter;
  21493. }
  21494. texture.format = texDatas.format;
  21495. texture.needsUpdate = true;
  21496. if (onLoad) onLoad(texture);
  21497. }, onProgress, onError);
  21498. }
  21499. return texture;
  21500. }
  21501. });
  21502. /**
  21503. * @author Nikos M. / https://github.com/foo123/
  21504. *
  21505. * Abstract Base class to load generic binary textures formats (rgbe, hdr, ...)
  21506. *
  21507. * Sub classes have to implement the parse() method which will be used in load().
  21508. */
  21509. function DataTextureLoader(manager) {
  21510. Loader.call(this, manager);
  21511. }
  21512. DataTextureLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  21513. constructor: DataTextureLoader,
  21514. load: function (url, onLoad, onProgress, onError) {
  21515. var scope = this;
  21516. var texture = new DataTexture();
  21517. var loader = new FileLoader(this.manager);
  21518. loader.setResponseType('arraybuffer');
  21519. loader.setPath(this.path);
  21520. loader.load(url, function (buffer) {
  21521. var texData = scope.parse(buffer);
  21522. if (!texData) return;
  21523. if (texData.image !== undefined) {
  21524. texture.image = texData.image;
  21525. } else if (texData.data !== undefined) {
  21526. texture.image.width = texData.width;
  21527. texture.image.height = texData.height;
  21528. texture.image.data = texData.data;
  21529. }
  21530. texture.wrapS = texData.wrapS !== undefined ? texData.wrapS : ClampToEdgeWrapping;
  21531. texture.wrapT = texData.wrapT !== undefined ? texData.wrapT : ClampToEdgeWrapping;
  21532. texture.magFilter = texData.magFilter !== undefined ? texData.magFilter : LinearFilter;
  21533. texture.minFilter = texData.minFilter !== undefined ? texData.minFilter : LinearMipmapLinearFilter;
  21534. texture.anisotropy = texData.anisotropy !== undefined ? texData.anisotropy : 1;
  21535. if (texData.format !== undefined) {
  21536. texture.format = texData.format;
  21537. }
  21538. if (texData.type !== undefined) {
  21539. texture.type = texData.type;
  21540. }
  21541. if (texData.mipmaps !== undefined) {
  21542. texture.mipmaps = texData.mipmaps;
  21543. }
  21544. if (texData.mipmapCount === 1) {
  21545. texture.minFilter = LinearFilter;
  21546. }
  21547. texture.needsUpdate = true;
  21548. if (onLoad) onLoad(texture, texData);
  21549. }, onProgress, onError);
  21550. return texture;
  21551. }
  21552. });
  21553. /**
  21554. * @author mrdoob / http://mrdoob.com/
  21555. */
  21556. function ImageLoader(manager) {
  21557. Loader.call(this, manager);
  21558. }
  21559. ImageLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  21560. constructor: ImageLoader,
  21561. load: function (url, onLoad, onProgress, onError) {
  21562. if (this.path !== undefined) url = this.path + url;
  21563. url = this.manager.resolveURL(url);
  21564. var scope = this;
  21565. var cached = Cache.get(url);
  21566. if (cached !== undefined) {
  21567. scope.manager.itemStart(url);
  21568. setTimeout(function () {
  21569. if (onLoad) onLoad(cached);
  21570. scope.manager.itemEnd(url);
  21571. }, 0);
  21572. return cached;
  21573. }
  21574. var image = document.createElementNS('http://www.w3.org/1999/xhtml', 'img');
  21575. function onImageLoad() {
  21576. image.removeEventListener('load', onImageLoad, false);
  21577. image.removeEventListener('error', onImageError, false);
  21578. Cache.add(url, this);
  21579. if (onLoad) onLoad(this);
  21580. scope.manager.itemEnd(url);
  21581. }
  21582. function onImageError(event) {
  21583. image.removeEventListener('load', onImageLoad, false);
  21584. image.removeEventListener('error', onImageError, false);
  21585. if (onError) onError(event);
  21586. scope.manager.itemError(url);
  21587. scope.manager.itemEnd(url);
  21588. }
  21589. image.addEventListener('load', onImageLoad, false);
  21590. image.addEventListener('error', onImageError, false);
  21591. if (url.substr(0, 5) !== 'data:') {
  21592. if (this.crossOrigin !== undefined) image.crossOrigin = this.crossOrigin;
  21593. }
  21594. scope.manager.itemStart(url);
  21595. image.src = url;
  21596. return image;
  21597. }
  21598. });
  21599. /**
  21600. * @author mrdoob / http://mrdoob.com/
  21601. */
  21602. function CubeTextureLoader(manager) {
  21603. Loader.call(this, manager);
  21604. }
  21605. CubeTextureLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  21606. constructor: CubeTextureLoader,
  21607. load: function (urls, onLoad, onProgress, onError) {
  21608. var texture = new CubeTexture();
  21609. var loader = new ImageLoader(this.manager);
  21610. loader.setCrossOrigin(this.crossOrigin);
  21611. loader.setPath(this.path);
  21612. var loaded = 0;
  21613. function loadTexture(i) {
  21614. loader.load(urls[i], function (image) {
  21615. texture.images[i] = image;
  21616. loaded++;
  21617. if (loaded === 6) {
  21618. texture.needsUpdate = true;
  21619. if (onLoad) onLoad(texture);
  21620. }
  21621. }, undefined, onError);
  21622. }
  21623. for (var i = 0; i < urls.length; ++i) {
  21624. loadTexture(i);
  21625. }
  21626. return texture;
  21627. }
  21628. });
  21629. /**
  21630. * @author mrdoob / http://mrdoob.com/
  21631. */
  21632. function TextureLoader(manager) {
  21633. Loader.call(this, manager);
  21634. }
  21635. TextureLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  21636. constructor: TextureLoader,
  21637. load: function (url, onLoad, onProgress, onError) {
  21638. var texture = new Texture();
  21639. var loader = new ImageLoader(this.manager);
  21640. loader.setCrossOrigin(this.crossOrigin);
  21641. loader.setPath(this.path);
  21642. loader.load(url, function (image) {
  21643. texture.image = image; // JPEGs can't have an alpha channel, so memory can be saved by storing them as RGB.
  21644. var isJPEG = url.search(/\.jpe?g($|\?)/i) > 0 || url.search(/^data\:image\/jpeg/) === 0;
  21645. texture.format = isJPEG ? RGBFormat : RGBAFormat;
  21646. texture.needsUpdate = true;
  21647. if (onLoad !== undefined) {
  21648. onLoad(texture);
  21649. }
  21650. }, onProgress, onError);
  21651. return texture;
  21652. }
  21653. });
  21654. /**
  21655. * @author zz85 / http://www.lab4games.net/zz85/blog
  21656. * Extensible curve object
  21657. *
  21658. * Some common of curve methods:
  21659. * .getPoint( t, optionalTarget ), .getTangent( t )
  21660. * .getPointAt( u, optionalTarget ), .getTangentAt( u )
  21661. * .getPoints(), .getSpacedPoints()
  21662. * .getLength()
  21663. * .updateArcLengths()
  21664. *
  21665. * This following curves inherit from THREE.Curve:
  21666. *
  21667. * -- 2D curves --
  21668. * THREE.ArcCurve
  21669. * THREE.CubicBezierCurve
  21670. * THREE.EllipseCurve
  21671. * THREE.LineCurve
  21672. * THREE.QuadraticBezierCurve
  21673. * THREE.SplineCurve
  21674. *
  21675. * -- 3D curves --
  21676. * THREE.CatmullRomCurve3
  21677. * THREE.CubicBezierCurve3
  21678. * THREE.LineCurve3
  21679. * THREE.QuadraticBezierCurve3
  21680. *
  21681. * A series of curves can be represented as a THREE.CurvePath.
  21682. *
  21683. **/
  21684. /**************************************************************
  21685. * Abstract Curve base class
  21686. **************************************************************/
  21687. function Curve() {
  21688. this.type = 'Curve';
  21689. this.arcLengthDivisions = 200;
  21690. }
  21691. Object.assign(Curve.prototype, {
  21692. // Virtual base class method to overwrite and implement in subclasses
  21693. // - t [0 .. 1]
  21694. getPoint: function ()
  21695. /* t, optionalTarget */
  21696. {
  21697. console.warn('THREE.Curve: .getPoint() not implemented.');
  21698. return null;
  21699. },
  21700. // Get point at relative position in curve according to arc length
  21701. // - u [0 .. 1]
  21702. getPointAt: function (u, optionalTarget) {
  21703. var t = this.getUtoTmapping(u);
  21704. return this.getPoint(t, optionalTarget);
  21705. },
  21706. // Get sequence of points using getPoint( t )
  21707. getPoints: function (divisions) {
  21708. if (divisions === undefined) divisions = 5;
  21709. var points = [];
  21710. for (var d = 0; d <= divisions; d++) {
  21711. points.push(this.getPoint(d / divisions));
  21712. }
  21713. return points;
  21714. },
  21715. // Get sequence of points using getPointAt( u )
  21716. getSpacedPoints: function (divisions) {
  21717. if (divisions === undefined) divisions = 5;
  21718. var points = [];
  21719. for (var d = 0; d <= divisions; d++) {
  21720. points.push(this.getPointAt(d / divisions));
  21721. }
  21722. return points;
  21723. },
  21724. // Get total curve arc length
  21725. getLength: function () {
  21726. var lengths = this.getLengths();
  21727. return lengths[lengths.length - 1];
  21728. },
  21729. // Get list of cumulative segment lengths
  21730. getLengths: function (divisions) {
  21731. if (divisions === undefined) divisions = this.arcLengthDivisions;
  21732. if (this.cacheArcLengths && this.cacheArcLengths.length === divisions + 1 && !this.needsUpdate) {
  21733. return this.cacheArcLengths;
  21734. }
  21735. this.needsUpdate = false;
  21736. var cache = [];
  21737. var current,
  21738. last = this.getPoint(0);
  21739. var p,
  21740. sum = 0;
  21741. cache.push(0);
  21742. for (p = 1; p <= divisions; p++) {
  21743. current = this.getPoint(p / divisions);
  21744. sum += current.distanceTo(last);
  21745. cache.push(sum);
  21746. last = current;
  21747. }
  21748. this.cacheArcLengths = cache;
  21749. return cache; // { sums: cache, sum: sum }; Sum is in the last element.
  21750. },
  21751. updateArcLengths: function () {
  21752. this.needsUpdate = true;
  21753. this.getLengths();
  21754. },
  21755. // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equidistant
  21756. getUtoTmapping: function (u, distance) {
  21757. var arcLengths = this.getLengths();
  21758. var i = 0,
  21759. il = arcLengths.length;
  21760. var targetArcLength; // The targeted u distance value to get
  21761. if (distance) {
  21762. targetArcLength = distance;
  21763. } else {
  21764. targetArcLength = u * arcLengths[il - 1];
  21765. } // binary search for the index with largest value smaller than target u distance
  21766. var low = 0,
  21767. high = il - 1,
  21768. comparison;
  21769. while (low <= high) {
  21770. 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
  21771. comparison = arcLengths[i] - targetArcLength;
  21772. if (comparison < 0) {
  21773. low = i + 1;
  21774. } else if (comparison > 0) {
  21775. high = i - 1;
  21776. } else {
  21777. high = i;
  21778. break; // DONE
  21779. }
  21780. }
  21781. i = high;
  21782. if (arcLengths[i] === targetArcLength) {
  21783. return i / (il - 1);
  21784. } // we could get finer grain at lengths, or use simple interpolation between two points
  21785. var lengthBefore = arcLengths[i];
  21786. var lengthAfter = arcLengths[i + 1];
  21787. var segmentLength = lengthAfter - lengthBefore; // determine where we are between the 'before' and 'after' points
  21788. var segmentFraction = (targetArcLength - lengthBefore) / segmentLength; // add that fractional amount to t
  21789. var t = (i + segmentFraction) / (il - 1);
  21790. return t;
  21791. },
  21792. // Returns a unit vector tangent at t
  21793. // In case any sub curve does not implement its tangent derivation,
  21794. // 2 points a small delta apart will be used to find its gradient
  21795. // which seems to give a reasonable approximation
  21796. getTangent: function (t) {
  21797. var delta = 0.0001;
  21798. var t1 = t - delta;
  21799. var t2 = t + delta; // Capping in case of danger
  21800. if (t1 < 0) t1 = 0;
  21801. if (t2 > 1) t2 = 1;
  21802. var pt1 = this.getPoint(t1);
  21803. var pt2 = this.getPoint(t2);
  21804. var vec = pt2.clone().sub(pt1);
  21805. return vec.normalize();
  21806. },
  21807. getTangentAt: function (u) {
  21808. var t = this.getUtoTmapping(u);
  21809. return this.getTangent(t);
  21810. },
  21811. computeFrenetFrames: function (segments, closed) {
  21812. // see http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  21813. var normal = new Vector3();
  21814. var tangents = [];
  21815. var normals = [];
  21816. var binormals = [];
  21817. var vec = new Vector3();
  21818. var mat = new Matrix4();
  21819. var i, u, theta; // compute the tangent vectors for each segment on the curve
  21820. for (i = 0; i <= segments; i++) {
  21821. u = i / segments;
  21822. tangents[i] = this.getTangentAt(u);
  21823. tangents[i].normalize();
  21824. } // select an initial normal vector perpendicular to the first tangent vector,
  21825. // and in the direction of the minimum tangent xyz component
  21826. normals[0] = new Vector3();
  21827. binormals[0] = new Vector3();
  21828. var min = Number.MAX_VALUE;
  21829. var tx = Math.abs(tangents[0].x);
  21830. var ty = Math.abs(tangents[0].y);
  21831. var tz = Math.abs(tangents[0].z);
  21832. if (tx <= min) {
  21833. min = tx;
  21834. normal.set(1, 0, 0);
  21835. }
  21836. if (ty <= min) {
  21837. min = ty;
  21838. normal.set(0, 1, 0);
  21839. }
  21840. if (tz <= min) {
  21841. normal.set(0, 0, 1);
  21842. }
  21843. vec.crossVectors(tangents[0], normal).normalize();
  21844. normals[0].crossVectors(tangents[0], vec);
  21845. binormals[0].crossVectors(tangents[0], normals[0]); // compute the slowly-varying normal and binormal vectors for each segment on the curve
  21846. for (i = 1; i <= segments; i++) {
  21847. normals[i] = normals[i - 1].clone();
  21848. binormals[i] = binormals[i - 1].clone();
  21849. vec.crossVectors(tangents[i - 1], tangents[i]);
  21850. if (vec.length() > Number.EPSILON) {
  21851. vec.normalize();
  21852. theta = Math.acos(_Math.clamp(tangents[i - 1].dot(tangents[i]), -1, 1)); // clamp for floating pt errors
  21853. normals[i].applyMatrix4(mat.makeRotationAxis(vec, theta));
  21854. }
  21855. binormals[i].crossVectors(tangents[i], normals[i]);
  21856. } // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  21857. if (closed === true) {
  21858. theta = Math.acos(_Math.clamp(normals[0].dot(normals[segments]), -1, 1));
  21859. theta /= segments;
  21860. if (tangents[0].dot(vec.crossVectors(normals[0], normals[segments])) > 0) {
  21861. theta = -theta;
  21862. }
  21863. for (i = 1; i <= segments; i++) {
  21864. // twist a little...
  21865. normals[i].applyMatrix4(mat.makeRotationAxis(tangents[i], theta * i));
  21866. binormals[i].crossVectors(tangents[i], normals[i]);
  21867. }
  21868. }
  21869. return {
  21870. tangents: tangents,
  21871. normals: normals,
  21872. binormals: binormals
  21873. };
  21874. },
  21875. clone: function () {
  21876. return new this.constructor().copy(this);
  21877. },
  21878. copy: function (source) {
  21879. this.arcLengthDivisions = source.arcLengthDivisions;
  21880. return this;
  21881. },
  21882. toJSON: function () {
  21883. var data = {
  21884. metadata: {
  21885. version: 4.5,
  21886. type: 'Curve',
  21887. generator: 'Curve.toJSON'
  21888. }
  21889. };
  21890. data.arcLengthDivisions = this.arcLengthDivisions;
  21891. data.type = this.type;
  21892. return data;
  21893. },
  21894. fromJSON: function (json) {
  21895. this.arcLengthDivisions = json.arcLengthDivisions;
  21896. return this;
  21897. }
  21898. });
  21899. function EllipseCurve(aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation) {
  21900. Curve.call(this);
  21901. this.type = 'EllipseCurve';
  21902. this.aX = aX || 0;
  21903. this.aY = aY || 0;
  21904. this.xRadius = xRadius || 1;
  21905. this.yRadius = yRadius || 1;
  21906. this.aStartAngle = aStartAngle || 0;
  21907. this.aEndAngle = aEndAngle || 2 * Math.PI;
  21908. this.aClockwise = aClockwise || false;
  21909. this.aRotation = aRotation || 0;
  21910. }
  21911. EllipseCurve.prototype = Object.create(Curve.prototype);
  21912. EllipseCurve.prototype.constructor = EllipseCurve;
  21913. EllipseCurve.prototype.isEllipseCurve = true;
  21914. EllipseCurve.prototype.getPoint = function (t, optionalTarget) {
  21915. var point = optionalTarget || new Vector2();
  21916. var twoPi = Math.PI * 2;
  21917. var deltaAngle = this.aEndAngle - this.aStartAngle;
  21918. var samePoints = Math.abs(deltaAngle) < Number.EPSILON; // ensures that deltaAngle is 0 .. 2 PI
  21919. while (deltaAngle < 0) deltaAngle += twoPi;
  21920. while (deltaAngle > twoPi) deltaAngle -= twoPi;
  21921. if (deltaAngle < Number.EPSILON) {
  21922. if (samePoints) {
  21923. deltaAngle = 0;
  21924. } else {
  21925. deltaAngle = twoPi;
  21926. }
  21927. }
  21928. if (this.aClockwise === true && !samePoints) {
  21929. if (deltaAngle === twoPi) {
  21930. deltaAngle = -twoPi;
  21931. } else {
  21932. deltaAngle = deltaAngle - twoPi;
  21933. }
  21934. }
  21935. var angle = this.aStartAngle + t * deltaAngle;
  21936. var x = this.aX + this.xRadius * Math.cos(angle);
  21937. var y = this.aY + this.yRadius * Math.sin(angle);
  21938. if (this.aRotation !== 0) {
  21939. var cos = Math.cos(this.aRotation);
  21940. var sin = Math.sin(this.aRotation);
  21941. var tx = x - this.aX;
  21942. var ty = y - this.aY; // Rotate the point about the center of the ellipse.
  21943. x = tx * cos - ty * sin + this.aX;
  21944. y = tx * sin + ty * cos + this.aY;
  21945. }
  21946. return point.set(x, y);
  21947. };
  21948. EllipseCurve.prototype.copy = function (source) {
  21949. Curve.prototype.copy.call(this, source);
  21950. this.aX = source.aX;
  21951. this.aY = source.aY;
  21952. this.xRadius = source.xRadius;
  21953. this.yRadius = source.yRadius;
  21954. this.aStartAngle = source.aStartAngle;
  21955. this.aEndAngle = source.aEndAngle;
  21956. this.aClockwise = source.aClockwise;
  21957. this.aRotation = source.aRotation;
  21958. return this;
  21959. };
  21960. EllipseCurve.prototype.toJSON = function () {
  21961. var data = Curve.prototype.toJSON.call(this);
  21962. data.aX = this.aX;
  21963. data.aY = this.aY;
  21964. data.xRadius = this.xRadius;
  21965. data.yRadius = this.yRadius;
  21966. data.aStartAngle = this.aStartAngle;
  21967. data.aEndAngle = this.aEndAngle;
  21968. data.aClockwise = this.aClockwise;
  21969. data.aRotation = this.aRotation;
  21970. return data;
  21971. };
  21972. EllipseCurve.prototype.fromJSON = function (json) {
  21973. Curve.prototype.fromJSON.call(this, json);
  21974. this.aX = json.aX;
  21975. this.aY = json.aY;
  21976. this.xRadius = json.xRadius;
  21977. this.yRadius = json.yRadius;
  21978. this.aStartAngle = json.aStartAngle;
  21979. this.aEndAngle = json.aEndAngle;
  21980. this.aClockwise = json.aClockwise;
  21981. this.aRotation = json.aRotation;
  21982. return this;
  21983. };
  21984. function ArcCurve(aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise) {
  21985. EllipseCurve.call(this, aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise);
  21986. this.type = 'ArcCurve';
  21987. }
  21988. ArcCurve.prototype = Object.create(EllipseCurve.prototype);
  21989. ArcCurve.prototype.constructor = ArcCurve;
  21990. ArcCurve.prototype.isArcCurve = true;
  21991. /**
  21992. * @author zz85 https://github.com/zz85
  21993. *
  21994. * Centripetal CatmullRom Curve - which is useful for avoiding
  21995. * cusps and self-intersections in non-uniform catmull rom curves.
  21996. * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf
  21997. *
  21998. * curve.type accepts centripetal(default), chordal and catmullrom
  21999. * curve.tension is used for catmullrom which defaults to 0.5
  22000. */
  22001. /*
  22002. Based on an optimized c++ solution in
  22003. - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/
  22004. - http://ideone.com/NoEbVM
  22005. This CubicPoly class could be used for reusing some variables and calculations,
  22006. but for three.js curve use, it could be possible inlined and flatten into a single function call
  22007. which can be placed in CurveUtils.
  22008. */
  22009. function CubicPoly() {
  22010. var c0 = 0,
  22011. c1 = 0,
  22012. c2 = 0,
  22013. c3 = 0;
  22014. /*
  22015. * Compute coefficients for a cubic polynomial
  22016. * p(s) = c0 + c1*s + c2*s^2 + c3*s^3
  22017. * such that
  22018. * p(0) = x0, p(1) = x1
  22019. * and
  22020. * p'(0) = t0, p'(1) = t1.
  22021. */
  22022. function init(x0, x1, t0, t1) {
  22023. c0 = x0;
  22024. c1 = t0;
  22025. c2 = -3 * x0 + 3 * x1 - 2 * t0 - t1;
  22026. c3 = 2 * x0 - 2 * x1 + t0 + t1;
  22027. }
  22028. return {
  22029. initCatmullRom: function (x0, x1, x2, x3, tension) {
  22030. init(x1, x2, tension * (x2 - x0), tension * (x3 - x1));
  22031. },
  22032. initNonuniformCatmullRom: function (x0, x1, x2, x3, dt0, dt1, dt2) {
  22033. // compute tangents when parameterized in [t1,t2]
  22034. var t1 = (x1 - x0) / dt0 - (x2 - x0) / (dt0 + dt1) + (x2 - x1) / dt1;
  22035. var t2 = (x2 - x1) / dt1 - (x3 - x1) / (dt1 + dt2) + (x3 - x2) / dt2; // rescale tangents for parametrization in [0,1]
  22036. t1 *= dt1;
  22037. t2 *= dt1;
  22038. init(x1, x2, t1, t2);
  22039. },
  22040. calc: function (t) {
  22041. var t2 = t * t;
  22042. var t3 = t2 * t;
  22043. return c0 + c1 * t + c2 * t2 + c3 * t3;
  22044. }
  22045. };
  22046. } //
  22047. var tmp = new Vector3();
  22048. var px = new CubicPoly(),
  22049. py = new CubicPoly(),
  22050. pz = new CubicPoly();
  22051. function CatmullRomCurve3(points, closed, curveType, tension) {
  22052. Curve.call(this);
  22053. this.type = 'CatmullRomCurve3';
  22054. this.points = points || [];
  22055. this.closed = closed || false;
  22056. this.curveType = curveType || 'centripetal';
  22057. this.tension = tension || 0.5;
  22058. }
  22059. CatmullRomCurve3.prototype = Object.create(Curve.prototype);
  22060. CatmullRomCurve3.prototype.constructor = CatmullRomCurve3;
  22061. CatmullRomCurve3.prototype.isCatmullRomCurve3 = true;
  22062. CatmullRomCurve3.prototype.getPoint = function (t, optionalTarget) {
  22063. var point = optionalTarget || new Vector3();
  22064. var points = this.points;
  22065. var l = points.length;
  22066. var p = (l - (this.closed ? 0 : 1)) * t;
  22067. var intPoint = Math.floor(p);
  22068. var weight = p - intPoint;
  22069. if (this.closed) {
  22070. intPoint += intPoint > 0 ? 0 : (Math.floor(Math.abs(intPoint) / l) + 1) * l;
  22071. } else if (weight === 0 && intPoint === l - 1) {
  22072. intPoint = l - 2;
  22073. weight = 1;
  22074. }
  22075. var p0, p1, p2, p3; // 4 points
  22076. if (this.closed || intPoint > 0) {
  22077. p0 = points[(intPoint - 1) % l];
  22078. } else {
  22079. // extrapolate first point
  22080. tmp.subVectors(points[0], points[1]).add(points[0]);
  22081. p0 = tmp;
  22082. }
  22083. p1 = points[intPoint % l];
  22084. p2 = points[(intPoint + 1) % l];
  22085. if (this.closed || intPoint + 2 < l) {
  22086. p3 = points[(intPoint + 2) % l];
  22087. } else {
  22088. // extrapolate last point
  22089. tmp.subVectors(points[l - 1], points[l - 2]).add(points[l - 1]);
  22090. p3 = tmp;
  22091. }
  22092. if (this.curveType === 'centripetal' || this.curveType === 'chordal') {
  22093. // init Centripetal / Chordal Catmull-Rom
  22094. var pow = this.curveType === 'chordal' ? 0.5 : 0.25;
  22095. var dt0 = Math.pow(p0.distanceToSquared(p1), pow);
  22096. var dt1 = Math.pow(p1.distanceToSquared(p2), pow);
  22097. var dt2 = Math.pow(p2.distanceToSquared(p3), pow); // safety check for repeated points
  22098. if (dt1 < 1e-4) dt1 = 1.0;
  22099. if (dt0 < 1e-4) dt0 = dt1;
  22100. if (dt2 < 1e-4) dt2 = dt1;
  22101. px.initNonuniformCatmullRom(p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2);
  22102. py.initNonuniformCatmullRom(p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2);
  22103. pz.initNonuniformCatmullRom(p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2);
  22104. } else if (this.curveType === 'catmullrom') {
  22105. px.initCatmullRom(p0.x, p1.x, p2.x, p3.x, this.tension);
  22106. py.initCatmullRom(p0.y, p1.y, p2.y, p3.y, this.tension);
  22107. pz.initCatmullRom(p0.z, p1.z, p2.z, p3.z, this.tension);
  22108. }
  22109. point.set(px.calc(weight), py.calc(weight), pz.calc(weight));
  22110. return point;
  22111. };
  22112. CatmullRomCurve3.prototype.copy = function (source) {
  22113. Curve.prototype.copy.call(this, source);
  22114. this.points = [];
  22115. for (var i = 0, l = source.points.length; i < l; i++) {
  22116. var point = source.points[i];
  22117. this.points.push(point.clone());
  22118. }
  22119. this.closed = source.closed;
  22120. this.curveType = source.curveType;
  22121. this.tension = source.tension;
  22122. return this;
  22123. };
  22124. CatmullRomCurve3.prototype.toJSON = function () {
  22125. var data = Curve.prototype.toJSON.call(this);
  22126. data.points = [];
  22127. for (var i = 0, l = this.points.length; i < l; i++) {
  22128. var point = this.points[i];
  22129. data.points.push(point.toArray());
  22130. }
  22131. data.closed = this.closed;
  22132. data.curveType = this.curveType;
  22133. data.tension = this.tension;
  22134. return data;
  22135. };
  22136. CatmullRomCurve3.prototype.fromJSON = function (json) {
  22137. Curve.prototype.fromJSON.call(this, json);
  22138. this.points = [];
  22139. for (var i = 0, l = json.points.length; i < l; i++) {
  22140. var point = json.points[i];
  22141. this.points.push(new Vector3().fromArray(point));
  22142. }
  22143. this.closed = json.closed;
  22144. this.curveType = json.curveType;
  22145. this.tension = json.tension;
  22146. return this;
  22147. };
  22148. /**
  22149. * @author zz85 / http://www.lab4games.net/zz85/blog
  22150. *
  22151. * Bezier Curves formulas obtained from
  22152. * http://en.wikipedia.org/wiki/Bézier_curve
  22153. */
  22154. function CatmullRom(t, p0, p1, p2, p3) {
  22155. var v0 = (p2 - p0) * 0.5;
  22156. var v1 = (p3 - p1) * 0.5;
  22157. var t2 = t * t;
  22158. var t3 = t * t2;
  22159. return (2 * p1 - 2 * p2 + v0 + v1) * t3 + (-3 * p1 + 3 * p2 - 2 * v0 - v1) * t2 + v0 * t + p1;
  22160. } //
  22161. function QuadraticBezierP0(t, p) {
  22162. var k = 1 - t;
  22163. return k * k * p;
  22164. }
  22165. function QuadraticBezierP1(t, p) {
  22166. return 2 * (1 - t) * t * p;
  22167. }
  22168. function QuadraticBezierP2(t, p) {
  22169. return t * t * p;
  22170. }
  22171. function QuadraticBezier(t, p0, p1, p2) {
  22172. return QuadraticBezierP0(t, p0) + QuadraticBezierP1(t, p1) + QuadraticBezierP2(t, p2);
  22173. } //
  22174. function CubicBezierP0(t, p) {
  22175. var k = 1 - t;
  22176. return k * k * k * p;
  22177. }
  22178. function CubicBezierP1(t, p) {
  22179. var k = 1 - t;
  22180. return 3 * k * k * t * p;
  22181. }
  22182. function CubicBezierP2(t, p) {
  22183. return 3 * (1 - t) * t * t * p;
  22184. }
  22185. function CubicBezierP3(t, p) {
  22186. return t * t * t * p;
  22187. }
  22188. function CubicBezier(t, p0, p1, p2, p3) {
  22189. return CubicBezierP0(t, p0) + CubicBezierP1(t, p1) + CubicBezierP2(t, p2) + CubicBezierP3(t, p3);
  22190. }
  22191. function CubicBezierCurve(v0, v1, v2, v3) {
  22192. Curve.call(this);
  22193. this.type = 'CubicBezierCurve';
  22194. this.v0 = v0 || new Vector2();
  22195. this.v1 = v1 || new Vector2();
  22196. this.v2 = v2 || new Vector2();
  22197. this.v3 = v3 || new Vector2();
  22198. }
  22199. CubicBezierCurve.prototype = Object.create(Curve.prototype);
  22200. CubicBezierCurve.prototype.constructor = CubicBezierCurve;
  22201. CubicBezierCurve.prototype.isCubicBezierCurve = true;
  22202. CubicBezierCurve.prototype.getPoint = function (t, optionalTarget) {
  22203. var point = optionalTarget || new Vector2();
  22204. var v0 = this.v0,
  22205. v1 = this.v1,
  22206. v2 = this.v2,
  22207. v3 = this.v3;
  22208. point.set(CubicBezier(t, v0.x, v1.x, v2.x, v3.x), CubicBezier(t, v0.y, v1.y, v2.y, v3.y));
  22209. return point;
  22210. };
  22211. CubicBezierCurve.prototype.copy = function (source) {
  22212. Curve.prototype.copy.call(this, source);
  22213. this.v0.copy(source.v0);
  22214. this.v1.copy(source.v1);
  22215. this.v2.copy(source.v2);
  22216. this.v3.copy(source.v3);
  22217. return this;
  22218. };
  22219. CubicBezierCurve.prototype.toJSON = function () {
  22220. var data = Curve.prototype.toJSON.call(this);
  22221. data.v0 = this.v0.toArray();
  22222. data.v1 = this.v1.toArray();
  22223. data.v2 = this.v2.toArray();
  22224. data.v3 = this.v3.toArray();
  22225. return data;
  22226. };
  22227. CubicBezierCurve.prototype.fromJSON = function (json) {
  22228. Curve.prototype.fromJSON.call(this, json);
  22229. this.v0.fromArray(json.v0);
  22230. this.v1.fromArray(json.v1);
  22231. this.v2.fromArray(json.v2);
  22232. this.v3.fromArray(json.v3);
  22233. return this;
  22234. };
  22235. function CubicBezierCurve3(v0, v1, v2, v3) {
  22236. Curve.call(this);
  22237. this.type = 'CubicBezierCurve3';
  22238. this.v0 = v0 || new Vector3();
  22239. this.v1 = v1 || new Vector3();
  22240. this.v2 = v2 || new Vector3();
  22241. this.v3 = v3 || new Vector3();
  22242. }
  22243. CubicBezierCurve3.prototype = Object.create(Curve.prototype);
  22244. CubicBezierCurve3.prototype.constructor = CubicBezierCurve3;
  22245. CubicBezierCurve3.prototype.isCubicBezierCurve3 = true;
  22246. CubicBezierCurve3.prototype.getPoint = function (t, optionalTarget) {
  22247. var point = optionalTarget || new Vector3();
  22248. var v0 = this.v0,
  22249. v1 = this.v1,
  22250. v2 = this.v2,
  22251. v3 = this.v3;
  22252. 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));
  22253. return point;
  22254. };
  22255. CubicBezierCurve3.prototype.copy = function (source) {
  22256. Curve.prototype.copy.call(this, source);
  22257. this.v0.copy(source.v0);
  22258. this.v1.copy(source.v1);
  22259. this.v2.copy(source.v2);
  22260. this.v3.copy(source.v3);
  22261. return this;
  22262. };
  22263. CubicBezierCurve3.prototype.toJSON = function () {
  22264. var data = Curve.prototype.toJSON.call(this);
  22265. data.v0 = this.v0.toArray();
  22266. data.v1 = this.v1.toArray();
  22267. data.v2 = this.v2.toArray();
  22268. data.v3 = this.v3.toArray();
  22269. return data;
  22270. };
  22271. CubicBezierCurve3.prototype.fromJSON = function (json) {
  22272. Curve.prototype.fromJSON.call(this, json);
  22273. this.v0.fromArray(json.v0);
  22274. this.v1.fromArray(json.v1);
  22275. this.v2.fromArray(json.v2);
  22276. this.v3.fromArray(json.v3);
  22277. return this;
  22278. };
  22279. function LineCurve(v1, v2) {
  22280. Curve.call(this);
  22281. this.type = 'LineCurve';
  22282. this.v1 = v1 || new Vector2();
  22283. this.v2 = v2 || new Vector2();
  22284. }
  22285. LineCurve.prototype = Object.create(Curve.prototype);
  22286. LineCurve.prototype.constructor = LineCurve;
  22287. LineCurve.prototype.isLineCurve = true;
  22288. LineCurve.prototype.getPoint = function (t, optionalTarget) {
  22289. var point = optionalTarget || new Vector2();
  22290. if (t === 1) {
  22291. point.copy(this.v2);
  22292. } else {
  22293. point.copy(this.v2).sub(this.v1);
  22294. point.multiplyScalar(t).add(this.v1);
  22295. }
  22296. return point;
  22297. }; // Line curve is linear, so we can overwrite default getPointAt
  22298. LineCurve.prototype.getPointAt = function (u, optionalTarget) {
  22299. return this.getPoint(u, optionalTarget);
  22300. };
  22301. LineCurve.prototype.getTangent = function ()
  22302. /* t */
  22303. {
  22304. var tangent = this.v2.clone().sub(this.v1);
  22305. return tangent.normalize();
  22306. };
  22307. LineCurve.prototype.copy = function (source) {
  22308. Curve.prototype.copy.call(this, source);
  22309. this.v1.copy(source.v1);
  22310. this.v2.copy(source.v2);
  22311. return this;
  22312. };
  22313. LineCurve.prototype.toJSON = function () {
  22314. var data = Curve.prototype.toJSON.call(this);
  22315. data.v1 = this.v1.toArray();
  22316. data.v2 = this.v2.toArray();
  22317. return data;
  22318. };
  22319. LineCurve.prototype.fromJSON = function (json) {
  22320. Curve.prototype.fromJSON.call(this, json);
  22321. this.v1.fromArray(json.v1);
  22322. this.v2.fromArray(json.v2);
  22323. return this;
  22324. };
  22325. function LineCurve3(v1, v2) {
  22326. Curve.call(this);
  22327. this.type = 'LineCurve3';
  22328. this.v1 = v1 || new Vector3();
  22329. this.v2 = v2 || new Vector3();
  22330. }
  22331. LineCurve3.prototype = Object.create(Curve.prototype);
  22332. LineCurve3.prototype.constructor = LineCurve3;
  22333. LineCurve3.prototype.isLineCurve3 = true;
  22334. LineCurve3.prototype.getPoint = function (t, optionalTarget) {
  22335. var point = optionalTarget || new Vector3();
  22336. if (t === 1) {
  22337. point.copy(this.v2);
  22338. } else {
  22339. point.copy(this.v2).sub(this.v1);
  22340. point.multiplyScalar(t).add(this.v1);
  22341. }
  22342. return point;
  22343. }; // Line curve is linear, so we can overwrite default getPointAt
  22344. LineCurve3.prototype.getPointAt = function (u, optionalTarget) {
  22345. return this.getPoint(u, optionalTarget);
  22346. };
  22347. LineCurve3.prototype.copy = function (source) {
  22348. Curve.prototype.copy.call(this, source);
  22349. this.v1.copy(source.v1);
  22350. this.v2.copy(source.v2);
  22351. return this;
  22352. };
  22353. LineCurve3.prototype.toJSON = function () {
  22354. var data = Curve.prototype.toJSON.call(this);
  22355. data.v1 = this.v1.toArray();
  22356. data.v2 = this.v2.toArray();
  22357. return data;
  22358. };
  22359. LineCurve3.prototype.fromJSON = function (json) {
  22360. Curve.prototype.fromJSON.call(this, json);
  22361. this.v1.fromArray(json.v1);
  22362. this.v2.fromArray(json.v2);
  22363. return this;
  22364. };
  22365. function QuadraticBezierCurve(v0, v1, v2) {
  22366. Curve.call(this);
  22367. this.type = 'QuadraticBezierCurve';
  22368. this.v0 = v0 || new Vector2();
  22369. this.v1 = v1 || new Vector2();
  22370. this.v2 = v2 || new Vector2();
  22371. }
  22372. QuadraticBezierCurve.prototype = Object.create(Curve.prototype);
  22373. QuadraticBezierCurve.prototype.constructor = QuadraticBezierCurve;
  22374. QuadraticBezierCurve.prototype.isQuadraticBezierCurve = true;
  22375. QuadraticBezierCurve.prototype.getPoint = function (t, optionalTarget) {
  22376. var point = optionalTarget || new Vector2();
  22377. var v0 = this.v0,
  22378. v1 = this.v1,
  22379. v2 = this.v2;
  22380. point.set(QuadraticBezier(t, v0.x, v1.x, v2.x), QuadraticBezier(t, v0.y, v1.y, v2.y));
  22381. return point;
  22382. };
  22383. QuadraticBezierCurve.prototype.copy = function (source) {
  22384. Curve.prototype.copy.call(this, source);
  22385. this.v0.copy(source.v0);
  22386. this.v1.copy(source.v1);
  22387. this.v2.copy(source.v2);
  22388. return this;
  22389. };
  22390. QuadraticBezierCurve.prototype.toJSON = function () {
  22391. var data = Curve.prototype.toJSON.call(this);
  22392. data.v0 = this.v0.toArray();
  22393. data.v1 = this.v1.toArray();
  22394. data.v2 = this.v2.toArray();
  22395. return data;
  22396. };
  22397. QuadraticBezierCurve.prototype.fromJSON = function (json) {
  22398. Curve.prototype.fromJSON.call(this, json);
  22399. this.v0.fromArray(json.v0);
  22400. this.v1.fromArray(json.v1);
  22401. this.v2.fromArray(json.v2);
  22402. return this;
  22403. };
  22404. function QuadraticBezierCurve3(v0, v1, v2) {
  22405. Curve.call(this);
  22406. this.type = 'QuadraticBezierCurve3';
  22407. this.v0 = v0 || new Vector3();
  22408. this.v1 = v1 || new Vector3();
  22409. this.v2 = v2 || new Vector3();
  22410. }
  22411. QuadraticBezierCurve3.prototype = Object.create(Curve.prototype);
  22412. QuadraticBezierCurve3.prototype.constructor = QuadraticBezierCurve3;
  22413. QuadraticBezierCurve3.prototype.isQuadraticBezierCurve3 = true;
  22414. QuadraticBezierCurve3.prototype.getPoint = function (t, optionalTarget) {
  22415. var point = optionalTarget || new Vector3();
  22416. var v0 = this.v0,
  22417. v1 = this.v1,
  22418. v2 = this.v2;
  22419. 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));
  22420. return point;
  22421. };
  22422. QuadraticBezierCurve3.prototype.copy = function (source) {
  22423. Curve.prototype.copy.call(this, source);
  22424. this.v0.copy(source.v0);
  22425. this.v1.copy(source.v1);
  22426. this.v2.copy(source.v2);
  22427. return this;
  22428. };
  22429. QuadraticBezierCurve3.prototype.toJSON = function () {
  22430. var data = Curve.prototype.toJSON.call(this);
  22431. data.v0 = this.v0.toArray();
  22432. data.v1 = this.v1.toArray();
  22433. data.v2 = this.v2.toArray();
  22434. return data;
  22435. };
  22436. QuadraticBezierCurve3.prototype.fromJSON = function (json) {
  22437. Curve.prototype.fromJSON.call(this, json);
  22438. this.v0.fromArray(json.v0);
  22439. this.v1.fromArray(json.v1);
  22440. this.v2.fromArray(json.v2);
  22441. return this;
  22442. };
  22443. function SplineCurve(points
  22444. /* array of Vector2 */
  22445. ) {
  22446. Curve.call(this);
  22447. this.type = 'SplineCurve';
  22448. this.points = points || [];
  22449. }
  22450. SplineCurve.prototype = Object.create(Curve.prototype);
  22451. SplineCurve.prototype.constructor = SplineCurve;
  22452. SplineCurve.prototype.isSplineCurve = true;
  22453. SplineCurve.prototype.getPoint = function (t, optionalTarget) {
  22454. var point = optionalTarget || new Vector2();
  22455. var points = this.points;
  22456. var p = (points.length - 1) * t;
  22457. var intPoint = Math.floor(p);
  22458. var weight = p - intPoint;
  22459. var p0 = points[intPoint === 0 ? intPoint : intPoint - 1];
  22460. var p1 = points[intPoint];
  22461. var p2 = points[intPoint > points.length - 2 ? points.length - 1 : intPoint + 1];
  22462. var p3 = points[intPoint > points.length - 3 ? points.length - 1 : intPoint + 2];
  22463. point.set(CatmullRom(weight, p0.x, p1.x, p2.x, p3.x), CatmullRom(weight, p0.y, p1.y, p2.y, p3.y));
  22464. return point;
  22465. };
  22466. SplineCurve.prototype.copy = function (source) {
  22467. Curve.prototype.copy.call(this, source);
  22468. this.points = [];
  22469. for (var i = 0, l = source.points.length; i < l; i++) {
  22470. var point = source.points[i];
  22471. this.points.push(point.clone());
  22472. }
  22473. return this;
  22474. };
  22475. SplineCurve.prototype.toJSON = function () {
  22476. var data = Curve.prototype.toJSON.call(this);
  22477. data.points = [];
  22478. for (var i = 0, l = this.points.length; i < l; i++) {
  22479. var point = this.points[i];
  22480. data.points.push(point.toArray());
  22481. }
  22482. return data;
  22483. };
  22484. SplineCurve.prototype.fromJSON = function (json) {
  22485. Curve.prototype.fromJSON.call(this, json);
  22486. this.points = [];
  22487. for (var i = 0, l = json.points.length; i < l; i++) {
  22488. var point = json.points[i];
  22489. this.points.push(new Vector2().fromArray(point));
  22490. }
  22491. return this;
  22492. };
  22493. var Curves =
  22494. /*#__PURE__*/
  22495. Object.freeze({
  22496. ArcCurve: ArcCurve,
  22497. CatmullRomCurve3: CatmullRomCurve3,
  22498. CubicBezierCurve: CubicBezierCurve,
  22499. CubicBezierCurve3: CubicBezierCurve3,
  22500. EllipseCurve: EllipseCurve,
  22501. LineCurve: LineCurve,
  22502. LineCurve3: LineCurve3,
  22503. QuadraticBezierCurve: QuadraticBezierCurve,
  22504. QuadraticBezierCurve3: QuadraticBezierCurve3,
  22505. SplineCurve: SplineCurve
  22506. });
  22507. /**
  22508. * @author zz85 / http://www.lab4games.net/zz85/blog
  22509. *
  22510. **/
  22511. /**************************************************************
  22512. * Curved Path - a curve path is simply a array of connected
  22513. * curves, but retains the api of a curve
  22514. **************************************************************/
  22515. function CurvePath() {
  22516. Curve.call(this);
  22517. this.type = 'CurvePath';
  22518. this.curves = [];
  22519. this.autoClose = false; // Automatically closes the path
  22520. }
  22521. CurvePath.prototype = Object.assign(Object.create(Curve.prototype), {
  22522. constructor: CurvePath,
  22523. add: function (curve) {
  22524. this.curves.push(curve);
  22525. },
  22526. closePath: function () {
  22527. // Add a line curve if start and end of lines are not connected
  22528. var startPoint = this.curves[0].getPoint(0);
  22529. var endPoint = this.curves[this.curves.length - 1].getPoint(1);
  22530. if (!startPoint.equals(endPoint)) {
  22531. this.curves.push(new LineCurve(endPoint, startPoint));
  22532. }
  22533. },
  22534. // To get accurate point with reference to
  22535. // entire path distance at time t,
  22536. // following has to be done:
  22537. // 1. Length of each sub path have to be known
  22538. // 2. Locate and identify type of curve
  22539. // 3. Get t for the curve
  22540. // 4. Return curve.getPointAt(t')
  22541. getPoint: function (t) {
  22542. var d = t * this.getLength();
  22543. var curveLengths = this.getCurveLengths();
  22544. var i = 0; // To think about boundaries points.
  22545. while (i < curveLengths.length) {
  22546. if (curveLengths[i] >= d) {
  22547. var diff = curveLengths[i] - d;
  22548. var curve = this.curves[i];
  22549. var segmentLength = curve.getLength();
  22550. var u = segmentLength === 0 ? 0 : 1 - diff / segmentLength;
  22551. return curve.getPointAt(u);
  22552. }
  22553. i++;
  22554. }
  22555. return null; // loop where sum != 0, sum > d , sum+1 <d
  22556. },
  22557. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  22558. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  22559. // getPoint() depends on getLength
  22560. getLength: function () {
  22561. var lens = this.getCurveLengths();
  22562. return lens[lens.length - 1];
  22563. },
  22564. // cacheLengths must be recalculated.
  22565. updateArcLengths: function () {
  22566. this.needsUpdate = true;
  22567. this.cacheLengths = null;
  22568. this.getCurveLengths();
  22569. },
  22570. // Compute lengths and cache them
  22571. // We cannot overwrite getLengths() because UtoT mapping uses it.
  22572. getCurveLengths: function () {
  22573. // We use cache values if curves and cache array are same length
  22574. if (this.cacheLengths && this.cacheLengths.length === this.curves.length) {
  22575. return this.cacheLengths;
  22576. } // Get length of sub-curve
  22577. // Push sums into cached array
  22578. var lengths = [],
  22579. sums = 0;
  22580. for (var i = 0, l = this.curves.length; i < l; i++) {
  22581. sums += this.curves[i].getLength();
  22582. lengths.push(sums);
  22583. }
  22584. this.cacheLengths = lengths;
  22585. return lengths;
  22586. },
  22587. getSpacedPoints: function (divisions) {
  22588. if (divisions === undefined) divisions = 40;
  22589. var points = [];
  22590. for (var i = 0; i <= divisions; i++) {
  22591. points.push(this.getPoint(i / divisions));
  22592. }
  22593. if (this.autoClose) {
  22594. points.push(points[0]);
  22595. }
  22596. return points;
  22597. },
  22598. getPoints: function (divisions) {
  22599. divisions = divisions || 12;
  22600. var points = [],
  22601. last;
  22602. for (var i = 0, curves = this.curves; i < curves.length; i++) {
  22603. var curve = curves[i];
  22604. var resolution = curve && curve.isEllipseCurve ? divisions * 2 : curve && (curve.isLineCurve || curve.isLineCurve3) ? 1 : curve && curve.isSplineCurve ? divisions * curve.points.length : divisions;
  22605. var pts = curve.getPoints(resolution);
  22606. for (var j = 0; j < pts.length; j++) {
  22607. var point = pts[j];
  22608. if (last && last.equals(point)) continue; // ensures no consecutive points are duplicates
  22609. points.push(point);
  22610. last = point;
  22611. }
  22612. }
  22613. if (this.autoClose && points.length > 1 && !points[points.length - 1].equals(points[0])) {
  22614. points.push(points[0]);
  22615. }
  22616. return points;
  22617. },
  22618. copy: function (source) {
  22619. Curve.prototype.copy.call(this, source);
  22620. this.curves = [];
  22621. for (var i = 0, l = source.curves.length; i < l; i++) {
  22622. var curve = source.curves[i];
  22623. this.curves.push(curve.clone());
  22624. }
  22625. this.autoClose = source.autoClose;
  22626. return this;
  22627. },
  22628. toJSON: function () {
  22629. var data = Curve.prototype.toJSON.call(this);
  22630. data.autoClose = this.autoClose;
  22631. data.curves = [];
  22632. for (var i = 0, l = this.curves.length; i < l; i++) {
  22633. var curve = this.curves[i];
  22634. data.curves.push(curve.toJSON());
  22635. }
  22636. return data;
  22637. },
  22638. fromJSON: function (json) {
  22639. Curve.prototype.fromJSON.call(this, json);
  22640. this.autoClose = json.autoClose;
  22641. this.curves = [];
  22642. for (var i = 0, l = json.curves.length; i < l; i++) {
  22643. var curve = json.curves[i];
  22644. this.curves.push(new Curves[curve.type]().fromJSON(curve));
  22645. }
  22646. return this;
  22647. }
  22648. });
  22649. /**
  22650. * @author zz85 / http://www.lab4games.net/zz85/blog
  22651. * Creates free form 2d path using series of points, lines or curves.
  22652. **/
  22653. function Path(points) {
  22654. CurvePath.call(this);
  22655. this.type = 'Path';
  22656. this.currentPoint = new Vector2();
  22657. if (points) {
  22658. this.setFromPoints(points);
  22659. }
  22660. }
  22661. Path.prototype = Object.assign(Object.create(CurvePath.prototype), {
  22662. constructor: Path,
  22663. setFromPoints: function (points) {
  22664. this.moveTo(points[0].x, points[0].y);
  22665. for (var i = 1, l = points.length; i < l; i++) {
  22666. this.lineTo(points[i].x, points[i].y);
  22667. }
  22668. },
  22669. moveTo: function (x, y) {
  22670. this.currentPoint.set(x, y); // TODO consider referencing vectors instead of copying?
  22671. },
  22672. lineTo: function (x, y) {
  22673. var curve = new LineCurve(this.currentPoint.clone(), new Vector2(x, y));
  22674. this.curves.push(curve);
  22675. this.currentPoint.set(x, y);
  22676. },
  22677. quadraticCurveTo: function (aCPx, aCPy, aX, aY) {
  22678. var curve = new QuadraticBezierCurve(this.currentPoint.clone(), new Vector2(aCPx, aCPy), new Vector2(aX, aY));
  22679. this.curves.push(curve);
  22680. this.currentPoint.set(aX, aY);
  22681. },
  22682. bezierCurveTo: function (aCP1x, aCP1y, aCP2x, aCP2y, aX, aY) {
  22683. var curve = new CubicBezierCurve(this.currentPoint.clone(), new Vector2(aCP1x, aCP1y), new Vector2(aCP2x, aCP2y), new Vector2(aX, aY));
  22684. this.curves.push(curve);
  22685. this.currentPoint.set(aX, aY);
  22686. },
  22687. splineThru: function (pts
  22688. /*Array of Vector*/
  22689. ) {
  22690. var npts = [this.currentPoint.clone()].concat(pts);
  22691. var curve = new SplineCurve(npts);
  22692. this.curves.push(curve);
  22693. this.currentPoint.copy(pts[pts.length - 1]);
  22694. },
  22695. arc: function (aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise) {
  22696. var x0 = this.currentPoint.x;
  22697. var y0 = this.currentPoint.y;
  22698. this.absarc(aX + x0, aY + y0, aRadius, aStartAngle, aEndAngle, aClockwise);
  22699. },
  22700. absarc: function (aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise) {
  22701. this.absellipse(aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise);
  22702. },
  22703. ellipse: function (aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation) {
  22704. var x0 = this.currentPoint.x;
  22705. var y0 = this.currentPoint.y;
  22706. this.absellipse(aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation);
  22707. },
  22708. absellipse: function (aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation) {
  22709. var curve = new EllipseCurve(aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation);
  22710. if (this.curves.length > 0) {
  22711. // if a previous curve is present, attempt to join
  22712. var firstPoint = curve.getPoint(0);
  22713. if (!firstPoint.equals(this.currentPoint)) {
  22714. this.lineTo(firstPoint.x, firstPoint.y);
  22715. }
  22716. }
  22717. this.curves.push(curve);
  22718. var lastPoint = curve.getPoint(1);
  22719. this.currentPoint.copy(lastPoint);
  22720. },
  22721. copy: function (source) {
  22722. CurvePath.prototype.copy.call(this, source);
  22723. this.currentPoint.copy(source.currentPoint);
  22724. return this;
  22725. },
  22726. toJSON: function () {
  22727. var data = CurvePath.prototype.toJSON.call(this);
  22728. data.currentPoint = this.currentPoint.toArray();
  22729. return data;
  22730. },
  22731. fromJSON: function (json) {
  22732. CurvePath.prototype.fromJSON.call(this, json);
  22733. this.currentPoint.fromArray(json.currentPoint);
  22734. return this;
  22735. }
  22736. });
  22737. /**
  22738. * @author zz85 / http://www.lab4games.net/zz85/blog
  22739. * Defines a 2d shape plane using paths.
  22740. **/
  22741. // STEP 1 Create a path.
  22742. // STEP 2 Turn path into shape.
  22743. // STEP 3 ExtrudeGeometry takes in Shape/Shapes
  22744. // STEP 3a - Extract points from each shape, turn to vertices
  22745. // STEP 3b - Triangulate each shape, add faces.
  22746. function Shape(points) {
  22747. Path.call(this, points);
  22748. this.uuid = _Math.generateUUID();
  22749. this.type = 'Shape';
  22750. this.holes = [];
  22751. }
  22752. Shape.prototype = Object.assign(Object.create(Path.prototype), {
  22753. constructor: Shape,
  22754. getPointsHoles: function (divisions) {
  22755. var holesPts = [];
  22756. for (var i = 0, l = this.holes.length; i < l; i++) {
  22757. holesPts[i] = this.holes[i].getPoints(divisions);
  22758. }
  22759. return holesPts;
  22760. },
  22761. // get points of shape and holes (keypoints based on segments parameter)
  22762. extractPoints: function (divisions) {
  22763. return {
  22764. shape: this.getPoints(divisions),
  22765. holes: this.getPointsHoles(divisions)
  22766. };
  22767. },
  22768. copy: function (source) {
  22769. Path.prototype.copy.call(this, source);
  22770. this.holes = [];
  22771. for (var i = 0, l = source.holes.length; i < l; i++) {
  22772. var hole = source.holes[i];
  22773. this.holes.push(hole.clone());
  22774. }
  22775. return this;
  22776. },
  22777. toJSON: function () {
  22778. var data = Path.prototype.toJSON.call(this);
  22779. data.uuid = this.uuid;
  22780. data.holes = [];
  22781. for (var i = 0, l = this.holes.length; i < l; i++) {
  22782. var hole = this.holes[i];
  22783. data.holes.push(hole.toJSON());
  22784. }
  22785. return data;
  22786. },
  22787. fromJSON: function (json) {
  22788. Path.prototype.fromJSON.call(this, json);
  22789. this.uuid = json.uuid;
  22790. this.holes = [];
  22791. for (var i = 0, l = json.holes.length; i < l; i++) {
  22792. var hole = json.holes[i];
  22793. this.holes.push(new Path().fromJSON(hole));
  22794. }
  22795. return this;
  22796. }
  22797. });
  22798. /**
  22799. * @author mrdoob / http://mrdoob.com/
  22800. * @author alteredq / http://alteredqualia.com/
  22801. */
  22802. function Light(color, intensity) {
  22803. Object3D.call(this);
  22804. this.type = 'Light';
  22805. this.color = new Color(color);
  22806. this.intensity = intensity !== undefined ? intensity : 1;
  22807. this.receiveShadow = undefined;
  22808. }
  22809. Light.prototype = Object.assign(Object.create(Object3D.prototype), {
  22810. constructor: Light,
  22811. isLight: true,
  22812. copy: function (source) {
  22813. Object3D.prototype.copy.call(this, source);
  22814. this.color.copy(source.color);
  22815. this.intensity = source.intensity;
  22816. return this;
  22817. },
  22818. toJSON: function (meta) {
  22819. var data = Object3D.prototype.toJSON.call(this, meta);
  22820. data.object.color = this.color.getHex();
  22821. data.object.intensity = this.intensity;
  22822. if (this.groundColor !== undefined) data.object.groundColor = this.groundColor.getHex();
  22823. if (this.distance !== undefined) data.object.distance = this.distance;
  22824. if (this.angle !== undefined) data.object.angle = this.angle;
  22825. if (this.decay !== undefined) data.object.decay = this.decay;
  22826. if (this.penumbra !== undefined) data.object.penumbra = this.penumbra;
  22827. if (this.shadow !== undefined) data.object.shadow = this.shadow.toJSON();
  22828. return data;
  22829. }
  22830. });
  22831. /**
  22832. * @author alteredq / http://alteredqualia.com/
  22833. */
  22834. function HemisphereLight(skyColor, groundColor, intensity) {
  22835. Light.call(this, skyColor, intensity);
  22836. this.type = 'HemisphereLight';
  22837. this.castShadow = undefined;
  22838. this.position.copy(Object3D.DefaultUp);
  22839. this.updateMatrix();
  22840. this.groundColor = new Color(groundColor);
  22841. }
  22842. HemisphereLight.prototype = Object.assign(Object.create(Light.prototype), {
  22843. constructor: HemisphereLight,
  22844. isHemisphereLight: true,
  22845. copy: function (source) {
  22846. Light.prototype.copy.call(this, source);
  22847. this.groundColor.copy(source.groundColor);
  22848. return this;
  22849. }
  22850. });
  22851. /**
  22852. * @author mrdoob / http://mrdoob.com/
  22853. */
  22854. function LightShadow(camera) {
  22855. this.camera = camera;
  22856. this.bias = 0;
  22857. this.radius = 1;
  22858. this.mapSize = new Vector2(512, 512);
  22859. this.map = null;
  22860. this.mapPass = null;
  22861. this.matrix = new Matrix4();
  22862. this._frustum = new Frustum();
  22863. this._frameExtents = new Vector2(1, 1);
  22864. this._viewportCount = 1;
  22865. this._viewports = [new Vector4(0, 0, 1, 1)];
  22866. }
  22867. Object.assign(LightShadow.prototype, {
  22868. _projScreenMatrix: new Matrix4(),
  22869. _lightPositionWorld: new Vector3(),
  22870. _lookTarget: new Vector3(),
  22871. getViewportCount: function () {
  22872. return this._viewportCount;
  22873. },
  22874. getFrustum: function () {
  22875. return this._frustum;
  22876. },
  22877. updateMatrices: function (light) {
  22878. var shadowCamera = this.camera,
  22879. shadowMatrix = this.matrix,
  22880. projScreenMatrix = this._projScreenMatrix,
  22881. lookTarget = this._lookTarget,
  22882. lightPositionWorld = this._lightPositionWorld;
  22883. lightPositionWorld.setFromMatrixPosition(light.matrixWorld);
  22884. shadowCamera.position.copy(lightPositionWorld);
  22885. lookTarget.setFromMatrixPosition(light.target.matrixWorld);
  22886. shadowCamera.lookAt(lookTarget);
  22887. shadowCamera.updateMatrixWorld();
  22888. projScreenMatrix.multiplyMatrices(shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse);
  22889. this._frustum.setFromMatrix(projScreenMatrix);
  22890. 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);
  22891. shadowMatrix.multiply(shadowCamera.projectionMatrix);
  22892. shadowMatrix.multiply(shadowCamera.matrixWorldInverse);
  22893. },
  22894. getViewport: function (viewportIndex) {
  22895. return this._viewports[viewportIndex];
  22896. },
  22897. getFrameExtents: function () {
  22898. return this._frameExtents;
  22899. },
  22900. copy: function (source) {
  22901. this.camera = source.camera.clone();
  22902. this.bias = source.bias;
  22903. this.radius = source.radius;
  22904. this.mapSize.copy(source.mapSize);
  22905. return this;
  22906. },
  22907. clone: function () {
  22908. return new this.constructor().copy(this);
  22909. },
  22910. toJSON: function () {
  22911. var object = {};
  22912. if (this.bias !== 0) object.bias = this.bias;
  22913. if (this.radius !== 1) object.radius = this.radius;
  22914. if (this.mapSize.x !== 512 || this.mapSize.y !== 512) object.mapSize = this.mapSize.toArray();
  22915. object.camera = this.camera.toJSON(false).object;
  22916. delete object.camera.matrix;
  22917. return object;
  22918. }
  22919. });
  22920. /**
  22921. * @author mrdoob / http://mrdoob.com/
  22922. */
  22923. function SpotLightShadow() {
  22924. LightShadow.call(this, new PerspectiveCamera(50, 1, 0.5, 500));
  22925. }
  22926. SpotLightShadow.prototype = Object.assign(Object.create(LightShadow.prototype), {
  22927. constructor: SpotLightShadow,
  22928. isSpotLightShadow: true,
  22929. updateMatrices: function (light, viewCamera, viewportIndex) {
  22930. var camera = this.camera;
  22931. var fov = _Math.RAD2DEG * 2 * light.angle;
  22932. var aspect = this.mapSize.width / this.mapSize.height;
  22933. var far = light.distance || camera.far;
  22934. if (fov !== camera.fov || aspect !== camera.aspect || far !== camera.far) {
  22935. camera.fov = fov;
  22936. camera.aspect = aspect;
  22937. camera.far = far;
  22938. camera.updateProjectionMatrix();
  22939. }
  22940. LightShadow.prototype.updateMatrices.call(this, light, viewCamera, viewportIndex);
  22941. }
  22942. });
  22943. /**
  22944. * @author alteredq / http://alteredqualia.com/
  22945. */
  22946. function SpotLight(color, intensity, distance, angle, penumbra, decay) {
  22947. Light.call(this, color, intensity);
  22948. this.type = 'SpotLight';
  22949. this.position.copy(Object3D.DefaultUp);
  22950. this.updateMatrix();
  22951. this.target = new Object3D();
  22952. Object.defineProperty(this, 'power', {
  22953. get: function () {
  22954. // intensity = power per solid angle.
  22955. // ref: equation (17) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  22956. return this.intensity * Math.PI;
  22957. },
  22958. set: function (power) {
  22959. // intensity = power per solid angle.
  22960. // ref: equation (17) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  22961. this.intensity = power / Math.PI;
  22962. }
  22963. });
  22964. this.distance = distance !== undefined ? distance : 0;
  22965. this.angle = angle !== undefined ? angle : Math.PI / 3;
  22966. this.penumbra = penumbra !== undefined ? penumbra : 0;
  22967. this.decay = decay !== undefined ? decay : 1; // for physically correct lights, should be 2.
  22968. this.shadow = new SpotLightShadow();
  22969. }
  22970. SpotLight.prototype = Object.assign(Object.create(Light.prototype), {
  22971. constructor: SpotLight,
  22972. isSpotLight: true,
  22973. copy: function (source) {
  22974. Light.prototype.copy.call(this, source);
  22975. this.distance = source.distance;
  22976. this.angle = source.angle;
  22977. this.penumbra = source.penumbra;
  22978. this.decay = source.decay;
  22979. this.target = source.target.clone();
  22980. this.shadow = source.shadow.clone();
  22981. return this;
  22982. }
  22983. });
  22984. function PointLightShadow() {
  22985. LightShadow.call(this, new PerspectiveCamera(90, 1, 0.5, 500));
  22986. this._frameExtents = new Vector2(4, 2);
  22987. this._viewportCount = 6;
  22988. this._viewports = [// These viewports map a cube-map onto a 2D texture with the
  22989. // following orientation:
  22990. //
  22991. // xzXZ
  22992. // y Y
  22993. //
  22994. // X - Positive x direction
  22995. // x - Negative x direction
  22996. // Y - Positive y direction
  22997. // y - Negative y direction
  22998. // Z - Positive z direction
  22999. // z - Negative z direction
  23000. // positive X
  23001. new Vector4(2, 1, 1, 1), // negative X
  23002. new Vector4(0, 1, 1, 1), // positive Z
  23003. new Vector4(3, 1, 1, 1), // negative Z
  23004. new Vector4(1, 1, 1, 1), // positive Y
  23005. new Vector4(3, 0, 1, 1), // negative Y
  23006. new Vector4(1, 0, 1, 1)];
  23007. 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)];
  23008. 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)];
  23009. }
  23010. PointLightShadow.prototype = Object.assign(Object.create(LightShadow.prototype), {
  23011. constructor: PointLightShadow,
  23012. isPointLightShadow: true,
  23013. updateMatrices: function (light, viewCamera, viewportIndex) {
  23014. var camera = this.camera,
  23015. shadowMatrix = this.matrix,
  23016. lightPositionWorld = this._lightPositionWorld,
  23017. lookTarget = this._lookTarget,
  23018. projScreenMatrix = this._projScreenMatrix;
  23019. lightPositionWorld.setFromMatrixPosition(light.matrixWorld);
  23020. camera.position.copy(lightPositionWorld);
  23021. lookTarget.copy(camera.position);
  23022. lookTarget.add(this._cubeDirections[viewportIndex]);
  23023. camera.up.copy(this._cubeUps[viewportIndex]);
  23024. camera.lookAt(lookTarget);
  23025. camera.updateMatrixWorld();
  23026. shadowMatrix.makeTranslation(-lightPositionWorld.x, -lightPositionWorld.y, -lightPositionWorld.z);
  23027. projScreenMatrix.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse);
  23028. this._frustum.setFromMatrix(projScreenMatrix);
  23029. }
  23030. });
  23031. /**
  23032. * @author mrdoob / http://mrdoob.com/
  23033. */
  23034. function PointLight(color, intensity, distance, decay) {
  23035. Light.call(this, color, intensity);
  23036. this.type = 'PointLight';
  23037. Object.defineProperty(this, 'power', {
  23038. get: function () {
  23039. // intensity = power per solid angle.
  23040. // ref: equation (15) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  23041. return this.intensity * 4 * Math.PI;
  23042. },
  23043. set: function (power) {
  23044. // intensity = power per solid angle.
  23045. // ref: equation (15) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  23046. this.intensity = power / (4 * Math.PI);
  23047. }
  23048. });
  23049. this.distance = distance !== undefined ? distance : 0;
  23050. this.decay = decay !== undefined ? decay : 1; // for physically correct lights, should be 2.
  23051. this.shadow = new PointLightShadow();
  23052. }
  23053. PointLight.prototype = Object.assign(Object.create(Light.prototype), {
  23054. constructor: PointLight,
  23055. isPointLight: true,
  23056. copy: function (source) {
  23057. Light.prototype.copy.call(this, source);
  23058. this.distance = source.distance;
  23059. this.decay = source.decay;
  23060. this.shadow = source.shadow.clone();
  23061. return this;
  23062. }
  23063. });
  23064. /**
  23065. * @author alteredq / http://alteredqualia.com/
  23066. * @author arose / http://github.com/arose
  23067. */
  23068. function OrthographicCamera(left, right, top, bottom, near, far) {
  23069. Camera.call(this);
  23070. this.type = 'OrthographicCamera';
  23071. this.zoom = 1;
  23072. this.view = null;
  23073. this.left = left !== undefined ? left : -1;
  23074. this.right = right !== undefined ? right : 1;
  23075. this.top = top !== undefined ? top : 1;
  23076. this.bottom = bottom !== undefined ? bottom : -1;
  23077. this.near = near !== undefined ? near : 0.1;
  23078. this.far = far !== undefined ? far : 2000;
  23079. this.updateProjectionMatrix();
  23080. }
  23081. OrthographicCamera.prototype = Object.assign(Object.create(Camera.prototype), {
  23082. constructor: OrthographicCamera,
  23083. isOrthographicCamera: true,
  23084. copy: function (source, recursive) {
  23085. Camera.prototype.copy.call(this, source, recursive);
  23086. this.left = source.left;
  23087. this.right = source.right;
  23088. this.top = source.top;
  23089. this.bottom = source.bottom;
  23090. this.near = source.near;
  23091. this.far = source.far;
  23092. this.zoom = source.zoom;
  23093. this.view = source.view === null ? null : Object.assign({}, source.view);
  23094. return this;
  23095. },
  23096. setViewOffset: function (fullWidth, fullHeight, x, y, width, height) {
  23097. if (this.view === null) {
  23098. this.view = {
  23099. enabled: true,
  23100. fullWidth: 1,
  23101. fullHeight: 1,
  23102. offsetX: 0,
  23103. offsetY: 0,
  23104. width: 1,
  23105. height: 1
  23106. };
  23107. }
  23108. this.view.enabled = true;
  23109. this.view.fullWidth = fullWidth;
  23110. this.view.fullHeight = fullHeight;
  23111. this.view.offsetX = x;
  23112. this.view.offsetY = y;
  23113. this.view.width = width;
  23114. this.view.height = height;
  23115. this.updateProjectionMatrix();
  23116. },
  23117. clearViewOffset: function () {
  23118. if (this.view !== null) {
  23119. this.view.enabled = false;
  23120. }
  23121. this.updateProjectionMatrix();
  23122. },
  23123. updateProjectionMatrix: function () {
  23124. var dx = (this.right - this.left) / (2 * this.zoom);
  23125. var dy = (this.top - this.bottom) / (2 * this.zoom);
  23126. var cx = (this.right + this.left) / 2;
  23127. var cy = (this.top + this.bottom) / 2;
  23128. var left = cx - dx;
  23129. var right = cx + dx;
  23130. var top = cy + dy;
  23131. var bottom = cy - dy;
  23132. if (this.view !== null && this.view.enabled) {
  23133. var zoomW = this.zoom / (this.view.width / this.view.fullWidth);
  23134. var zoomH = this.zoom / (this.view.height / this.view.fullHeight);
  23135. var scaleW = (this.right - this.left) / this.view.width;
  23136. var scaleH = (this.top - this.bottom) / this.view.height;
  23137. left += scaleW * (this.view.offsetX / zoomW);
  23138. right = left + scaleW * (this.view.width / zoomW);
  23139. top -= scaleH * (this.view.offsetY / zoomH);
  23140. bottom = top - scaleH * (this.view.height / zoomH);
  23141. }
  23142. this.projectionMatrix.makeOrthographic(left, right, top, bottom, this.near, this.far);
  23143. this.projectionMatrixInverse.getInverse(this.projectionMatrix);
  23144. },
  23145. toJSON: function (meta) {
  23146. var data = Object3D.prototype.toJSON.call(this, meta);
  23147. data.object.zoom = this.zoom;
  23148. data.object.left = this.left;
  23149. data.object.right = this.right;
  23150. data.object.top = this.top;
  23151. data.object.bottom = this.bottom;
  23152. data.object.near = this.near;
  23153. data.object.far = this.far;
  23154. if (this.view !== null) data.object.view = Object.assign({}, this.view);
  23155. return data;
  23156. }
  23157. });
  23158. /**
  23159. * @author mrdoob / http://mrdoob.com/
  23160. */
  23161. function DirectionalLightShadow() {
  23162. LightShadow.call(this, new OrthographicCamera(-5, 5, 5, -5, 0.5, 500));
  23163. }
  23164. DirectionalLightShadow.prototype = Object.assign(Object.create(LightShadow.prototype), {
  23165. constructor: DirectionalLightShadow,
  23166. isDirectionalLightShadow: true,
  23167. updateMatrices: function (light, viewCamera, viewportIndex) {
  23168. LightShadow.prototype.updateMatrices.call(this, light, viewCamera, viewportIndex);
  23169. }
  23170. });
  23171. /**
  23172. * @author mrdoob / http://mrdoob.com/
  23173. * @author alteredq / http://alteredqualia.com/
  23174. */
  23175. function DirectionalLight(color, intensity) {
  23176. Light.call(this, color, intensity);
  23177. this.type = 'DirectionalLight';
  23178. this.position.copy(Object3D.DefaultUp);
  23179. this.updateMatrix();
  23180. this.target = new Object3D();
  23181. this.shadow = new DirectionalLightShadow();
  23182. }
  23183. DirectionalLight.prototype = Object.assign(Object.create(Light.prototype), {
  23184. constructor: DirectionalLight,
  23185. isDirectionalLight: true,
  23186. copy: function (source) {
  23187. Light.prototype.copy.call(this, source);
  23188. this.target = source.target.clone();
  23189. this.shadow = source.shadow.clone();
  23190. return this;
  23191. }
  23192. });
  23193. /**
  23194. * @author mrdoob / http://mrdoob.com/
  23195. */
  23196. function AmbientLight(color, intensity) {
  23197. Light.call(this, color, intensity);
  23198. this.type = 'AmbientLight';
  23199. this.castShadow = undefined;
  23200. }
  23201. AmbientLight.prototype = Object.assign(Object.create(Light.prototype), {
  23202. constructor: AmbientLight,
  23203. isAmbientLight: true
  23204. });
  23205. /**
  23206. * @author abelnation / http://github.com/abelnation
  23207. */
  23208. function RectAreaLight(color, intensity, width, height) {
  23209. Light.call(this, color, intensity);
  23210. this.type = 'RectAreaLight';
  23211. this.width = width !== undefined ? width : 10;
  23212. this.height = height !== undefined ? height : 10;
  23213. }
  23214. RectAreaLight.prototype = Object.assign(Object.create(Light.prototype), {
  23215. constructor: RectAreaLight,
  23216. isRectAreaLight: true,
  23217. copy: function (source) {
  23218. Light.prototype.copy.call(this, source);
  23219. this.width = source.width;
  23220. this.height = source.height;
  23221. return this;
  23222. },
  23223. toJSON: function (meta) {
  23224. var data = Light.prototype.toJSON.call(this, meta);
  23225. data.object.width = this.width;
  23226. data.object.height = this.height;
  23227. return data;
  23228. }
  23229. });
  23230. /**
  23231. * @author mrdoob / http://mrdoob.com/
  23232. */
  23233. function MaterialLoader(manager) {
  23234. Loader.call(this, manager);
  23235. this.textures = {};
  23236. }
  23237. MaterialLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  23238. constructor: MaterialLoader,
  23239. load: function (url, onLoad, onProgress, onError) {
  23240. var scope = this;
  23241. var loader = new FileLoader(scope.manager);
  23242. loader.setPath(scope.path);
  23243. loader.load(url, function (text) {
  23244. onLoad(scope.parse(JSON.parse(text)));
  23245. }, onProgress, onError);
  23246. },
  23247. parse: function (json) {
  23248. var textures = this.textures;
  23249. function getTexture(name) {
  23250. if (textures[name] === undefined) {
  23251. console.warn('THREE.MaterialLoader: Undefined texture', name);
  23252. }
  23253. return textures[name];
  23254. }
  23255. var material = new Materials[json.type]();
  23256. if (json.uuid !== undefined) material.uuid = json.uuid;
  23257. if (json.name !== undefined) material.name = json.name;
  23258. if (json.color !== undefined) material.color.setHex(json.color);
  23259. if (json.roughness !== undefined) material.roughness = json.roughness;
  23260. if (json.metalness !== undefined) material.metalness = json.metalness;
  23261. if (json.sheen !== undefined) material.sheen = new Color().setHex(json.sheen);
  23262. if (json.emissive !== undefined) material.emissive.setHex(json.emissive);
  23263. if (json.specular !== undefined) material.specular.setHex(json.specular);
  23264. if (json.shininess !== undefined) material.shininess = json.shininess;
  23265. if (json.clearcoat !== undefined) material.clearcoat = json.clearcoat;
  23266. if (json.clearcoatRoughness !== undefined) material.clearcoatRoughness = json.clearcoatRoughness;
  23267. if (json.vertexColors !== undefined) material.vertexColors = json.vertexColors;
  23268. if (json.fog !== undefined) material.fog = json.fog;
  23269. if (json.flatShading !== undefined) material.flatShading = json.flatShading;
  23270. if (json.blending !== undefined) material.blending = json.blending;
  23271. if (json.combine !== undefined) material.combine = json.combine;
  23272. if (json.side !== undefined) material.side = json.side;
  23273. if (json.opacity !== undefined) material.opacity = json.opacity;
  23274. if (json.transparent !== undefined) material.transparent = json.transparent;
  23275. if (json.alphaTest !== undefined) material.alphaTest = json.alphaTest;
  23276. if (json.depthTest !== undefined) material.depthTest = json.depthTest;
  23277. if (json.depthWrite !== undefined) material.depthWrite = json.depthWrite;
  23278. if (json.colorWrite !== undefined) material.colorWrite = json.colorWrite;
  23279. if (json.stencilWrite !== undefined) material.stencilWrite = json.stencilWrite;
  23280. if (json.stencilWriteMask !== undefined) material.stencilWriteMask = json.stencilWriteMask;
  23281. if (json.stencilFunc !== undefined) material.stencilFunc = json.stencilFunc;
  23282. if (json.stencilRef !== undefined) material.stencilRef = json.stencilRef;
  23283. if (json.stencilFuncMask !== undefined) material.stencilFuncMask = json.stencilFuncMask;
  23284. if (json.stencilFail !== undefined) material.stencilFail = json.stencilFail;
  23285. if (json.stencilZFail !== undefined) material.stencilZFail = json.stencilZFail;
  23286. if (json.stencilZPass !== undefined) material.stencilZPass = json.stencilZPass;
  23287. if (json.wireframe !== undefined) material.wireframe = json.wireframe;
  23288. if (json.wireframeLinewidth !== undefined) material.wireframeLinewidth = json.wireframeLinewidth;
  23289. if (json.wireframeLinecap !== undefined) material.wireframeLinecap = json.wireframeLinecap;
  23290. if (json.wireframeLinejoin !== undefined) material.wireframeLinejoin = json.wireframeLinejoin;
  23291. if (json.rotation !== undefined) material.rotation = json.rotation;
  23292. if (json.linewidth !== 1) material.linewidth = json.linewidth;
  23293. if (json.dashSize !== undefined) material.dashSize = json.dashSize;
  23294. if (json.gapSize !== undefined) material.gapSize = json.gapSize;
  23295. if (json.scale !== undefined) material.scale = json.scale;
  23296. if (json.polygonOffset !== undefined) material.polygonOffset = json.polygonOffset;
  23297. if (json.polygonOffsetFactor !== undefined) material.polygonOffsetFactor = json.polygonOffsetFactor;
  23298. if (json.polygonOffsetUnits !== undefined) material.polygonOffsetUnits = json.polygonOffsetUnits;
  23299. if (json.skinning !== undefined) material.skinning = json.skinning;
  23300. if (json.morphTargets !== undefined) material.morphTargets = json.morphTargets;
  23301. if (json.morphNormals !== undefined) material.morphNormals = json.morphNormals;
  23302. if (json.dithering !== undefined) material.dithering = json.dithering;
  23303. if (json.visible !== undefined) material.visible = json.visible;
  23304. if (json.toneMapped !== undefined) material.toneMapped = json.toneMapped;
  23305. if (json.userData !== undefined) material.userData = json.userData; // Shader Material
  23306. if (json.uniforms !== undefined) {
  23307. for (var name in json.uniforms) {
  23308. var uniform = json.uniforms[name];
  23309. material.uniforms[name] = {};
  23310. switch (uniform.type) {
  23311. case 't':
  23312. material.uniforms[name].value = getTexture(uniform.value);
  23313. break;
  23314. case 'c':
  23315. material.uniforms[name].value = new Color().setHex(uniform.value);
  23316. break;
  23317. case 'v2':
  23318. material.uniforms[name].value = new Vector2().fromArray(uniform.value);
  23319. break;
  23320. case 'v3':
  23321. material.uniforms[name].value = new Vector3().fromArray(uniform.value);
  23322. break;
  23323. case 'v4':
  23324. material.uniforms[name].value = new Vector4().fromArray(uniform.value);
  23325. break;
  23326. case 'm3':
  23327. material.uniforms[name].value = new Matrix3().fromArray(uniform.value);
  23328. case 'm4':
  23329. material.uniforms[name].value = new Matrix4().fromArray(uniform.value);
  23330. break;
  23331. default:
  23332. material.uniforms[name].value = uniform.value;
  23333. }
  23334. }
  23335. }
  23336. if (json.defines !== undefined) material.defines = json.defines;
  23337. if (json.vertexShader !== undefined) material.vertexShader = json.vertexShader;
  23338. if (json.fragmentShader !== undefined) material.fragmentShader = json.fragmentShader;
  23339. if (json.extensions !== undefined) {
  23340. for (var key in json.extensions) {
  23341. material.extensions[key] = json.extensions[key];
  23342. }
  23343. } // Deprecated
  23344. if (json.shading !== undefined) material.flatShading = json.shading === 1; // THREE.FlatShading
  23345. // for PointsMaterial
  23346. if (json.size !== undefined) material.size = json.size;
  23347. if (json.sizeAttenuation !== undefined) material.sizeAttenuation = json.sizeAttenuation; // maps
  23348. if (json.map !== undefined) material.map = getTexture(json.map);
  23349. if (json.matcap !== undefined) material.matcap = getTexture(json.matcap);
  23350. if (json.alphaMap !== undefined) {
  23351. material.alphaMap = getTexture(json.alphaMap);
  23352. material.transparent = true;
  23353. }
  23354. if (json.bumpMap !== undefined) material.bumpMap = getTexture(json.bumpMap);
  23355. if (json.bumpScale !== undefined) material.bumpScale = json.bumpScale;
  23356. if (json.normalMap !== undefined) material.normalMap = getTexture(json.normalMap);
  23357. if (json.normalMapType !== undefined) material.normalMapType = json.normalMapType;
  23358. if (json.normalScale !== undefined) {
  23359. var normalScale = json.normalScale;
  23360. if (Array.isArray(normalScale) === false) {
  23361. // Blender exporter used to export a scalar. See #7459
  23362. normalScale = [normalScale, normalScale];
  23363. }
  23364. material.normalScale = new Vector2().fromArray(normalScale);
  23365. }
  23366. if (json.displacementMap !== undefined) material.displacementMap = getTexture(json.displacementMap);
  23367. if (json.displacementScale !== undefined) material.displacementScale = json.displacementScale;
  23368. if (json.displacementBias !== undefined) material.displacementBias = json.displacementBias;
  23369. if (json.roughnessMap !== undefined) material.roughnessMap = getTexture(json.roughnessMap);
  23370. if (json.metalnessMap !== undefined) material.metalnessMap = getTexture(json.metalnessMap);
  23371. if (json.emissiveMap !== undefined) material.emissiveMap = getTexture(json.emissiveMap);
  23372. if (json.emissiveIntensity !== undefined) material.emissiveIntensity = json.emissiveIntensity;
  23373. if (json.specularMap !== undefined) material.specularMap = getTexture(json.specularMap);
  23374. if (json.envMap !== undefined) material.envMap = getTexture(json.envMap);
  23375. if (json.envMapIntensity !== undefined) material.envMapIntensity = json.envMapIntensity;
  23376. if (json.reflectivity !== undefined) material.reflectivity = json.reflectivity;
  23377. if (json.refractionRatio !== undefined) material.refractionRatio = json.refractionRatio;
  23378. if (json.lightMap !== undefined) material.lightMap = getTexture(json.lightMap);
  23379. if (json.lightMapIntensity !== undefined) material.lightMapIntensity = json.lightMapIntensity;
  23380. if (json.aoMap !== undefined) material.aoMap = getTexture(json.aoMap);
  23381. if (json.aoMapIntensity !== undefined) material.aoMapIntensity = json.aoMapIntensity;
  23382. if (json.gradientMap !== undefined) material.gradientMap = getTexture(json.gradientMap);
  23383. if (json.clearcoatNormalMap !== undefined) material.clearcoatNormalMap = getTexture(json.clearcoatNormalMap);
  23384. if (json.clearcoatNormalScale !== undefined) material.clearcoatNormalScale = new Vector2().fromArray(json.clearcoatNormalScale);
  23385. return material;
  23386. },
  23387. setTextures: function (value) {
  23388. this.textures = value;
  23389. return this;
  23390. }
  23391. });
  23392. /**
  23393. * @author Don McCurdy / https://www.donmccurdy.com
  23394. */
  23395. var LoaderUtils = {
  23396. decodeText: function (array) {
  23397. if (typeof TextDecoder !== 'undefined') {
  23398. return new TextDecoder().decode(array);
  23399. } // Avoid the String.fromCharCode.apply(null, array) shortcut, which
  23400. // throws a "maximum call stack size exceeded" error for large arrays.
  23401. var s = '';
  23402. for (var i = 0, il = array.length; i < il; i++) {
  23403. // Implicitly assumes little-endian.
  23404. s += String.fromCharCode(array[i]);
  23405. }
  23406. try {
  23407. // merges multi-byte utf-8 characters.
  23408. return decodeURIComponent(escape(s));
  23409. } catch (e) {
  23410. // see #16358
  23411. return s;
  23412. }
  23413. },
  23414. extractUrlBase: function (url) {
  23415. var index = url.lastIndexOf('/');
  23416. if (index === -1) return './';
  23417. return url.substr(0, index + 1);
  23418. }
  23419. };
  23420. /**
  23421. * @author benaadams / https://twitter.com/ben_a_adams
  23422. */
  23423. exports.LoaderUtils = LoaderUtils;
  23424. function InstancedBufferGeometry() {
  23425. BufferGeometry.call(this);
  23426. this.type = 'InstancedBufferGeometry';
  23427. this.maxInstancedCount = undefined;
  23428. }
  23429. InstancedBufferGeometry.prototype = Object.assign(Object.create(BufferGeometry.prototype), {
  23430. constructor: InstancedBufferGeometry,
  23431. isInstancedBufferGeometry: true,
  23432. copy: function (source) {
  23433. BufferGeometry.prototype.copy.call(this, source);
  23434. this.maxInstancedCount = source.maxInstancedCount;
  23435. return this;
  23436. },
  23437. clone: function () {
  23438. return new this.constructor().copy(this);
  23439. },
  23440. toJSON: function () {
  23441. var data = BufferGeometry.prototype.toJSON.call(this);
  23442. data.maxInstancedCount = this.maxInstancedCount;
  23443. data.isInstancedBufferGeometry = true;
  23444. return data;
  23445. }
  23446. });
  23447. /**
  23448. * @author benaadams / https://twitter.com/ben_a_adams
  23449. */
  23450. function InstancedBufferAttribute(array, itemSize, normalized, meshPerAttribute) {
  23451. if (typeof normalized === 'number') {
  23452. meshPerAttribute = normalized;
  23453. normalized = false;
  23454. console.error('THREE.InstancedBufferAttribute: The constructor now expects normalized as the third argument.');
  23455. }
  23456. BufferAttribute.call(this, array, itemSize, normalized);
  23457. this.meshPerAttribute = meshPerAttribute || 1;
  23458. }
  23459. InstancedBufferAttribute.prototype = Object.assign(Object.create(BufferAttribute.prototype), {
  23460. constructor: InstancedBufferAttribute,
  23461. isInstancedBufferAttribute: true,
  23462. copy: function (source) {
  23463. BufferAttribute.prototype.copy.call(this, source);
  23464. this.meshPerAttribute = source.meshPerAttribute;
  23465. return this;
  23466. },
  23467. toJSON: function () {
  23468. var data = BufferAttribute.prototype.toJSON.call(this);
  23469. data.meshPerAttribute = this.meshPerAttribute;
  23470. data.isInstancedBufferAttribute = true;
  23471. return data;
  23472. }
  23473. });
  23474. /**
  23475. * @author mrdoob / http://mrdoob.com/
  23476. */
  23477. function BufferGeometryLoader(manager) {
  23478. Loader.call(this, manager);
  23479. }
  23480. BufferGeometryLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  23481. constructor: BufferGeometryLoader,
  23482. load: function (url, onLoad, onProgress, onError) {
  23483. var scope = this;
  23484. var loader = new FileLoader(scope.manager);
  23485. loader.setPath(scope.path);
  23486. loader.load(url, function (text) {
  23487. onLoad(scope.parse(JSON.parse(text)));
  23488. }, onProgress, onError);
  23489. },
  23490. parse: function (json) {
  23491. var geometry = json.isInstancedBufferGeometry ? new InstancedBufferGeometry() : new BufferGeometry();
  23492. var index = json.data.index;
  23493. if (index !== undefined) {
  23494. var typedArray = new TYPED_ARRAYS[index.type](index.array);
  23495. geometry.setIndex(new BufferAttribute(typedArray, 1));
  23496. }
  23497. var attributes = json.data.attributes;
  23498. for (var key in attributes) {
  23499. var attribute = attributes[key];
  23500. var typedArray = new TYPED_ARRAYS[attribute.type](attribute.array);
  23501. var bufferAttributeConstr = attribute.isInstancedBufferAttribute ? InstancedBufferAttribute : BufferAttribute;
  23502. var bufferAttribute = new bufferAttributeConstr(typedArray, attribute.itemSize, attribute.normalized);
  23503. if (attribute.name !== undefined) bufferAttribute.name = attribute.name;
  23504. geometry.addAttribute(key, bufferAttribute);
  23505. }
  23506. var morphAttributes = json.data.morphAttributes;
  23507. if (morphAttributes) {
  23508. for (var key in morphAttributes) {
  23509. var attributeArray = morphAttributes[key];
  23510. var array = [];
  23511. for (var i = 0, il = attributeArray.length; i < il; i++) {
  23512. var attribute = attributeArray[i];
  23513. var typedArray = new TYPED_ARRAYS[attribute.type](attribute.array);
  23514. var bufferAttribute = new BufferAttribute(typedArray, attribute.itemSize, attribute.normalized);
  23515. if (attribute.name !== undefined) bufferAttribute.name = attribute.name;
  23516. array.push(bufferAttribute);
  23517. }
  23518. geometry.morphAttributes[key] = array;
  23519. }
  23520. }
  23521. var groups = json.data.groups || json.data.drawcalls || json.data.offsets;
  23522. if (groups !== undefined) {
  23523. for (var i = 0, n = groups.length; i !== n; ++i) {
  23524. var group = groups[i];
  23525. geometry.addGroup(group.start, group.count, group.materialIndex);
  23526. }
  23527. }
  23528. var boundingSphere = json.data.boundingSphere;
  23529. if (boundingSphere !== undefined) {
  23530. var center = new Vector3();
  23531. if (boundingSphere.center !== undefined) {
  23532. center.fromArray(boundingSphere.center);
  23533. }
  23534. geometry.boundingSphere = new Sphere(center, boundingSphere.radius);
  23535. }
  23536. if (json.name) geometry.name = json.name;
  23537. if (json.userData) geometry.userData = json.userData;
  23538. return geometry;
  23539. }
  23540. });
  23541. var TYPED_ARRAYS = {
  23542. Int8Array: Int8Array,
  23543. Uint8Array: Uint8Array,
  23544. // Workaround for IE11 pre KB2929437. See #11440
  23545. Uint8ClampedArray: typeof Uint8ClampedArray !== 'undefined' ? Uint8ClampedArray : Uint8Array,
  23546. Int16Array: Int16Array,
  23547. Uint16Array: Uint16Array,
  23548. Int32Array: Int32Array,
  23549. Uint32Array: Uint32Array,
  23550. Float32Array: Float32Array,
  23551. Float64Array: Float64Array
  23552. };
  23553. /**
  23554. * @author mrdoob / http://mrdoob.com/
  23555. */
  23556. function ObjectLoader(manager) {
  23557. Loader.call(this, manager);
  23558. }
  23559. ObjectLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  23560. constructor: ObjectLoader,
  23561. load: function (url, onLoad, onProgress, onError) {
  23562. var scope = this;
  23563. var path = this.path === '' ? LoaderUtils.extractUrlBase(url) : this.path;
  23564. this.resourcePath = this.resourcePath || path;
  23565. var loader = new FileLoader(scope.manager);
  23566. loader.setPath(this.path);
  23567. loader.load(url, function (text) {
  23568. var json = null;
  23569. try {
  23570. json = JSON.parse(text);
  23571. } catch (error) {
  23572. if (onError !== undefined) onError(error);
  23573. console.error('THREE:ObjectLoader: Can\'t parse ' + url + '.', error.message);
  23574. return;
  23575. }
  23576. var metadata = json.metadata;
  23577. if (metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry') {
  23578. console.error('THREE.ObjectLoader: Can\'t load ' + url);
  23579. return;
  23580. }
  23581. scope.parse(json, onLoad);
  23582. }, onProgress, onError);
  23583. },
  23584. parse: function (json, onLoad) {
  23585. var shapes = this.parseShape(json.shapes);
  23586. var geometries = this.parseGeometries(json.geometries, shapes);
  23587. var images = this.parseImages(json.images, function () {
  23588. if (onLoad !== undefined) onLoad(object);
  23589. });
  23590. var textures = this.parseTextures(json.textures, images);
  23591. var materials = this.parseMaterials(json.materials, textures);
  23592. var object = this.parseObject(json.object, geometries, materials);
  23593. if (json.animations) {
  23594. object.animations = this.parseAnimations(json.animations);
  23595. }
  23596. if (json.images === undefined || json.images.length === 0) {
  23597. if (onLoad !== undefined) onLoad(object);
  23598. }
  23599. return object;
  23600. },
  23601. parseShape: function (json) {
  23602. var shapes = {};
  23603. if (json !== undefined) {
  23604. for (var i = 0, l = json.length; i < l; i++) {
  23605. var shape = new Shape().fromJSON(json[i]);
  23606. shapes[shape.uuid] = shape;
  23607. }
  23608. }
  23609. return shapes;
  23610. },
  23611. parseGeometries: function (json, shapes) {
  23612. var geometries = {};
  23613. if (json !== undefined) {
  23614. var bufferGeometryLoader = new BufferGeometryLoader();
  23615. for (var i = 0, l = json.length; i < l; i++) {
  23616. var geometry;
  23617. var data = json[i];
  23618. switch (data.type) {
  23619. case 'PlaneGeometry':
  23620. case 'PlaneBufferGeometry':
  23621. geometry = new Geometries[data.type](data.width, data.height, data.widthSegments, data.heightSegments);
  23622. break;
  23623. case 'BoxGeometry':
  23624. case 'BoxBufferGeometry':
  23625. case 'CubeGeometry':
  23626. // backwards compatible
  23627. geometry = new Geometries[data.type](data.width, data.height, data.depth, data.widthSegments, data.heightSegments, data.depthSegments);
  23628. break;
  23629. case 'CircleGeometry':
  23630. case 'CircleBufferGeometry':
  23631. geometry = new Geometries[data.type](data.radius, data.segments, data.thetaStart, data.thetaLength);
  23632. break;
  23633. case 'CylinderGeometry':
  23634. case 'CylinderBufferGeometry':
  23635. geometry = new Geometries[data.type](data.radiusTop, data.radiusBottom, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength);
  23636. break;
  23637. case 'ConeGeometry':
  23638. case 'ConeBufferGeometry':
  23639. geometry = new Geometries[data.type](data.radius, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength);
  23640. break;
  23641. case 'SphereGeometry':
  23642. case 'SphereBufferGeometry':
  23643. geometry = new Geometries[data.type](data.radius, data.widthSegments, data.heightSegments, data.phiStart, data.phiLength, data.thetaStart, data.thetaLength);
  23644. break;
  23645. case 'DodecahedronGeometry':
  23646. case 'DodecahedronBufferGeometry':
  23647. case 'IcosahedronGeometry':
  23648. case 'IcosahedronBufferGeometry':
  23649. case 'OctahedronGeometry':
  23650. case 'OctahedronBufferGeometry':
  23651. case 'TetrahedronGeometry':
  23652. case 'TetrahedronBufferGeometry':
  23653. geometry = new Geometries[data.type](data.radius, data.detail);
  23654. break;
  23655. case 'RingGeometry':
  23656. case 'RingBufferGeometry':
  23657. geometry = new Geometries[data.type](data.innerRadius, data.outerRadius, data.thetaSegments, data.phiSegments, data.thetaStart, data.thetaLength);
  23658. break;
  23659. case 'TorusGeometry':
  23660. case 'TorusBufferGeometry':
  23661. geometry = new Geometries[data.type](data.radius, data.tube, data.radialSegments, data.tubularSegments, data.arc);
  23662. break;
  23663. case 'TorusKnotGeometry':
  23664. case 'TorusKnotBufferGeometry':
  23665. geometry = new Geometries[data.type](data.radius, data.tube, data.tubularSegments, data.radialSegments, data.p, data.q);
  23666. break;
  23667. case 'TubeGeometry':
  23668. case 'TubeBufferGeometry':
  23669. // This only works for built-in curves (e.g. CatmullRomCurve3).
  23670. // User defined curves or instances of CurvePath will not be deserialized.
  23671. geometry = new Geometries[data.type](new Curves[data.path.type]().fromJSON(data.path), data.tubularSegments, data.radius, data.radialSegments, data.closed);
  23672. break;
  23673. case 'LatheGeometry':
  23674. case 'LatheBufferGeometry':
  23675. geometry = new Geometries[data.type](data.points, data.segments, data.phiStart, data.phiLength);
  23676. break;
  23677. case 'PolyhedronGeometry':
  23678. case 'PolyhedronBufferGeometry':
  23679. geometry = new Geometries[data.type](data.vertices, data.indices, data.radius, data.details);
  23680. break;
  23681. case 'ShapeGeometry':
  23682. case 'ShapeBufferGeometry':
  23683. var geometryShapes = [];
  23684. for (var j = 0, jl = data.shapes.length; j < jl; j++) {
  23685. var shape = shapes[data.shapes[j]];
  23686. geometryShapes.push(shape);
  23687. }
  23688. geometry = new Geometries[data.type](geometryShapes, data.curveSegments);
  23689. break;
  23690. case 'ExtrudeGeometry':
  23691. case 'ExtrudeBufferGeometry':
  23692. var geometryShapes = [];
  23693. for (var j = 0, jl = data.shapes.length; j < jl; j++) {
  23694. var shape = shapes[data.shapes[j]];
  23695. geometryShapes.push(shape);
  23696. }
  23697. var extrudePath = data.options.extrudePath;
  23698. if (extrudePath !== undefined) {
  23699. data.options.extrudePath = new Curves[extrudePath.type]().fromJSON(extrudePath);
  23700. }
  23701. geometry = new Geometries[data.type](geometryShapes, data.options);
  23702. break;
  23703. case 'BufferGeometry':
  23704. case 'InstancedBufferGeometry':
  23705. geometry = bufferGeometryLoader.parse(data);
  23706. break;
  23707. case 'Geometry':
  23708. if ('THREE' in window && 'LegacyJSONLoader' in THREE) {
  23709. var geometryLoader = new THREE.LegacyJSONLoader();
  23710. geometry = geometryLoader.parse(data, this.resourcePath).geometry;
  23711. } else {
  23712. console.error('THREE.ObjectLoader: You have to import LegacyJSONLoader in order load geometry data of type "Geometry".');
  23713. }
  23714. break;
  23715. default:
  23716. console.warn('THREE.ObjectLoader: Unsupported geometry type "' + data.type + '"');
  23717. continue;
  23718. }
  23719. geometry.uuid = data.uuid;
  23720. if (data.name !== undefined) geometry.name = data.name;
  23721. if (geometry.isBufferGeometry === true && data.userData !== undefined) geometry.userData = data.userData;
  23722. geometries[data.uuid] = geometry;
  23723. }
  23724. }
  23725. return geometries;
  23726. },
  23727. parseMaterials: function (json, textures) {
  23728. var cache = {}; // MultiMaterial
  23729. var materials = {};
  23730. if (json !== undefined) {
  23731. var loader = new MaterialLoader();
  23732. loader.setTextures(textures);
  23733. for (var i = 0, l = json.length; i < l; i++) {
  23734. var data = json[i];
  23735. if (data.type === 'MultiMaterial') {
  23736. // Deprecated
  23737. var array = [];
  23738. for (var j = 0; j < data.materials.length; j++) {
  23739. var material = data.materials[j];
  23740. if (cache[material.uuid] === undefined) {
  23741. cache[material.uuid] = loader.parse(material);
  23742. }
  23743. array.push(cache[material.uuid]);
  23744. }
  23745. materials[data.uuid] = array;
  23746. } else {
  23747. if (cache[data.uuid] === undefined) {
  23748. cache[data.uuid] = loader.parse(data);
  23749. }
  23750. materials[data.uuid] = cache[data.uuid];
  23751. }
  23752. }
  23753. }
  23754. return materials;
  23755. },
  23756. parseAnimations: function (json) {
  23757. var animations = [];
  23758. for (var i = 0; i < json.length; i++) {
  23759. var data = json[i];
  23760. var clip = AnimationClip.parse(data);
  23761. if (data.uuid !== undefined) clip.uuid = data.uuid;
  23762. animations.push(clip);
  23763. }
  23764. return animations;
  23765. },
  23766. parseImages: function (json, onLoad) {
  23767. var scope = this;
  23768. var images = {};
  23769. function loadImage(url) {
  23770. scope.manager.itemStart(url);
  23771. return loader.load(url, function () {
  23772. scope.manager.itemEnd(url);
  23773. }, undefined, function () {
  23774. scope.manager.itemError(url);
  23775. scope.manager.itemEnd(url);
  23776. });
  23777. }
  23778. if (json !== undefined && json.length > 0) {
  23779. var manager = new LoadingManager(onLoad);
  23780. var loader = new ImageLoader(manager);
  23781. loader.setCrossOrigin(this.crossOrigin);
  23782. for (var i = 0, il = json.length; i < il; i++) {
  23783. var image = json[i];
  23784. var url = image.url;
  23785. if (Array.isArray(url)) {
  23786. // load array of images e.g CubeTexture
  23787. images[image.uuid] = [];
  23788. for (var j = 0, jl = url.length; j < jl; j++) {
  23789. var currentUrl = url[j];
  23790. var path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test(currentUrl) ? currentUrl : scope.resourcePath + currentUrl;
  23791. images[image.uuid].push(loadImage(path));
  23792. }
  23793. } else {
  23794. // load single image
  23795. var path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test(image.url) ? image.url : scope.resourcePath + image.url;
  23796. images[image.uuid] = loadImage(path);
  23797. }
  23798. }
  23799. }
  23800. return images;
  23801. },
  23802. parseTextures: function (json, images) {
  23803. function parseConstant(value, type) {
  23804. if (typeof value === 'number') return value;
  23805. console.warn('THREE.ObjectLoader.parseTexture: Constant should be in numeric form.', value);
  23806. return type[value];
  23807. }
  23808. var textures = {};
  23809. if (json !== undefined) {
  23810. for (var i = 0, l = json.length; i < l; i++) {
  23811. var data = json[i];
  23812. if (data.image === undefined) {
  23813. console.warn('THREE.ObjectLoader: No "image" specified for', data.uuid);
  23814. }
  23815. if (images[data.image] === undefined) {
  23816. console.warn('THREE.ObjectLoader: Undefined image', data.image);
  23817. }
  23818. var texture;
  23819. if (Array.isArray(images[data.image])) {
  23820. texture = new CubeTexture(images[data.image]);
  23821. } else {
  23822. texture = new Texture(images[data.image]);
  23823. }
  23824. texture.needsUpdate = true;
  23825. texture.uuid = data.uuid;
  23826. if (data.name !== undefined) texture.name = data.name;
  23827. if (data.mapping !== undefined) texture.mapping = parseConstant(data.mapping, TEXTURE_MAPPING);
  23828. if (data.offset !== undefined) texture.offset.fromArray(data.offset);
  23829. if (data.repeat !== undefined) texture.repeat.fromArray(data.repeat);
  23830. if (data.center !== undefined) texture.center.fromArray(data.center);
  23831. if (data.rotation !== undefined) texture.rotation = data.rotation;
  23832. if (data.wrap !== undefined) {
  23833. texture.wrapS = parseConstant(data.wrap[0], TEXTURE_WRAPPING);
  23834. texture.wrapT = parseConstant(data.wrap[1], TEXTURE_WRAPPING);
  23835. }
  23836. if (data.format !== undefined) texture.format = data.format;
  23837. if (data.type !== undefined) texture.type = data.type;
  23838. if (data.encoding !== undefined) texture.encoding = data.encoding;
  23839. if (data.minFilter !== undefined) texture.minFilter = parseConstant(data.minFilter, TEXTURE_FILTER);
  23840. if (data.magFilter !== undefined) texture.magFilter = parseConstant(data.magFilter, TEXTURE_FILTER);
  23841. if (data.anisotropy !== undefined) texture.anisotropy = data.anisotropy;
  23842. if (data.flipY !== undefined) texture.flipY = data.flipY;
  23843. if (data.premultiplyAlpha !== undefined) texture.premultiplyAlpha = data.premultiplyAlpha;
  23844. if (data.unpackAlignment !== undefined) texture.unpackAlignment = data.unpackAlignment;
  23845. textures[data.uuid] = texture;
  23846. }
  23847. }
  23848. return textures;
  23849. },
  23850. parseObject: function (data, geometries, materials) {
  23851. var object;
  23852. function getGeometry(name) {
  23853. if (geometries[name] === undefined) {
  23854. console.warn('THREE.ObjectLoader: Undefined geometry', name);
  23855. }
  23856. return geometries[name];
  23857. }
  23858. function getMaterial(name) {
  23859. if (name === undefined) return undefined;
  23860. if (Array.isArray(name)) {
  23861. var array = [];
  23862. for (var i = 0, l = name.length; i < l; i++) {
  23863. var uuid = name[i];
  23864. if (materials[uuid] === undefined) {
  23865. console.warn('THREE.ObjectLoader: Undefined material', uuid);
  23866. }
  23867. array.push(materials[uuid]);
  23868. }
  23869. return array;
  23870. }
  23871. if (materials[name] === undefined) {
  23872. console.warn('THREE.ObjectLoader: Undefined material', name);
  23873. }
  23874. return materials[name];
  23875. }
  23876. switch (data.type) {
  23877. case 'Scene':
  23878. object = new Scene();
  23879. if (data.background !== undefined) {
  23880. if (Number.isInteger(data.background)) {
  23881. object.background = new Color(data.background);
  23882. }
  23883. }
  23884. if (data.fog !== undefined) {
  23885. if (data.fog.type === 'Fog') {
  23886. object.fog = new Fog(data.fog.color, data.fog.near, data.fog.far);
  23887. } else if (data.fog.type === 'FogExp2') {
  23888. object.fog = new FogExp2(data.fog.color, data.fog.density);
  23889. }
  23890. }
  23891. break;
  23892. case 'PerspectiveCamera':
  23893. object = new PerspectiveCamera(data.fov, data.aspect, data.near, data.far);
  23894. if (data.focus !== undefined) object.focus = data.focus;
  23895. if (data.zoom !== undefined) object.zoom = data.zoom;
  23896. if (data.filmGauge !== undefined) object.filmGauge = data.filmGauge;
  23897. if (data.filmOffset !== undefined) object.filmOffset = data.filmOffset;
  23898. if (data.view !== undefined) object.view = Object.assign({}, data.view);
  23899. break;
  23900. case 'OrthographicCamera':
  23901. object = new OrthographicCamera(data.left, data.right, data.top, data.bottom, data.near, data.far);
  23902. if (data.zoom !== undefined) object.zoom = data.zoom;
  23903. if (data.view !== undefined) object.view = Object.assign({}, data.view);
  23904. break;
  23905. case 'AmbientLight':
  23906. object = new AmbientLight(data.color, data.intensity);
  23907. break;
  23908. case 'DirectionalLight':
  23909. object = new DirectionalLight(data.color, data.intensity);
  23910. break;
  23911. case 'PointLight':
  23912. object = new PointLight(data.color, data.intensity, data.distance, data.decay);
  23913. break;
  23914. case 'RectAreaLight':
  23915. object = new RectAreaLight(data.color, data.intensity, data.width, data.height);
  23916. break;
  23917. case 'SpotLight':
  23918. object = new SpotLight(data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay);
  23919. break;
  23920. case 'HemisphereLight':
  23921. object = new HemisphereLight(data.color, data.groundColor, data.intensity);
  23922. break;
  23923. case 'SkinnedMesh':
  23924. console.warn('THREE.ObjectLoader.parseObject() does not support SkinnedMesh yet.');
  23925. case 'Mesh':
  23926. var geometry = getGeometry(data.geometry);
  23927. var material = getMaterial(data.material);
  23928. if (geometry.bones && geometry.bones.length > 0) {
  23929. object = new SkinnedMesh(geometry, material);
  23930. } else {
  23931. object = new Mesh(geometry, material);
  23932. }
  23933. if (data.drawMode !== undefined) object.setDrawMode(data.drawMode);
  23934. break;
  23935. case 'LOD':
  23936. object = new LOD();
  23937. break;
  23938. case 'Line':
  23939. object = new Line(getGeometry(data.geometry), getMaterial(data.material), data.mode);
  23940. break;
  23941. case 'LineLoop':
  23942. object = new LineLoop(getGeometry(data.geometry), getMaterial(data.material));
  23943. break;
  23944. case 'LineSegments':
  23945. object = new LineSegments(getGeometry(data.geometry), getMaterial(data.material));
  23946. break;
  23947. case 'PointCloud':
  23948. case 'Points':
  23949. object = new Points(getGeometry(data.geometry), getMaterial(data.material));
  23950. break;
  23951. case 'Sprite':
  23952. object = new Sprite(getMaterial(data.material));
  23953. break;
  23954. case 'Group':
  23955. object = new Group();
  23956. break;
  23957. default:
  23958. object = new Object3D();
  23959. }
  23960. object.uuid = data.uuid;
  23961. if (data.name !== undefined) object.name = data.name;
  23962. if (data.matrix !== undefined) {
  23963. object.matrix.fromArray(data.matrix);
  23964. if (data.matrixAutoUpdate !== undefined) object.matrixAutoUpdate = data.matrixAutoUpdate;
  23965. if (object.matrixAutoUpdate) object.matrix.decompose(object.position, object.quaternion, object.scale);
  23966. } else {
  23967. if (data.position !== undefined) object.position.fromArray(data.position);
  23968. if (data.rotation !== undefined) object.rotation.fromArray(data.rotation);
  23969. if (data.quaternion !== undefined) object.quaternion.fromArray(data.quaternion);
  23970. if (data.scale !== undefined) object.scale.fromArray(data.scale);
  23971. }
  23972. if (data.castShadow !== undefined) object.castShadow = data.castShadow;
  23973. if (data.receiveShadow !== undefined) object.receiveShadow = data.receiveShadow;
  23974. if (data.shadow) {
  23975. if (data.shadow.bias !== undefined) object.shadow.bias = data.shadow.bias;
  23976. if (data.shadow.radius !== undefined) object.shadow.radius = data.shadow.radius;
  23977. if (data.shadow.mapSize !== undefined) object.shadow.mapSize.fromArray(data.shadow.mapSize);
  23978. if (data.shadow.camera !== undefined) object.shadow.camera = this.parseObject(data.shadow.camera);
  23979. }
  23980. if (data.visible !== undefined) object.visible = data.visible;
  23981. if (data.frustumCulled !== undefined) object.frustumCulled = data.frustumCulled;
  23982. if (data.renderOrder !== undefined) object.renderOrder = data.renderOrder;
  23983. if (data.userData !== undefined) object.userData = data.userData;
  23984. if (data.layers !== undefined) object.layers.mask = data.layers;
  23985. if (data.children !== undefined) {
  23986. var children = data.children;
  23987. for (var i = 0; i < children.length; i++) {
  23988. object.add(this.parseObject(children[i], geometries, materials));
  23989. }
  23990. }
  23991. if (data.type === 'LOD') {
  23992. var levels = data.levels;
  23993. for (var l = 0; l < levels.length; l++) {
  23994. var level = levels[l];
  23995. var child = object.getObjectByProperty('uuid', level.object);
  23996. if (child !== undefined) {
  23997. object.addLevel(child, level.distance);
  23998. }
  23999. }
  24000. }
  24001. return object;
  24002. }
  24003. });
  24004. var TEXTURE_MAPPING = {
  24005. UVMapping: UVMapping,
  24006. CubeReflectionMapping: CubeReflectionMapping,
  24007. CubeRefractionMapping: CubeRefractionMapping,
  24008. EquirectangularReflectionMapping: EquirectangularReflectionMapping,
  24009. EquirectangularRefractionMapping: EquirectangularRefractionMapping,
  24010. SphericalReflectionMapping: SphericalReflectionMapping,
  24011. CubeUVReflectionMapping: CubeUVReflectionMapping,
  24012. CubeUVRefractionMapping: CubeUVRefractionMapping
  24013. };
  24014. var TEXTURE_WRAPPING = {
  24015. RepeatWrapping: RepeatWrapping,
  24016. ClampToEdgeWrapping: ClampToEdgeWrapping,
  24017. MirroredRepeatWrapping: MirroredRepeatWrapping
  24018. };
  24019. var TEXTURE_FILTER = {
  24020. NearestFilter: NearestFilter,
  24021. NearestMipmapNearestFilter: NearestMipmapNearestFilter,
  24022. NearestMipmapLinearFilter: NearestMipmapLinearFilter,
  24023. LinearFilter: LinearFilter,
  24024. LinearMipmapNearestFilter: LinearMipmapNearestFilter,
  24025. LinearMipmapLinearFilter: LinearMipmapLinearFilter
  24026. };
  24027. /**
  24028. * @author thespite / http://clicktorelease.com/
  24029. */
  24030. function ImageBitmapLoader(manager) {
  24031. if (typeof createImageBitmap === 'undefined') {
  24032. console.warn('THREE.ImageBitmapLoader: createImageBitmap() not supported.');
  24033. }
  24034. if (typeof fetch === 'undefined') {
  24035. console.warn('THREE.ImageBitmapLoader: fetch() not supported.');
  24036. }
  24037. Loader.call(this, manager);
  24038. this.options = undefined;
  24039. }
  24040. ImageBitmapLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  24041. constructor: ImageBitmapLoader,
  24042. setOptions: function setOptions(options) {
  24043. this.options = options;
  24044. return this;
  24045. },
  24046. load: function (url, onLoad, onProgress, onError) {
  24047. if (url === undefined) url = '';
  24048. if (this.path !== undefined) url = this.path + url;
  24049. url = this.manager.resolveURL(url);
  24050. var scope = this;
  24051. var cached = Cache.get(url);
  24052. if (cached !== undefined) {
  24053. scope.manager.itemStart(url);
  24054. setTimeout(function () {
  24055. if (onLoad) onLoad(cached);
  24056. scope.manager.itemEnd(url);
  24057. }, 0);
  24058. return cached;
  24059. }
  24060. fetch(url).then(function (res) {
  24061. return res.blob();
  24062. }).then(function (blob) {
  24063. if (scope.options === undefined) {
  24064. // Workaround for FireFox. It causes an error if you pass options.
  24065. return createImageBitmap(blob);
  24066. } else {
  24067. return createImageBitmap(blob, scope.options);
  24068. }
  24069. }).then(function (imageBitmap) {
  24070. Cache.add(url, imageBitmap);
  24071. if (onLoad) onLoad(imageBitmap);
  24072. scope.manager.itemEnd(url);
  24073. }).catch(function (e) {
  24074. if (onError) onError(e);
  24075. scope.manager.itemError(url);
  24076. scope.manager.itemEnd(url);
  24077. });
  24078. scope.manager.itemStart(url);
  24079. }
  24080. });
  24081. /**
  24082. * @author zz85 / http://www.lab4games.net/zz85/blog
  24083. * minimal class for proxing functions to Path. Replaces old "extractSubpaths()"
  24084. **/
  24085. function ShapePath() {
  24086. this.type = 'ShapePath';
  24087. this.color = new Color();
  24088. this.subPaths = [];
  24089. this.currentPath = null;
  24090. }
  24091. Object.assign(ShapePath.prototype, {
  24092. moveTo: function (x, y) {
  24093. this.currentPath = new Path();
  24094. this.subPaths.push(this.currentPath);
  24095. this.currentPath.moveTo(x, y);
  24096. },
  24097. lineTo: function (x, y) {
  24098. this.currentPath.lineTo(x, y);
  24099. },
  24100. quadraticCurveTo: function (aCPx, aCPy, aX, aY) {
  24101. this.currentPath.quadraticCurveTo(aCPx, aCPy, aX, aY);
  24102. },
  24103. bezierCurveTo: function (aCP1x, aCP1y, aCP2x, aCP2y, aX, aY) {
  24104. this.currentPath.bezierCurveTo(aCP1x, aCP1y, aCP2x, aCP2y, aX, aY);
  24105. },
  24106. splineThru: function (pts) {
  24107. this.currentPath.splineThru(pts);
  24108. },
  24109. toShapes: function (isCCW, noHoles) {
  24110. function toShapesNoHoles(inSubpaths) {
  24111. var shapes = [];
  24112. for (var i = 0, l = inSubpaths.length; i < l; i++) {
  24113. var tmpPath = inSubpaths[i];
  24114. var tmpShape = new Shape();
  24115. tmpShape.curves = tmpPath.curves;
  24116. shapes.push(tmpShape);
  24117. }
  24118. return shapes;
  24119. }
  24120. function isPointInsidePolygon(inPt, inPolygon) {
  24121. var polyLen = inPolygon.length; // inPt on polygon contour => immediate success or
  24122. // toggling of inside/outside at every single! intersection point of an edge
  24123. // with the horizontal line through inPt, left of inPt
  24124. // not counting lowerY endpoints of edges and whole edges on that line
  24125. var inside = false;
  24126. for (var p = polyLen - 1, q = 0; q < polyLen; p = q++) {
  24127. var edgeLowPt = inPolygon[p];
  24128. var edgeHighPt = inPolygon[q];
  24129. var edgeDx = edgeHighPt.x - edgeLowPt.x;
  24130. var edgeDy = edgeHighPt.y - edgeLowPt.y;
  24131. if (Math.abs(edgeDy) > Number.EPSILON) {
  24132. // not parallel
  24133. if (edgeDy < 0) {
  24134. edgeLowPt = inPolygon[q];
  24135. edgeDx = -edgeDx;
  24136. edgeHighPt = inPolygon[p];
  24137. edgeDy = -edgeDy;
  24138. }
  24139. if (inPt.y < edgeLowPt.y || inPt.y > edgeHighPt.y) continue;
  24140. if (inPt.y === edgeLowPt.y) {
  24141. if (inPt.x === edgeLowPt.x) return true; // inPt is on contour ?
  24142. // continue; // no intersection or edgeLowPt => doesn't count !!!
  24143. } else {
  24144. var perpEdge = edgeDy * (inPt.x - edgeLowPt.x) - edgeDx * (inPt.y - edgeLowPt.y);
  24145. if (perpEdge === 0) return true; // inPt is on contour ?
  24146. if (perpEdge < 0) continue;
  24147. inside = !inside; // true intersection left of inPt
  24148. }
  24149. } else {
  24150. // parallel or collinear
  24151. if (inPt.y !== edgeLowPt.y) continue; // parallel
  24152. // edge lies on the same horizontal line as inPt
  24153. if (edgeHighPt.x <= inPt.x && inPt.x <= edgeLowPt.x || edgeLowPt.x <= inPt.x && inPt.x <= edgeHighPt.x) return true; // inPt: Point on contour !
  24154. // continue;
  24155. }
  24156. }
  24157. return inside;
  24158. }
  24159. var isClockWise = ShapeUtils.isClockWise;
  24160. var subPaths = this.subPaths;
  24161. if (subPaths.length === 0) return [];
  24162. if (noHoles === true) return toShapesNoHoles(subPaths);
  24163. var solid,
  24164. tmpPath,
  24165. tmpShape,
  24166. shapes = [];
  24167. if (subPaths.length === 1) {
  24168. tmpPath = subPaths[0];
  24169. tmpShape = new Shape();
  24170. tmpShape.curves = tmpPath.curves;
  24171. shapes.push(tmpShape);
  24172. return shapes;
  24173. }
  24174. var holesFirst = !isClockWise(subPaths[0].getPoints());
  24175. holesFirst = isCCW ? !holesFirst : holesFirst; // console.log("Holes first", holesFirst);
  24176. var betterShapeHoles = [];
  24177. var newShapes = [];
  24178. var newShapeHoles = [];
  24179. var mainIdx = 0;
  24180. var tmpPoints;
  24181. newShapes[mainIdx] = undefined;
  24182. newShapeHoles[mainIdx] = [];
  24183. for (var i = 0, l = subPaths.length; i < l; i++) {
  24184. tmpPath = subPaths[i];
  24185. tmpPoints = tmpPath.getPoints();
  24186. solid = isClockWise(tmpPoints);
  24187. solid = isCCW ? !solid : solid;
  24188. if (solid) {
  24189. if (!holesFirst && newShapes[mainIdx]) mainIdx++;
  24190. newShapes[mainIdx] = {
  24191. s: new Shape(),
  24192. p: tmpPoints
  24193. };
  24194. newShapes[mainIdx].s.curves = tmpPath.curves;
  24195. if (holesFirst) mainIdx++;
  24196. newShapeHoles[mainIdx] = []; //console.log('cw', i);
  24197. } else {
  24198. newShapeHoles[mainIdx].push({
  24199. h: tmpPath,
  24200. p: tmpPoints[0]
  24201. }); //console.log('ccw', i);
  24202. }
  24203. } // only Holes? -> probably all Shapes with wrong orientation
  24204. if (!newShapes[0]) return toShapesNoHoles(subPaths);
  24205. if (newShapes.length > 1) {
  24206. var ambiguous = false;
  24207. var toChange = [];
  24208. for (var sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx++) {
  24209. betterShapeHoles[sIdx] = [];
  24210. }
  24211. for (var sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx++) {
  24212. var sho = newShapeHoles[sIdx];
  24213. for (var hIdx = 0; hIdx < sho.length; hIdx++) {
  24214. var ho = sho[hIdx];
  24215. var hole_unassigned = true;
  24216. for (var s2Idx = 0; s2Idx < newShapes.length; s2Idx++) {
  24217. if (isPointInsidePolygon(ho.p, newShapes[s2Idx].p)) {
  24218. if (sIdx !== s2Idx) toChange.push({
  24219. froms: sIdx,
  24220. tos: s2Idx,
  24221. hole: hIdx
  24222. });
  24223. if (hole_unassigned) {
  24224. hole_unassigned = false;
  24225. betterShapeHoles[s2Idx].push(ho);
  24226. } else {
  24227. ambiguous = true;
  24228. }
  24229. }
  24230. }
  24231. if (hole_unassigned) {
  24232. betterShapeHoles[sIdx].push(ho);
  24233. }
  24234. }
  24235. } // console.log("ambiguous: ", ambiguous);
  24236. if (toChange.length > 0) {
  24237. // console.log("to change: ", toChange);
  24238. if (!ambiguous) newShapeHoles = betterShapeHoles;
  24239. }
  24240. }
  24241. var tmpHoles;
  24242. for (var i = 0, il = newShapes.length; i < il; i++) {
  24243. tmpShape = newShapes[i].s;
  24244. shapes.push(tmpShape);
  24245. tmpHoles = newShapeHoles[i];
  24246. for (var j = 0, jl = tmpHoles.length; j < jl; j++) {
  24247. tmpShape.holes.push(tmpHoles[j].h);
  24248. }
  24249. } //console.log("shape", shapes);
  24250. return shapes;
  24251. }
  24252. });
  24253. /**
  24254. * @author zz85 / http://www.lab4games.net/zz85/blog
  24255. * @author mrdoob / http://mrdoob.com/
  24256. */
  24257. function Font(data) {
  24258. this.type = 'Font';
  24259. this.data = data;
  24260. }
  24261. Object.assign(Font.prototype, {
  24262. isFont: true,
  24263. generateShapes: function (text, size) {
  24264. if (size === undefined) size = 100;
  24265. var shapes = [];
  24266. var paths = createPaths(text, size, this.data);
  24267. for (var p = 0, pl = paths.length; p < pl; p++) {
  24268. Array.prototype.push.apply(shapes, paths[p].toShapes());
  24269. }
  24270. return shapes;
  24271. }
  24272. });
  24273. function createPaths(text, size, data) {
  24274. var chars = Array.from ? Array.from(text) : String(text).split(''); // see #13988
  24275. var scale = size / data.resolution;
  24276. var line_height = (data.boundingBox.yMax - data.boundingBox.yMin + data.underlineThickness) * scale;
  24277. var paths = [];
  24278. var offsetX = 0,
  24279. offsetY = 0;
  24280. for (var i = 0; i < chars.length; i++) {
  24281. var char = chars[i];
  24282. if (char === '\n') {
  24283. offsetX = 0;
  24284. offsetY -= line_height;
  24285. } else {
  24286. var ret = createPath(char, scale, offsetX, offsetY, data);
  24287. offsetX += ret.offsetX;
  24288. paths.push(ret.path);
  24289. }
  24290. }
  24291. return paths;
  24292. }
  24293. function createPath(char, scale, offsetX, offsetY, data) {
  24294. var glyph = data.glyphs[char] || data.glyphs['?'];
  24295. if (!glyph) {
  24296. console.error('THREE.Font: character "' + char + '" does not exists in font family ' + data.familyName + '.');
  24297. return;
  24298. }
  24299. var path = new ShapePath();
  24300. var x, y, cpx, cpy, cpx1, cpy1, cpx2, cpy2;
  24301. if (glyph.o) {
  24302. var outline = glyph._cachedOutline || (glyph._cachedOutline = glyph.o.split(' '));
  24303. for (var i = 0, l = outline.length; i < l;) {
  24304. var action = outline[i++];
  24305. switch (action) {
  24306. case 'm':
  24307. // moveTo
  24308. x = outline[i++] * scale + offsetX;
  24309. y = outline[i++] * scale + offsetY;
  24310. path.moveTo(x, y);
  24311. break;
  24312. case 'l':
  24313. // lineTo
  24314. x = outline[i++] * scale + offsetX;
  24315. y = outline[i++] * scale + offsetY;
  24316. path.lineTo(x, y);
  24317. break;
  24318. case 'q':
  24319. // quadraticCurveTo
  24320. cpx = outline[i++] * scale + offsetX;
  24321. cpy = outline[i++] * scale + offsetY;
  24322. cpx1 = outline[i++] * scale + offsetX;
  24323. cpy1 = outline[i++] * scale + offsetY;
  24324. path.quadraticCurveTo(cpx1, cpy1, cpx, cpy);
  24325. break;
  24326. case 'b':
  24327. // bezierCurveTo
  24328. cpx = outline[i++] * scale + offsetX;
  24329. cpy = outline[i++] * scale + offsetY;
  24330. cpx1 = outline[i++] * scale + offsetX;
  24331. cpy1 = outline[i++] * scale + offsetY;
  24332. cpx2 = outline[i++] * scale + offsetX;
  24333. cpy2 = outline[i++] * scale + offsetY;
  24334. path.bezierCurveTo(cpx1, cpy1, cpx2, cpy2, cpx, cpy);
  24335. break;
  24336. }
  24337. }
  24338. }
  24339. return {
  24340. offsetX: glyph.ha * scale,
  24341. path: path
  24342. };
  24343. }
  24344. /**
  24345. * @author mrdoob / http://mrdoob.com/
  24346. */
  24347. function FontLoader(manager) {
  24348. Loader.call(this, manager);
  24349. }
  24350. FontLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  24351. constructor: FontLoader,
  24352. load: function (url, onLoad, onProgress, onError) {
  24353. var scope = this;
  24354. var loader = new FileLoader(this.manager);
  24355. loader.setPath(this.path);
  24356. loader.load(url, function (text) {
  24357. var json;
  24358. try {
  24359. json = JSON.parse(text);
  24360. } catch (e) {
  24361. console.warn('THREE.FontLoader: typeface.js support is being deprecated. Use typeface.json instead.');
  24362. json = JSON.parse(text.substring(65, text.length - 2));
  24363. }
  24364. var font = scope.parse(json);
  24365. if (onLoad) onLoad(font);
  24366. }, onProgress, onError);
  24367. },
  24368. parse: function (json) {
  24369. return new Font(json);
  24370. }
  24371. });
  24372. /**
  24373. * @author mrdoob / http://mrdoob.com/
  24374. */
  24375. var _context;
  24376. var AudioContext = {
  24377. getContext: function () {
  24378. if (_context === undefined) {
  24379. _context = new (window.AudioContext || window.webkitAudioContext)();
  24380. }
  24381. return _context;
  24382. },
  24383. setContext: function (value) {
  24384. _context = value;
  24385. }
  24386. };
  24387. /**
  24388. * @author Reece Aaron Lecrivain / http://reecenotes.com/
  24389. */
  24390. exports.AudioContext = AudioContext;
  24391. function AudioLoader(manager) {
  24392. Loader.call(this, manager);
  24393. }
  24394. AudioLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  24395. constructor: AudioLoader,
  24396. load: function (url, onLoad, onProgress, onError) {
  24397. var loader = new FileLoader(this.manager);
  24398. loader.setResponseType('arraybuffer');
  24399. loader.setPath(this.path);
  24400. loader.load(url, function (buffer) {
  24401. // Create a copy of the buffer. The `decodeAudioData` method
  24402. // detaches the buffer when complete, preventing reuse.
  24403. var bufferCopy = buffer.slice(0);
  24404. var context = AudioContext.getContext();
  24405. context.decodeAudioData(bufferCopy, function (audioBuffer) {
  24406. onLoad(audioBuffer);
  24407. });
  24408. }, onProgress, onError);
  24409. }
  24410. });
  24411. /**
  24412. * @author bhouston / http://clara.io
  24413. * @author WestLangley / http://github.com/WestLangley
  24414. *
  24415. * Primary reference:
  24416. * https://graphics.stanford.edu/papers/envmap/envmap.pdf
  24417. *
  24418. * Secondary reference:
  24419. * https://www.ppsloan.org/publications/StupidSH36.pdf
  24420. */
  24421. // 3-band SH defined by 9 coefficients
  24422. function SphericalHarmonics3() {
  24423. this.coefficients = [];
  24424. for (var i = 0; i < 9; i++) {
  24425. this.coefficients.push(new Vector3());
  24426. }
  24427. }
  24428. Object.assign(SphericalHarmonics3.prototype, {
  24429. isSphericalHarmonics3: true,
  24430. set: function (coefficients) {
  24431. for (var i = 0; i < 9; i++) {
  24432. this.coefficients[i].copy(coefficients[i]);
  24433. }
  24434. return this;
  24435. },
  24436. zero: function () {
  24437. for (var i = 0; i < 9; i++) {
  24438. this.coefficients[i].set(0, 0, 0);
  24439. }
  24440. return this;
  24441. },
  24442. // get the radiance in the direction of the normal
  24443. // target is a Vector3
  24444. getAt: function (normal, target) {
  24445. // normal is assumed to be unit length
  24446. var x = normal.x,
  24447. y = normal.y,
  24448. z = normal.z;
  24449. var coeff = this.coefficients; // band 0
  24450. target.copy(coeff[0]).multiplyScalar(0.282095); // band 1
  24451. target.addScale(coeff[1], 0.488603 * y);
  24452. target.addScale(coeff[2], 0.488603 * z);
  24453. target.addScale(coeff[3], 0.488603 * x); // band 2
  24454. target.addScale(coeff[4], 1.092548 * (x * y));
  24455. target.addScale(coeff[5], 1.092548 * (y * z));
  24456. target.addScale(coeff[6], 0.315392 * (3.0 * z * z - 1.0));
  24457. target.addScale(coeff[7], 1.092548 * (x * z));
  24458. target.addScale(coeff[8], 0.546274 * (x * x - y * y));
  24459. return target;
  24460. },
  24461. // get the irradiance (radiance convolved with cosine lobe) in the direction of the normal
  24462. // target is a Vector3
  24463. // https://graphics.stanford.edu/papers/envmap/envmap.pdf
  24464. getIrradianceAt: function (normal, target) {
  24465. // normal is assumed to be unit length
  24466. var x = normal.x,
  24467. y = normal.y,
  24468. z = normal.z;
  24469. var coeff = this.coefficients; // band 0
  24470. target.copy(coeff[0]).multiplyScalar(0.886227); // π * 0.282095
  24471. // band 1
  24472. target.addScale(coeff[1], 2.0 * 0.511664 * y); // ( 2 * π / 3 ) * 0.488603
  24473. target.addScale(coeff[2], 2.0 * 0.511664 * z);
  24474. target.addScale(coeff[3], 2.0 * 0.511664 * x); // band 2
  24475. target.addScale(coeff[4], 2.0 * 0.429043 * x * y); // ( π / 4 ) * 1.092548
  24476. target.addScale(coeff[5], 2.0 * 0.429043 * y * z);
  24477. target.addScale(coeff[6], 0.743125 * z * z - 0.247708); // ( π / 4 ) * 0.315392 * 3
  24478. target.addScale(coeff[7], 2.0 * 0.429043 * x * z);
  24479. target.addScale(coeff[8], 0.429043 * (x * x - y * y)); // ( π / 4 ) * 0.546274
  24480. return target;
  24481. },
  24482. add: function (sh) {
  24483. for (var i = 0; i < 9; i++) {
  24484. this.coefficients[i].add(sh.coefficients[i]);
  24485. }
  24486. return this;
  24487. },
  24488. scale: function (s) {
  24489. for (var i = 0; i < 9; i++) {
  24490. this.coefficients[i].multiplyScalar(s);
  24491. }
  24492. return this;
  24493. },
  24494. lerp: function (sh, alpha) {
  24495. for (var i = 0; i < 9; i++) {
  24496. this.coefficients[i].lerp(sh.coefficients[i], alpha);
  24497. }
  24498. return this;
  24499. },
  24500. equals: function (sh) {
  24501. for (var i = 0; i < 9; i++) {
  24502. if (!this.coefficients[i].equals(sh.coefficients[i])) {
  24503. return false;
  24504. }
  24505. }
  24506. return true;
  24507. },
  24508. copy: function (sh) {
  24509. return this.set(sh.coefficients);
  24510. },
  24511. clone: function () {
  24512. return new this.constructor().copy(this);
  24513. },
  24514. fromArray: function (array, offset) {
  24515. if (offset === undefined) offset = 0;
  24516. var coefficients = this.coefficients;
  24517. for (var i = 0; i < 9; i++) {
  24518. coefficients[i].fromArray(array, offset + i * 3);
  24519. }
  24520. return this;
  24521. },
  24522. toArray: function (array, offset) {
  24523. if (array === undefined) array = [];
  24524. if (offset === undefined) offset = 0;
  24525. var coefficients = this.coefficients;
  24526. for (var i = 0; i < 9; i++) {
  24527. coefficients[i].toArray(array, offset + i * 3);
  24528. }
  24529. return array;
  24530. }
  24531. });
  24532. Object.assign(SphericalHarmonics3, {
  24533. // evaluate the basis functions
  24534. // shBasis is an Array[ 9 ]
  24535. getBasisAt: function (normal, shBasis) {
  24536. // normal is assumed to be unit length
  24537. var x = normal.x,
  24538. y = normal.y,
  24539. z = normal.z; // band 0
  24540. shBasis[0] = 0.282095; // band 1
  24541. shBasis[1] = 0.488603 * y;
  24542. shBasis[2] = 0.488603 * z;
  24543. shBasis[3] = 0.488603 * x; // band 2
  24544. shBasis[4] = 1.092548 * x * y;
  24545. shBasis[5] = 1.092548 * y * z;
  24546. shBasis[6] = 0.315392 * (3 * z * z - 1);
  24547. shBasis[7] = 1.092548 * x * z;
  24548. shBasis[8] = 0.546274 * (x * x - y * y);
  24549. }
  24550. });
  24551. /**
  24552. * @author WestLangley / http://github.com/WestLangley
  24553. *
  24554. * A LightProbe is a source of indirect-diffuse light
  24555. */
  24556. function LightProbe(sh, intensity) {
  24557. Light.call(this, undefined, intensity);
  24558. this.sh = sh !== undefined ? sh : new SphericalHarmonics3();
  24559. }
  24560. LightProbe.prototype = Object.assign(Object.create(Light.prototype), {
  24561. constructor: LightProbe,
  24562. isLightProbe: true,
  24563. copy: function (source) {
  24564. Light.prototype.copy.call(this, source);
  24565. this.sh.copy(source.sh);
  24566. this.intensity = source.intensity;
  24567. return this;
  24568. },
  24569. toJSON: function (meta) {
  24570. var data = Light.prototype.toJSON.call(this, meta); // data.sh = this.sh.toArray(); // todo
  24571. return data;
  24572. }
  24573. });
  24574. /**
  24575. * @author WestLangley / http://github.com/WestLangley
  24576. */
  24577. function HemisphereLightProbe(skyColor, groundColor, intensity) {
  24578. LightProbe.call(this, undefined, intensity);
  24579. var color1 = new Color().set(skyColor);
  24580. var color2 = new Color().set(groundColor);
  24581. var sky = new Vector3(color1.r, color1.g, color1.b);
  24582. var ground = new Vector3(color2.r, color2.g, color2.b); // without extra factor of PI in the shader, should = 1 / Math.sqrt( Math.PI );
  24583. var c0 = Math.sqrt(Math.PI);
  24584. var c1 = c0 * Math.sqrt(0.75);
  24585. this.sh.coefficients[0].copy(sky).add(ground).multiplyScalar(c0);
  24586. this.sh.coefficients[1].copy(sky).sub(ground).multiplyScalar(c1);
  24587. }
  24588. HemisphereLightProbe.prototype = Object.assign(Object.create(LightProbe.prototype), {
  24589. constructor: HemisphereLightProbe,
  24590. isHemisphereLightProbe: true,
  24591. copy: function (source) {
  24592. // modifying colors not currently supported
  24593. LightProbe.prototype.copy.call(this, source);
  24594. return this;
  24595. },
  24596. toJSON: function (meta) {
  24597. var data = LightProbe.prototype.toJSON.call(this, meta); // data.sh = this.sh.toArray(); // todo
  24598. return data;
  24599. }
  24600. });
  24601. /**
  24602. * @author WestLangley / http://github.com/WestLangley
  24603. */
  24604. function AmbientLightProbe(color, intensity) {
  24605. LightProbe.call(this, undefined, intensity);
  24606. var color1 = new Color().set(color); // without extra factor of PI in the shader, would be 2 / Math.sqrt( Math.PI );
  24607. this.sh.coefficients[0].set(color1.r, color1.g, color1.b).multiplyScalar(2 * Math.sqrt(Math.PI));
  24608. }
  24609. AmbientLightProbe.prototype = Object.assign(Object.create(LightProbe.prototype), {
  24610. constructor: AmbientLightProbe,
  24611. isAmbientLightProbe: true,
  24612. copy: function (source) {
  24613. // modifying color not currently supported
  24614. LightProbe.prototype.copy.call(this, source);
  24615. return this;
  24616. },
  24617. toJSON: function (meta) {
  24618. var data = LightProbe.prototype.toJSON.call(this, meta); // data.sh = this.sh.toArray(); // todo
  24619. return data;
  24620. }
  24621. });
  24622. var _eyeRight = new Matrix4();
  24623. var _eyeLeft = new Matrix4();
  24624. /**
  24625. * @author mrdoob / http://mrdoob.com/
  24626. */
  24627. function StereoCamera() {
  24628. this.type = 'StereoCamera';
  24629. this.aspect = 1;
  24630. this.eyeSep = 0.064;
  24631. this.cameraL = new PerspectiveCamera();
  24632. this.cameraL.layers.enable(1);
  24633. this.cameraL.matrixAutoUpdate = false;
  24634. this.cameraR = new PerspectiveCamera();
  24635. this.cameraR.layers.enable(2);
  24636. this.cameraR.matrixAutoUpdate = false;
  24637. this._cache = {
  24638. focus: null,
  24639. fov: null,
  24640. aspect: null,
  24641. near: null,
  24642. far: null,
  24643. zoom: null,
  24644. eyeSep: null
  24645. };
  24646. }
  24647. Object.assign(StereoCamera.prototype, {
  24648. update: function (camera) {
  24649. var cache = this._cache;
  24650. 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;
  24651. if (needsUpdate) {
  24652. cache.focus = camera.focus;
  24653. cache.fov = camera.fov;
  24654. cache.aspect = camera.aspect * this.aspect;
  24655. cache.near = camera.near;
  24656. cache.far = camera.far;
  24657. cache.zoom = camera.zoom;
  24658. cache.eyeSep = this.eyeSep; // Off-axis stereoscopic effect based on
  24659. // http://paulbourke.net/stereographics/stereorender/
  24660. var projectionMatrix = camera.projectionMatrix.clone();
  24661. var eyeSepHalf = cache.eyeSep / 2;
  24662. var eyeSepOnProjection = eyeSepHalf * cache.near / cache.focus;
  24663. var ymax = cache.near * Math.tan(_Math.DEG2RAD * cache.fov * 0.5) / cache.zoom;
  24664. var xmin, xmax; // translate xOffset
  24665. _eyeLeft.elements[12] = -eyeSepHalf;
  24666. _eyeRight.elements[12] = eyeSepHalf; // for left eye
  24667. xmin = -ymax * cache.aspect + eyeSepOnProjection;
  24668. xmax = ymax * cache.aspect + eyeSepOnProjection;
  24669. projectionMatrix.elements[0] = 2 * cache.near / (xmax - xmin);
  24670. projectionMatrix.elements[8] = (xmax + xmin) / (xmax - xmin);
  24671. this.cameraL.projectionMatrix.copy(projectionMatrix); // for right eye
  24672. xmin = -ymax * cache.aspect - eyeSepOnProjection;
  24673. xmax = ymax * cache.aspect - eyeSepOnProjection;
  24674. projectionMatrix.elements[0] = 2 * cache.near / (xmax - xmin);
  24675. projectionMatrix.elements[8] = (xmax + xmin) / (xmax - xmin);
  24676. this.cameraR.projectionMatrix.copy(projectionMatrix);
  24677. }
  24678. this.cameraL.matrixWorld.copy(camera.matrixWorld).multiply(_eyeLeft);
  24679. this.cameraR.matrixWorld.copy(camera.matrixWorld).multiply(_eyeRight);
  24680. }
  24681. });
  24682. /**
  24683. * @author alteredq / http://alteredqualia.com/
  24684. */
  24685. function Clock(autoStart) {
  24686. this.autoStart = autoStart !== undefined ? autoStart : true;
  24687. this.startTime = 0;
  24688. this.oldTime = 0;
  24689. this.elapsedTime = 0;
  24690. this.running = false;
  24691. }
  24692. Object.assign(Clock.prototype, {
  24693. start: function () {
  24694. this.startTime = (typeof performance === 'undefined' ? Date : performance).now(); // see #10732
  24695. this.oldTime = this.startTime;
  24696. this.elapsedTime = 0;
  24697. this.running = true;
  24698. },
  24699. stop: function () {
  24700. this.getElapsedTime();
  24701. this.running = false;
  24702. this.autoStart = false;
  24703. },
  24704. getElapsedTime: function () {
  24705. this.getDelta();
  24706. return this.elapsedTime;
  24707. },
  24708. getDelta: function () {
  24709. var diff = 0;
  24710. if (this.autoStart && !this.running) {
  24711. this.start();
  24712. return 0;
  24713. }
  24714. if (this.running) {
  24715. var newTime = (typeof performance === 'undefined' ? Date : performance).now();
  24716. diff = (newTime - this.oldTime) / 1000;
  24717. this.oldTime = newTime;
  24718. this.elapsedTime += diff;
  24719. }
  24720. return diff;
  24721. }
  24722. });
  24723. /**
  24724. * @author mrdoob / http://mrdoob.com/
  24725. */
  24726. var _position$2 = new Vector3();
  24727. var _quaternion$3 = new Quaternion();
  24728. var _scale$1 = new Vector3();
  24729. var _orientation = new Vector3();
  24730. function AudioListener() {
  24731. Object3D.call(this);
  24732. this.type = 'AudioListener';
  24733. this.context = AudioContext.getContext();
  24734. this.gain = this.context.createGain();
  24735. this.gain.connect(this.context.destination);
  24736. this.filter = null;
  24737. this.timeDelta = 0; // private
  24738. this._clock = new Clock();
  24739. }
  24740. AudioListener.prototype = Object.assign(Object.create(Object3D.prototype), {
  24741. constructor: AudioListener,
  24742. getInput: function () {
  24743. return this.gain;
  24744. },
  24745. removeFilter: function () {
  24746. if (this.filter !== null) {
  24747. this.gain.disconnect(this.filter);
  24748. this.filter.disconnect(this.context.destination);
  24749. this.gain.connect(this.context.destination);
  24750. this.filter = null;
  24751. }
  24752. return this;
  24753. },
  24754. getFilter: function () {
  24755. return this.filter;
  24756. },
  24757. setFilter: function (value) {
  24758. if (this.filter !== null) {
  24759. this.gain.disconnect(this.filter);
  24760. this.filter.disconnect(this.context.destination);
  24761. } else {
  24762. this.gain.disconnect(this.context.destination);
  24763. }
  24764. this.filter = value;
  24765. this.gain.connect(this.filter);
  24766. this.filter.connect(this.context.destination);
  24767. return this;
  24768. },
  24769. getMasterVolume: function () {
  24770. return this.gain.gain.value;
  24771. },
  24772. setMasterVolume: function (value) {
  24773. this.gain.gain.setTargetAtTime(value, this.context.currentTime, 0.01);
  24774. return this;
  24775. },
  24776. updateMatrixWorld: function (force) {
  24777. Object3D.prototype.updateMatrixWorld.call(this, force);
  24778. var listener = this.context.listener;
  24779. var up = this.up;
  24780. this.timeDelta = this._clock.getDelta();
  24781. this.matrixWorld.decompose(_position$2, _quaternion$3, _scale$1);
  24782. _orientation.set(0, 0, -1).applyQuaternion(_quaternion$3);
  24783. if (listener.positionX) {
  24784. // code path for Chrome (see #14393)
  24785. var endTime = this.context.currentTime + this.timeDelta;
  24786. listener.positionX.linearRampToValueAtTime(_position$2.x, endTime);
  24787. listener.positionY.linearRampToValueAtTime(_position$2.y, endTime);
  24788. listener.positionZ.linearRampToValueAtTime(_position$2.z, endTime);
  24789. listener.forwardX.linearRampToValueAtTime(_orientation.x, endTime);
  24790. listener.forwardY.linearRampToValueAtTime(_orientation.y, endTime);
  24791. listener.forwardZ.linearRampToValueAtTime(_orientation.z, endTime);
  24792. listener.upX.linearRampToValueAtTime(up.x, endTime);
  24793. listener.upY.linearRampToValueAtTime(up.y, endTime);
  24794. listener.upZ.linearRampToValueAtTime(up.z, endTime);
  24795. } else {
  24796. listener.setPosition(_position$2.x, _position$2.y, _position$2.z);
  24797. listener.setOrientation(_orientation.x, _orientation.y, _orientation.z, up.x, up.y, up.z);
  24798. }
  24799. }
  24800. });
  24801. /**
  24802. * @author mrdoob / http://mrdoob.com/
  24803. * @author Reece Aaron Lecrivain / http://reecenotes.com/
  24804. */
  24805. function Audio(listener) {
  24806. Object3D.call(this);
  24807. this.type = 'Audio';
  24808. this.listener = listener;
  24809. this.context = listener.context;
  24810. this.gain = this.context.createGain();
  24811. this.gain.connect(listener.getInput());
  24812. this.autoplay = false;
  24813. this.buffer = null;
  24814. this.detune = 0;
  24815. this.loop = false;
  24816. this.startTime = 0;
  24817. this.offset = 0;
  24818. this.duration = undefined;
  24819. this.playbackRate = 1;
  24820. this.isPlaying = false;
  24821. this.hasPlaybackControl = true;
  24822. this.sourceType = 'empty';
  24823. this.filters = [];
  24824. }
  24825. Audio.prototype = Object.assign(Object.create(Object3D.prototype), {
  24826. constructor: Audio,
  24827. getOutput: function () {
  24828. return this.gain;
  24829. },
  24830. setNodeSource: function (audioNode) {
  24831. this.hasPlaybackControl = false;
  24832. this.sourceType = 'audioNode';
  24833. this.source = audioNode;
  24834. this.connect();
  24835. return this;
  24836. },
  24837. setMediaElementSource: function (mediaElement) {
  24838. this.hasPlaybackControl = false;
  24839. this.sourceType = 'mediaNode';
  24840. this.source = this.context.createMediaElementSource(mediaElement);
  24841. this.connect();
  24842. return this;
  24843. },
  24844. setMediaStreamSource: function (mediaStream) {
  24845. this.hasPlaybackControl = false;
  24846. this.sourceType = 'mediaStreamNode';
  24847. this.source = this.context.createMediaStreamSource(mediaStream);
  24848. this.connect();
  24849. return this;
  24850. },
  24851. setBuffer: function (audioBuffer) {
  24852. this.buffer = audioBuffer;
  24853. this.sourceType = 'buffer';
  24854. if (this.autoplay) this.play();
  24855. return this;
  24856. },
  24857. play: function () {
  24858. if (this.isPlaying === true) {
  24859. console.warn('THREE.Audio: Audio is already playing.');
  24860. return;
  24861. }
  24862. if (this.hasPlaybackControl === false) {
  24863. console.warn('THREE.Audio: this Audio has no playback control.');
  24864. return;
  24865. }
  24866. var source = this.context.createBufferSource();
  24867. source.buffer = this.buffer;
  24868. source.loop = this.loop;
  24869. source.onended = this.onEnded.bind(this);
  24870. this.startTime = this.context.currentTime;
  24871. source.start(this.startTime, this.offset, this.duration);
  24872. this.isPlaying = true;
  24873. this.source = source;
  24874. this.setDetune(this.detune);
  24875. this.setPlaybackRate(this.playbackRate);
  24876. return this.connect();
  24877. },
  24878. pause: function () {
  24879. if (this.hasPlaybackControl === false) {
  24880. console.warn('THREE.Audio: this Audio has no playback control.');
  24881. return;
  24882. }
  24883. if (this.isPlaying === true) {
  24884. this.source.stop();
  24885. this.source.onended = null;
  24886. this.offset += (this.context.currentTime - this.startTime) * this.playbackRate;
  24887. this.isPlaying = false;
  24888. }
  24889. return this;
  24890. },
  24891. stop: function () {
  24892. if (this.hasPlaybackControl === false) {
  24893. console.warn('THREE.Audio: this Audio has no playback control.');
  24894. return;
  24895. }
  24896. this.source.stop();
  24897. this.source.onended = null;
  24898. this.offset = 0;
  24899. this.isPlaying = false;
  24900. return this;
  24901. },
  24902. connect: function () {
  24903. if (this.filters.length > 0) {
  24904. this.source.connect(this.filters[0]);
  24905. for (var i = 1, l = this.filters.length; i < l; i++) {
  24906. this.filters[i - 1].connect(this.filters[i]);
  24907. }
  24908. this.filters[this.filters.length - 1].connect(this.getOutput());
  24909. } else {
  24910. this.source.connect(this.getOutput());
  24911. }
  24912. return this;
  24913. },
  24914. disconnect: function () {
  24915. if (this.filters.length > 0) {
  24916. this.source.disconnect(this.filters[0]);
  24917. for (var i = 1, l = this.filters.length; i < l; i++) {
  24918. this.filters[i - 1].disconnect(this.filters[i]);
  24919. }
  24920. this.filters[this.filters.length - 1].disconnect(this.getOutput());
  24921. } else {
  24922. this.source.disconnect(this.getOutput());
  24923. }
  24924. return this;
  24925. },
  24926. getFilters: function () {
  24927. return this.filters;
  24928. },
  24929. setFilters: function (value) {
  24930. if (!value) value = [];
  24931. if (this.isPlaying === true) {
  24932. this.disconnect();
  24933. this.filters = value;
  24934. this.connect();
  24935. } else {
  24936. this.filters = value;
  24937. }
  24938. return this;
  24939. },
  24940. setDetune: function (value) {
  24941. this.detune = value;
  24942. if (this.source.detune === undefined) return; // only set detune when available
  24943. if (this.isPlaying === true) {
  24944. this.source.detune.setTargetAtTime(this.detune, this.context.currentTime, 0.01);
  24945. }
  24946. return this;
  24947. },
  24948. getDetune: function () {
  24949. return this.detune;
  24950. },
  24951. getFilter: function () {
  24952. return this.getFilters()[0];
  24953. },
  24954. setFilter: function (filter) {
  24955. return this.setFilters(filter ? [filter] : []);
  24956. },
  24957. setPlaybackRate: function (value) {
  24958. if (this.hasPlaybackControl === false) {
  24959. console.warn('THREE.Audio: this Audio has no playback control.');
  24960. return;
  24961. }
  24962. this.playbackRate = value;
  24963. if (this.isPlaying === true) {
  24964. this.source.playbackRate.setTargetAtTime(this.playbackRate, this.context.currentTime, 0.01);
  24965. }
  24966. return this;
  24967. },
  24968. getPlaybackRate: function () {
  24969. return this.playbackRate;
  24970. },
  24971. onEnded: function () {
  24972. this.isPlaying = false;
  24973. },
  24974. getLoop: function () {
  24975. if (this.hasPlaybackControl === false) {
  24976. console.warn('THREE.Audio: this Audio has no playback control.');
  24977. return false;
  24978. }
  24979. return this.loop;
  24980. },
  24981. setLoop: function (value) {
  24982. if (this.hasPlaybackControl === false) {
  24983. console.warn('THREE.Audio: this Audio has no playback control.');
  24984. return;
  24985. }
  24986. this.loop = value;
  24987. if (this.isPlaying === true) {
  24988. this.source.loop = this.loop;
  24989. }
  24990. return this;
  24991. },
  24992. getVolume: function () {
  24993. return this.gain.gain.value;
  24994. },
  24995. setVolume: function (value) {
  24996. this.gain.gain.setTargetAtTime(value, this.context.currentTime, 0.01);
  24997. return this;
  24998. }
  24999. });
  25000. /**
  25001. * @author mrdoob / http://mrdoob.com/
  25002. */
  25003. var _position$3 = new Vector3();
  25004. var _quaternion$4 = new Quaternion();
  25005. var _scale$2 = new Vector3();
  25006. var _orientation$1 = new Vector3();
  25007. function PositionalAudio(listener) {
  25008. Audio.call(this, listener);
  25009. this.panner = this.context.createPanner();
  25010. this.panner.panningModel = 'HRTF';
  25011. this.panner.connect(this.gain);
  25012. }
  25013. PositionalAudio.prototype = Object.assign(Object.create(Audio.prototype), {
  25014. constructor: PositionalAudio,
  25015. getOutput: function () {
  25016. return this.panner;
  25017. },
  25018. getRefDistance: function () {
  25019. return this.panner.refDistance;
  25020. },
  25021. setRefDistance: function (value) {
  25022. this.panner.refDistance = value;
  25023. return this;
  25024. },
  25025. getRolloffFactor: function () {
  25026. return this.panner.rolloffFactor;
  25027. },
  25028. setRolloffFactor: function (value) {
  25029. this.panner.rolloffFactor = value;
  25030. return this;
  25031. },
  25032. getDistanceModel: function () {
  25033. return this.panner.distanceModel;
  25034. },
  25035. setDistanceModel: function (value) {
  25036. this.panner.distanceModel = value;
  25037. return this;
  25038. },
  25039. getMaxDistance: function () {
  25040. return this.panner.maxDistance;
  25041. },
  25042. setMaxDistance: function (value) {
  25043. this.panner.maxDistance = value;
  25044. return this;
  25045. },
  25046. setDirectionalCone: function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  25047. this.panner.coneInnerAngle = coneInnerAngle;
  25048. this.panner.coneOuterAngle = coneOuterAngle;
  25049. this.panner.coneOuterGain = coneOuterGain;
  25050. return this;
  25051. },
  25052. updateMatrixWorld: function (force) {
  25053. Object3D.prototype.updateMatrixWorld.call(this, force);
  25054. if (this.hasPlaybackControl === true && this.isPlaying === false) return;
  25055. this.matrixWorld.decompose(_position$3, _quaternion$4, _scale$2);
  25056. _orientation$1.set(0, 0, 1).applyQuaternion(_quaternion$4);
  25057. var panner = this.panner;
  25058. if (panner.positionX) {
  25059. // code path for Chrome and Firefox (see #14393)
  25060. var endTime = this.context.currentTime + this.listener.timeDelta;
  25061. panner.positionX.linearRampToValueAtTime(_position$3.x, endTime);
  25062. panner.positionY.linearRampToValueAtTime(_position$3.y, endTime);
  25063. panner.positionZ.linearRampToValueAtTime(_position$3.z, endTime);
  25064. panner.orientationX.linearRampToValueAtTime(_orientation$1.x, endTime);
  25065. panner.orientationY.linearRampToValueAtTime(_orientation$1.y, endTime);
  25066. panner.orientationZ.linearRampToValueAtTime(_orientation$1.z, endTime);
  25067. } else {
  25068. panner.setPosition(_position$3.x, _position$3.y, _position$3.z);
  25069. panner.setOrientation(_orientation$1.x, _orientation$1.y, _orientation$1.z);
  25070. }
  25071. }
  25072. });
  25073. /**
  25074. * @author mrdoob / http://mrdoob.com/
  25075. */
  25076. function AudioAnalyser(audio, fftSize) {
  25077. this.analyser = audio.context.createAnalyser();
  25078. this.analyser.fftSize = fftSize !== undefined ? fftSize : 2048;
  25079. this.data = new Uint8Array(this.analyser.frequencyBinCount);
  25080. audio.getOutput().connect(this.analyser);
  25081. }
  25082. Object.assign(AudioAnalyser.prototype, {
  25083. getFrequencyData: function () {
  25084. this.analyser.getByteFrequencyData(this.data);
  25085. return this.data;
  25086. },
  25087. getAverageFrequency: function () {
  25088. var value = 0,
  25089. data = this.getFrequencyData();
  25090. for (var i = 0; i < data.length; i++) {
  25091. value += data[i];
  25092. }
  25093. return value / data.length;
  25094. }
  25095. });
  25096. /**
  25097. *
  25098. * Buffered scene graph property that allows weighted accumulation.
  25099. *
  25100. *
  25101. * @author Ben Houston / http://clara.io/
  25102. * @author David Sarno / http://lighthaus.us/
  25103. * @author tschw
  25104. */
  25105. function PropertyMixer(binding, typeName, valueSize) {
  25106. this.binding = binding;
  25107. this.valueSize = valueSize;
  25108. var bufferType = Float64Array,
  25109. mixFunction;
  25110. switch (typeName) {
  25111. case 'quaternion':
  25112. mixFunction = this._slerp;
  25113. break;
  25114. case 'string':
  25115. case 'bool':
  25116. bufferType = Array;
  25117. mixFunction = this._select;
  25118. break;
  25119. default:
  25120. mixFunction = this._lerp;
  25121. }
  25122. this.buffer = new bufferType(valueSize * 4); // layout: [ incoming | accu0 | accu1 | orig ]
  25123. //
  25124. // interpolators can use .buffer as their .result
  25125. // the data then goes to 'incoming'
  25126. //
  25127. // 'accu0' and 'accu1' are used frame-interleaved for
  25128. // the cumulative result and are compared to detect
  25129. // changes
  25130. //
  25131. // 'orig' stores the original state of the property
  25132. this._mixBufferRegion = mixFunction;
  25133. this.cumulativeWeight = 0;
  25134. this.useCount = 0;
  25135. this.referenceCount = 0;
  25136. }
  25137. Object.assign(PropertyMixer.prototype, {
  25138. // accumulate data in the 'incoming' region into 'accu<i>'
  25139. accumulate: function (accuIndex, weight) {
  25140. // note: happily accumulating nothing when weight = 0, the caller knows
  25141. // the weight and shouldn't have made the call in the first place
  25142. var buffer = this.buffer,
  25143. stride = this.valueSize,
  25144. offset = accuIndex * stride + stride,
  25145. currentWeight = this.cumulativeWeight;
  25146. if (currentWeight === 0) {
  25147. // accuN := incoming * weight
  25148. for (var i = 0; i !== stride; ++i) {
  25149. buffer[offset + i] = buffer[i];
  25150. }
  25151. currentWeight = weight;
  25152. } else {
  25153. // accuN := accuN + incoming * weight
  25154. currentWeight += weight;
  25155. var mix = weight / currentWeight;
  25156. this._mixBufferRegion(buffer, offset, 0, mix, stride);
  25157. }
  25158. this.cumulativeWeight = currentWeight;
  25159. },
  25160. // apply the state of 'accu<i>' to the binding when accus differ
  25161. apply: function (accuIndex) {
  25162. var stride = this.valueSize,
  25163. buffer = this.buffer,
  25164. offset = accuIndex * stride + stride,
  25165. weight = this.cumulativeWeight,
  25166. binding = this.binding;
  25167. this.cumulativeWeight = 0;
  25168. if (weight < 1) {
  25169. // accuN := accuN + original * ( 1 - cumulativeWeight )
  25170. var originalValueOffset = stride * 3;
  25171. this._mixBufferRegion(buffer, offset, originalValueOffset, 1 - weight, stride);
  25172. }
  25173. for (var i = stride, e = stride + stride; i !== e; ++i) {
  25174. if (buffer[i] !== buffer[i + stride]) {
  25175. // value has changed -> update scene graph
  25176. binding.setValue(buffer, offset);
  25177. break;
  25178. }
  25179. }
  25180. },
  25181. // remember the state of the bound property and copy it to both accus
  25182. saveOriginalState: function () {
  25183. var binding = this.binding;
  25184. var buffer = this.buffer,
  25185. stride = this.valueSize,
  25186. originalValueOffset = stride * 3;
  25187. binding.getValue(buffer, originalValueOffset); // accu[0..1] := orig -- initially detect changes against the original
  25188. for (var i = stride, e = originalValueOffset; i !== e; ++i) {
  25189. buffer[i] = buffer[originalValueOffset + i % stride];
  25190. }
  25191. this.cumulativeWeight = 0;
  25192. },
  25193. // apply the state previously taken via 'saveOriginalState' to the binding
  25194. restoreOriginalState: function () {
  25195. var originalValueOffset = this.valueSize * 3;
  25196. this.binding.setValue(this.buffer, originalValueOffset);
  25197. },
  25198. // mix functions
  25199. _select: function (buffer, dstOffset, srcOffset, t, stride) {
  25200. if (t >= 0.5) {
  25201. for (var i = 0; i !== stride; ++i) {
  25202. buffer[dstOffset + i] = buffer[srcOffset + i];
  25203. }
  25204. }
  25205. },
  25206. _slerp: function (buffer, dstOffset, srcOffset, t) {
  25207. Quaternion.slerpFlat(buffer, dstOffset, buffer, dstOffset, buffer, srcOffset, t);
  25208. },
  25209. _lerp: function (buffer, dstOffset, srcOffset, t, stride) {
  25210. var s = 1 - t;
  25211. for (var i = 0; i !== stride; ++i) {
  25212. var j = dstOffset + i;
  25213. buffer[j] = buffer[j] * s + buffer[srcOffset + i] * t;
  25214. }
  25215. }
  25216. });
  25217. /**
  25218. *
  25219. * A reference to a real property in the scene graph.
  25220. *
  25221. *
  25222. * @author Ben Houston / http://clara.io/
  25223. * @author David Sarno / http://lighthaus.us/
  25224. * @author tschw
  25225. */
  25226. // Characters [].:/ are reserved for track binding syntax.
  25227. var _RESERVED_CHARS_RE = '\\[\\]\\.:\\/';
  25228. var _reservedRe = new RegExp('[' + _RESERVED_CHARS_RE + ']', 'g'); // Attempts to allow node names from any language. ES5's `\w` regexp matches
  25229. // only latin characters, and the unicode \p{L} is not yet supported. So
  25230. // instead, we exclude reserved characters and match everything else.
  25231. var _wordChar = '[^' + _RESERVED_CHARS_RE + ']';
  25232. var _wordCharOrDot = '[^' + _RESERVED_CHARS_RE.replace('\\.', '') + ']'; // Parent directories, delimited by '/' or ':'. Currently unused, but must
  25233. // be matched to parse the rest of the track name.
  25234. var _directoryRe = /((?:WC+[\/:])*)/.source.replace('WC', _wordChar); // Target node. May contain word characters (a-zA-Z0-9_) and '.' or '-'.
  25235. var _nodeRe = /(WCOD+)?/.source.replace('WCOD', _wordCharOrDot); // Object on target node, and accessor. May not contain reserved
  25236. // characters. Accessor may contain any character except closing bracket.
  25237. var _objectRe = /(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace('WC', _wordChar); // Property and accessor. May not contain reserved characters. Accessor may
  25238. // contain any non-bracket characters.
  25239. var _propertyRe = /\.(WC+)(?:\[(.+)\])?/.source.replace('WC', _wordChar);
  25240. var _trackRe = new RegExp('' + '^' + _directoryRe + _nodeRe + _objectRe + _propertyRe + '$');
  25241. var _supportedObjectNames = ['material', 'materials', 'bones'];
  25242. function Composite(targetGroup, path, optionalParsedPath) {
  25243. var parsedPath = optionalParsedPath || PropertyBinding.parseTrackName(path);
  25244. this._targetGroup = targetGroup;
  25245. this._bindings = targetGroup.subscribe_(path, parsedPath);
  25246. }
  25247. Object.assign(Composite.prototype, {
  25248. getValue: function (array, offset) {
  25249. this.bind(); // bind all binding
  25250. var firstValidIndex = this._targetGroup.nCachedObjects_,
  25251. binding = this._bindings[firstValidIndex]; // and only call .getValue on the first
  25252. if (binding !== undefined) binding.getValue(array, offset);
  25253. },
  25254. setValue: function (array, offset) {
  25255. var bindings = this._bindings;
  25256. for (var i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++i) {
  25257. bindings[i].setValue(array, offset);
  25258. }
  25259. },
  25260. bind: function () {
  25261. var bindings = this._bindings;
  25262. for (var i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++i) {
  25263. bindings[i].bind();
  25264. }
  25265. },
  25266. unbind: function () {
  25267. var bindings = this._bindings;
  25268. for (var i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++i) {
  25269. bindings[i].unbind();
  25270. }
  25271. }
  25272. });
  25273. function PropertyBinding(rootNode, path, parsedPath) {
  25274. this.path = path;
  25275. this.parsedPath = parsedPath || PropertyBinding.parseTrackName(path);
  25276. this.node = PropertyBinding.findNode(rootNode, this.parsedPath.nodeName) || rootNode;
  25277. this.rootNode = rootNode;
  25278. }
  25279. Object.assign(PropertyBinding, {
  25280. Composite: Composite,
  25281. create: function (root, path, parsedPath) {
  25282. if (!(root && root.isAnimationObjectGroup)) {
  25283. return new PropertyBinding(root, path, parsedPath);
  25284. } else {
  25285. return new PropertyBinding.Composite(root, path, parsedPath);
  25286. }
  25287. },
  25288. /**
  25289. * Replaces spaces with underscores and removes unsupported characters from
  25290. * node names, to ensure compatibility with parseTrackName().
  25291. *
  25292. * @param {string} name Node name to be sanitized.
  25293. * @return {string}
  25294. */
  25295. sanitizeNodeName: function (name) {
  25296. return name.replace(/\s/g, '_').replace(_reservedRe, '');
  25297. },
  25298. parseTrackName: function (trackName) {
  25299. var matches = _trackRe.exec(trackName);
  25300. if (!matches) {
  25301. throw new Error('PropertyBinding: Cannot parse trackName: ' + trackName);
  25302. }
  25303. var results = {
  25304. // directoryName: matches[ 1 ], // (tschw) currently unused
  25305. nodeName: matches[2],
  25306. objectName: matches[3],
  25307. objectIndex: matches[4],
  25308. propertyName: matches[5],
  25309. // required
  25310. propertyIndex: matches[6]
  25311. };
  25312. var lastDot = results.nodeName && results.nodeName.lastIndexOf('.');
  25313. if (lastDot !== undefined && lastDot !== -1) {
  25314. var objectName = results.nodeName.substring(lastDot + 1); // Object names must be checked against a whitelist. Otherwise, there
  25315. // is no way to parse 'foo.bar.baz': 'baz' must be a property, but
  25316. // 'bar' could be the objectName, or part of a nodeName (which can
  25317. // include '.' characters).
  25318. if (_supportedObjectNames.indexOf(objectName) !== -1) {
  25319. results.nodeName = results.nodeName.substring(0, lastDot);
  25320. results.objectName = objectName;
  25321. }
  25322. }
  25323. if (results.propertyName === null || results.propertyName.length === 0) {
  25324. throw new Error('PropertyBinding: can not parse propertyName from trackName: ' + trackName);
  25325. }
  25326. return results;
  25327. },
  25328. findNode: function (root, nodeName) {
  25329. if (!nodeName || nodeName === "" || nodeName === "root" || nodeName === "." || nodeName === -1 || nodeName === root.name || nodeName === root.uuid) {
  25330. return root;
  25331. } // search into skeleton bones.
  25332. if (root.skeleton) {
  25333. var bone = root.skeleton.getBoneByName(nodeName);
  25334. if (bone !== undefined) {
  25335. return bone;
  25336. }
  25337. } // search into node subtree.
  25338. if (root.children) {
  25339. var searchNodeSubtree = function (children) {
  25340. for (var i = 0; i < children.length; i++) {
  25341. var childNode = children[i];
  25342. if (childNode.name === nodeName || childNode.uuid === nodeName) {
  25343. return childNode;
  25344. }
  25345. var result = searchNodeSubtree(childNode.children);
  25346. if (result) return result;
  25347. }
  25348. return null;
  25349. };
  25350. var subTreeNode = searchNodeSubtree(root.children);
  25351. if (subTreeNode) {
  25352. return subTreeNode;
  25353. }
  25354. }
  25355. return null;
  25356. }
  25357. });
  25358. Object.assign(PropertyBinding.prototype, {
  25359. // prototype, continued
  25360. // these are used to "bind" a nonexistent property
  25361. _getValue_unavailable: function () {},
  25362. _setValue_unavailable: function () {},
  25363. BindingType: {
  25364. Direct: 0,
  25365. EntireArray: 1,
  25366. ArrayElement: 2,
  25367. HasFromToArray: 3
  25368. },
  25369. Versioning: {
  25370. None: 0,
  25371. NeedsUpdate: 1,
  25372. MatrixWorldNeedsUpdate: 2
  25373. },
  25374. GetterByBindingType: [function getValue_direct(buffer, offset) {
  25375. buffer[offset] = this.node[this.propertyName];
  25376. }, function getValue_array(buffer, offset) {
  25377. var source = this.resolvedProperty;
  25378. for (var i = 0, n = source.length; i !== n; ++i) {
  25379. buffer[offset++] = source[i];
  25380. }
  25381. }, function getValue_arrayElement(buffer, offset) {
  25382. buffer[offset] = this.resolvedProperty[this.propertyIndex];
  25383. }, function getValue_toArray(buffer, offset) {
  25384. this.resolvedProperty.toArray(buffer, offset);
  25385. }],
  25386. SetterByBindingTypeAndVersioning: [[// Direct
  25387. function setValue_direct(buffer, offset) {
  25388. this.targetObject[this.propertyName] = buffer[offset];
  25389. }, function setValue_direct_setNeedsUpdate(buffer, offset) {
  25390. this.targetObject[this.propertyName] = buffer[offset];
  25391. this.targetObject.needsUpdate = true;
  25392. }, function setValue_direct_setMatrixWorldNeedsUpdate(buffer, offset) {
  25393. this.targetObject[this.propertyName] = buffer[offset];
  25394. this.targetObject.matrixWorldNeedsUpdate = true;
  25395. }], [// EntireArray
  25396. function setValue_array(buffer, offset) {
  25397. var dest = this.resolvedProperty;
  25398. for (var i = 0, n = dest.length; i !== n; ++i) {
  25399. dest[i] = buffer[offset++];
  25400. }
  25401. }, function setValue_array_setNeedsUpdate(buffer, offset) {
  25402. var dest = this.resolvedProperty;
  25403. for (var i = 0, n = dest.length; i !== n; ++i) {
  25404. dest[i] = buffer[offset++];
  25405. }
  25406. this.targetObject.needsUpdate = true;
  25407. }, function setValue_array_setMatrixWorldNeedsUpdate(buffer, offset) {
  25408. var dest = this.resolvedProperty;
  25409. for (var i = 0, n = dest.length; i !== n; ++i) {
  25410. dest[i] = buffer[offset++];
  25411. }
  25412. this.targetObject.matrixWorldNeedsUpdate = true;
  25413. }], [// ArrayElement
  25414. function setValue_arrayElement(buffer, offset) {
  25415. this.resolvedProperty[this.propertyIndex] = buffer[offset];
  25416. }, function setValue_arrayElement_setNeedsUpdate(buffer, offset) {
  25417. this.resolvedProperty[this.propertyIndex] = buffer[offset];
  25418. this.targetObject.needsUpdate = true;
  25419. }, function setValue_arrayElement_setMatrixWorldNeedsUpdate(buffer, offset) {
  25420. this.resolvedProperty[this.propertyIndex] = buffer[offset];
  25421. this.targetObject.matrixWorldNeedsUpdate = true;
  25422. }], [// HasToFromArray
  25423. function setValue_fromArray(buffer, offset) {
  25424. this.resolvedProperty.fromArray(buffer, offset);
  25425. }, function setValue_fromArray_setNeedsUpdate(buffer, offset) {
  25426. this.resolvedProperty.fromArray(buffer, offset);
  25427. this.targetObject.needsUpdate = true;
  25428. }, function setValue_fromArray_setMatrixWorldNeedsUpdate(buffer, offset) {
  25429. this.resolvedProperty.fromArray(buffer, offset);
  25430. this.targetObject.matrixWorldNeedsUpdate = true;
  25431. }]],
  25432. getValue: function getValue_unbound(targetArray, offset) {
  25433. this.bind();
  25434. this.getValue(targetArray, offset); // Note: This class uses a State pattern on a per-method basis:
  25435. // 'bind' sets 'this.getValue' / 'setValue' and shadows the
  25436. // prototype version of these methods with one that represents
  25437. // the bound state. When the property is not found, the methods
  25438. // become no-ops.
  25439. },
  25440. setValue: function getValue_unbound(sourceArray, offset) {
  25441. this.bind();
  25442. this.setValue(sourceArray, offset);
  25443. },
  25444. // create getter / setter pair for a property in the scene graph
  25445. bind: function () {
  25446. var targetObject = this.node,
  25447. parsedPath = this.parsedPath,
  25448. objectName = parsedPath.objectName,
  25449. propertyName = parsedPath.propertyName,
  25450. propertyIndex = parsedPath.propertyIndex;
  25451. if (!targetObject) {
  25452. targetObject = PropertyBinding.findNode(this.rootNode, parsedPath.nodeName) || this.rootNode;
  25453. this.node = targetObject;
  25454. } // set fail state so we can just 'return' on error
  25455. this.getValue = this._getValue_unavailable;
  25456. this.setValue = this._setValue_unavailable; // ensure there is a value node
  25457. if (!targetObject) {
  25458. console.error('THREE.PropertyBinding: Trying to update node for track: ' + this.path + ' but it wasn\'t found.');
  25459. return;
  25460. }
  25461. if (objectName) {
  25462. var objectIndex = parsedPath.objectIndex; // special cases were we need to reach deeper into the hierarchy to get the face materials....
  25463. switch (objectName) {
  25464. case 'materials':
  25465. if (!targetObject.material) {
  25466. console.error('THREE.PropertyBinding: Can not bind to material as node does not have a material.', this);
  25467. return;
  25468. }
  25469. if (!targetObject.material.materials) {
  25470. console.error('THREE.PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.', this);
  25471. return;
  25472. }
  25473. targetObject = targetObject.material.materials;
  25474. break;
  25475. case 'bones':
  25476. if (!targetObject.skeleton) {
  25477. console.error('THREE.PropertyBinding: Can not bind to bones as node does not have a skeleton.', this);
  25478. return;
  25479. } // potential future optimization: skip this if propertyIndex is already an integer
  25480. // and convert the integer string to a true integer.
  25481. targetObject = targetObject.skeleton.bones; // support resolving morphTarget names into indices.
  25482. for (var i = 0; i < targetObject.length; i++) {
  25483. if (targetObject[i].name === objectIndex) {
  25484. objectIndex = i;
  25485. break;
  25486. }
  25487. }
  25488. break;
  25489. default:
  25490. if (targetObject[objectName] === undefined) {
  25491. console.error('THREE.PropertyBinding: Can not bind to objectName of node undefined.', this);
  25492. return;
  25493. }
  25494. targetObject = targetObject[objectName];
  25495. }
  25496. if (objectIndex !== undefined) {
  25497. if (targetObject[objectIndex] === undefined) {
  25498. console.error('THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.', this, targetObject);
  25499. return;
  25500. }
  25501. targetObject = targetObject[objectIndex];
  25502. }
  25503. } // resolve property
  25504. var nodeProperty = targetObject[propertyName];
  25505. if (nodeProperty === undefined) {
  25506. var nodeName = parsedPath.nodeName;
  25507. console.error('THREE.PropertyBinding: Trying to update property for track: ' + nodeName + '.' + propertyName + ' but it wasn\'t found.', targetObject);
  25508. return;
  25509. } // determine versioning scheme
  25510. var versioning = this.Versioning.None;
  25511. this.targetObject = targetObject;
  25512. if (targetObject.needsUpdate !== undefined) {
  25513. // material
  25514. versioning = this.Versioning.NeedsUpdate;
  25515. } else if (targetObject.matrixWorldNeedsUpdate !== undefined) {
  25516. // node transform
  25517. versioning = this.Versioning.MatrixWorldNeedsUpdate;
  25518. } // determine how the property gets bound
  25519. var bindingType = this.BindingType.Direct;
  25520. if (propertyIndex !== undefined) {
  25521. // access a sub element of the property array (only primitives are supported right now)
  25522. if (propertyName === "morphTargetInfluences") {
  25523. // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer.
  25524. // support resolving morphTarget names into indices.
  25525. if (!targetObject.geometry) {
  25526. console.error('THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.', this);
  25527. return;
  25528. }
  25529. if (targetObject.geometry.isBufferGeometry) {
  25530. if (!targetObject.geometry.morphAttributes) {
  25531. console.error('THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.', this);
  25532. return;
  25533. }
  25534. for (var i = 0; i < this.node.geometry.morphAttributes.position.length; i++) {
  25535. if (targetObject.geometry.morphAttributes.position[i].name === propertyIndex) {
  25536. propertyIndex = i;
  25537. break;
  25538. }
  25539. }
  25540. } else {
  25541. if (!targetObject.geometry.morphTargets) {
  25542. console.error('THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphTargets.', this);
  25543. return;
  25544. }
  25545. for (var i = 0; i < this.node.geometry.morphTargets.length; i++) {
  25546. if (targetObject.geometry.morphTargets[i].name === propertyIndex) {
  25547. propertyIndex = i;
  25548. break;
  25549. }
  25550. }
  25551. }
  25552. }
  25553. bindingType = this.BindingType.ArrayElement;
  25554. this.resolvedProperty = nodeProperty;
  25555. this.propertyIndex = propertyIndex;
  25556. } else if (nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined) {
  25557. // must use copy for Object3D.Euler/Quaternion
  25558. bindingType = this.BindingType.HasFromToArray;
  25559. this.resolvedProperty = nodeProperty;
  25560. } else if (Array.isArray(nodeProperty)) {
  25561. bindingType = this.BindingType.EntireArray;
  25562. this.resolvedProperty = nodeProperty;
  25563. } else {
  25564. this.propertyName = propertyName;
  25565. } // select getter / setter
  25566. this.getValue = this.GetterByBindingType[bindingType];
  25567. this.setValue = this.SetterByBindingTypeAndVersioning[bindingType][versioning];
  25568. },
  25569. unbind: function () {
  25570. this.node = null; // back to the prototype version of getValue / setValue
  25571. // note: avoiding to mutate the shape of 'this' via 'delete'
  25572. this.getValue = this._getValue_unbound;
  25573. this.setValue = this._setValue_unbound;
  25574. }
  25575. }); //!\ DECLARE ALIAS AFTER assign prototype !
  25576. Object.assign(PropertyBinding.prototype, {
  25577. // initial state of these methods that calls 'bind'
  25578. _getValue_unbound: PropertyBinding.prototype.getValue,
  25579. _setValue_unbound: PropertyBinding.prototype.setValue
  25580. });
  25581. /**
  25582. *
  25583. * A group of objects that receives a shared animation state.
  25584. *
  25585. * Usage:
  25586. *
  25587. * - Add objects you would otherwise pass as 'root' to the
  25588. * constructor or the .clipAction method of AnimationMixer.
  25589. *
  25590. * - Instead pass this object as 'root'.
  25591. *
  25592. * - You can also add and remove objects later when the mixer
  25593. * is running.
  25594. *
  25595. * Note:
  25596. *
  25597. * Objects of this class appear as one object to the mixer,
  25598. * so cache control of the individual objects must be done
  25599. * on the group.
  25600. *
  25601. * Limitation:
  25602. *
  25603. * - The animated properties must be compatible among the
  25604. * all objects in the group.
  25605. *
  25606. * - A single property can either be controlled through a
  25607. * target group or directly, but not both.
  25608. *
  25609. * @author tschw
  25610. */
  25611. function AnimationObjectGroup() {
  25612. this.uuid = _Math.generateUUID(); // cached objects followed by the active ones
  25613. this._objects = Array.prototype.slice.call(arguments);
  25614. this.nCachedObjects_ = 0; // threshold
  25615. // note: read by PropertyBinding.Composite
  25616. var indices = {};
  25617. this._indicesByUUID = indices; // for bookkeeping
  25618. for (var i = 0, n = arguments.length; i !== n; ++i) {
  25619. indices[arguments[i].uuid] = i;
  25620. }
  25621. this._paths = []; // inside: string
  25622. this._parsedPaths = []; // inside: { we don't care, here }
  25623. this._bindings = []; // inside: Array< PropertyBinding >
  25624. this._bindingsIndicesByPath = {}; // inside: indices in these arrays
  25625. var scope = this;
  25626. this.stats = {
  25627. objects: {
  25628. get total() {
  25629. return scope._objects.length;
  25630. },
  25631. get inUse() {
  25632. return this.total - scope.nCachedObjects_;
  25633. }
  25634. },
  25635. get bindingsPerObject() {
  25636. return scope._bindings.length;
  25637. }
  25638. };
  25639. }
  25640. Object.assign(AnimationObjectGroup.prototype, {
  25641. isAnimationObjectGroup: true,
  25642. add: function () {
  25643. var objects = this._objects,
  25644. nObjects = objects.length,
  25645. nCachedObjects = this.nCachedObjects_,
  25646. indicesByUUID = this._indicesByUUID,
  25647. paths = this._paths,
  25648. parsedPaths = this._parsedPaths,
  25649. bindings = this._bindings,
  25650. nBindings = bindings.length,
  25651. knownObject = undefined;
  25652. for (var i = 0, n = arguments.length; i !== n; ++i) {
  25653. var object = arguments[i],
  25654. uuid = object.uuid,
  25655. index = indicesByUUID[uuid];
  25656. if (index === undefined) {
  25657. // unknown object -> add it to the ACTIVE region
  25658. index = nObjects++;
  25659. indicesByUUID[uuid] = index;
  25660. objects.push(object); // accounting is done, now do the same for all bindings
  25661. for (var j = 0, m = nBindings; j !== m; ++j) {
  25662. bindings[j].push(new PropertyBinding(object, paths[j], parsedPaths[j]));
  25663. }
  25664. } else if (index < nCachedObjects) {
  25665. knownObject = objects[index]; // move existing object to the ACTIVE region
  25666. var firstActiveIndex = --nCachedObjects,
  25667. lastCachedObject = objects[firstActiveIndex];
  25668. indicesByUUID[lastCachedObject.uuid] = index;
  25669. objects[index] = lastCachedObject;
  25670. indicesByUUID[uuid] = firstActiveIndex;
  25671. objects[firstActiveIndex] = object; // accounting is done, now do the same for all bindings
  25672. for (var j = 0, m = nBindings; j !== m; ++j) {
  25673. var bindingsForPath = bindings[j],
  25674. lastCached = bindingsForPath[firstActiveIndex],
  25675. binding = bindingsForPath[index];
  25676. bindingsForPath[index] = lastCached;
  25677. if (binding === undefined) {
  25678. // since we do not bother to create new bindings
  25679. // for objects that are cached, the binding may
  25680. // or may not exist
  25681. binding = new PropertyBinding(object, paths[j], parsedPaths[j]);
  25682. }
  25683. bindingsForPath[firstActiveIndex] = binding;
  25684. }
  25685. } else if (objects[index] !== knownObject) {
  25686. console.error('THREE.AnimationObjectGroup: Different objects with the same UUID ' + 'detected. Clean the caches or recreate your infrastructure when reloading scenes.');
  25687. } // else the object is already where we want it to be
  25688. } // for arguments
  25689. this.nCachedObjects_ = nCachedObjects;
  25690. },
  25691. remove: function () {
  25692. var objects = this._objects,
  25693. nCachedObjects = this.nCachedObjects_,
  25694. indicesByUUID = this._indicesByUUID,
  25695. bindings = this._bindings,
  25696. nBindings = bindings.length;
  25697. for (var i = 0, n = arguments.length; i !== n; ++i) {
  25698. var object = arguments[i],
  25699. uuid = object.uuid,
  25700. index = indicesByUUID[uuid];
  25701. if (index !== undefined && index >= nCachedObjects) {
  25702. // move existing object into the CACHED region
  25703. var lastCachedIndex = nCachedObjects++,
  25704. firstActiveObject = objects[lastCachedIndex];
  25705. indicesByUUID[firstActiveObject.uuid] = index;
  25706. objects[index] = firstActiveObject;
  25707. indicesByUUID[uuid] = lastCachedIndex;
  25708. objects[lastCachedIndex] = object; // accounting is done, now do the same for all bindings
  25709. for (var j = 0, m = nBindings; j !== m; ++j) {
  25710. var bindingsForPath = bindings[j],
  25711. firstActive = bindingsForPath[lastCachedIndex],
  25712. binding = bindingsForPath[index];
  25713. bindingsForPath[index] = firstActive;
  25714. bindingsForPath[lastCachedIndex] = binding;
  25715. }
  25716. }
  25717. } // for arguments
  25718. this.nCachedObjects_ = nCachedObjects;
  25719. },
  25720. // remove & forget
  25721. uncache: function () {
  25722. var objects = this._objects,
  25723. nObjects = objects.length,
  25724. nCachedObjects = this.nCachedObjects_,
  25725. indicesByUUID = this._indicesByUUID,
  25726. bindings = this._bindings,
  25727. nBindings = bindings.length;
  25728. for (var i = 0, n = arguments.length; i !== n; ++i) {
  25729. var object = arguments[i],
  25730. uuid = object.uuid,
  25731. index = indicesByUUID[uuid];
  25732. if (index !== undefined) {
  25733. delete indicesByUUID[uuid];
  25734. if (index < nCachedObjects) {
  25735. // object is cached, shrink the CACHED region
  25736. var firstActiveIndex = --nCachedObjects,
  25737. lastCachedObject = objects[firstActiveIndex],
  25738. lastIndex = --nObjects,
  25739. lastObject = objects[lastIndex]; // last cached object takes this object's place
  25740. indicesByUUID[lastCachedObject.uuid] = index;
  25741. objects[index] = lastCachedObject; // last object goes to the activated slot and pop
  25742. indicesByUUID[lastObject.uuid] = firstActiveIndex;
  25743. objects[firstActiveIndex] = lastObject;
  25744. objects.pop(); // accounting is done, now do the same for all bindings
  25745. for (var j = 0, m = nBindings; j !== m; ++j) {
  25746. var bindingsForPath = bindings[j],
  25747. lastCached = bindingsForPath[firstActiveIndex],
  25748. last = bindingsForPath[lastIndex];
  25749. bindingsForPath[index] = lastCached;
  25750. bindingsForPath[firstActiveIndex] = last;
  25751. bindingsForPath.pop();
  25752. }
  25753. } else {
  25754. // object is active, just swap with the last and pop
  25755. var lastIndex = --nObjects,
  25756. lastObject = objects[lastIndex];
  25757. indicesByUUID[lastObject.uuid] = index;
  25758. objects[index] = lastObject;
  25759. objects.pop(); // accounting is done, now do the same for all bindings
  25760. for (var j = 0, m = nBindings; j !== m; ++j) {
  25761. var bindingsForPath = bindings[j];
  25762. bindingsForPath[index] = bindingsForPath[lastIndex];
  25763. bindingsForPath.pop();
  25764. }
  25765. } // cached or active
  25766. } // if object is known
  25767. } // for arguments
  25768. this.nCachedObjects_ = nCachedObjects;
  25769. },
  25770. // Internal interface used by befriended PropertyBinding.Composite:
  25771. subscribe_: function (path, parsedPath) {
  25772. // returns an array of bindings for the given path that is changed
  25773. // according to the contained objects in the group
  25774. var indicesByPath = this._bindingsIndicesByPath,
  25775. index = indicesByPath[path],
  25776. bindings = this._bindings;
  25777. if (index !== undefined) return bindings[index];
  25778. var paths = this._paths,
  25779. parsedPaths = this._parsedPaths,
  25780. objects = this._objects,
  25781. nObjects = objects.length,
  25782. nCachedObjects = this.nCachedObjects_,
  25783. bindingsForPath = new Array(nObjects);
  25784. index = bindings.length;
  25785. indicesByPath[path] = index;
  25786. paths.push(path);
  25787. parsedPaths.push(parsedPath);
  25788. bindings.push(bindingsForPath);
  25789. for (var i = nCachedObjects, n = objects.length; i !== n; ++i) {
  25790. var object = objects[i];
  25791. bindingsForPath[i] = new PropertyBinding(object, path, parsedPath);
  25792. }
  25793. return bindingsForPath;
  25794. },
  25795. unsubscribe_: function (path) {
  25796. // tells the group to forget about a property path and no longer
  25797. // update the array previously obtained with 'subscribe_'
  25798. var indicesByPath = this._bindingsIndicesByPath,
  25799. index = indicesByPath[path];
  25800. if (index !== undefined) {
  25801. var paths = this._paths,
  25802. parsedPaths = this._parsedPaths,
  25803. bindings = this._bindings,
  25804. lastBindingsIndex = bindings.length - 1,
  25805. lastBindings = bindings[lastBindingsIndex],
  25806. lastBindingsPath = path[lastBindingsIndex];
  25807. indicesByPath[lastBindingsPath] = index;
  25808. bindings[index] = lastBindings;
  25809. bindings.pop();
  25810. parsedPaths[index] = parsedPaths[lastBindingsIndex];
  25811. parsedPaths.pop();
  25812. paths[index] = paths[lastBindingsIndex];
  25813. paths.pop();
  25814. }
  25815. }
  25816. });
  25817. /**
  25818. *
  25819. * Action provided by AnimationMixer for scheduling clip playback on specific
  25820. * objects.
  25821. *
  25822. * @author Ben Houston / http://clara.io/
  25823. * @author David Sarno / http://lighthaus.us/
  25824. * @author tschw
  25825. *
  25826. */
  25827. function AnimationAction(mixer, clip, localRoot) {
  25828. this._mixer = mixer;
  25829. this._clip = clip;
  25830. this._localRoot = localRoot || null;
  25831. var tracks = clip.tracks,
  25832. nTracks = tracks.length,
  25833. interpolants = new Array(nTracks);
  25834. var interpolantSettings = {
  25835. endingStart: ZeroCurvatureEnding,
  25836. endingEnd: ZeroCurvatureEnding
  25837. };
  25838. for (var i = 0; i !== nTracks; ++i) {
  25839. var interpolant = tracks[i].createInterpolant(null);
  25840. interpolants[i] = interpolant;
  25841. interpolant.settings = interpolantSettings;
  25842. }
  25843. this._interpolantSettings = interpolantSettings;
  25844. this._interpolants = interpolants; // bound by the mixer
  25845. // inside: PropertyMixer (managed by the mixer)
  25846. this._propertyBindings = new Array(nTracks);
  25847. this._cacheIndex = null; // for the memory manager
  25848. this._byClipCacheIndex = null; // for the memory manager
  25849. this._timeScaleInterpolant = null;
  25850. this._weightInterpolant = null;
  25851. this.loop = LoopRepeat;
  25852. this._loopCount = -1; // global mixer time when the action is to be started
  25853. // it's set back to 'null' upon start of the action
  25854. this._startTime = null; // scaled local time of the action
  25855. // gets clamped or wrapped to 0..clip.duration according to loop
  25856. this.time = 0;
  25857. this.timeScale = 1;
  25858. this._effectiveTimeScale = 1;
  25859. this.weight = 1;
  25860. this._effectiveWeight = 1;
  25861. this.repetitions = Infinity; // no. of repetitions when looping
  25862. this.paused = false; // true -> zero effective time scale
  25863. this.enabled = true; // false -> zero effective weight
  25864. this.clampWhenFinished = false; // keep feeding the last frame?
  25865. this.zeroSlopeAtStart = true; // for smooth interpolation w/o separate
  25866. this.zeroSlopeAtEnd = true; // clips for start, loop and end
  25867. }
  25868. Object.assign(AnimationAction.prototype, {
  25869. // State & Scheduling
  25870. play: function () {
  25871. this._mixer._activateAction(this);
  25872. return this;
  25873. },
  25874. stop: function () {
  25875. this._mixer._deactivateAction(this);
  25876. return this.reset();
  25877. },
  25878. reset: function () {
  25879. this.paused = false;
  25880. this.enabled = true;
  25881. this.time = 0; // restart clip
  25882. this._loopCount = -1; // forget previous loops
  25883. this._startTime = null; // forget scheduling
  25884. return this.stopFading().stopWarping();
  25885. },
  25886. isRunning: function () {
  25887. return this.enabled && !this.paused && this.timeScale !== 0 && this._startTime === null && this._mixer._isActiveAction(this);
  25888. },
  25889. // return true when play has been called
  25890. isScheduled: function () {
  25891. return this._mixer._isActiveAction(this);
  25892. },
  25893. startAt: function (time) {
  25894. this._startTime = time;
  25895. return this;
  25896. },
  25897. setLoop: function (mode, repetitions) {
  25898. this.loop = mode;
  25899. this.repetitions = repetitions;
  25900. return this;
  25901. },
  25902. // Weight
  25903. // set the weight stopping any scheduled fading
  25904. // although .enabled = false yields an effective weight of zero, this
  25905. // method does *not* change .enabled, because it would be confusing
  25906. setEffectiveWeight: function (weight) {
  25907. this.weight = weight; // note: same logic as when updated at runtime
  25908. this._effectiveWeight = this.enabled ? weight : 0;
  25909. return this.stopFading();
  25910. },
  25911. // return the weight considering fading and .enabled
  25912. getEffectiveWeight: function () {
  25913. return this._effectiveWeight;
  25914. },
  25915. fadeIn: function (duration) {
  25916. return this._scheduleFading(duration, 0, 1);
  25917. },
  25918. fadeOut: function (duration) {
  25919. return this._scheduleFading(duration, 1, 0);
  25920. },
  25921. crossFadeFrom: function (fadeOutAction, duration, warp) {
  25922. fadeOutAction.fadeOut(duration);
  25923. this.fadeIn(duration);
  25924. if (warp) {
  25925. var fadeInDuration = this._clip.duration,
  25926. fadeOutDuration = fadeOutAction._clip.duration,
  25927. startEndRatio = fadeOutDuration / fadeInDuration,
  25928. endStartRatio = fadeInDuration / fadeOutDuration;
  25929. fadeOutAction.warp(1.0, startEndRatio, duration);
  25930. this.warp(endStartRatio, 1.0, duration);
  25931. }
  25932. return this;
  25933. },
  25934. crossFadeTo: function (fadeInAction, duration, warp) {
  25935. return fadeInAction.crossFadeFrom(this, duration, warp);
  25936. },
  25937. stopFading: function () {
  25938. var weightInterpolant = this._weightInterpolant;
  25939. if (weightInterpolant !== null) {
  25940. this._weightInterpolant = null;
  25941. this._mixer._takeBackControlInterpolant(weightInterpolant);
  25942. }
  25943. return this;
  25944. },
  25945. // Time Scale Control
  25946. // set the time scale stopping any scheduled warping
  25947. // although .paused = true yields an effective time scale of zero, this
  25948. // method does *not* change .paused, because it would be confusing
  25949. setEffectiveTimeScale: function (timeScale) {
  25950. this.timeScale = timeScale;
  25951. this._effectiveTimeScale = this.paused ? 0 : timeScale;
  25952. return this.stopWarping();
  25953. },
  25954. // return the time scale considering warping and .paused
  25955. getEffectiveTimeScale: function () {
  25956. return this._effectiveTimeScale;
  25957. },
  25958. setDuration: function (duration) {
  25959. this.timeScale = this._clip.duration / duration;
  25960. return this.stopWarping();
  25961. },
  25962. syncWith: function (action) {
  25963. this.time = action.time;
  25964. this.timeScale = action.timeScale;
  25965. return this.stopWarping();
  25966. },
  25967. halt: function (duration) {
  25968. return this.warp(this._effectiveTimeScale, 0, duration);
  25969. },
  25970. warp: function (startTimeScale, endTimeScale, duration) {
  25971. var mixer = this._mixer,
  25972. now = mixer.time,
  25973. interpolant = this._timeScaleInterpolant,
  25974. timeScale = this.timeScale;
  25975. if (interpolant === null) {
  25976. interpolant = mixer._lendControlInterpolant();
  25977. this._timeScaleInterpolant = interpolant;
  25978. }
  25979. var times = interpolant.parameterPositions,
  25980. values = interpolant.sampleValues;
  25981. times[0] = now;
  25982. times[1] = now + duration;
  25983. values[0] = startTimeScale / timeScale;
  25984. values[1] = endTimeScale / timeScale;
  25985. return this;
  25986. },
  25987. stopWarping: function () {
  25988. var timeScaleInterpolant = this._timeScaleInterpolant;
  25989. if (timeScaleInterpolant !== null) {
  25990. this._timeScaleInterpolant = null;
  25991. this._mixer._takeBackControlInterpolant(timeScaleInterpolant);
  25992. }
  25993. return this;
  25994. },
  25995. // Object Accessors
  25996. getMixer: function () {
  25997. return this._mixer;
  25998. },
  25999. getClip: function () {
  26000. return this._clip;
  26001. },
  26002. getRoot: function () {
  26003. return this._localRoot || this._mixer._root;
  26004. },
  26005. // Interna
  26006. _update: function (time, deltaTime, timeDirection, accuIndex) {
  26007. // called by the mixer
  26008. if (!this.enabled) {
  26009. // call ._updateWeight() to update ._effectiveWeight
  26010. this._updateWeight(time);
  26011. return;
  26012. }
  26013. var startTime = this._startTime;
  26014. if (startTime !== null) {
  26015. // check for scheduled start of action
  26016. var timeRunning = (time - startTime) * timeDirection;
  26017. if (timeRunning < 0 || timeDirection === 0) {
  26018. return; // yet to come / don't decide when delta = 0
  26019. } // start
  26020. this._startTime = null; // unschedule
  26021. deltaTime = timeDirection * timeRunning;
  26022. } // apply time scale and advance time
  26023. deltaTime *= this._updateTimeScale(time);
  26024. var clipTime = this._updateTime(deltaTime); // note: _updateTime may disable the action resulting in
  26025. // an effective weight of 0
  26026. var weight = this._updateWeight(time);
  26027. if (weight > 0) {
  26028. var interpolants = this._interpolants;
  26029. var propertyMixers = this._propertyBindings;
  26030. for (var j = 0, m = interpolants.length; j !== m; ++j) {
  26031. interpolants[j].evaluate(clipTime);
  26032. propertyMixers[j].accumulate(accuIndex, weight);
  26033. }
  26034. }
  26035. },
  26036. _updateWeight: function (time) {
  26037. var weight = 0;
  26038. if (this.enabled) {
  26039. weight = this.weight;
  26040. var interpolant = this._weightInterpolant;
  26041. if (interpolant !== null) {
  26042. var interpolantValue = interpolant.evaluate(time)[0];
  26043. weight *= interpolantValue;
  26044. if (time > interpolant.parameterPositions[1]) {
  26045. this.stopFading();
  26046. if (interpolantValue === 0) {
  26047. // faded out, disable
  26048. this.enabled = false;
  26049. }
  26050. }
  26051. }
  26052. }
  26053. this._effectiveWeight = weight;
  26054. return weight;
  26055. },
  26056. _updateTimeScale: function (time) {
  26057. var timeScale = 0;
  26058. if (!this.paused) {
  26059. timeScale = this.timeScale;
  26060. var interpolant = this._timeScaleInterpolant;
  26061. if (interpolant !== null) {
  26062. var interpolantValue = interpolant.evaluate(time)[0];
  26063. timeScale *= interpolantValue;
  26064. if (time > interpolant.parameterPositions[1]) {
  26065. this.stopWarping();
  26066. if (timeScale === 0) {
  26067. // motion has halted, pause
  26068. this.paused = true;
  26069. } else {
  26070. // warp done - apply final time scale
  26071. this.timeScale = timeScale;
  26072. }
  26073. }
  26074. }
  26075. }
  26076. this._effectiveTimeScale = timeScale;
  26077. return timeScale;
  26078. },
  26079. _updateTime: function (deltaTime) {
  26080. var time = this.time + deltaTime;
  26081. var duration = this._clip.duration;
  26082. var loop = this.loop;
  26083. var loopCount = this._loopCount;
  26084. var pingPong = loop === LoopPingPong;
  26085. if (deltaTime === 0) {
  26086. if (loopCount === -1) return time;
  26087. return pingPong && (loopCount & 1) === 1 ? duration - time : time;
  26088. }
  26089. if (loop === LoopOnce) {
  26090. if (loopCount === -1) {
  26091. // just started
  26092. this._loopCount = 0;
  26093. this._setEndings(true, true, false);
  26094. }
  26095. handle_stop: {
  26096. if (time >= duration) {
  26097. time = duration;
  26098. } else if (time < 0) {
  26099. time = 0;
  26100. } else {
  26101. this.time = time;
  26102. break handle_stop;
  26103. }
  26104. if (this.clampWhenFinished) this.paused = true;else this.enabled = false;
  26105. this.time = time;
  26106. this._mixer.dispatchEvent({
  26107. type: 'finished',
  26108. action: this,
  26109. direction: deltaTime < 0 ? -1 : 1
  26110. });
  26111. }
  26112. } else {
  26113. // repetitive Repeat or PingPong
  26114. if (loopCount === -1) {
  26115. // just started
  26116. if (deltaTime >= 0) {
  26117. loopCount = 0;
  26118. this._setEndings(true, this.repetitions === 0, pingPong);
  26119. } else {
  26120. // when looping in reverse direction, the initial
  26121. // transition through zero counts as a repetition,
  26122. // so leave loopCount at -1
  26123. this._setEndings(this.repetitions === 0, true, pingPong);
  26124. }
  26125. }
  26126. if (time >= duration || time < 0) {
  26127. // wrap around
  26128. var loopDelta = Math.floor(time / duration); // signed
  26129. time -= duration * loopDelta;
  26130. loopCount += Math.abs(loopDelta);
  26131. var pending = this.repetitions - loopCount;
  26132. if (pending <= 0) {
  26133. // have to stop (switch state, clamp time, fire event)
  26134. if (this.clampWhenFinished) this.paused = true;else this.enabled = false;
  26135. time = deltaTime > 0 ? duration : 0;
  26136. this.time = time;
  26137. this._mixer.dispatchEvent({
  26138. type: 'finished',
  26139. action: this,
  26140. direction: deltaTime > 0 ? 1 : -1
  26141. });
  26142. } else {
  26143. // keep running
  26144. if (pending === 1) {
  26145. // entering the last round
  26146. var atStart = deltaTime < 0;
  26147. this._setEndings(atStart, !atStart, pingPong);
  26148. } else {
  26149. this._setEndings(false, false, pingPong);
  26150. }
  26151. this._loopCount = loopCount;
  26152. this.time = time;
  26153. this._mixer.dispatchEvent({
  26154. type: 'loop',
  26155. action: this,
  26156. loopDelta: loopDelta
  26157. });
  26158. }
  26159. } else {
  26160. this.time = time;
  26161. }
  26162. if (pingPong && (loopCount & 1) === 1) {
  26163. // invert time for the "pong round"
  26164. return duration - time;
  26165. }
  26166. }
  26167. return time;
  26168. },
  26169. _setEndings: function (atStart, atEnd, pingPong) {
  26170. var settings = this._interpolantSettings;
  26171. if (pingPong) {
  26172. settings.endingStart = ZeroSlopeEnding;
  26173. settings.endingEnd = ZeroSlopeEnding;
  26174. } else {
  26175. // assuming for LoopOnce atStart == atEnd == true
  26176. if (atStart) {
  26177. settings.endingStart = this.zeroSlopeAtStart ? ZeroSlopeEnding : ZeroCurvatureEnding;
  26178. } else {
  26179. settings.endingStart = WrapAroundEnding;
  26180. }
  26181. if (atEnd) {
  26182. settings.endingEnd = this.zeroSlopeAtEnd ? ZeroSlopeEnding : ZeroCurvatureEnding;
  26183. } else {
  26184. settings.endingEnd = WrapAroundEnding;
  26185. }
  26186. }
  26187. },
  26188. _scheduleFading: function (duration, weightNow, weightThen) {
  26189. var mixer = this._mixer,
  26190. now = mixer.time,
  26191. interpolant = this._weightInterpolant;
  26192. if (interpolant === null) {
  26193. interpolant = mixer._lendControlInterpolant();
  26194. this._weightInterpolant = interpolant;
  26195. }
  26196. var times = interpolant.parameterPositions,
  26197. values = interpolant.sampleValues;
  26198. times[0] = now;
  26199. values[0] = weightNow;
  26200. times[1] = now + duration;
  26201. values[1] = weightThen;
  26202. return this;
  26203. }
  26204. });
  26205. /**
  26206. *
  26207. * Player for AnimationClips.
  26208. *
  26209. *
  26210. * @author Ben Houston / http://clara.io/
  26211. * @author David Sarno / http://lighthaus.us/
  26212. * @author tschw
  26213. */
  26214. function AnimationMixer(root) {
  26215. this._root = root;
  26216. this._initMemoryManager();
  26217. this._accuIndex = 0;
  26218. this.time = 0;
  26219. this.timeScale = 1.0;
  26220. }
  26221. AnimationMixer.prototype = Object.assign(Object.create(EventDispatcher.prototype), {
  26222. constructor: AnimationMixer,
  26223. _bindAction: function (action, prototypeAction) {
  26224. var root = action._localRoot || this._root,
  26225. tracks = action._clip.tracks,
  26226. nTracks = tracks.length,
  26227. bindings = action._propertyBindings,
  26228. interpolants = action._interpolants,
  26229. rootUuid = root.uuid,
  26230. bindingsByRoot = this._bindingsByRootAndName,
  26231. bindingsByName = bindingsByRoot[rootUuid];
  26232. if (bindingsByName === undefined) {
  26233. bindingsByName = {};
  26234. bindingsByRoot[rootUuid] = bindingsByName;
  26235. }
  26236. for (var i = 0; i !== nTracks; ++i) {
  26237. var track = tracks[i],
  26238. trackName = track.name,
  26239. binding = bindingsByName[trackName];
  26240. if (binding !== undefined) {
  26241. bindings[i] = binding;
  26242. } else {
  26243. binding = bindings[i];
  26244. if (binding !== undefined) {
  26245. // existing binding, make sure the cache knows
  26246. if (binding._cacheIndex === null) {
  26247. ++binding.referenceCount;
  26248. this._addInactiveBinding(binding, rootUuid, trackName);
  26249. }
  26250. continue;
  26251. }
  26252. var path = prototypeAction && prototypeAction._propertyBindings[i].binding.parsedPath;
  26253. binding = new PropertyMixer(PropertyBinding.create(root, trackName, path), track.ValueTypeName, track.getValueSize());
  26254. ++binding.referenceCount;
  26255. this._addInactiveBinding(binding, rootUuid, trackName);
  26256. bindings[i] = binding;
  26257. }
  26258. interpolants[i].resultBuffer = binding.buffer;
  26259. }
  26260. },
  26261. _activateAction: function (action) {
  26262. if (!this._isActiveAction(action)) {
  26263. if (action._cacheIndex === null) {
  26264. // this action has been forgotten by the cache, but the user
  26265. // appears to be still using it -> rebind
  26266. var rootUuid = (action._localRoot || this._root).uuid,
  26267. clipUuid = action._clip.uuid,
  26268. actionsForClip = this._actionsByClip[clipUuid];
  26269. this._bindAction(action, actionsForClip && actionsForClip.knownActions[0]);
  26270. this._addInactiveAction(action, clipUuid, rootUuid);
  26271. }
  26272. var bindings = action._propertyBindings; // increment reference counts / sort out state
  26273. for (var i = 0, n = bindings.length; i !== n; ++i) {
  26274. var binding = bindings[i];
  26275. if (binding.useCount++ === 0) {
  26276. this._lendBinding(binding);
  26277. binding.saveOriginalState();
  26278. }
  26279. }
  26280. this._lendAction(action);
  26281. }
  26282. },
  26283. _deactivateAction: function (action) {
  26284. if (this._isActiveAction(action)) {
  26285. var bindings = action._propertyBindings; // decrement reference counts / sort out state
  26286. for (var i = 0, n = bindings.length; i !== n; ++i) {
  26287. var binding = bindings[i];
  26288. if (--binding.useCount === 0) {
  26289. binding.restoreOriginalState();
  26290. this._takeBackBinding(binding);
  26291. }
  26292. }
  26293. this._takeBackAction(action);
  26294. }
  26295. },
  26296. // Memory manager
  26297. _initMemoryManager: function () {
  26298. this._actions = []; // 'nActiveActions' followed by inactive ones
  26299. this._nActiveActions = 0;
  26300. this._actionsByClip = {}; // inside:
  26301. // {
  26302. // knownActions: Array< AnimationAction > - used as prototypes
  26303. // actionByRoot: AnimationAction - lookup
  26304. // }
  26305. this._bindings = []; // 'nActiveBindings' followed by inactive ones
  26306. this._nActiveBindings = 0;
  26307. this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer >
  26308. this._controlInterpolants = []; // same game as above
  26309. this._nActiveControlInterpolants = 0;
  26310. var scope = this;
  26311. this.stats = {
  26312. actions: {
  26313. get total() {
  26314. return scope._actions.length;
  26315. },
  26316. get inUse() {
  26317. return scope._nActiveActions;
  26318. }
  26319. },
  26320. bindings: {
  26321. get total() {
  26322. return scope._bindings.length;
  26323. },
  26324. get inUse() {
  26325. return scope._nActiveBindings;
  26326. }
  26327. },
  26328. controlInterpolants: {
  26329. get total() {
  26330. return scope._controlInterpolants.length;
  26331. },
  26332. get inUse() {
  26333. return scope._nActiveControlInterpolants;
  26334. }
  26335. }
  26336. };
  26337. },
  26338. // Memory management for AnimationAction objects
  26339. _isActiveAction: function (action) {
  26340. var index = action._cacheIndex;
  26341. return index !== null && index < this._nActiveActions;
  26342. },
  26343. _addInactiveAction: function (action, clipUuid, rootUuid) {
  26344. var actions = this._actions,
  26345. actionsByClip = this._actionsByClip,
  26346. actionsForClip = actionsByClip[clipUuid];
  26347. if (actionsForClip === undefined) {
  26348. actionsForClip = {
  26349. knownActions: [action],
  26350. actionByRoot: {}
  26351. };
  26352. action._byClipCacheIndex = 0;
  26353. actionsByClip[clipUuid] = actionsForClip;
  26354. } else {
  26355. var knownActions = actionsForClip.knownActions;
  26356. action._byClipCacheIndex = knownActions.length;
  26357. knownActions.push(action);
  26358. }
  26359. action._cacheIndex = actions.length;
  26360. actions.push(action);
  26361. actionsForClip.actionByRoot[rootUuid] = action;
  26362. },
  26363. _removeInactiveAction: function (action) {
  26364. var actions = this._actions,
  26365. lastInactiveAction = actions[actions.length - 1],
  26366. cacheIndex = action._cacheIndex;
  26367. lastInactiveAction._cacheIndex = cacheIndex;
  26368. actions[cacheIndex] = lastInactiveAction;
  26369. actions.pop();
  26370. action._cacheIndex = null;
  26371. var clipUuid = action._clip.uuid,
  26372. actionsByClip = this._actionsByClip,
  26373. actionsForClip = actionsByClip[clipUuid],
  26374. knownActionsForClip = actionsForClip.knownActions,
  26375. lastKnownAction = knownActionsForClip[knownActionsForClip.length - 1],
  26376. byClipCacheIndex = action._byClipCacheIndex;
  26377. lastKnownAction._byClipCacheIndex = byClipCacheIndex;
  26378. knownActionsForClip[byClipCacheIndex] = lastKnownAction;
  26379. knownActionsForClip.pop();
  26380. action._byClipCacheIndex = null;
  26381. var actionByRoot = actionsForClip.actionByRoot,
  26382. rootUuid = (action._localRoot || this._root).uuid;
  26383. delete actionByRoot[rootUuid];
  26384. if (knownActionsForClip.length === 0) {
  26385. delete actionsByClip[clipUuid];
  26386. }
  26387. this._removeInactiveBindingsForAction(action);
  26388. },
  26389. _removeInactiveBindingsForAction: function (action) {
  26390. var bindings = action._propertyBindings;
  26391. for (var i = 0, n = bindings.length; i !== n; ++i) {
  26392. var binding = bindings[i];
  26393. if (--binding.referenceCount === 0) {
  26394. this._removeInactiveBinding(binding);
  26395. }
  26396. }
  26397. },
  26398. _lendAction: function (action) {
  26399. // [ active actions | inactive actions ]
  26400. // [ active actions >| inactive actions ]
  26401. // s a
  26402. // <-swap->
  26403. // a s
  26404. var actions = this._actions,
  26405. prevIndex = action._cacheIndex,
  26406. lastActiveIndex = this._nActiveActions++,
  26407. firstInactiveAction = actions[lastActiveIndex];
  26408. action._cacheIndex = lastActiveIndex;
  26409. actions[lastActiveIndex] = action;
  26410. firstInactiveAction._cacheIndex = prevIndex;
  26411. actions[prevIndex] = firstInactiveAction;
  26412. },
  26413. _takeBackAction: function (action) {
  26414. // [ active actions | inactive actions ]
  26415. // [ active actions |< inactive actions ]
  26416. // a s
  26417. // <-swap->
  26418. // s a
  26419. var actions = this._actions,
  26420. prevIndex = action._cacheIndex,
  26421. firstInactiveIndex = --this._nActiveActions,
  26422. lastActiveAction = actions[firstInactiveIndex];
  26423. action._cacheIndex = firstInactiveIndex;
  26424. actions[firstInactiveIndex] = action;
  26425. lastActiveAction._cacheIndex = prevIndex;
  26426. actions[prevIndex] = lastActiveAction;
  26427. },
  26428. // Memory management for PropertyMixer objects
  26429. _addInactiveBinding: function (binding, rootUuid, trackName) {
  26430. var bindingsByRoot = this._bindingsByRootAndName,
  26431. bindingByName = bindingsByRoot[rootUuid],
  26432. bindings = this._bindings;
  26433. if (bindingByName === undefined) {
  26434. bindingByName = {};
  26435. bindingsByRoot[rootUuid] = bindingByName;
  26436. }
  26437. bindingByName[trackName] = binding;
  26438. binding._cacheIndex = bindings.length;
  26439. bindings.push(binding);
  26440. },
  26441. _removeInactiveBinding: function (binding) {
  26442. var bindings = this._bindings,
  26443. propBinding = binding.binding,
  26444. rootUuid = propBinding.rootNode.uuid,
  26445. trackName = propBinding.path,
  26446. bindingsByRoot = this._bindingsByRootAndName,
  26447. bindingByName = bindingsByRoot[rootUuid],
  26448. lastInactiveBinding = bindings[bindings.length - 1],
  26449. cacheIndex = binding._cacheIndex;
  26450. lastInactiveBinding._cacheIndex = cacheIndex;
  26451. bindings[cacheIndex] = lastInactiveBinding;
  26452. bindings.pop();
  26453. delete bindingByName[trackName];
  26454. if (Object.keys(bindingByName).length === 0) {
  26455. delete bindingsByRoot[rootUuid];
  26456. }
  26457. },
  26458. _lendBinding: function (binding) {
  26459. var bindings = this._bindings,
  26460. prevIndex = binding._cacheIndex,
  26461. lastActiveIndex = this._nActiveBindings++,
  26462. firstInactiveBinding = bindings[lastActiveIndex];
  26463. binding._cacheIndex = lastActiveIndex;
  26464. bindings[lastActiveIndex] = binding;
  26465. firstInactiveBinding._cacheIndex = prevIndex;
  26466. bindings[prevIndex] = firstInactiveBinding;
  26467. },
  26468. _takeBackBinding: function (binding) {
  26469. var bindings = this._bindings,
  26470. prevIndex = binding._cacheIndex,
  26471. firstInactiveIndex = --this._nActiveBindings,
  26472. lastActiveBinding = bindings[firstInactiveIndex];
  26473. binding._cacheIndex = firstInactiveIndex;
  26474. bindings[firstInactiveIndex] = binding;
  26475. lastActiveBinding._cacheIndex = prevIndex;
  26476. bindings[prevIndex] = lastActiveBinding;
  26477. },
  26478. // Memory management of Interpolants for weight and time scale
  26479. _lendControlInterpolant: function () {
  26480. var interpolants = this._controlInterpolants,
  26481. lastActiveIndex = this._nActiveControlInterpolants++,
  26482. interpolant = interpolants[lastActiveIndex];
  26483. if (interpolant === undefined) {
  26484. interpolant = new LinearInterpolant(new Float32Array(2), new Float32Array(2), 1, this._controlInterpolantsResultBuffer);
  26485. interpolant.__cacheIndex = lastActiveIndex;
  26486. interpolants[lastActiveIndex] = interpolant;
  26487. }
  26488. return interpolant;
  26489. },
  26490. _takeBackControlInterpolant: function (interpolant) {
  26491. var interpolants = this._controlInterpolants,
  26492. prevIndex = interpolant.__cacheIndex,
  26493. firstInactiveIndex = --this._nActiveControlInterpolants,
  26494. lastActiveInterpolant = interpolants[firstInactiveIndex];
  26495. interpolant.__cacheIndex = firstInactiveIndex;
  26496. interpolants[firstInactiveIndex] = interpolant;
  26497. lastActiveInterpolant.__cacheIndex = prevIndex;
  26498. interpolants[prevIndex] = lastActiveInterpolant;
  26499. },
  26500. _controlInterpolantsResultBuffer: new Float32Array(1),
  26501. // return an action for a clip optionally using a custom root target
  26502. // object (this method allocates a lot of dynamic memory in case a
  26503. // previously unknown clip/root combination is specified)
  26504. clipAction: function (clip, optionalRoot) {
  26505. var root = optionalRoot || this._root,
  26506. rootUuid = root.uuid,
  26507. clipObject = typeof clip === 'string' ? AnimationClip.findByName(root, clip) : clip,
  26508. clipUuid = clipObject !== null ? clipObject.uuid : clip,
  26509. actionsForClip = this._actionsByClip[clipUuid],
  26510. prototypeAction = null;
  26511. if (actionsForClip !== undefined) {
  26512. var existingAction = actionsForClip.actionByRoot[rootUuid];
  26513. if (existingAction !== undefined) {
  26514. return existingAction;
  26515. } // we know the clip, so we don't have to parse all
  26516. // the bindings again but can just copy
  26517. prototypeAction = actionsForClip.knownActions[0]; // also, take the clip from the prototype action
  26518. if (clipObject === null) clipObject = prototypeAction._clip;
  26519. } // clip must be known when specified via string
  26520. if (clipObject === null) return null; // allocate all resources required to run it
  26521. var newAction = new AnimationAction(this, clipObject, optionalRoot);
  26522. this._bindAction(newAction, prototypeAction); // and make the action known to the memory manager
  26523. this._addInactiveAction(newAction, clipUuid, rootUuid);
  26524. return newAction;
  26525. },
  26526. // get an existing action
  26527. existingAction: function (clip, optionalRoot) {
  26528. var root = optionalRoot || this._root,
  26529. rootUuid = root.uuid,
  26530. clipObject = typeof clip === 'string' ? AnimationClip.findByName(root, clip) : clip,
  26531. clipUuid = clipObject ? clipObject.uuid : clip,
  26532. actionsForClip = this._actionsByClip[clipUuid];
  26533. if (actionsForClip !== undefined) {
  26534. return actionsForClip.actionByRoot[rootUuid] || null;
  26535. }
  26536. return null;
  26537. },
  26538. // deactivates all previously scheduled actions
  26539. stopAllAction: function () {
  26540. var actions = this._actions,
  26541. nActions = this._nActiveActions,
  26542. bindings = this._bindings,
  26543. nBindings = this._nActiveBindings;
  26544. this._nActiveActions = 0;
  26545. this._nActiveBindings = 0;
  26546. for (var i = 0; i !== nActions; ++i) {
  26547. actions[i].reset();
  26548. }
  26549. for (var i = 0; i !== nBindings; ++i) {
  26550. bindings[i].useCount = 0;
  26551. }
  26552. return this;
  26553. },
  26554. // advance the time and update apply the animation
  26555. update: function (deltaTime) {
  26556. deltaTime *= this.timeScale;
  26557. var actions = this._actions,
  26558. nActions = this._nActiveActions,
  26559. time = this.time += deltaTime,
  26560. timeDirection = Math.sign(deltaTime),
  26561. accuIndex = this._accuIndex ^= 1; // run active actions
  26562. for (var i = 0; i !== nActions; ++i) {
  26563. var action = actions[i];
  26564. action._update(time, deltaTime, timeDirection, accuIndex);
  26565. } // update scene graph
  26566. var bindings = this._bindings,
  26567. nBindings = this._nActiveBindings;
  26568. for (var i = 0; i !== nBindings; ++i) {
  26569. bindings[i].apply(accuIndex);
  26570. }
  26571. return this;
  26572. },
  26573. // Allows you to seek to a specific time in an animation.
  26574. setTime: function (timeInSeconds) {
  26575. this.time = 0; // Zero out time attribute for AnimationMixer object;
  26576. for (var i = 0; i < this._actions.length; i++) {
  26577. this._actions[i].time = 0; // Zero out time attribute for all associated AnimationAction objects.
  26578. }
  26579. return this.update(timeInSeconds); // Update used to set exact time. Returns "this" AnimationMixer object.
  26580. },
  26581. // return this mixer's root target object
  26582. getRoot: function () {
  26583. return this._root;
  26584. },
  26585. // free all resources specific to a particular clip
  26586. uncacheClip: function (clip) {
  26587. var actions = this._actions,
  26588. clipUuid = clip.uuid,
  26589. actionsByClip = this._actionsByClip,
  26590. actionsForClip = actionsByClip[clipUuid];
  26591. if (actionsForClip !== undefined) {
  26592. // note: just calling _removeInactiveAction would mess up the
  26593. // iteration state and also require updating the state we can
  26594. // just throw away
  26595. var actionsToRemove = actionsForClip.knownActions;
  26596. for (var i = 0, n = actionsToRemove.length; i !== n; ++i) {
  26597. var action = actionsToRemove[i];
  26598. this._deactivateAction(action);
  26599. var cacheIndex = action._cacheIndex,
  26600. lastInactiveAction = actions[actions.length - 1];
  26601. action._cacheIndex = null;
  26602. action._byClipCacheIndex = null;
  26603. lastInactiveAction._cacheIndex = cacheIndex;
  26604. actions[cacheIndex] = lastInactiveAction;
  26605. actions.pop();
  26606. this._removeInactiveBindingsForAction(action);
  26607. }
  26608. delete actionsByClip[clipUuid];
  26609. }
  26610. },
  26611. // free all resources specific to a particular root target object
  26612. uncacheRoot: function (root) {
  26613. var rootUuid = root.uuid,
  26614. actionsByClip = this._actionsByClip;
  26615. for (var clipUuid in actionsByClip) {
  26616. var actionByRoot = actionsByClip[clipUuid].actionByRoot,
  26617. action = actionByRoot[rootUuid];
  26618. if (action !== undefined) {
  26619. this._deactivateAction(action);
  26620. this._removeInactiveAction(action);
  26621. }
  26622. }
  26623. var bindingsByRoot = this._bindingsByRootAndName,
  26624. bindingByName = bindingsByRoot[rootUuid];
  26625. if (bindingByName !== undefined) {
  26626. for (var trackName in bindingByName) {
  26627. var binding = bindingByName[trackName];
  26628. binding.restoreOriginalState();
  26629. this._removeInactiveBinding(binding);
  26630. }
  26631. }
  26632. },
  26633. // remove a targeted clip from the cache
  26634. uncacheAction: function (clip, optionalRoot) {
  26635. var action = this.existingAction(clip, optionalRoot);
  26636. if (action !== null) {
  26637. this._deactivateAction(action);
  26638. this._removeInactiveAction(action);
  26639. }
  26640. }
  26641. });
  26642. /**
  26643. * @author mrdoob / http://mrdoob.com/
  26644. */
  26645. function Uniform(value) {
  26646. if (typeof value === 'string') {
  26647. console.warn('THREE.Uniform: Type parameter is no longer needed.');
  26648. value = arguments[1];
  26649. }
  26650. this.value = value;
  26651. }
  26652. Uniform.prototype.clone = function () {
  26653. return new Uniform(this.value.clone === undefined ? this.value : this.value.clone());
  26654. };
  26655. /**
  26656. * @author benaadams / https://twitter.com/ben_a_adams
  26657. */
  26658. function InstancedInterleavedBuffer(array, stride, meshPerAttribute) {
  26659. InterleavedBuffer.call(this, array, stride);
  26660. this.meshPerAttribute = meshPerAttribute || 1;
  26661. }
  26662. InstancedInterleavedBuffer.prototype = Object.assign(Object.create(InterleavedBuffer.prototype), {
  26663. constructor: InstancedInterleavedBuffer,
  26664. isInstancedInterleavedBuffer: true,
  26665. copy: function (source) {
  26666. InterleavedBuffer.prototype.copy.call(this, source);
  26667. this.meshPerAttribute = source.meshPerAttribute;
  26668. return this;
  26669. }
  26670. });
  26671. /**
  26672. * @author mrdoob / http://mrdoob.com/
  26673. * @author bhouston / http://clara.io/
  26674. * @author stephomi / http://stephaneginier.com/
  26675. */
  26676. function Raycaster(origin, direction, near, far) {
  26677. this.ray = new Ray(origin, direction); // direction is assumed to be normalized (for accurate distance calculations)
  26678. this.near = near || 0;
  26679. this.far = far || Infinity;
  26680. this.camera = null;
  26681. this.params = {
  26682. Mesh: {},
  26683. Line: {},
  26684. LOD: {},
  26685. Points: {
  26686. threshold: 1
  26687. },
  26688. Sprite: {}
  26689. };
  26690. Object.defineProperties(this.params, {
  26691. PointCloud: {
  26692. get: function () {
  26693. console.warn('THREE.Raycaster: params.PointCloud has been renamed to params.Points.');
  26694. return this.Points;
  26695. }
  26696. }
  26697. });
  26698. }
  26699. function ascSort(a, b) {
  26700. return a.distance - b.distance;
  26701. }
  26702. function intersectObject(object, raycaster, intersects, recursive) {
  26703. if (object.visible === false) return;
  26704. object.raycast(raycaster, intersects);
  26705. if (recursive === true) {
  26706. var children = object.children;
  26707. for (var i = 0, l = children.length; i < l; i++) {
  26708. intersectObject(children[i], raycaster, intersects, true);
  26709. }
  26710. }
  26711. }
  26712. Object.assign(Raycaster.prototype, {
  26713. linePrecision: 1,
  26714. set: function (origin, direction) {
  26715. // direction is assumed to be normalized (for accurate distance calculations)
  26716. this.ray.set(origin, direction);
  26717. },
  26718. setFromCamera: function (coords, camera) {
  26719. if (camera && camera.isPerspectiveCamera) {
  26720. this.ray.origin.setFromMatrixPosition(camera.matrixWorld);
  26721. this.ray.direction.set(coords.x, coords.y, 0.5).unproject(camera).sub(this.ray.origin).normalize();
  26722. this.camera = camera;
  26723. } else if (camera && camera.isOrthographicCamera) {
  26724. this.ray.origin.set(coords.x, coords.y, (camera.near + camera.far) / (camera.near - camera.far)).unproject(camera); // set origin in plane of camera
  26725. this.ray.direction.set(0, 0, -1).transformDirection(camera.matrixWorld);
  26726. this.camera = camera;
  26727. } else {
  26728. console.error('THREE.Raycaster: Unsupported camera type.');
  26729. }
  26730. },
  26731. intersectObject: function (object, recursive, optionalTarget) {
  26732. var intersects = optionalTarget || [];
  26733. intersectObject(object, this, intersects, recursive);
  26734. intersects.sort(ascSort);
  26735. return intersects;
  26736. },
  26737. intersectObjects: function (objects, recursive, optionalTarget) {
  26738. var intersects = optionalTarget || [];
  26739. if (Array.isArray(objects) === false) {
  26740. console.warn('THREE.Raycaster.intersectObjects: objects is not an Array.');
  26741. return intersects;
  26742. }
  26743. for (var i = 0, l = objects.length; i < l; i++) {
  26744. intersectObject(objects[i], this, intersects, recursive);
  26745. }
  26746. intersects.sort(ascSort);
  26747. return intersects;
  26748. }
  26749. });
  26750. /**
  26751. * @author bhouston / http://clara.io
  26752. * @author WestLangley / http://github.com/WestLangley
  26753. *
  26754. * Ref: https://en.wikipedia.org/wiki/Spherical_coordinate_system
  26755. *
  26756. * The polar angle (phi) is measured from the positive y-axis. The positive y-axis is up.
  26757. * The azimuthal angle (theta) is measured from the positive z-axiz.
  26758. */
  26759. function Spherical(radius, phi, theta) {
  26760. this.radius = radius !== undefined ? radius : 1.0;
  26761. this.phi = phi !== undefined ? phi : 0; // polar angle
  26762. this.theta = theta !== undefined ? theta : 0; // azimuthal angle
  26763. return this;
  26764. }
  26765. Object.assign(Spherical.prototype, {
  26766. set: function (radius, phi, theta) {
  26767. this.radius = radius;
  26768. this.phi = phi;
  26769. this.theta = theta;
  26770. return this;
  26771. },
  26772. clone: function () {
  26773. return new this.constructor().copy(this);
  26774. },
  26775. copy: function (other) {
  26776. this.radius = other.radius;
  26777. this.phi = other.phi;
  26778. this.theta = other.theta;
  26779. return this;
  26780. },
  26781. // restrict phi to be betwee EPS and PI-EPS
  26782. makeSafe: function () {
  26783. var EPS = 0.000001;
  26784. this.phi = Math.max(EPS, Math.min(Math.PI - EPS, this.phi));
  26785. return this;
  26786. },
  26787. setFromVector3: function (v) {
  26788. return this.setFromCartesianCoords(v.x, v.y, v.z);
  26789. },
  26790. setFromCartesianCoords: function (x, y, z) {
  26791. this.radius = Math.sqrt(x * x + y * y + z * z);
  26792. if (this.radius === 0) {
  26793. this.theta = 0;
  26794. this.phi = 0;
  26795. } else {
  26796. this.theta = Math.atan2(x, z);
  26797. this.phi = Math.acos(_Math.clamp(y / this.radius, -1, 1));
  26798. }
  26799. return this;
  26800. }
  26801. });
  26802. /**
  26803. * @author Mugen87 / https://github.com/Mugen87
  26804. *
  26805. * Ref: https://en.wikipedia.org/wiki/Cylindrical_coordinate_system
  26806. *
  26807. */
  26808. function Cylindrical(radius, theta, y) {
  26809. this.radius = radius !== undefined ? radius : 1.0; // distance from the origin to a point in the x-z plane
  26810. this.theta = theta !== undefined ? theta : 0; // counterclockwise angle in the x-z plane measured in radians from the positive z-axis
  26811. this.y = y !== undefined ? y : 0; // height above the x-z plane
  26812. return this;
  26813. }
  26814. Object.assign(Cylindrical.prototype, {
  26815. set: function (radius, theta, y) {
  26816. this.radius = radius;
  26817. this.theta = theta;
  26818. this.y = y;
  26819. return this;
  26820. },
  26821. clone: function () {
  26822. return new this.constructor().copy(this);
  26823. },
  26824. copy: function (other) {
  26825. this.radius = other.radius;
  26826. this.theta = other.theta;
  26827. this.y = other.y;
  26828. return this;
  26829. },
  26830. setFromVector3: function (v) {
  26831. return this.setFromCartesianCoords(v.x, v.y, v.z);
  26832. },
  26833. setFromCartesianCoords: function (x, y, z) {
  26834. this.radius = Math.sqrt(x * x + z * z);
  26835. this.theta = Math.atan2(x, z);
  26836. this.y = y;
  26837. return this;
  26838. }
  26839. });
  26840. /**
  26841. * @author bhouston / http://clara.io
  26842. */
  26843. var _vector$6 = new Vector2();
  26844. function Box2(min, max) {
  26845. this.min = min !== undefined ? min : new Vector2(+Infinity, +Infinity);
  26846. this.max = max !== undefined ? max : new Vector2(-Infinity, -Infinity);
  26847. }
  26848. Object.assign(Box2.prototype, {
  26849. set: function (min, max) {
  26850. this.min.copy(min);
  26851. this.max.copy(max);
  26852. return this;
  26853. },
  26854. setFromPoints: function (points) {
  26855. this.makeEmpty();
  26856. for (var i = 0, il = points.length; i < il; i++) {
  26857. this.expandByPoint(points[i]);
  26858. }
  26859. return this;
  26860. },
  26861. setFromCenterAndSize: function (center, size) {
  26862. var halfSize = _vector$6.copy(size).multiplyScalar(0.5);
  26863. this.min.copy(center).sub(halfSize);
  26864. this.max.copy(center).add(halfSize);
  26865. return this;
  26866. },
  26867. clone: function () {
  26868. return new this.constructor().copy(this);
  26869. },
  26870. copy: function (box) {
  26871. this.min.copy(box.min);
  26872. this.max.copy(box.max);
  26873. return this;
  26874. },
  26875. makeEmpty: function () {
  26876. this.min.x = this.min.y = +Infinity;
  26877. this.max.x = this.max.y = -Infinity;
  26878. return this;
  26879. },
  26880. isEmpty: function () {
  26881. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  26882. return this.max.x < this.min.x || this.max.y < this.min.y;
  26883. },
  26884. getCenter: function (target) {
  26885. if (target === undefined) {
  26886. console.warn('THREE.Box2: .getCenter() target is now required');
  26887. target = new Vector2();
  26888. }
  26889. return this.isEmpty() ? target.set(0, 0) : target.addVectors(this.min, this.max).multiplyScalar(0.5);
  26890. },
  26891. getSize: function (target) {
  26892. if (target === undefined) {
  26893. console.warn('THREE.Box2: .getSize() target is now required');
  26894. target = new Vector2();
  26895. }
  26896. return this.isEmpty() ? target.set(0, 0) : target.subVectors(this.max, this.min);
  26897. },
  26898. expandByPoint: function (point) {
  26899. this.min.min(point);
  26900. this.max.max(point);
  26901. return this;
  26902. },
  26903. expandByVector: function (vector) {
  26904. this.min.sub(vector);
  26905. this.max.add(vector);
  26906. return this;
  26907. },
  26908. expandByScalar: function (scalar) {
  26909. this.min.addScalar(-scalar);
  26910. this.max.addScalar(scalar);
  26911. return this;
  26912. },
  26913. containsPoint: function (point) {
  26914. return point.x < this.min.x || point.x > this.max.x || point.y < this.min.y || point.y > this.max.y ? false : true;
  26915. },
  26916. containsBox: function (box) {
  26917. 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;
  26918. },
  26919. getParameter: function (point, target) {
  26920. // This can potentially have a divide by zero if the box
  26921. // has a size dimension of 0.
  26922. if (target === undefined) {
  26923. console.warn('THREE.Box2: .getParameter() target is now required');
  26924. target = new Vector2();
  26925. }
  26926. 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));
  26927. },
  26928. intersectsBox: function (box) {
  26929. // using 4 splitting planes to rule out intersections
  26930. 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;
  26931. },
  26932. clampPoint: function (point, target) {
  26933. if (target === undefined) {
  26934. console.warn('THREE.Box2: .clampPoint() target is now required');
  26935. target = new Vector2();
  26936. }
  26937. return target.copy(point).clamp(this.min, this.max);
  26938. },
  26939. distanceToPoint: function (point) {
  26940. var clampedPoint = _vector$6.copy(point).clamp(this.min, this.max);
  26941. return clampedPoint.sub(point).length();
  26942. },
  26943. intersect: function (box) {
  26944. this.min.max(box.min);
  26945. this.max.min(box.max);
  26946. return this;
  26947. },
  26948. union: function (box) {
  26949. this.min.min(box.min);
  26950. this.max.max(box.max);
  26951. return this;
  26952. },
  26953. translate: function (offset) {
  26954. this.min.add(offset);
  26955. this.max.add(offset);
  26956. return this;
  26957. },
  26958. equals: function (box) {
  26959. return box.min.equals(this.min) && box.max.equals(this.max);
  26960. }
  26961. });
  26962. /**
  26963. * @author bhouston / http://clara.io
  26964. */
  26965. var _startP = new Vector3();
  26966. var _startEnd = new Vector3();
  26967. function Line3(start, end) {
  26968. this.start = start !== undefined ? start : new Vector3();
  26969. this.end = end !== undefined ? end : new Vector3();
  26970. }
  26971. Object.assign(Line3.prototype, {
  26972. set: function (start, end) {
  26973. this.start.copy(start);
  26974. this.end.copy(end);
  26975. return this;
  26976. },
  26977. clone: function () {
  26978. return new this.constructor().copy(this);
  26979. },
  26980. copy: function (line) {
  26981. this.start.copy(line.start);
  26982. this.end.copy(line.end);
  26983. return this;
  26984. },
  26985. getCenter: function (target) {
  26986. if (target === undefined) {
  26987. console.warn('THREE.Line3: .getCenter() target is now required');
  26988. target = new Vector3();
  26989. }
  26990. return target.addVectors(this.start, this.end).multiplyScalar(0.5);
  26991. },
  26992. delta: function (target) {
  26993. if (target === undefined) {
  26994. console.warn('THREE.Line3: .delta() target is now required');
  26995. target = new Vector3();
  26996. }
  26997. return target.subVectors(this.end, this.start);
  26998. },
  26999. distanceSq: function () {
  27000. return this.start.distanceToSquared(this.end);
  27001. },
  27002. distance: function () {
  27003. return this.start.distanceTo(this.end);
  27004. },
  27005. at: function (t, target) {
  27006. if (target === undefined) {
  27007. console.warn('THREE.Line3: .at() target is now required');
  27008. target = new Vector3();
  27009. }
  27010. return this.delta(target).multiplyScalar(t).add(this.start);
  27011. },
  27012. closestPointToPointParameter: function (point, clampToLine) {
  27013. _startP.subVectors(point, this.start);
  27014. _startEnd.subVectors(this.end, this.start);
  27015. var startEnd2 = _startEnd.dot(_startEnd);
  27016. var startEnd_startP = _startEnd.dot(_startP);
  27017. var t = startEnd_startP / startEnd2;
  27018. if (clampToLine) {
  27019. t = _Math.clamp(t, 0, 1);
  27020. }
  27021. return t;
  27022. },
  27023. closestPointToPoint: function (point, clampToLine, target) {
  27024. var t = this.closestPointToPointParameter(point, clampToLine);
  27025. if (target === undefined) {
  27026. console.warn('THREE.Line3: .closestPointToPoint() target is now required');
  27027. target = new Vector3();
  27028. }
  27029. return this.delta(target).multiplyScalar(t).add(this.start);
  27030. },
  27031. applyMatrix4: function (matrix) {
  27032. this.start.applyMatrix4(matrix);
  27033. this.end.applyMatrix4(matrix);
  27034. return this;
  27035. },
  27036. equals: function (line) {
  27037. return line.start.equals(this.start) && line.end.equals(this.end);
  27038. }
  27039. });
  27040. /**
  27041. * @author alteredq / http://alteredqualia.com/
  27042. */
  27043. function ImmediateRenderObject(material) {
  27044. Object3D.call(this);
  27045. this.material = material;
  27046. this.render = function ()
  27047. /* renderCallback */
  27048. {};
  27049. }
  27050. ImmediateRenderObject.prototype = Object.create(Object3D.prototype);
  27051. ImmediateRenderObject.prototype.constructor = ImmediateRenderObject;
  27052. ImmediateRenderObject.prototype.isImmediateRenderObject = true;
  27053. /**
  27054. * @author mrdoob / http://mrdoob.com/
  27055. * @author WestLangley / http://github.com/WestLangley
  27056. */
  27057. var _v1$5 = new Vector3();
  27058. var _v2$3 = new Vector3();
  27059. var _normalMatrix$1 = new Matrix3();
  27060. var _keys = ['a', 'b', 'c'];
  27061. function VertexNormalsHelper(object, size, hex, linewidth) {
  27062. this.object = object;
  27063. this.size = size !== undefined ? size : 1;
  27064. var color = hex !== undefined ? hex : 0xff0000;
  27065. var width = linewidth !== undefined ? linewidth : 1; //
  27066. var nNormals = 0;
  27067. var objGeometry = this.object.geometry;
  27068. if (objGeometry && objGeometry.isGeometry) {
  27069. nNormals = objGeometry.faces.length * 3;
  27070. } else if (objGeometry && objGeometry.isBufferGeometry) {
  27071. nNormals = objGeometry.attributes.normal.count;
  27072. } //
  27073. var geometry = new BufferGeometry();
  27074. var positions = new Float32BufferAttribute(nNormals * 2 * 3, 3);
  27075. geometry.addAttribute('position', positions);
  27076. LineSegments.call(this, geometry, new LineBasicMaterial({
  27077. color: color,
  27078. linewidth: width
  27079. })); //
  27080. this.matrixAutoUpdate = false;
  27081. this.update();
  27082. }
  27083. VertexNormalsHelper.prototype = Object.create(LineSegments.prototype);
  27084. VertexNormalsHelper.prototype.constructor = VertexNormalsHelper;
  27085. VertexNormalsHelper.prototype.update = function () {
  27086. this.object.updateMatrixWorld(true);
  27087. _normalMatrix$1.getNormalMatrix(this.object.matrixWorld);
  27088. var matrixWorld = this.object.matrixWorld;
  27089. var position = this.geometry.attributes.position; //
  27090. var objGeometry = this.object.geometry;
  27091. if (objGeometry && objGeometry.isGeometry) {
  27092. var vertices = objGeometry.vertices;
  27093. var faces = objGeometry.faces;
  27094. var idx = 0;
  27095. for (var i = 0, l = faces.length; i < l; i++) {
  27096. var face = faces[i];
  27097. for (var j = 0, jl = face.vertexNormals.length; j < jl; j++) {
  27098. var vertex = vertices[face[_keys[j]]];
  27099. var normal = face.vertexNormals[j];
  27100. _v1$5.copy(vertex).applyMatrix4(matrixWorld);
  27101. _v2$3.copy(normal).applyMatrix3(_normalMatrix$1).normalize().multiplyScalar(this.size).add(_v1$5);
  27102. position.setXYZ(idx, _v1$5.x, _v1$5.y, _v1$5.z);
  27103. idx = idx + 1;
  27104. position.setXYZ(idx, _v2$3.x, _v2$3.y, _v2$3.z);
  27105. idx = idx + 1;
  27106. }
  27107. }
  27108. } else if (objGeometry && objGeometry.isBufferGeometry) {
  27109. var objPos = objGeometry.attributes.position;
  27110. var objNorm = objGeometry.attributes.normal;
  27111. var idx = 0; // for simplicity, ignore index and drawcalls, and render every normal
  27112. for (var j = 0, jl = objPos.count; j < jl; j++) {
  27113. _v1$5.set(objPos.getX(j), objPos.getY(j), objPos.getZ(j)).applyMatrix4(matrixWorld);
  27114. _v2$3.set(objNorm.getX(j), objNorm.getY(j), objNorm.getZ(j));
  27115. _v2$3.applyMatrix3(_normalMatrix$1).normalize().multiplyScalar(this.size).add(_v1$5);
  27116. position.setXYZ(idx, _v1$5.x, _v1$5.y, _v1$5.z);
  27117. idx = idx + 1;
  27118. position.setXYZ(idx, _v2$3.x, _v2$3.y, _v2$3.z);
  27119. idx = idx + 1;
  27120. }
  27121. }
  27122. position.needsUpdate = true;
  27123. };
  27124. /**
  27125. * @author alteredq / http://alteredqualia.com/
  27126. * @author mrdoob / http://mrdoob.com/
  27127. * @author WestLangley / http://github.com/WestLangley
  27128. */
  27129. var _vector$7 = new Vector3();
  27130. function SpotLightHelper(light, color) {
  27131. Object3D.call(this);
  27132. this.light = light;
  27133. this.light.updateMatrixWorld();
  27134. this.matrix = light.matrixWorld;
  27135. this.matrixAutoUpdate = false;
  27136. this.color = color;
  27137. var geometry = new BufferGeometry();
  27138. 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];
  27139. for (var i = 0, j = 1, l = 32; i < l; i++, j++) {
  27140. var p1 = i / l * Math.PI * 2;
  27141. var p2 = j / l * Math.PI * 2;
  27142. positions.push(Math.cos(p1), Math.sin(p1), 1, Math.cos(p2), Math.sin(p2), 1);
  27143. }
  27144. geometry.addAttribute('position', new Float32BufferAttribute(positions, 3));
  27145. var material = new LineBasicMaterial({
  27146. fog: false
  27147. });
  27148. this.cone = new LineSegments(geometry, material);
  27149. this.add(this.cone);
  27150. this.update();
  27151. }
  27152. SpotLightHelper.prototype = Object.create(Object3D.prototype);
  27153. SpotLightHelper.prototype.constructor = SpotLightHelper;
  27154. SpotLightHelper.prototype.dispose = function () {
  27155. this.cone.geometry.dispose();
  27156. this.cone.material.dispose();
  27157. };
  27158. SpotLightHelper.prototype.update = function () {
  27159. this.light.updateMatrixWorld();
  27160. var coneLength = this.light.distance ? this.light.distance : 1000;
  27161. var coneWidth = coneLength * Math.tan(this.light.angle);
  27162. this.cone.scale.set(coneWidth, coneWidth, coneLength);
  27163. _vector$7.setFromMatrixPosition(this.light.target.matrixWorld);
  27164. this.cone.lookAt(_vector$7);
  27165. if (this.color !== undefined) {
  27166. this.cone.material.color.set(this.color);
  27167. } else {
  27168. this.cone.material.color.copy(this.light.color);
  27169. }
  27170. };
  27171. /**
  27172. * @author Sean Griffin / http://twitter.com/sgrif
  27173. * @author Michael Guerrero / http://realitymeltdown.com
  27174. * @author mrdoob / http://mrdoob.com/
  27175. * @author ikerr / http://verold.com
  27176. * @author Mugen87 / https://github.com/Mugen87
  27177. */
  27178. var _vector$8 = new Vector3();
  27179. var _boneMatrix = new Matrix4();
  27180. var _matrixWorldInv = new Matrix4();
  27181. function getBoneList(object) {
  27182. var boneList = [];
  27183. if (object && object.isBone) {
  27184. boneList.push(object);
  27185. }
  27186. for (var i = 0; i < object.children.length; i++) {
  27187. boneList.push.apply(boneList, getBoneList(object.children[i]));
  27188. }
  27189. return boneList;
  27190. }
  27191. function SkeletonHelper(object) {
  27192. var bones = getBoneList(object);
  27193. var geometry = new BufferGeometry();
  27194. var vertices = [];
  27195. var colors = [];
  27196. var color1 = new Color(0, 0, 1);
  27197. var color2 = new Color(0, 1, 0);
  27198. for (var i = 0; i < bones.length; i++) {
  27199. var bone = bones[i];
  27200. if (bone.parent && bone.parent.isBone) {
  27201. vertices.push(0, 0, 0);
  27202. vertices.push(0, 0, 0);
  27203. colors.push(color1.r, color1.g, color1.b);
  27204. colors.push(color2.r, color2.g, color2.b);
  27205. }
  27206. }
  27207. geometry.addAttribute('position', new Float32BufferAttribute(vertices, 3));
  27208. geometry.addAttribute('color', new Float32BufferAttribute(colors, 3));
  27209. var material = new LineBasicMaterial({
  27210. vertexColors: VertexColors,
  27211. depthTest: false,
  27212. depthWrite: false,
  27213. transparent: true
  27214. });
  27215. LineSegments.call(this, geometry, material);
  27216. this.root = object;
  27217. this.bones = bones;
  27218. this.matrix = object.matrixWorld;
  27219. this.matrixAutoUpdate = false;
  27220. }
  27221. SkeletonHelper.prototype = Object.create(LineSegments.prototype);
  27222. SkeletonHelper.prototype.constructor = SkeletonHelper;
  27223. SkeletonHelper.prototype.updateMatrixWorld = function (force) {
  27224. var bones = this.bones;
  27225. var geometry = this.geometry;
  27226. var position = geometry.getAttribute('position');
  27227. _matrixWorldInv.getInverse(this.root.matrixWorld);
  27228. for (var i = 0, j = 0; i < bones.length; i++) {
  27229. var bone = bones[i];
  27230. if (bone.parent && bone.parent.isBone) {
  27231. _boneMatrix.multiplyMatrices(_matrixWorldInv, bone.matrixWorld);
  27232. _vector$8.setFromMatrixPosition(_boneMatrix);
  27233. position.setXYZ(j, _vector$8.x, _vector$8.y, _vector$8.z);
  27234. _boneMatrix.multiplyMatrices(_matrixWorldInv, bone.parent.matrixWorld);
  27235. _vector$8.setFromMatrixPosition(_boneMatrix);
  27236. position.setXYZ(j + 1, _vector$8.x, _vector$8.y, _vector$8.z);
  27237. j += 2;
  27238. }
  27239. }
  27240. geometry.getAttribute('position').needsUpdate = true;
  27241. Object3D.prototype.updateMatrixWorld.call(this, force);
  27242. };
  27243. /**
  27244. * @author alteredq / http://alteredqualia.com/
  27245. * @author mrdoob / http://mrdoob.com/
  27246. */
  27247. function PointLightHelper(light, sphereSize, color) {
  27248. this.light = light;
  27249. this.light.updateMatrixWorld();
  27250. this.color = color;
  27251. var geometry = new SphereBufferGeometry(sphereSize, 4, 2);
  27252. var material = new MeshBasicMaterial({
  27253. wireframe: true,
  27254. fog: false
  27255. });
  27256. Mesh.call(this, geometry, material);
  27257. this.matrix = this.light.matrixWorld;
  27258. this.matrixAutoUpdate = false;
  27259. this.update();
  27260. /*
  27261. var distanceGeometry = new THREE.IcosahedronBufferGeometry( 1, 2 );
  27262. var distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  27263. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  27264. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  27265. var d = light.distance;
  27266. if ( d === 0.0 ) {
  27267. this.lightDistance.visible = false;
  27268. } else {
  27269. this.lightDistance.scale.set( d, d, d );
  27270. }
  27271. this.add( this.lightDistance );
  27272. */
  27273. }
  27274. PointLightHelper.prototype = Object.create(Mesh.prototype);
  27275. PointLightHelper.prototype.constructor = PointLightHelper;
  27276. PointLightHelper.prototype.dispose = function () {
  27277. this.geometry.dispose();
  27278. this.material.dispose();
  27279. };
  27280. PointLightHelper.prototype.update = function () {
  27281. if (this.color !== undefined) {
  27282. this.material.color.set(this.color);
  27283. } else {
  27284. this.material.color.copy(this.light.color);
  27285. }
  27286. /*
  27287. var d = this.light.distance;
  27288. if ( d === 0.0 ) {
  27289. this.lightDistance.visible = false;
  27290. } else {
  27291. this.lightDistance.visible = true;
  27292. this.lightDistance.scale.set( d, d, d );
  27293. }
  27294. */
  27295. };
  27296. /**
  27297. * @author abelnation / http://github.com/abelnation
  27298. * @author Mugen87 / http://github.com/Mugen87
  27299. * @author WestLangley / http://github.com/WestLangley
  27300. *
  27301. * This helper must be added as a child of the light
  27302. */
  27303. function RectAreaLightHelper(light, color) {
  27304. this.type = 'RectAreaLightHelper';
  27305. this.light = light;
  27306. this.color = color; // optional hardwired color for the helper
  27307. var positions = [1, 1, 0, -1, 1, 0, -1, -1, 0, 1, -1, 0, 1, 1, 0];
  27308. var geometry = new BufferGeometry();
  27309. geometry.addAttribute('position', new Float32BufferAttribute(positions, 3));
  27310. geometry.computeBoundingSphere();
  27311. var material = new LineBasicMaterial({
  27312. fog: false
  27313. });
  27314. Line.call(this, geometry, material); //
  27315. var positions2 = [1, 1, 0, -1, 1, 0, -1, -1, 0, 1, 1, 0, -1, -1, 0, 1, -1, 0];
  27316. var geometry2 = new BufferGeometry();
  27317. geometry2.addAttribute('position', new Float32BufferAttribute(positions2, 3));
  27318. geometry2.computeBoundingSphere();
  27319. this.add(new Mesh(geometry2, new MeshBasicMaterial({
  27320. side: BackSide,
  27321. fog: false
  27322. })));
  27323. this.update();
  27324. }
  27325. RectAreaLightHelper.prototype = Object.create(Line.prototype);
  27326. RectAreaLightHelper.prototype.constructor = RectAreaLightHelper;
  27327. RectAreaLightHelper.prototype.update = function () {
  27328. this.scale.set(0.5 * this.light.width, 0.5 * this.light.height, 1);
  27329. if (this.color !== undefined) {
  27330. this.material.color.set(this.color);
  27331. this.children[0].material.color.set(this.color);
  27332. } else {
  27333. this.material.color.copy(this.light.color).multiplyScalar(this.light.intensity); // prevent hue shift
  27334. var c = this.material.color;
  27335. var max = Math.max(c.r, c.g, c.b);
  27336. if (max > 1) c.multiplyScalar(1 / max);
  27337. this.children[0].material.color.copy(this.material.color);
  27338. }
  27339. };
  27340. RectAreaLightHelper.prototype.dispose = function () {
  27341. this.geometry.dispose();
  27342. this.material.dispose();
  27343. this.children[0].geometry.dispose();
  27344. this.children[0].material.dispose();
  27345. };
  27346. /**
  27347. * @author alteredq / http://alteredqualia.com/
  27348. * @author mrdoob / http://mrdoob.com/
  27349. * @author Mugen87 / https://github.com/Mugen87
  27350. */
  27351. var _vector$9 = new Vector3();
  27352. var _color1 = new Color();
  27353. var _color2 = new Color();
  27354. function HemisphereLightHelper(light, size, color) {
  27355. Object3D.call(this);
  27356. this.light = light;
  27357. this.light.updateMatrixWorld();
  27358. this.matrix = light.matrixWorld;
  27359. this.matrixAutoUpdate = false;
  27360. this.color = color;
  27361. var geometry = new OctahedronBufferGeometry(size);
  27362. geometry.rotateY(Math.PI * 0.5);
  27363. this.material = new MeshBasicMaterial({
  27364. wireframe: true,
  27365. fog: false
  27366. });
  27367. if (this.color === undefined) this.material.vertexColors = VertexColors;
  27368. var position = geometry.getAttribute('position');
  27369. var colors = new Float32Array(position.count * 3);
  27370. geometry.addAttribute('color', new BufferAttribute(colors, 3));
  27371. this.add(new Mesh(geometry, this.material));
  27372. this.update();
  27373. }
  27374. HemisphereLightHelper.prototype = Object.create(Object3D.prototype);
  27375. HemisphereLightHelper.prototype.constructor = HemisphereLightHelper;
  27376. HemisphereLightHelper.prototype.dispose = function () {
  27377. this.children[0].geometry.dispose();
  27378. this.children[0].material.dispose();
  27379. };
  27380. HemisphereLightHelper.prototype.update = function () {
  27381. var mesh = this.children[0];
  27382. if (this.color !== undefined) {
  27383. this.material.color.set(this.color);
  27384. } else {
  27385. var colors = mesh.geometry.getAttribute('color');
  27386. _color1.copy(this.light.color);
  27387. _color2.copy(this.light.groundColor);
  27388. for (var i = 0, l = colors.count; i < l; i++) {
  27389. var color = i < l / 2 ? _color1 : _color2;
  27390. colors.setXYZ(i, color.r, color.g, color.b);
  27391. }
  27392. colors.needsUpdate = true;
  27393. }
  27394. mesh.lookAt(_vector$9.setFromMatrixPosition(this.light.matrixWorld).negate());
  27395. };
  27396. /**
  27397. * @author WestLangley / http://github.com/WestLangley
  27398. */
  27399. function LightProbeHelper(lightProbe, size) {
  27400. this.lightProbe = lightProbe;
  27401. this.size = size;
  27402. var defines = {};
  27403. defines['GAMMA_OUTPUT'] = ""; // material
  27404. var material = new ShaderMaterial({
  27405. defines: defines,
  27406. uniforms: {
  27407. sh: {
  27408. value: this.lightProbe.sh.coefficients
  27409. },
  27410. // by reference
  27411. intensity: {
  27412. value: this.lightProbe.intensity
  27413. }
  27414. },
  27415. vertexShader: ['varying vec3 vNormal;', 'void main() {', ' vNormal = normalize( normalMatrix * normal );', ' gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );', '}'].join('\n'),
  27416. 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')
  27417. });
  27418. var geometry = new SphereBufferGeometry(1, 32, 16);
  27419. Mesh.call(this, geometry, material);
  27420. this.onBeforeRender();
  27421. }
  27422. LightProbeHelper.prototype = Object.create(Mesh.prototype);
  27423. LightProbeHelper.prototype.constructor = LightProbeHelper;
  27424. LightProbeHelper.prototype.dispose = function () {
  27425. this.geometry.dispose();
  27426. this.material.dispose();
  27427. };
  27428. LightProbeHelper.prototype.onBeforeRender = function () {
  27429. this.position.copy(this.lightProbe.position);
  27430. this.scale.set(1, 1, 1).multiplyScalar(this.size);
  27431. this.material.uniforms.intensity.value = this.lightProbe.intensity;
  27432. };
  27433. /**
  27434. * @author mrdoob / http://mrdoob.com/
  27435. */
  27436. function GridHelper(size, divisions, color1, color2) {
  27437. size = size || 10;
  27438. divisions = divisions || 10;
  27439. color1 = new Color(color1 !== undefined ? color1 : 0x444444);
  27440. color2 = new Color(color2 !== undefined ? color2 : 0x888888);
  27441. var center = divisions / 2;
  27442. var step = size / divisions;
  27443. var halfSize = size / 2;
  27444. var vertices = [],
  27445. colors = [];
  27446. for (var i = 0, j = 0, k = -halfSize; i <= divisions; i++, k += step) {
  27447. vertices.push(-halfSize, 0, k, halfSize, 0, k);
  27448. vertices.push(k, 0, -halfSize, k, 0, halfSize);
  27449. var color = i === center ? color1 : color2;
  27450. color.toArray(colors, j);
  27451. j += 3;
  27452. color.toArray(colors, j);
  27453. j += 3;
  27454. color.toArray(colors, j);
  27455. j += 3;
  27456. color.toArray(colors, j);
  27457. j += 3;
  27458. }
  27459. var geometry = new BufferGeometry();
  27460. geometry.addAttribute('position', new Float32BufferAttribute(vertices, 3));
  27461. geometry.addAttribute('color', new Float32BufferAttribute(colors, 3));
  27462. var material = new LineBasicMaterial({
  27463. vertexColors: VertexColors
  27464. });
  27465. LineSegments.call(this, geometry, material);
  27466. }
  27467. GridHelper.prototype = Object.assign(Object.create(LineSegments.prototype), {
  27468. constructor: GridHelper,
  27469. copy: function (source) {
  27470. LineSegments.prototype.copy.call(this, source);
  27471. this.geometry.copy(source.geometry);
  27472. this.material.copy(source.material);
  27473. return this;
  27474. },
  27475. clone: function () {
  27476. return new this.constructor().copy(this);
  27477. }
  27478. });
  27479. /**
  27480. * @author mrdoob / http://mrdoob.com/
  27481. * @author Mugen87 / http://github.com/Mugen87
  27482. * @author Hectate / http://www.github.com/Hectate
  27483. */
  27484. function PolarGridHelper(radius, radials, circles, divisions, color1, color2) {
  27485. radius = radius || 10;
  27486. radials = radials || 16;
  27487. circles = circles || 8;
  27488. divisions = divisions || 64;
  27489. color1 = new Color(color1 !== undefined ? color1 : 0x444444);
  27490. color2 = new Color(color2 !== undefined ? color2 : 0x888888);
  27491. var vertices = [];
  27492. var colors = [];
  27493. var x, z;
  27494. var v, i, j, r, color; // create the radials
  27495. for (i = 0; i <= radials; i++) {
  27496. v = i / radials * (Math.PI * 2);
  27497. x = Math.sin(v) * radius;
  27498. z = Math.cos(v) * radius;
  27499. vertices.push(0, 0, 0);
  27500. vertices.push(x, 0, z);
  27501. color = i & 1 ? color1 : color2;
  27502. colors.push(color.r, color.g, color.b);
  27503. colors.push(color.r, color.g, color.b);
  27504. } // create the circles
  27505. for (i = 0; i <= circles; i++) {
  27506. color = i & 1 ? color1 : color2;
  27507. r = radius - radius / circles * i;
  27508. for (j = 0; j < divisions; j++) {
  27509. // first vertex
  27510. v = j / divisions * (Math.PI * 2);
  27511. x = Math.sin(v) * r;
  27512. z = Math.cos(v) * r;
  27513. vertices.push(x, 0, z);
  27514. colors.push(color.r, color.g, color.b); // second vertex
  27515. v = (j + 1) / divisions * (Math.PI * 2);
  27516. x = Math.sin(v) * r;
  27517. z = Math.cos(v) * r;
  27518. vertices.push(x, 0, z);
  27519. colors.push(color.r, color.g, color.b);
  27520. }
  27521. }
  27522. var geometry = new BufferGeometry();
  27523. geometry.addAttribute('position', new Float32BufferAttribute(vertices, 3));
  27524. geometry.addAttribute('color', new Float32BufferAttribute(colors, 3));
  27525. var material = new LineBasicMaterial({
  27526. vertexColors: VertexColors
  27527. });
  27528. LineSegments.call(this, geometry, material);
  27529. }
  27530. PolarGridHelper.prototype = Object.create(LineSegments.prototype);
  27531. PolarGridHelper.prototype.constructor = PolarGridHelper;
  27532. /**
  27533. * @author Mugen87 / http://github.com/Mugen87
  27534. */
  27535. function PositionalAudioHelper(audio, range, divisionsInnerAngle, divisionsOuterAngle) {
  27536. this.audio = audio;
  27537. this.range = range || 1;
  27538. this.divisionsInnerAngle = divisionsInnerAngle || 16;
  27539. this.divisionsOuterAngle = divisionsOuterAngle || 2;
  27540. var geometry = new BufferGeometry();
  27541. var divisions = this.divisionsInnerAngle + this.divisionsOuterAngle * 2;
  27542. var positions = new Float32Array((divisions * 3 + 3) * 3);
  27543. geometry.addAttribute('position', new BufferAttribute(positions, 3));
  27544. var materialInnerAngle = new LineBasicMaterial({
  27545. color: 0x00ff00
  27546. });
  27547. var materialOuterAngle = new LineBasicMaterial({
  27548. color: 0xffff00
  27549. });
  27550. Line.call(this, geometry, [materialOuterAngle, materialInnerAngle]);
  27551. this.update();
  27552. }
  27553. PositionalAudioHelper.prototype = Object.create(Line.prototype);
  27554. PositionalAudioHelper.prototype.constructor = PositionalAudioHelper;
  27555. PositionalAudioHelper.prototype.update = function () {
  27556. var audio = this.audio;
  27557. var range = this.range;
  27558. var divisionsInnerAngle = this.divisionsInnerAngle;
  27559. var divisionsOuterAngle = this.divisionsOuterAngle;
  27560. var coneInnerAngle = _Math.degToRad(audio.panner.coneInnerAngle);
  27561. var coneOuterAngle = _Math.degToRad(audio.panner.coneOuterAngle);
  27562. var halfConeInnerAngle = coneInnerAngle / 2;
  27563. var halfConeOuterAngle = coneOuterAngle / 2;
  27564. var start = 0;
  27565. var count = 0;
  27566. var i, stride;
  27567. var geometry = this.geometry;
  27568. var positionAttribute = geometry.attributes.position;
  27569. geometry.clearGroups(); //
  27570. function generateSegment(from, to, divisions, materialIndex) {
  27571. var step = (to - from) / divisions;
  27572. positionAttribute.setXYZ(start, 0, 0, 0);
  27573. count++;
  27574. for (i = from; i < to; i += step) {
  27575. stride = start + count;
  27576. positionAttribute.setXYZ(stride, Math.sin(i) * range, 0, Math.cos(i) * range);
  27577. positionAttribute.setXYZ(stride + 1, Math.sin(Math.min(i + step, to)) * range, 0, Math.cos(Math.min(i + step, to)) * range);
  27578. positionAttribute.setXYZ(stride + 2, 0, 0, 0);
  27579. count += 3;
  27580. }
  27581. geometry.addGroup(start, count, materialIndex);
  27582. start += count;
  27583. count = 0;
  27584. } //
  27585. generateSegment(-halfConeOuterAngle, -halfConeInnerAngle, divisionsOuterAngle, 0);
  27586. generateSegment(-halfConeInnerAngle, halfConeInnerAngle, divisionsInnerAngle, 1);
  27587. generateSegment(halfConeInnerAngle, halfConeOuterAngle, divisionsOuterAngle, 0); //
  27588. positionAttribute.needsUpdate = true;
  27589. if (coneInnerAngle === coneOuterAngle) this.material[0].visible = false;
  27590. };
  27591. PositionalAudioHelper.prototype.dispose = function () {
  27592. this.geometry.dispose();
  27593. this.material[0].dispose();
  27594. this.material[1].dispose();
  27595. };
  27596. /**
  27597. * @author mrdoob / http://mrdoob.com/
  27598. * @author WestLangley / http://github.com/WestLangley
  27599. */
  27600. var _v1$6 = new Vector3();
  27601. var _v2$4 = new Vector3();
  27602. var _normalMatrix$2 = new Matrix3();
  27603. function FaceNormalsHelper(object, size, hex, linewidth) {
  27604. // FaceNormalsHelper only supports THREE.Geometry
  27605. this.object = object;
  27606. this.size = size !== undefined ? size : 1;
  27607. var color = hex !== undefined ? hex : 0xffff00;
  27608. var width = linewidth !== undefined ? linewidth : 1; //
  27609. var nNormals = 0;
  27610. var objGeometry = this.object.geometry;
  27611. if (objGeometry && objGeometry.isGeometry) {
  27612. nNormals = objGeometry.faces.length;
  27613. } else {
  27614. console.warn('THREE.FaceNormalsHelper: only THREE.Geometry is supported. Use THREE.VertexNormalsHelper, instead.');
  27615. } //
  27616. var geometry = new BufferGeometry();
  27617. var positions = new Float32BufferAttribute(nNormals * 2 * 3, 3);
  27618. geometry.addAttribute('position', positions);
  27619. LineSegments.call(this, geometry, new LineBasicMaterial({
  27620. color: color,
  27621. linewidth: width
  27622. })); //
  27623. this.matrixAutoUpdate = false;
  27624. this.update();
  27625. }
  27626. FaceNormalsHelper.prototype = Object.create(LineSegments.prototype);
  27627. FaceNormalsHelper.prototype.constructor = FaceNormalsHelper;
  27628. FaceNormalsHelper.prototype.update = function () {
  27629. this.object.updateMatrixWorld(true);
  27630. _normalMatrix$2.getNormalMatrix(this.object.matrixWorld);
  27631. var matrixWorld = this.object.matrixWorld;
  27632. var position = this.geometry.attributes.position; //
  27633. var objGeometry = this.object.geometry;
  27634. var vertices = objGeometry.vertices;
  27635. var faces = objGeometry.faces;
  27636. var idx = 0;
  27637. for (var i = 0, l = faces.length; i < l; i++) {
  27638. var face = faces[i];
  27639. var normal = face.normal;
  27640. _v1$6.copy(vertices[face.a]).add(vertices[face.b]).add(vertices[face.c]).divideScalar(3).applyMatrix4(matrixWorld);
  27641. _v2$4.copy(normal).applyMatrix3(_normalMatrix$2).normalize().multiplyScalar(this.size).add(_v1$6);
  27642. position.setXYZ(idx, _v1$6.x, _v1$6.y, _v1$6.z);
  27643. idx = idx + 1;
  27644. position.setXYZ(idx, _v2$4.x, _v2$4.y, _v2$4.z);
  27645. idx = idx + 1;
  27646. }
  27647. position.needsUpdate = true;
  27648. };
  27649. /**
  27650. * @author alteredq / http://alteredqualia.com/
  27651. * @author mrdoob / http://mrdoob.com/
  27652. * @author WestLangley / http://github.com/WestLangley
  27653. */
  27654. var _v1$7 = new Vector3();
  27655. var _v2$5 = new Vector3();
  27656. var _v3$1 = new Vector3();
  27657. function DirectionalLightHelper(light, size, color) {
  27658. Object3D.call(this);
  27659. this.light = light;
  27660. this.light.updateMatrixWorld();
  27661. this.matrix = light.matrixWorld;
  27662. this.matrixAutoUpdate = false;
  27663. this.color = color;
  27664. if (size === undefined) size = 1;
  27665. var geometry = new BufferGeometry();
  27666. geometry.addAttribute('position', new Float32BufferAttribute([-size, size, 0, size, size, 0, size, -size, 0, -size, -size, 0, -size, size, 0], 3));
  27667. var material = new LineBasicMaterial({
  27668. fog: false
  27669. });
  27670. this.lightPlane = new Line(geometry, material);
  27671. this.add(this.lightPlane);
  27672. geometry = new BufferGeometry();
  27673. geometry.addAttribute('position', new Float32BufferAttribute([0, 0, 0, 0, 0, 1], 3));
  27674. this.targetLine = new Line(geometry, material);
  27675. this.add(this.targetLine);
  27676. this.update();
  27677. }
  27678. DirectionalLightHelper.prototype = Object.create(Object3D.prototype);
  27679. DirectionalLightHelper.prototype.constructor = DirectionalLightHelper;
  27680. DirectionalLightHelper.prototype.dispose = function () {
  27681. this.lightPlane.geometry.dispose();
  27682. this.lightPlane.material.dispose();
  27683. this.targetLine.geometry.dispose();
  27684. this.targetLine.material.dispose();
  27685. };
  27686. DirectionalLightHelper.prototype.update = function () {
  27687. _v1$7.setFromMatrixPosition(this.light.matrixWorld);
  27688. _v2$5.setFromMatrixPosition(this.light.target.matrixWorld);
  27689. _v3$1.subVectors(_v2$5, _v1$7);
  27690. this.lightPlane.lookAt(_v2$5);
  27691. if (this.color !== undefined) {
  27692. this.lightPlane.material.color.set(this.color);
  27693. this.targetLine.material.color.set(this.color);
  27694. } else {
  27695. this.lightPlane.material.color.copy(this.light.color);
  27696. this.targetLine.material.color.copy(this.light.color);
  27697. }
  27698. this.targetLine.lookAt(_v2$5);
  27699. this.targetLine.scale.z = _v3$1.length();
  27700. };
  27701. /**
  27702. * @author alteredq / http://alteredqualia.com/
  27703. * @author Mugen87 / https://github.com/Mugen87
  27704. *
  27705. * - shows frustum, line of sight and up of the camera
  27706. * - suitable for fast updates
  27707. * - based on frustum visualization in lightgl.js shadowmap example
  27708. * http://evanw.github.com/lightgl.js/tests/shadowmap.html
  27709. */
  27710. var _vector$a = new Vector3();
  27711. var _camera = new Camera();
  27712. function CameraHelper(camera) {
  27713. var geometry = new BufferGeometry();
  27714. var material = new LineBasicMaterial({
  27715. color: 0xffffff,
  27716. vertexColors: FaceColors
  27717. });
  27718. var vertices = [];
  27719. var colors = [];
  27720. var pointMap = {}; // colors
  27721. var colorFrustum = new Color(0xffaa00);
  27722. var colorCone = new Color(0xff0000);
  27723. var colorUp = new Color(0x00aaff);
  27724. var colorTarget = new Color(0xffffff);
  27725. var colorCross = new Color(0x333333); // near
  27726. addLine('n1', 'n2', colorFrustum);
  27727. addLine('n2', 'n4', colorFrustum);
  27728. addLine('n4', 'n3', colorFrustum);
  27729. addLine('n3', 'n1', colorFrustum); // far
  27730. addLine('f1', 'f2', colorFrustum);
  27731. addLine('f2', 'f4', colorFrustum);
  27732. addLine('f4', 'f3', colorFrustum);
  27733. addLine('f3', 'f1', colorFrustum); // sides
  27734. addLine('n1', 'f1', colorFrustum);
  27735. addLine('n2', 'f2', colorFrustum);
  27736. addLine('n3', 'f3', colorFrustum);
  27737. addLine('n4', 'f4', colorFrustum); // cone
  27738. addLine('p', 'n1', colorCone);
  27739. addLine('p', 'n2', colorCone);
  27740. addLine('p', 'n3', colorCone);
  27741. addLine('p', 'n4', colorCone); // up
  27742. addLine('u1', 'u2', colorUp);
  27743. addLine('u2', 'u3', colorUp);
  27744. addLine('u3', 'u1', colorUp); // target
  27745. addLine('c', 't', colorTarget);
  27746. addLine('p', 'c', colorCross); // cross
  27747. addLine('cn1', 'cn2', colorCross);
  27748. addLine('cn3', 'cn4', colorCross);
  27749. addLine('cf1', 'cf2', colorCross);
  27750. addLine('cf3', 'cf4', colorCross);
  27751. function addLine(a, b, color) {
  27752. addPoint(a, color);
  27753. addPoint(b, color);
  27754. }
  27755. function addPoint(id, color) {
  27756. vertices.push(0, 0, 0);
  27757. colors.push(color.r, color.g, color.b);
  27758. if (pointMap[id] === undefined) {
  27759. pointMap[id] = [];
  27760. }
  27761. pointMap[id].push(vertices.length / 3 - 1);
  27762. }
  27763. geometry.addAttribute('position', new Float32BufferAttribute(vertices, 3));
  27764. geometry.addAttribute('color', new Float32BufferAttribute(colors, 3));
  27765. LineSegments.call(this, geometry, material);
  27766. this.camera = camera;
  27767. if (this.camera.updateProjectionMatrix) this.camera.updateProjectionMatrix();
  27768. this.matrix = camera.matrixWorld;
  27769. this.matrixAutoUpdate = false;
  27770. this.pointMap = pointMap;
  27771. this.update();
  27772. }
  27773. CameraHelper.prototype = Object.create(LineSegments.prototype);
  27774. CameraHelper.prototype.constructor = CameraHelper;
  27775. CameraHelper.prototype.update = function () {
  27776. var geometry = this.geometry;
  27777. var pointMap = this.pointMap;
  27778. var w = 1,
  27779. h = 1; // we need just camera projection matrix inverse
  27780. // world matrix must be identity
  27781. _camera.projectionMatrixInverse.copy(this.camera.projectionMatrixInverse); // center / target
  27782. setPoint('c', pointMap, geometry, _camera, 0, 0, -1);
  27783. setPoint('t', pointMap, geometry, _camera, 0, 0, 1); // near
  27784. setPoint('n1', pointMap, geometry, _camera, -w, -h, -1);
  27785. setPoint('n2', pointMap, geometry, _camera, w, -h, -1);
  27786. setPoint('n3', pointMap, geometry, _camera, -w, h, -1);
  27787. setPoint('n4', pointMap, geometry, _camera, w, h, -1); // far
  27788. setPoint('f1', pointMap, geometry, _camera, -w, -h, 1);
  27789. setPoint('f2', pointMap, geometry, _camera, w, -h, 1);
  27790. setPoint('f3', pointMap, geometry, _camera, -w, h, 1);
  27791. setPoint('f4', pointMap, geometry, _camera, w, h, 1); // up
  27792. setPoint('u1', pointMap, geometry, _camera, w * 0.7, h * 1.1, -1);
  27793. setPoint('u2', pointMap, geometry, _camera, -w * 0.7, h * 1.1, -1);
  27794. setPoint('u3', pointMap, geometry, _camera, 0, h * 2, -1); // cross
  27795. setPoint('cf1', pointMap, geometry, _camera, -w, 0, 1);
  27796. setPoint('cf2', pointMap, geometry, _camera, w, 0, 1);
  27797. setPoint('cf3', pointMap, geometry, _camera, 0, -h, 1);
  27798. setPoint('cf4', pointMap, geometry, _camera, 0, h, 1);
  27799. setPoint('cn1', pointMap, geometry, _camera, -w, 0, -1);
  27800. setPoint('cn2', pointMap, geometry, _camera, w, 0, -1);
  27801. setPoint('cn3', pointMap, geometry, _camera, 0, -h, -1);
  27802. setPoint('cn4', pointMap, geometry, _camera, 0, h, -1);
  27803. geometry.getAttribute('position').needsUpdate = true;
  27804. };
  27805. function setPoint(point, pointMap, geometry, camera, x, y, z) {
  27806. _vector$a.set(x, y, z).unproject(camera);
  27807. var points = pointMap[point];
  27808. if (points !== undefined) {
  27809. var position = geometry.getAttribute('position');
  27810. for (var i = 0, l = points.length; i < l; i++) {
  27811. position.setXYZ(points[i], _vector$a.x, _vector$a.y, _vector$a.z);
  27812. }
  27813. }
  27814. }
  27815. /**
  27816. * @author mrdoob / http://mrdoob.com/
  27817. * @author Mugen87 / http://github.com/Mugen87
  27818. */
  27819. var _box$2 = new Box3();
  27820. function BoxHelper(object, color) {
  27821. this.object = object;
  27822. if (color === undefined) color = 0xffff00;
  27823. 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]);
  27824. var positions = new Float32Array(8 * 3);
  27825. var geometry = new BufferGeometry();
  27826. geometry.setIndex(new BufferAttribute(indices, 1));
  27827. geometry.addAttribute('position', new BufferAttribute(positions, 3));
  27828. LineSegments.call(this, geometry, new LineBasicMaterial({
  27829. color: color
  27830. }));
  27831. this.matrixAutoUpdate = false;
  27832. this.update();
  27833. }
  27834. BoxHelper.prototype = Object.create(LineSegments.prototype);
  27835. BoxHelper.prototype.constructor = BoxHelper;
  27836. BoxHelper.prototype.update = function (object) {
  27837. if (object !== undefined) {
  27838. console.warn('THREE.BoxHelper: .update() has no longer arguments.');
  27839. }
  27840. if (this.object !== undefined) {
  27841. _box$2.setFromObject(this.object);
  27842. }
  27843. if (_box$2.isEmpty()) return;
  27844. var min = _box$2.min;
  27845. var max = _box$2.max;
  27846. /*
  27847. 5____4
  27848. 1/___0/|
  27849. | 6__|_7
  27850. 2/___3/
  27851. 0: max.x, max.y, max.z
  27852. 1: min.x, max.y, max.z
  27853. 2: min.x, min.y, max.z
  27854. 3: max.x, min.y, max.z
  27855. 4: max.x, max.y, min.z
  27856. 5: min.x, max.y, min.z
  27857. 6: min.x, min.y, min.z
  27858. 7: max.x, min.y, min.z
  27859. */
  27860. var position = this.geometry.attributes.position;
  27861. var array = position.array;
  27862. array[0] = max.x;
  27863. array[1] = max.y;
  27864. array[2] = max.z;
  27865. array[3] = min.x;
  27866. array[4] = max.y;
  27867. array[5] = max.z;
  27868. array[6] = min.x;
  27869. array[7] = min.y;
  27870. array[8] = max.z;
  27871. array[9] = max.x;
  27872. array[10] = min.y;
  27873. array[11] = max.z;
  27874. array[12] = max.x;
  27875. array[13] = max.y;
  27876. array[14] = min.z;
  27877. array[15] = min.x;
  27878. array[16] = max.y;
  27879. array[17] = min.z;
  27880. array[18] = min.x;
  27881. array[19] = min.y;
  27882. array[20] = min.z;
  27883. array[21] = max.x;
  27884. array[22] = min.y;
  27885. array[23] = min.z;
  27886. position.needsUpdate = true;
  27887. this.geometry.computeBoundingSphere();
  27888. };
  27889. BoxHelper.prototype.setFromObject = function (object) {
  27890. this.object = object;
  27891. this.update();
  27892. return this;
  27893. };
  27894. BoxHelper.prototype.copy = function (source) {
  27895. LineSegments.prototype.copy.call(this, source);
  27896. this.object = source.object;
  27897. return this;
  27898. };
  27899. BoxHelper.prototype.clone = function () {
  27900. return new this.constructor().copy(this);
  27901. };
  27902. /**
  27903. * @author WestLangley / http://github.com/WestLangley
  27904. */
  27905. function Box3Helper(box, color) {
  27906. this.type = 'Box3Helper';
  27907. this.box = box;
  27908. color = color || 0xffff00;
  27909. 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]);
  27910. 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];
  27911. var geometry = new BufferGeometry();
  27912. geometry.setIndex(new BufferAttribute(indices, 1));
  27913. geometry.addAttribute('position', new Float32BufferAttribute(positions, 3));
  27914. LineSegments.call(this, geometry, new LineBasicMaterial({
  27915. color: color
  27916. }));
  27917. this.geometry.computeBoundingSphere();
  27918. }
  27919. Box3Helper.prototype = Object.create(LineSegments.prototype);
  27920. Box3Helper.prototype.constructor = Box3Helper;
  27921. Box3Helper.prototype.updateMatrixWorld = function (force) {
  27922. var box = this.box;
  27923. if (box.isEmpty()) return;
  27924. box.getCenter(this.position);
  27925. box.getSize(this.scale);
  27926. this.scale.multiplyScalar(0.5);
  27927. Object3D.prototype.updateMatrixWorld.call(this, force);
  27928. };
  27929. /**
  27930. * @author WestLangley / http://github.com/WestLangley
  27931. */
  27932. function PlaneHelper(plane, size, hex) {
  27933. this.type = 'PlaneHelper';
  27934. this.plane = plane;
  27935. this.size = size === undefined ? 1 : size;
  27936. var color = hex !== undefined ? hex : 0xffff00;
  27937. 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];
  27938. var geometry = new BufferGeometry();
  27939. geometry.addAttribute('position', new Float32BufferAttribute(positions, 3));
  27940. geometry.computeBoundingSphere();
  27941. Line.call(this, geometry, new LineBasicMaterial({
  27942. color: color
  27943. })); //
  27944. var positions2 = [1, 1, 1, -1, 1, 1, -1, -1, 1, 1, 1, 1, -1, -1, 1, 1, -1, 1];
  27945. var geometry2 = new BufferGeometry();
  27946. geometry2.addAttribute('position', new Float32BufferAttribute(positions2, 3));
  27947. geometry2.computeBoundingSphere();
  27948. this.add(new Mesh(geometry2, new MeshBasicMaterial({
  27949. color: color,
  27950. opacity: 0.2,
  27951. transparent: true,
  27952. depthWrite: false
  27953. })));
  27954. }
  27955. PlaneHelper.prototype = Object.create(Line.prototype);
  27956. PlaneHelper.prototype.constructor = PlaneHelper;
  27957. PlaneHelper.prototype.updateMatrixWorld = function (force) {
  27958. var scale = -this.plane.constant;
  27959. if (Math.abs(scale) < 1e-8) scale = 1e-8; // sign does not matter
  27960. this.scale.set(0.5 * this.size, 0.5 * this.size, scale);
  27961. this.children[0].material.side = scale < 0 ? BackSide : FrontSide; // renderer flips side when determinant < 0; flipping not wanted here
  27962. this.lookAt(this.plane.normal);
  27963. Object3D.prototype.updateMatrixWorld.call(this, force);
  27964. };
  27965. /**
  27966. * @author WestLangley / http://github.com/WestLangley
  27967. * @author zz85 / http://github.com/zz85
  27968. * @author bhouston / http://clara.io
  27969. *
  27970. * Creates an arrow for visualizing directions
  27971. *
  27972. * Parameters:
  27973. * dir - Vector3
  27974. * origin - Vector3
  27975. * length - Number
  27976. * color - color in hex value
  27977. * headLength - Number
  27978. * headWidth - Number
  27979. */
  27980. var _axis = new Vector3();
  27981. var _lineGeometry, _coneGeometry;
  27982. function ArrowHelper(dir, origin, length, color, headLength, headWidth) {
  27983. // dir is assumed to be normalized
  27984. Object3D.call(this);
  27985. if (dir === undefined) dir = new Vector3(0, 0, 1);
  27986. if (origin === undefined) origin = new Vector3(0, 0, 0);
  27987. if (length === undefined) length = 1;
  27988. if (color === undefined) color = 0xffff00;
  27989. if (headLength === undefined) headLength = 0.2 * length;
  27990. if (headWidth === undefined) headWidth = 0.2 * headLength;
  27991. if (_lineGeometry === undefined) {
  27992. _lineGeometry = new BufferGeometry();
  27993. _lineGeometry.addAttribute('position', new Float32BufferAttribute([0, 0, 0, 0, 1, 0], 3));
  27994. _coneGeometry = new CylinderBufferGeometry(0, 0.5, 1, 5, 1);
  27995. _coneGeometry.translate(0, -0.5, 0);
  27996. }
  27997. this.position.copy(origin);
  27998. this.line = new Line(_lineGeometry, new LineBasicMaterial({
  27999. color: color
  28000. }));
  28001. this.line.matrixAutoUpdate = false;
  28002. this.add(this.line);
  28003. this.cone = new Mesh(_coneGeometry, new MeshBasicMaterial({
  28004. color: color
  28005. }));
  28006. this.cone.matrixAutoUpdate = false;
  28007. this.add(this.cone);
  28008. this.setDirection(dir);
  28009. this.setLength(length, headLength, headWidth);
  28010. }
  28011. ArrowHelper.prototype = Object.create(Object3D.prototype);
  28012. ArrowHelper.prototype.constructor = ArrowHelper;
  28013. ArrowHelper.prototype.setDirection = function (dir) {
  28014. // dir is assumed to be normalized
  28015. if (dir.y > 0.99999) {
  28016. this.quaternion.set(0, 0, 0, 1);
  28017. } else if (dir.y < -0.99999) {
  28018. this.quaternion.set(1, 0, 0, 0);
  28019. } else {
  28020. _axis.set(dir.z, 0, -dir.x).normalize();
  28021. var radians = Math.acos(dir.y);
  28022. this.quaternion.setFromAxisAngle(_axis, radians);
  28023. }
  28024. };
  28025. ArrowHelper.prototype.setLength = function (length, headLength, headWidth) {
  28026. if (headLength === undefined) headLength = 0.2 * length;
  28027. if (headWidth === undefined) headWidth = 0.2 * headLength;
  28028. this.line.scale.set(1, Math.max(0.0001, length - headLength), 1); // see #17458
  28029. this.line.updateMatrix();
  28030. this.cone.scale.set(headWidth, headLength, headWidth);
  28031. this.cone.position.y = length;
  28032. this.cone.updateMatrix();
  28033. };
  28034. ArrowHelper.prototype.setColor = function (color) {
  28035. this.line.material.color.set(color);
  28036. this.cone.material.color.set(color);
  28037. };
  28038. ArrowHelper.prototype.copy = function (source) {
  28039. Object3D.prototype.copy.call(this, source, false);
  28040. this.line.copy(source.line);
  28041. this.cone.copy(source.cone);
  28042. return this;
  28043. };
  28044. ArrowHelper.prototype.clone = function () {
  28045. return new this.constructor().copy(this);
  28046. };
  28047. /**
  28048. * @author sroucheray / http://sroucheray.org/
  28049. * @author mrdoob / http://mrdoob.com/
  28050. */
  28051. function AxesHelper(size) {
  28052. size = size || 1;
  28053. var vertices = [0, 0, 0, size, 0, 0, 0, 0, 0, 0, size, 0, 0, 0, 0, 0, 0, size];
  28054. var colors = [1, 0, 0, 1, 0.6, 0, 0, 1, 0, 0.6, 1, 0, 0, 0, 1, 0, 0.6, 1];
  28055. var geometry = new BufferGeometry();
  28056. geometry.addAttribute('position', new Float32BufferAttribute(vertices, 3));
  28057. geometry.addAttribute('color', new Float32BufferAttribute(colors, 3));
  28058. var material = new LineBasicMaterial({
  28059. vertexColors: VertexColors
  28060. });
  28061. LineSegments.call(this, geometry, material);
  28062. }
  28063. AxesHelper.prototype = Object.create(LineSegments.prototype);
  28064. AxesHelper.prototype.constructor = AxesHelper;
  28065. /**
  28066. * @author mrdoob / http://mrdoob.com/
  28067. */
  28068. function Face4(a, b, c, d, normal, color, materialIndex) {
  28069. console.warn('THREE.Face4 has been removed. A THREE.Face3 will be created instead.');
  28070. return new Face3(a, b, c, normal, color, materialIndex);
  28071. }
  28072. var LineStrip = 0;
  28073. exports.LineStrip = LineStrip;
  28074. var LinePieces = 1;
  28075. exports.LinePieces = LinePieces;
  28076. function MeshFaceMaterial(materials) {
  28077. console.warn('THREE.MeshFaceMaterial has been removed. Use an Array instead.');
  28078. return materials;
  28079. }
  28080. function MultiMaterial(materials) {
  28081. if (materials === undefined) materials = [];
  28082. console.warn('THREE.MultiMaterial has been removed. Use an Array instead.');
  28083. materials.isMultiMaterial = true;
  28084. materials.materials = materials;
  28085. materials.clone = function () {
  28086. return materials.slice();
  28087. };
  28088. return materials;
  28089. }
  28090. function PointCloud(geometry, material) {
  28091. console.warn('THREE.PointCloud has been renamed to THREE.Points.');
  28092. return new Points(geometry, material);
  28093. }
  28094. function Particle(material) {
  28095. console.warn('THREE.Particle has been renamed to THREE.Sprite.');
  28096. return new Sprite(material);
  28097. }
  28098. function ParticleSystem(geometry, material) {
  28099. console.warn('THREE.ParticleSystem has been renamed to THREE.Points.');
  28100. return new Points(geometry, material);
  28101. }
  28102. function PointCloudMaterial(parameters) {
  28103. console.warn('THREE.PointCloudMaterial has been renamed to THREE.PointsMaterial.');
  28104. return new PointsMaterial(parameters);
  28105. }
  28106. function ParticleBasicMaterial(parameters) {
  28107. console.warn('THREE.ParticleBasicMaterial has been renamed to THREE.PointsMaterial.');
  28108. return new PointsMaterial(parameters);
  28109. }
  28110. function ParticleSystemMaterial(parameters) {
  28111. console.warn('THREE.ParticleSystemMaterial has been renamed to THREE.PointsMaterial.');
  28112. return new PointsMaterial(parameters);
  28113. }
  28114. function Vertex(x, y, z) {
  28115. console.warn('THREE.Vertex has been removed. Use THREE.Vector3 instead.');
  28116. return new Vector3(x, y, z);
  28117. } //
  28118. function DynamicBufferAttribute(array, itemSize) {
  28119. console.warn('THREE.DynamicBufferAttribute has been removed. Use new THREE.BufferAttribute().setDynamic( true ) instead.');
  28120. return new BufferAttribute(array, itemSize).setDynamic(true);
  28121. }
  28122. function Int8Attribute(array, itemSize) {
  28123. console.warn('THREE.Int8Attribute has been removed. Use new THREE.Int8BufferAttribute() instead.');
  28124. return new Int8BufferAttribute(array, itemSize);
  28125. }
  28126. function Uint8Attribute(array, itemSize) {
  28127. console.warn('THREE.Uint8Attribute has been removed. Use new THREE.Uint8BufferAttribute() instead.');
  28128. return new Uint8BufferAttribute(array, itemSize);
  28129. }
  28130. function Uint8ClampedAttribute(array, itemSize) {
  28131. console.warn('THREE.Uint8ClampedAttribute has been removed. Use new THREE.Uint8ClampedBufferAttribute() instead.');
  28132. return new Uint8ClampedBufferAttribute(array, itemSize);
  28133. }
  28134. function Int16Attribute(array, itemSize) {
  28135. console.warn('THREE.Int16Attribute has been removed. Use new THREE.Int16BufferAttribute() instead.');
  28136. return new Int16BufferAttribute(array, itemSize);
  28137. }
  28138. function Uint16Attribute(array, itemSize) {
  28139. console.warn('THREE.Uint16Attribute has been removed. Use new THREE.Uint16BufferAttribute() instead.');
  28140. return new Uint16BufferAttribute(array, itemSize);
  28141. }
  28142. function Int32Attribute(array, itemSize) {
  28143. console.warn('THREE.Int32Attribute has been removed. Use new THREE.Int32BufferAttribute() instead.');
  28144. return new Int32BufferAttribute(array, itemSize);
  28145. }
  28146. function Uint32Attribute(array, itemSize) {
  28147. console.warn('THREE.Uint32Attribute has been removed. Use new THREE.Uint32BufferAttribute() instead.');
  28148. return new Uint32BufferAttribute(array, itemSize);
  28149. }
  28150. function Float32Attribute(array, itemSize) {
  28151. console.warn('THREE.Float32Attribute has been removed. Use new THREE.Float32BufferAttribute() instead.');
  28152. return new Float32BufferAttribute(array, itemSize);
  28153. }
  28154. function Float64Attribute(array, itemSize) {
  28155. console.warn('THREE.Float64Attribute has been removed. Use new THREE.Float64BufferAttribute() instead.');
  28156. return new Float64BufferAttribute(array, itemSize);
  28157. } //
  28158. Curve.create = function (construct, getPoint) {
  28159. console.log('THREE.Curve.create() has been deprecated');
  28160. construct.prototype = Object.create(Curve.prototype);
  28161. construct.prototype.constructor = construct;
  28162. construct.prototype.getPoint = getPoint;
  28163. return construct;
  28164. }; //
  28165. Object.assign(CurvePath.prototype, {
  28166. createPointsGeometry: function (divisions) {
  28167. 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)
  28168. var pts = this.getPoints(divisions);
  28169. return this.createGeometry(pts);
  28170. },
  28171. createSpacedPointsGeometry: function (divisions) {
  28172. console.warn('THREE.CurvePath: .createSpacedPointsGeometry() has been removed. Use new THREE.Geometry().setFromPoints( points ) instead.'); // generate geometry from equidistant sampling along the path
  28173. var pts = this.getSpacedPoints(divisions);
  28174. return this.createGeometry(pts);
  28175. },
  28176. createGeometry: function (points) {
  28177. console.warn('THREE.CurvePath: .createGeometry() has been removed. Use new THREE.Geometry().setFromPoints( points ) instead.');
  28178. var geometry = new Geometry();
  28179. for (var i = 0, l = points.length; i < l; i++) {
  28180. var point = points[i];
  28181. geometry.vertices.push(new Vector3(point.x, point.y, point.z || 0));
  28182. }
  28183. return geometry;
  28184. }
  28185. }); //
  28186. Object.assign(Path.prototype, {
  28187. fromPoints: function (points) {
  28188. console.warn('THREE.Path: .fromPoints() has been renamed to .setFromPoints().');
  28189. this.setFromPoints(points);
  28190. }
  28191. }); //
  28192. function ClosedSplineCurve3(points) {
  28193. console.warn('THREE.ClosedSplineCurve3 has been deprecated. Use THREE.CatmullRomCurve3 instead.');
  28194. CatmullRomCurve3.call(this, points);
  28195. this.type = 'catmullrom';
  28196. this.closed = true;
  28197. }
  28198. ClosedSplineCurve3.prototype = Object.create(CatmullRomCurve3.prototype); //
  28199. function SplineCurve3(points) {
  28200. console.warn('THREE.SplineCurve3 has been deprecated. Use THREE.CatmullRomCurve3 instead.');
  28201. CatmullRomCurve3.call(this, points);
  28202. this.type = 'catmullrom';
  28203. }
  28204. SplineCurve3.prototype = Object.create(CatmullRomCurve3.prototype); //
  28205. function Spline(points) {
  28206. console.warn('THREE.Spline has been removed. Use THREE.CatmullRomCurve3 instead.');
  28207. CatmullRomCurve3.call(this, points);
  28208. this.type = 'catmullrom';
  28209. }
  28210. Spline.prototype = Object.create(CatmullRomCurve3.prototype);
  28211. Object.assign(Spline.prototype, {
  28212. initFromArray: function ()
  28213. /* a */
  28214. {
  28215. console.error('THREE.Spline: .initFromArray() has been removed.');
  28216. },
  28217. getControlPointsArray: function ()
  28218. /* optionalTarget */
  28219. {
  28220. console.error('THREE.Spline: .getControlPointsArray() has been removed.');
  28221. },
  28222. reparametrizeByArcLength: function ()
  28223. /* samplingCoef */
  28224. {
  28225. console.error('THREE.Spline: .reparametrizeByArcLength() has been removed.');
  28226. }
  28227. }); //
  28228. function AxisHelper(size) {
  28229. console.warn('THREE.AxisHelper has been renamed to THREE.AxesHelper.');
  28230. return new AxesHelper(size);
  28231. }
  28232. function BoundingBoxHelper(object, color) {
  28233. console.warn('THREE.BoundingBoxHelper has been deprecated. Creating a THREE.BoxHelper instead.');
  28234. return new BoxHelper(object, color);
  28235. }
  28236. function EdgesHelper(object, hex) {
  28237. console.warn('THREE.EdgesHelper has been removed. Use THREE.EdgesGeometry instead.');
  28238. return new LineSegments(new EdgesGeometry(object.geometry), new LineBasicMaterial({
  28239. color: hex !== undefined ? hex : 0xffffff
  28240. }));
  28241. }
  28242. GridHelper.prototype.setColors = function () {
  28243. console.error('THREE.GridHelper: setColors() has been deprecated, pass them in the constructor instead.');
  28244. };
  28245. SkeletonHelper.prototype.update = function () {
  28246. console.error('THREE.SkeletonHelper: update() no longer needs to be called.');
  28247. };
  28248. function WireframeHelper(object, hex) {
  28249. console.warn('THREE.WireframeHelper has been removed. Use THREE.WireframeGeometry instead.');
  28250. return new LineSegments(new WireframeGeometry(object.geometry), new LineBasicMaterial({
  28251. color: hex !== undefined ? hex : 0xffffff
  28252. }));
  28253. } //
  28254. Object.assign(Loader.prototype, {
  28255. extractUrlBase: function (url) {
  28256. console.warn('THREE.Loader: .extractUrlBase() has been deprecated. Use THREE.LoaderUtils.extractUrlBase() instead.');
  28257. return LoaderUtils.extractUrlBase(url);
  28258. }
  28259. });
  28260. Loader.Handlers = {
  28261. add: function ()
  28262. /* regex, loader */
  28263. {
  28264. console.error('THREE.Loader: Handlers.add() has been removed. Use LoadingManager.addHandler() instead.');
  28265. },
  28266. get: function ()
  28267. /* file */
  28268. {
  28269. console.error('THREE.Loader: Handlers.get() has been removed. Use LoadingManager.getHandler() instead.');
  28270. }
  28271. };
  28272. function XHRLoader(manager) {
  28273. console.warn('THREE.XHRLoader has been renamed to THREE.FileLoader.');
  28274. return new FileLoader(manager);
  28275. }
  28276. function BinaryTextureLoader(manager) {
  28277. console.warn('THREE.BinaryTextureLoader has been renamed to THREE.DataTextureLoader.');
  28278. return new DataTextureLoader(manager);
  28279. }
  28280. Object.assign(ObjectLoader.prototype, {
  28281. setTexturePath: function (value) {
  28282. console.warn('THREE.ObjectLoader: .setTexturePath() has been renamed to .setResourcePath().');
  28283. return this.setResourcePath(value);
  28284. }
  28285. }); //
  28286. Object.assign(Box2.prototype, {
  28287. center: function (optionalTarget) {
  28288. console.warn('THREE.Box2: .center() has been renamed to .getCenter().');
  28289. return this.getCenter(optionalTarget);
  28290. },
  28291. empty: function () {
  28292. console.warn('THREE.Box2: .empty() has been renamed to .isEmpty().');
  28293. return this.isEmpty();
  28294. },
  28295. isIntersectionBox: function (box) {
  28296. console.warn('THREE.Box2: .isIntersectionBox() has been renamed to .intersectsBox().');
  28297. return this.intersectsBox(box);
  28298. },
  28299. size: function (optionalTarget) {
  28300. console.warn('THREE.Box2: .size() has been renamed to .getSize().');
  28301. return this.getSize(optionalTarget);
  28302. }
  28303. });
  28304. Object.assign(Box3.prototype, {
  28305. center: function (optionalTarget) {
  28306. console.warn('THREE.Box3: .center() has been renamed to .getCenter().');
  28307. return this.getCenter(optionalTarget);
  28308. },
  28309. empty: function () {
  28310. console.warn('THREE.Box3: .empty() has been renamed to .isEmpty().');
  28311. return this.isEmpty();
  28312. },
  28313. isIntersectionBox: function (box) {
  28314. console.warn('THREE.Box3: .isIntersectionBox() has been renamed to .intersectsBox().');
  28315. return this.intersectsBox(box);
  28316. },
  28317. isIntersectionSphere: function (sphere) {
  28318. console.warn('THREE.Box3: .isIntersectionSphere() has been renamed to .intersectsSphere().');
  28319. return this.intersectsSphere(sphere);
  28320. },
  28321. size: function (optionalTarget) {
  28322. console.warn('THREE.Box3: .size() has been renamed to .getSize().');
  28323. return this.getSize(optionalTarget);
  28324. }
  28325. });
  28326. Line3.prototype.center = function (optionalTarget) {
  28327. console.warn('THREE.Line3: .center() has been renamed to .getCenter().');
  28328. return this.getCenter(optionalTarget);
  28329. };
  28330. Object.assign(_Math, {
  28331. random16: function () {
  28332. console.warn('THREE.Math: .random16() has been deprecated. Use Math.random() instead.');
  28333. return Math.random();
  28334. },
  28335. nearestPowerOfTwo: function (value) {
  28336. console.warn('THREE.Math: .nearestPowerOfTwo() has been renamed to .floorPowerOfTwo().');
  28337. return _Math.floorPowerOfTwo(value);
  28338. },
  28339. nextPowerOfTwo: function (value) {
  28340. console.warn('THREE.Math: .nextPowerOfTwo() has been renamed to .ceilPowerOfTwo().');
  28341. return _Math.ceilPowerOfTwo(value);
  28342. }
  28343. });
  28344. Object.assign(Matrix3.prototype, {
  28345. flattenToArrayOffset: function (array, offset) {
  28346. console.warn("THREE.Matrix3: .flattenToArrayOffset() has been deprecated. Use .toArray() instead.");
  28347. return this.toArray(array, offset);
  28348. },
  28349. multiplyVector3: function (vector) {
  28350. console.warn('THREE.Matrix3: .multiplyVector3() has been removed. Use vector.applyMatrix3( matrix ) instead.');
  28351. return vector.applyMatrix3(this);
  28352. },
  28353. multiplyVector3Array: function ()
  28354. /* a */
  28355. {
  28356. console.error('THREE.Matrix3: .multiplyVector3Array() has been removed.');
  28357. },
  28358. applyToBuffer: function (buffer
  28359. /*, offset, length */
  28360. ) {
  28361. console.warn('THREE.Matrix3: .applyToBuffer() has been removed. Use matrix.applyToBufferAttribute( attribute ) instead.');
  28362. return this.applyToBufferAttribute(buffer);
  28363. },
  28364. applyToVector3Array: function ()
  28365. /* array, offset, length */
  28366. {
  28367. console.error('THREE.Matrix3: .applyToVector3Array() has been removed.');
  28368. }
  28369. });
  28370. Object.assign(Matrix4.prototype, {
  28371. extractPosition: function (m) {
  28372. console.warn('THREE.Matrix4: .extractPosition() has been renamed to .copyPosition().');
  28373. return this.copyPosition(m);
  28374. },
  28375. flattenToArrayOffset: function (array, offset) {
  28376. console.warn("THREE.Matrix4: .flattenToArrayOffset() has been deprecated. Use .toArray() instead.");
  28377. return this.toArray(array, offset);
  28378. },
  28379. getPosition: function () {
  28380. console.warn('THREE.Matrix4: .getPosition() has been removed. Use Vector3.setFromMatrixPosition( matrix ) instead.');
  28381. return new Vector3().setFromMatrixColumn(this, 3);
  28382. },
  28383. setRotationFromQuaternion: function (q) {
  28384. console.warn('THREE.Matrix4: .setRotationFromQuaternion() has been renamed to .makeRotationFromQuaternion().');
  28385. return this.makeRotationFromQuaternion(q);
  28386. },
  28387. multiplyToArray: function () {
  28388. console.warn('THREE.Matrix4: .multiplyToArray() has been removed.');
  28389. },
  28390. multiplyVector3: function (vector) {
  28391. console.warn('THREE.Matrix4: .multiplyVector3() has been removed. Use vector.applyMatrix4( matrix ) instead.');
  28392. return vector.applyMatrix4(this);
  28393. },
  28394. multiplyVector4: function (vector) {
  28395. console.warn('THREE.Matrix4: .multiplyVector4() has been removed. Use vector.applyMatrix4( matrix ) instead.');
  28396. return vector.applyMatrix4(this);
  28397. },
  28398. multiplyVector3Array: function ()
  28399. /* a */
  28400. {
  28401. console.error('THREE.Matrix4: .multiplyVector3Array() has been removed.');
  28402. },
  28403. rotateAxis: function (v) {
  28404. console.warn('THREE.Matrix4: .rotateAxis() has been removed. Use Vector3.transformDirection( matrix ) instead.');
  28405. v.transformDirection(this);
  28406. },
  28407. crossVector: function (vector) {
  28408. console.warn('THREE.Matrix4: .crossVector() has been removed. Use vector.applyMatrix4( matrix ) instead.');
  28409. return vector.applyMatrix4(this);
  28410. },
  28411. translate: function () {
  28412. console.error('THREE.Matrix4: .translate() has been removed.');
  28413. },
  28414. rotateX: function () {
  28415. console.error('THREE.Matrix4: .rotateX() has been removed.');
  28416. },
  28417. rotateY: function () {
  28418. console.error('THREE.Matrix4: .rotateY() has been removed.');
  28419. },
  28420. rotateZ: function () {
  28421. console.error('THREE.Matrix4: .rotateZ() has been removed.');
  28422. },
  28423. rotateByAxis: function () {
  28424. console.error('THREE.Matrix4: .rotateByAxis() has been removed.');
  28425. },
  28426. applyToBuffer: function (buffer
  28427. /*, offset, length */
  28428. ) {
  28429. console.warn('THREE.Matrix4: .applyToBuffer() has been removed. Use matrix.applyToBufferAttribute( attribute ) instead.');
  28430. return this.applyToBufferAttribute(buffer);
  28431. },
  28432. applyToVector3Array: function ()
  28433. /* array, offset, length */
  28434. {
  28435. console.error('THREE.Matrix4: .applyToVector3Array() has been removed.');
  28436. },
  28437. makeFrustum: function (left, right, bottom, top, near, far) {
  28438. console.warn('THREE.Matrix4: .makeFrustum() has been removed. Use .makePerspective( left, right, top, bottom, near, far ) instead.');
  28439. return this.makePerspective(left, right, top, bottom, near, far);
  28440. }
  28441. });
  28442. Plane.prototype.isIntersectionLine = function (line) {
  28443. console.warn('THREE.Plane: .isIntersectionLine() has been renamed to .intersectsLine().');
  28444. return this.intersectsLine(line);
  28445. };
  28446. Quaternion.prototype.multiplyVector3 = function (vector) {
  28447. console.warn('THREE.Quaternion: .multiplyVector3() has been removed. Use is now vector.applyQuaternion( quaternion ) instead.');
  28448. return vector.applyQuaternion(this);
  28449. };
  28450. Object.assign(Ray.prototype, {
  28451. isIntersectionBox: function (box) {
  28452. console.warn('THREE.Ray: .isIntersectionBox() has been renamed to .intersectsBox().');
  28453. return this.intersectsBox(box);
  28454. },
  28455. isIntersectionPlane: function (plane) {
  28456. console.warn('THREE.Ray: .isIntersectionPlane() has been renamed to .intersectsPlane().');
  28457. return this.intersectsPlane(plane);
  28458. },
  28459. isIntersectionSphere: function (sphere) {
  28460. console.warn('THREE.Ray: .isIntersectionSphere() has been renamed to .intersectsSphere().');
  28461. return this.intersectsSphere(sphere);
  28462. }
  28463. });
  28464. Object.assign(Triangle.prototype, {
  28465. area: function () {
  28466. console.warn('THREE.Triangle: .area() has been renamed to .getArea().');
  28467. return this.getArea();
  28468. },
  28469. barycoordFromPoint: function (point, target) {
  28470. console.warn('THREE.Triangle: .barycoordFromPoint() has been renamed to .getBarycoord().');
  28471. return this.getBarycoord(point, target);
  28472. },
  28473. midpoint: function (target) {
  28474. console.warn('THREE.Triangle: .midpoint() has been renamed to .getMidpoint().');
  28475. return this.getMidpoint(target);
  28476. },
  28477. normal: function (target) {
  28478. console.warn('THREE.Triangle: .normal() has been renamed to .getNormal().');
  28479. return this.getNormal(target);
  28480. },
  28481. plane: function (target) {
  28482. console.warn('THREE.Triangle: .plane() has been renamed to .getPlane().');
  28483. return this.getPlane(target);
  28484. }
  28485. });
  28486. Object.assign(Triangle, {
  28487. barycoordFromPoint: function (point, a, b, c, target) {
  28488. console.warn('THREE.Triangle: .barycoordFromPoint() has been renamed to .getBarycoord().');
  28489. return Triangle.getBarycoord(point, a, b, c, target);
  28490. },
  28491. normal: function (a, b, c, target) {
  28492. console.warn('THREE.Triangle: .normal() has been renamed to .getNormal().');
  28493. return Triangle.getNormal(a, b, c, target);
  28494. }
  28495. });
  28496. Object.assign(Shape.prototype, {
  28497. extractAllPoints: function (divisions) {
  28498. console.warn('THREE.Shape: .extractAllPoints() has been removed. Use .extractPoints() instead.');
  28499. return this.extractPoints(divisions);
  28500. },
  28501. extrude: function (options) {
  28502. console.warn('THREE.Shape: .extrude() has been removed. Use ExtrudeGeometry() instead.');
  28503. return new ExtrudeGeometry(this, options);
  28504. },
  28505. makeGeometry: function (options) {
  28506. console.warn('THREE.Shape: .makeGeometry() has been removed. Use ShapeGeometry() instead.');
  28507. return new ShapeGeometry(this, options);
  28508. }
  28509. });
  28510. Object.assign(Vector2.prototype, {
  28511. fromAttribute: function (attribute, index, offset) {
  28512. console.warn('THREE.Vector2: .fromAttribute() has been renamed to .fromBufferAttribute().');
  28513. return this.fromBufferAttribute(attribute, index, offset);
  28514. },
  28515. distanceToManhattan: function (v) {
  28516. console.warn('THREE.Vector2: .distanceToManhattan() has been renamed to .manhattanDistanceTo().');
  28517. return this.manhattanDistanceTo(v);
  28518. },
  28519. lengthManhattan: function () {
  28520. console.warn('THREE.Vector2: .lengthManhattan() has been renamed to .manhattanLength().');
  28521. return this.manhattanLength();
  28522. }
  28523. });
  28524. Object.assign(Vector3.prototype, {
  28525. setEulerFromRotationMatrix: function () {
  28526. console.error('THREE.Vector3: .setEulerFromRotationMatrix() has been removed. Use Euler.setFromRotationMatrix() instead.');
  28527. },
  28528. setEulerFromQuaternion: function () {
  28529. console.error('THREE.Vector3: .setEulerFromQuaternion() has been removed. Use Euler.setFromQuaternion() instead.');
  28530. },
  28531. getPositionFromMatrix: function (m) {
  28532. console.warn('THREE.Vector3: .getPositionFromMatrix() has been renamed to .setFromMatrixPosition().');
  28533. return this.setFromMatrixPosition(m);
  28534. },
  28535. getScaleFromMatrix: function (m) {
  28536. console.warn('THREE.Vector3: .getScaleFromMatrix() has been renamed to .setFromMatrixScale().');
  28537. return this.setFromMatrixScale(m);
  28538. },
  28539. getColumnFromMatrix: function (index, matrix) {
  28540. console.warn('THREE.Vector3: .getColumnFromMatrix() has been renamed to .setFromMatrixColumn().');
  28541. return this.setFromMatrixColumn(matrix, index);
  28542. },
  28543. applyProjection: function (m) {
  28544. console.warn('THREE.Vector3: .applyProjection() has been removed. Use .applyMatrix4( m ) instead.');
  28545. return this.applyMatrix4(m);
  28546. },
  28547. fromAttribute: function (attribute, index, offset) {
  28548. console.warn('THREE.Vector3: .fromAttribute() has been renamed to .fromBufferAttribute().');
  28549. return this.fromBufferAttribute(attribute, index, offset);
  28550. },
  28551. distanceToManhattan: function (v) {
  28552. console.warn('THREE.Vector3: .distanceToManhattan() has been renamed to .manhattanDistanceTo().');
  28553. return this.manhattanDistanceTo(v);
  28554. },
  28555. lengthManhattan: function () {
  28556. console.warn('THREE.Vector3: .lengthManhattan() has been renamed to .manhattanLength().');
  28557. return this.manhattanLength();
  28558. }
  28559. });
  28560. Object.assign(Vector4.prototype, {
  28561. fromAttribute: function (attribute, index, offset) {
  28562. console.warn('THREE.Vector4: .fromAttribute() has been renamed to .fromBufferAttribute().');
  28563. return this.fromBufferAttribute(attribute, index, offset);
  28564. },
  28565. lengthManhattan: function () {
  28566. console.warn('THREE.Vector4: .lengthManhattan() has been renamed to .manhattanLength().');
  28567. return this.manhattanLength();
  28568. }
  28569. }); //
  28570. Object.assign(Geometry.prototype, {
  28571. computeTangents: function () {
  28572. console.error('THREE.Geometry: .computeTangents() has been removed.');
  28573. },
  28574. computeLineDistances: function () {
  28575. console.error('THREE.Geometry: .computeLineDistances() has been removed. Use THREE.Line.computeLineDistances() instead.');
  28576. }
  28577. });
  28578. Object.assign(Object3D.prototype, {
  28579. getChildByName: function (name) {
  28580. console.warn('THREE.Object3D: .getChildByName() has been renamed to .getObjectByName().');
  28581. return this.getObjectByName(name);
  28582. },
  28583. renderDepth: function () {
  28584. console.warn('THREE.Object3D: .renderDepth has been removed. Use .renderOrder, instead.');
  28585. },
  28586. translate: function (distance, axis) {
  28587. console.warn('THREE.Object3D: .translate() has been removed. Use .translateOnAxis( axis, distance ) instead.');
  28588. return this.translateOnAxis(axis, distance);
  28589. },
  28590. getWorldRotation: function () {
  28591. console.error('THREE.Object3D: .getWorldRotation() has been removed. Use THREE.Object3D.getWorldQuaternion( target ) instead.');
  28592. }
  28593. });
  28594. Object.defineProperties(Object3D.prototype, {
  28595. eulerOrder: {
  28596. get: function () {
  28597. console.warn('THREE.Object3D: .eulerOrder is now .rotation.order.');
  28598. return this.rotation.order;
  28599. },
  28600. set: function (value) {
  28601. console.warn('THREE.Object3D: .eulerOrder is now .rotation.order.');
  28602. this.rotation.order = value;
  28603. }
  28604. },
  28605. useQuaternion: {
  28606. get: function () {
  28607. console.warn('THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.');
  28608. },
  28609. set: function () {
  28610. console.warn('THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.');
  28611. }
  28612. }
  28613. });
  28614. Object.defineProperties(LOD.prototype, {
  28615. objects: {
  28616. get: function () {
  28617. console.warn('THREE.LOD: .objects has been renamed to .levels.');
  28618. return this.levels;
  28619. }
  28620. }
  28621. });
  28622. Object.defineProperty(Skeleton.prototype, 'useVertexTexture', {
  28623. get: function () {
  28624. console.warn('THREE.Skeleton: useVertexTexture has been removed.');
  28625. },
  28626. set: function () {
  28627. console.warn('THREE.Skeleton: useVertexTexture has been removed.');
  28628. }
  28629. });
  28630. SkinnedMesh.prototype.initBones = function () {
  28631. console.error('THREE.SkinnedMesh: initBones() has been removed.');
  28632. };
  28633. Object.defineProperty(Curve.prototype, '__arcLengthDivisions', {
  28634. get: function () {
  28635. console.warn('THREE.Curve: .__arcLengthDivisions is now .arcLengthDivisions.');
  28636. return this.arcLengthDivisions;
  28637. },
  28638. set: function (value) {
  28639. console.warn('THREE.Curve: .__arcLengthDivisions is now .arcLengthDivisions.');
  28640. this.arcLengthDivisions = value;
  28641. }
  28642. }); //
  28643. PerspectiveCamera.prototype.setLens = function (focalLength, filmGauge) {
  28644. console.warn("THREE.PerspectiveCamera.setLens is deprecated. " + "Use .setFocalLength and .filmGauge for a photographic setup.");
  28645. if (filmGauge !== undefined) this.filmGauge = filmGauge;
  28646. this.setFocalLength(focalLength);
  28647. }; //
  28648. Object.defineProperties(Light.prototype, {
  28649. onlyShadow: {
  28650. set: function () {
  28651. console.warn('THREE.Light: .onlyShadow has been removed.');
  28652. }
  28653. },
  28654. shadowCameraFov: {
  28655. set: function (value) {
  28656. console.warn('THREE.Light: .shadowCameraFov is now .shadow.camera.fov.');
  28657. this.shadow.camera.fov = value;
  28658. }
  28659. },
  28660. shadowCameraLeft: {
  28661. set: function (value) {
  28662. console.warn('THREE.Light: .shadowCameraLeft is now .shadow.camera.left.');
  28663. this.shadow.camera.left = value;
  28664. }
  28665. },
  28666. shadowCameraRight: {
  28667. set: function (value) {
  28668. console.warn('THREE.Light: .shadowCameraRight is now .shadow.camera.right.');
  28669. this.shadow.camera.right = value;
  28670. }
  28671. },
  28672. shadowCameraTop: {
  28673. set: function (value) {
  28674. console.warn('THREE.Light: .shadowCameraTop is now .shadow.camera.top.');
  28675. this.shadow.camera.top = value;
  28676. }
  28677. },
  28678. shadowCameraBottom: {
  28679. set: function (value) {
  28680. console.warn('THREE.Light: .shadowCameraBottom is now .shadow.camera.bottom.');
  28681. this.shadow.camera.bottom = value;
  28682. }
  28683. },
  28684. shadowCameraNear: {
  28685. set: function (value) {
  28686. console.warn('THREE.Light: .shadowCameraNear is now .shadow.camera.near.');
  28687. this.shadow.camera.near = value;
  28688. }
  28689. },
  28690. shadowCameraFar: {
  28691. set: function (value) {
  28692. console.warn('THREE.Light: .shadowCameraFar is now .shadow.camera.far.');
  28693. this.shadow.camera.far = value;
  28694. }
  28695. },
  28696. shadowCameraVisible: {
  28697. set: function () {
  28698. console.warn('THREE.Light: .shadowCameraVisible has been removed. Use new THREE.CameraHelper( light.shadow.camera ) instead.');
  28699. }
  28700. },
  28701. shadowBias: {
  28702. set: function (value) {
  28703. console.warn('THREE.Light: .shadowBias is now .shadow.bias.');
  28704. this.shadow.bias = value;
  28705. }
  28706. },
  28707. shadowDarkness: {
  28708. set: function () {
  28709. console.warn('THREE.Light: .shadowDarkness has been removed.');
  28710. }
  28711. },
  28712. shadowMapWidth: {
  28713. set: function (value) {
  28714. console.warn('THREE.Light: .shadowMapWidth is now .shadow.mapSize.width.');
  28715. this.shadow.mapSize.width = value;
  28716. }
  28717. },
  28718. shadowMapHeight: {
  28719. set: function (value) {
  28720. console.warn('THREE.Light: .shadowMapHeight is now .shadow.mapSize.height.');
  28721. this.shadow.mapSize.height = value;
  28722. }
  28723. }
  28724. }); //
  28725. Object.defineProperties(BufferAttribute.prototype, {
  28726. length: {
  28727. get: function () {
  28728. console.warn('THREE.BufferAttribute: .length has been deprecated. Use .count instead.');
  28729. return this.array.length;
  28730. }
  28731. }
  28732. });
  28733. Object.assign(BufferAttribute.prototype, {
  28734. copyIndicesArray: function ()
  28735. /* indices */
  28736. {
  28737. console.error('THREE.BufferAttribute: .copyIndicesArray() has been removed.');
  28738. },
  28739. setArray: function (array) {
  28740. console.warn('THREE.BufferAttribute: .setArray has been deprecated. Use BufferGeometry .setAttribute to replace/resize attribute buffers');
  28741. this.count = array !== undefined ? array.length / this.itemSize : 0;
  28742. this.array = array;
  28743. return this;
  28744. }
  28745. });
  28746. Object.assign(BufferGeometry.prototype, {
  28747. addIndex: function (index) {
  28748. console.warn('THREE.BufferGeometry: .addIndex() has been renamed to .setIndex().');
  28749. this.setIndex(index);
  28750. },
  28751. addDrawCall: function (start, count, indexOffset) {
  28752. if (indexOffset !== undefined) {
  28753. console.warn('THREE.BufferGeometry: .addDrawCall() no longer supports indexOffset.');
  28754. }
  28755. console.warn('THREE.BufferGeometry: .addDrawCall() is now .addGroup().');
  28756. this.addGroup(start, count);
  28757. },
  28758. clearDrawCalls: function () {
  28759. console.warn('THREE.BufferGeometry: .clearDrawCalls() is now .clearGroups().');
  28760. this.clearGroups();
  28761. },
  28762. computeTangents: function () {
  28763. console.warn('THREE.BufferGeometry: .computeTangents() has been removed.');
  28764. },
  28765. computeOffsets: function () {
  28766. console.warn('THREE.BufferGeometry: .computeOffsets() has been removed.');
  28767. }
  28768. });
  28769. Object.defineProperties(BufferGeometry.prototype, {
  28770. drawcalls: {
  28771. get: function () {
  28772. console.error('THREE.BufferGeometry: .drawcalls has been renamed to .groups.');
  28773. return this.groups;
  28774. }
  28775. },
  28776. offsets: {
  28777. get: function () {
  28778. console.warn('THREE.BufferGeometry: .offsets has been renamed to .groups.');
  28779. return this.groups;
  28780. }
  28781. }
  28782. });
  28783. Object.assign(InterleavedBuffer.prototype, {
  28784. setArray: function (array) {
  28785. console.warn('THREE.InterleavedBuffer: .setArray has been deprecated. Use BufferGeometry .setAttribute to replace/resize attribute buffers');
  28786. this.count = array !== undefined ? array.length / this.stride : 0;
  28787. this.array = array;
  28788. return this;
  28789. }
  28790. }); //
  28791. Object.assign(ExtrudeBufferGeometry.prototype, {
  28792. getArrays: function () {
  28793. console.error('THREE.ExtrudeBufferGeometry: .getArrays() has been removed.');
  28794. },
  28795. addShapeList: function () {
  28796. console.error('THREE.ExtrudeBufferGeometry: .addShapeList() has been removed.');
  28797. },
  28798. addShape: function () {
  28799. console.error('THREE.ExtrudeBufferGeometry: .addShape() has been removed.');
  28800. }
  28801. }); //
  28802. Object.defineProperties(Uniform.prototype, {
  28803. dynamic: {
  28804. set: function () {
  28805. console.warn('THREE.Uniform: .dynamic has been removed. Use object.onBeforeRender() instead.');
  28806. }
  28807. },
  28808. onUpdate: {
  28809. value: function () {
  28810. console.warn('THREE.Uniform: .onUpdate() has been removed. Use object.onBeforeRender() instead.');
  28811. return this;
  28812. }
  28813. }
  28814. }); //
  28815. Object.defineProperties(Material.prototype, {
  28816. wrapAround: {
  28817. get: function () {
  28818. console.warn('THREE.Material: .wrapAround has been removed.');
  28819. },
  28820. set: function () {
  28821. console.warn('THREE.Material: .wrapAround has been removed.');
  28822. }
  28823. },
  28824. overdraw: {
  28825. get: function () {
  28826. console.warn('THREE.Material: .overdraw has been removed.');
  28827. },
  28828. set: function () {
  28829. console.warn('THREE.Material: .overdraw has been removed.');
  28830. }
  28831. },
  28832. wrapRGB: {
  28833. get: function () {
  28834. console.warn('THREE.Material: .wrapRGB has been removed.');
  28835. return new Color();
  28836. }
  28837. },
  28838. shading: {
  28839. get: function () {
  28840. console.error('THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.');
  28841. },
  28842. set: function (value) {
  28843. console.warn('THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.');
  28844. this.flatShading = value === FlatShading;
  28845. }
  28846. },
  28847. stencilMask: {
  28848. get: function () {
  28849. console.warn('THREE.' + this.type + ': .stencilMask has been removed. Use .stencilFuncMask instead.');
  28850. return this.stencilFuncMask;
  28851. },
  28852. set: function (value) {
  28853. console.warn('THREE.' + this.type + ': .stencilMask has been removed. Use .stencilFuncMask instead.');
  28854. this.stencilFuncMask = value;
  28855. }
  28856. }
  28857. });
  28858. Object.defineProperties(MeshPhongMaterial.prototype, {
  28859. metal: {
  28860. get: function () {
  28861. console.warn('THREE.MeshPhongMaterial: .metal has been removed. Use THREE.MeshStandardMaterial instead.');
  28862. return false;
  28863. },
  28864. set: function () {
  28865. console.warn('THREE.MeshPhongMaterial: .metal has been removed. Use THREE.MeshStandardMaterial instead');
  28866. }
  28867. }
  28868. });
  28869. Object.defineProperties(ShaderMaterial.prototype, {
  28870. derivatives: {
  28871. get: function () {
  28872. console.warn('THREE.ShaderMaterial: .derivatives has been moved to .extensions.derivatives.');
  28873. return this.extensions.derivatives;
  28874. },
  28875. set: function (value) {
  28876. console.warn('THREE. ShaderMaterial: .derivatives has been moved to .extensions.derivatives.');
  28877. this.extensions.derivatives = value;
  28878. }
  28879. }
  28880. }); //
  28881. Object.assign(WebGLRenderer.prototype, {
  28882. clearTarget: function (renderTarget, color, depth, stencil) {
  28883. console.warn('THREE.WebGLRenderer: .clearTarget() has been deprecated. Use .setRenderTarget() and .clear() instead.');
  28884. this.setRenderTarget(renderTarget);
  28885. this.clear(color, depth, stencil);
  28886. },
  28887. animate: function (callback) {
  28888. console.warn('THREE.WebGLRenderer: .animate() is now .setAnimationLoop().');
  28889. this.setAnimationLoop(callback);
  28890. },
  28891. getCurrentRenderTarget: function () {
  28892. console.warn('THREE.WebGLRenderer: .getCurrentRenderTarget() is now .getRenderTarget().');
  28893. return this.getRenderTarget();
  28894. },
  28895. getMaxAnisotropy: function () {
  28896. console.warn('THREE.WebGLRenderer: .getMaxAnisotropy() is now .capabilities.getMaxAnisotropy().');
  28897. return this.capabilities.getMaxAnisotropy();
  28898. },
  28899. getPrecision: function () {
  28900. console.warn('THREE.WebGLRenderer: .getPrecision() is now .capabilities.precision.');
  28901. return this.capabilities.precision;
  28902. },
  28903. resetGLState: function () {
  28904. console.warn('THREE.WebGLRenderer: .resetGLState() is now .state.reset().');
  28905. return this.state.reset();
  28906. },
  28907. supportsFloatTextures: function () {
  28908. console.warn('THREE.WebGLRenderer: .supportsFloatTextures() is now .extensions.get( \'OES_texture_float\' ).');
  28909. return this.extensions.get('OES_texture_float');
  28910. },
  28911. supportsHalfFloatTextures: function () {
  28912. console.warn('THREE.WebGLRenderer: .supportsHalfFloatTextures() is now .extensions.get( \'OES_texture_half_float\' ).');
  28913. return this.extensions.get('OES_texture_half_float');
  28914. },
  28915. supportsStandardDerivatives: function () {
  28916. console.warn('THREE.WebGLRenderer: .supportsStandardDerivatives() is now .extensions.get( \'OES_standard_derivatives\' ).');
  28917. return this.extensions.get('OES_standard_derivatives');
  28918. },
  28919. supportsCompressedTextureS3TC: function () {
  28920. console.warn('THREE.WebGLRenderer: .supportsCompressedTextureS3TC() is now .extensions.get( \'WEBGL_compressed_texture_s3tc\' ).');
  28921. return this.extensions.get('WEBGL_compressed_texture_s3tc');
  28922. },
  28923. supportsCompressedTexturePVRTC: function () {
  28924. console.warn('THREE.WebGLRenderer: .supportsCompressedTexturePVRTC() is now .extensions.get( \'WEBGL_compressed_texture_pvrtc\' ).');
  28925. return this.extensions.get('WEBGL_compressed_texture_pvrtc');
  28926. },
  28927. supportsBlendMinMax: function () {
  28928. console.warn('THREE.WebGLRenderer: .supportsBlendMinMax() is now .extensions.get( \'EXT_blend_minmax\' ).');
  28929. return this.extensions.get('EXT_blend_minmax');
  28930. },
  28931. supportsVertexTextures: function () {
  28932. console.warn('THREE.WebGLRenderer: .supportsVertexTextures() is now .capabilities.vertexTextures.');
  28933. return this.capabilities.vertexTextures;
  28934. },
  28935. supportsInstancedArrays: function () {
  28936. console.warn('THREE.WebGLRenderer: .supportsInstancedArrays() is now .extensions.get( \'ANGLE_instanced_arrays\' ).');
  28937. return this.extensions.get('ANGLE_instanced_arrays');
  28938. },
  28939. enableScissorTest: function (boolean) {
  28940. console.warn('THREE.WebGLRenderer: .enableScissorTest() is now .setScissorTest().');
  28941. this.setScissorTest(boolean);
  28942. },
  28943. initMaterial: function () {
  28944. console.warn('THREE.WebGLRenderer: .initMaterial() has been removed.');
  28945. },
  28946. addPrePlugin: function () {
  28947. console.warn('THREE.WebGLRenderer: .addPrePlugin() has been removed.');
  28948. },
  28949. addPostPlugin: function () {
  28950. console.warn('THREE.WebGLRenderer: .addPostPlugin() has been removed.');
  28951. },
  28952. updateShadowMap: function () {
  28953. console.warn('THREE.WebGLRenderer: .updateShadowMap() has been removed.');
  28954. },
  28955. setFaceCulling: function () {
  28956. console.warn('THREE.WebGLRenderer: .setFaceCulling() has been removed.');
  28957. },
  28958. allocTextureUnit: function () {
  28959. console.warn('THREE.WebGLRenderer: .allocTextureUnit() has been removed.');
  28960. },
  28961. setTexture: function () {
  28962. console.warn('THREE.WebGLRenderer: .setTexture() has been removed.');
  28963. },
  28964. setTexture2D: function () {
  28965. console.warn('THREE.WebGLRenderer: .setTexture2D() has been removed.');
  28966. },
  28967. setTextureCube: function () {
  28968. console.warn('THREE.WebGLRenderer: .setTextureCube() has been removed.');
  28969. },
  28970. getActiveMipMapLevel: function () {
  28971. console.warn('THREE.WebGLRenderer: .getActiveMipMapLevel() is now .getActiveMipmapLevel().');
  28972. return this.getActiveMipmapLevel();
  28973. }
  28974. });
  28975. Object.defineProperties(WebGLRenderer.prototype, {
  28976. shadowMapEnabled: {
  28977. get: function () {
  28978. return this.shadowMap.enabled;
  28979. },
  28980. set: function (value) {
  28981. console.warn('THREE.WebGLRenderer: .shadowMapEnabled is now .shadowMap.enabled.');
  28982. this.shadowMap.enabled = value;
  28983. }
  28984. },
  28985. shadowMapType: {
  28986. get: function () {
  28987. return this.shadowMap.type;
  28988. },
  28989. set: function (value) {
  28990. console.warn('THREE.WebGLRenderer: .shadowMapType is now .shadowMap.type.');
  28991. this.shadowMap.type = value;
  28992. }
  28993. },
  28994. shadowMapCullFace: {
  28995. get: function () {
  28996. console.warn('THREE.WebGLRenderer: .shadowMapCullFace has been removed. Set Material.shadowSide instead.');
  28997. return undefined;
  28998. },
  28999. set: function ()
  29000. /* value */
  29001. {
  29002. console.warn('THREE.WebGLRenderer: .shadowMapCullFace has been removed. Set Material.shadowSide instead.');
  29003. }
  29004. },
  29005. context: {
  29006. get: function () {
  29007. console.warn('THREE.WebGLRenderer: .context has been removed. Use .getContext() instead.');
  29008. return this.getContext();
  29009. }
  29010. }
  29011. });
  29012. Object.defineProperties(WebGLShadowMap.prototype, {
  29013. cullFace: {
  29014. get: function () {
  29015. console.warn('THREE.WebGLRenderer: .shadowMap.cullFace has been removed. Set Material.shadowSide instead.');
  29016. return undefined;
  29017. },
  29018. set: function ()
  29019. /* cullFace */
  29020. {
  29021. console.warn('THREE.WebGLRenderer: .shadowMap.cullFace has been removed. Set Material.shadowSide instead.');
  29022. }
  29023. },
  29024. renderReverseSided: {
  29025. get: function () {
  29026. console.warn('THREE.WebGLRenderer: .shadowMap.renderReverseSided has been removed. Set Material.shadowSide instead.');
  29027. return undefined;
  29028. },
  29029. set: function () {
  29030. console.warn('THREE.WebGLRenderer: .shadowMap.renderReverseSided has been removed. Set Material.shadowSide instead.');
  29031. }
  29032. },
  29033. renderSingleSided: {
  29034. get: function () {
  29035. console.warn('THREE.WebGLRenderer: .shadowMap.renderSingleSided has been removed. Set Material.shadowSide instead.');
  29036. return undefined;
  29037. },
  29038. set: function () {
  29039. console.warn('THREE.WebGLRenderer: .shadowMap.renderSingleSided has been removed. Set Material.shadowSide instead.');
  29040. }
  29041. }
  29042. }); //
  29043. Object.defineProperties(WebGLRenderTargetCube.prototype, {
  29044. activeCubeFace: {
  29045. set: function ()
  29046. /* value */
  29047. {
  29048. console.warn('THREE.WebGLRenderTargetCube: .activeCubeFace has been removed. It is now the second parameter of WebGLRenderer.setRenderTarget().');
  29049. }
  29050. },
  29051. activeMipMapLevel: {
  29052. set: function ()
  29053. /* value */
  29054. {
  29055. console.warn('THREE.WebGLRenderTargetCube: .activeMipMapLevel has been removed. It is now the third parameter of WebGLRenderer.setRenderTarget().');
  29056. }
  29057. }
  29058. }); //
  29059. Object.defineProperties(WebGLRenderTarget.prototype, {
  29060. wrapS: {
  29061. get: function () {
  29062. console.warn('THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.');
  29063. return this.texture.wrapS;
  29064. },
  29065. set: function (value) {
  29066. console.warn('THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.');
  29067. this.texture.wrapS = value;
  29068. }
  29069. },
  29070. wrapT: {
  29071. get: function () {
  29072. console.warn('THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.');
  29073. return this.texture.wrapT;
  29074. },
  29075. set: function (value) {
  29076. console.warn('THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.');
  29077. this.texture.wrapT = value;
  29078. }
  29079. },
  29080. magFilter: {
  29081. get: function () {
  29082. console.warn('THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.');
  29083. return this.texture.magFilter;
  29084. },
  29085. set: function (value) {
  29086. console.warn('THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.');
  29087. this.texture.magFilter = value;
  29088. }
  29089. },
  29090. minFilter: {
  29091. get: function () {
  29092. console.warn('THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.');
  29093. return this.texture.minFilter;
  29094. },
  29095. set: function (value) {
  29096. console.warn('THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.');
  29097. this.texture.minFilter = value;
  29098. }
  29099. },
  29100. anisotropy: {
  29101. get: function () {
  29102. console.warn('THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.');
  29103. return this.texture.anisotropy;
  29104. },
  29105. set: function (value) {
  29106. console.warn('THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.');
  29107. this.texture.anisotropy = value;
  29108. }
  29109. },
  29110. offset: {
  29111. get: function () {
  29112. console.warn('THREE.WebGLRenderTarget: .offset is now .texture.offset.');
  29113. return this.texture.offset;
  29114. },
  29115. set: function (value) {
  29116. console.warn('THREE.WebGLRenderTarget: .offset is now .texture.offset.');
  29117. this.texture.offset = value;
  29118. }
  29119. },
  29120. repeat: {
  29121. get: function () {
  29122. console.warn('THREE.WebGLRenderTarget: .repeat is now .texture.repeat.');
  29123. return this.texture.repeat;
  29124. },
  29125. set: function (value) {
  29126. console.warn('THREE.WebGLRenderTarget: .repeat is now .texture.repeat.');
  29127. this.texture.repeat = value;
  29128. }
  29129. },
  29130. format: {
  29131. get: function () {
  29132. console.warn('THREE.WebGLRenderTarget: .format is now .texture.format.');
  29133. return this.texture.format;
  29134. },
  29135. set: function (value) {
  29136. console.warn('THREE.WebGLRenderTarget: .format is now .texture.format.');
  29137. this.texture.format = value;
  29138. }
  29139. },
  29140. type: {
  29141. get: function () {
  29142. console.warn('THREE.WebGLRenderTarget: .type is now .texture.type.');
  29143. return this.texture.type;
  29144. },
  29145. set: function (value) {
  29146. console.warn('THREE.WebGLRenderTarget: .type is now .texture.type.');
  29147. this.texture.type = value;
  29148. }
  29149. },
  29150. generateMipmaps: {
  29151. get: function () {
  29152. console.warn('THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.');
  29153. return this.texture.generateMipmaps;
  29154. },
  29155. set: function (value) {
  29156. console.warn('THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.');
  29157. this.texture.generateMipmaps = value;
  29158. }
  29159. }
  29160. }); //
  29161. Object.defineProperties(WebVRManager.prototype, {
  29162. standing: {
  29163. set: function ()
  29164. /* value */
  29165. {
  29166. console.warn('THREE.WebVRManager: .standing has been removed.');
  29167. }
  29168. },
  29169. userHeight: {
  29170. set: function ()
  29171. /* value */
  29172. {
  29173. console.warn('THREE.WebVRManager: .userHeight has been removed.');
  29174. }
  29175. }
  29176. }); //
  29177. Audio.prototype.load = function (file) {
  29178. console.warn('THREE.Audio: .load has been deprecated. Use THREE.AudioLoader instead.');
  29179. var scope = this;
  29180. var audioLoader = new AudioLoader();
  29181. audioLoader.load(file, function (buffer) {
  29182. scope.setBuffer(buffer);
  29183. });
  29184. return this;
  29185. };
  29186. AudioAnalyser.prototype.getData = function () {
  29187. console.warn('THREE.AudioAnalyser: .getData() is now .getFrequencyData().');
  29188. return this.getFrequencyData();
  29189. }; //
  29190. CubeCamera.prototype.updateCubeMap = function (renderer, scene) {
  29191. console.warn('THREE.CubeCamera: .updateCubeMap() is now .update().');
  29192. return this.update(renderer, scene);
  29193. }; //
  29194. var GeometryUtils = {
  29195. merge: function (geometry1, geometry2, materialIndexOffset) {
  29196. console.warn('THREE.GeometryUtils: .merge() has been moved to Geometry. Use geometry.merge( geometry2, matrix, materialIndexOffset ) instead.');
  29197. var matrix;
  29198. if (geometry2.isMesh) {
  29199. geometry2.matrixAutoUpdate && geometry2.updateMatrix();
  29200. matrix = geometry2.matrix;
  29201. geometry2 = geometry2.geometry;
  29202. }
  29203. geometry1.merge(geometry2, matrix, materialIndexOffset);
  29204. },
  29205. center: function (geometry) {
  29206. console.warn('THREE.GeometryUtils: .center() has been moved to Geometry. Use geometry.center() instead.');
  29207. return geometry.center();
  29208. }
  29209. };
  29210. exports.GeometryUtils = GeometryUtils;
  29211. ImageUtils.crossOrigin = undefined;
  29212. ImageUtils.loadTexture = function (url, mapping, onLoad, onError) {
  29213. console.warn('THREE.ImageUtils.loadTexture has been deprecated. Use THREE.TextureLoader() instead.');
  29214. var loader = new TextureLoader();
  29215. loader.setCrossOrigin(this.crossOrigin);
  29216. var texture = loader.load(url, onLoad, undefined, onError);
  29217. if (mapping) texture.mapping = mapping;
  29218. return texture;
  29219. };
  29220. ImageUtils.loadTextureCube = function (urls, mapping, onLoad, onError) {
  29221. console.warn('THREE.ImageUtils.loadTextureCube has been deprecated. Use THREE.CubeTextureLoader() instead.');
  29222. var loader = new CubeTextureLoader();
  29223. loader.setCrossOrigin(this.crossOrigin);
  29224. var texture = loader.load(urls, onLoad, undefined, onError);
  29225. if (mapping) texture.mapping = mapping;
  29226. return texture;
  29227. };
  29228. ImageUtils.loadCompressedTexture = function () {
  29229. console.error('THREE.ImageUtils.loadCompressedTexture has been removed. Use THREE.DDSLoader instead.');
  29230. };
  29231. ImageUtils.loadCompressedTextureCube = function () {
  29232. console.error('THREE.ImageUtils.loadCompressedTextureCube has been removed. Use THREE.DDSLoader instead.');
  29233. }; //
  29234. function CanvasRenderer() {
  29235. console.error('THREE.CanvasRenderer has been removed');
  29236. } //
  29237. function JSONLoader() {
  29238. console.error('THREE.JSONLoader has been removed.');
  29239. } //
  29240. var SceneUtils = {
  29241. createMultiMaterialObject: function ()
  29242. /* geometry, materials */
  29243. {
  29244. console.error('THREE.SceneUtils has been moved to /examples/js/utils/SceneUtils.js');
  29245. },
  29246. detach: function ()
  29247. /* child, parent, scene */
  29248. {
  29249. console.error('THREE.SceneUtils has been moved to /examples/js/utils/SceneUtils.js');
  29250. },
  29251. attach: function ()
  29252. /* child, scene, parent */
  29253. {
  29254. console.error('THREE.SceneUtils has been moved to /examples/js/utils/SceneUtils.js');
  29255. }
  29256. }; //
  29257. exports.SceneUtils = SceneUtils;
  29258. function LensFlare() {
  29259. console.error('THREE.LensFlare has been moved to /examples/js/objects/Lensflare.js');
  29260. }
  29261. if (typeof __THREE_DEVTOOLS__ !== 'undefined') {
  29262. /* eslint-disable no-undef */
  29263. __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent('register', {
  29264. detail: {
  29265. revision: REVISION
  29266. }
  29267. }));
  29268. /* eslint-enable no-undef */
  29269. }
  29270. },{}],"../node_modules/process/browser.js":[function(require,module,exports) {
  29271. // shim for using process in browser
  29272. var process = module.exports = {}; // cached from whatever global is present so that test runners that stub it
  29273. // don't break things. But we need to wrap it in a try catch in case it is
  29274. // wrapped in strict mode code which doesn't define any globals. It's inside a
  29275. // function because try/catches deoptimize in certain engines.
  29276. var cachedSetTimeout;
  29277. var cachedClearTimeout;
  29278. function defaultSetTimout() {
  29279. throw new Error('setTimeout has not been defined');
  29280. }
  29281. function defaultClearTimeout() {
  29282. throw new Error('clearTimeout has not been defined');
  29283. }
  29284. (function () {
  29285. try {
  29286. if (typeof setTimeout === 'function') {
  29287. cachedSetTimeout = setTimeout;
  29288. } else {
  29289. cachedSetTimeout = defaultSetTimout;
  29290. }
  29291. } catch (e) {
  29292. cachedSetTimeout = defaultSetTimout;
  29293. }
  29294. try {
  29295. if (typeof clearTimeout === 'function') {
  29296. cachedClearTimeout = clearTimeout;
  29297. } else {
  29298. cachedClearTimeout = defaultClearTimeout;
  29299. }
  29300. } catch (e) {
  29301. cachedClearTimeout = defaultClearTimeout;
  29302. }
  29303. })();
  29304. function runTimeout(fun) {
  29305. if (cachedSetTimeout === setTimeout) {
  29306. //normal enviroments in sane situations
  29307. return setTimeout(fun, 0);
  29308. } // if setTimeout wasn't available but was latter defined
  29309. if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
  29310. cachedSetTimeout = setTimeout;
  29311. return setTimeout(fun, 0);
  29312. }
  29313. try {
  29314. // when when somebody has screwed with setTimeout but no I.E. maddness
  29315. return cachedSetTimeout(fun, 0);
  29316. } catch (e) {
  29317. try {
  29318. // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
  29319. return cachedSetTimeout.call(null, fun, 0);
  29320. } catch (e) {
  29321. // 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
  29322. return cachedSetTimeout.call(this, fun, 0);
  29323. }
  29324. }
  29325. }
  29326. function runClearTimeout(marker) {
  29327. if (cachedClearTimeout === clearTimeout) {
  29328. //normal enviroments in sane situations
  29329. return clearTimeout(marker);
  29330. } // if clearTimeout wasn't available but was latter defined
  29331. if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
  29332. cachedClearTimeout = clearTimeout;
  29333. return clearTimeout(marker);
  29334. }
  29335. try {
  29336. // when when somebody has screwed with setTimeout but no I.E. maddness
  29337. return cachedClearTimeout(marker);
  29338. } catch (e) {
  29339. try {
  29340. // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
  29341. return cachedClearTimeout.call(null, marker);
  29342. } catch (e) {
  29343. // 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.
  29344. // Some versions of I.E. have different rules for clearTimeout vs setTimeout
  29345. return cachedClearTimeout.call(this, marker);
  29346. }
  29347. }
  29348. }
  29349. var queue = [];
  29350. var draining = false;
  29351. var currentQueue;
  29352. var queueIndex = -1;
  29353. function cleanUpNextTick() {
  29354. if (!draining || !currentQueue) {
  29355. return;
  29356. }
  29357. draining = false;
  29358. if (currentQueue.length) {
  29359. queue = currentQueue.concat(queue);
  29360. } else {
  29361. queueIndex = -1;
  29362. }
  29363. if (queue.length) {
  29364. drainQueue();
  29365. }
  29366. }
  29367. function drainQueue() {
  29368. if (draining) {
  29369. return;
  29370. }
  29371. var timeout = runTimeout(cleanUpNextTick);
  29372. draining = true;
  29373. var len = queue.length;
  29374. while (len) {
  29375. currentQueue = queue;
  29376. queue = [];
  29377. while (++queueIndex < len) {
  29378. if (currentQueue) {
  29379. currentQueue[queueIndex].run();
  29380. }
  29381. }
  29382. queueIndex = -1;
  29383. len = queue.length;
  29384. }
  29385. currentQueue = null;
  29386. draining = false;
  29387. runClearTimeout(timeout);
  29388. }
  29389. process.nextTick = function (fun) {
  29390. var args = new Array(arguments.length - 1);
  29391. if (arguments.length > 1) {
  29392. for (var i = 1; i < arguments.length; i++) {
  29393. args[i - 1] = arguments[i];
  29394. }
  29395. }
  29396. queue.push(new Item(fun, args));
  29397. if (queue.length === 1 && !draining) {
  29398. runTimeout(drainQueue);
  29399. }
  29400. }; // v8 likes predictible objects
  29401. function Item(fun, array) {
  29402. this.fun = fun;
  29403. this.array = array;
  29404. }
  29405. Item.prototype.run = function () {
  29406. this.fun.apply(null, this.array);
  29407. };
  29408. process.title = 'browser';
  29409. process.env = {};
  29410. process.argv = [];
  29411. process.version = ''; // empty string to avoid regexp issues
  29412. process.versions = {};
  29413. function noop() {}
  29414. process.on = noop;
  29415. process.addListener = noop;
  29416. process.once = noop;
  29417. process.off = noop;
  29418. process.removeListener = noop;
  29419. process.removeAllListeners = noop;
  29420. process.emit = noop;
  29421. process.prependListener = noop;
  29422. process.prependOnceListener = noop;
  29423. process.listeners = function (name) {
  29424. return [];
  29425. };
  29426. process.binding = function (name) {
  29427. throw new Error('process.binding is not supported');
  29428. };
  29429. process.cwd = function () {
  29430. return '/';
  29431. };
  29432. process.chdir = function (dir) {
  29433. throw new Error('process.chdir is not supported');
  29434. };
  29435. process.umask = function () {
  29436. return 0;
  29437. };
  29438. },{}],"../node_modules/path-browserify/index.js":[function(require,module,exports) {
  29439. var process = require("process");
  29440. // .dirname, .basename, and .extname methods are extracted from Node.js v8.11.1,
  29441. // backported and transplited with Babel, with backwards-compat fixes
  29442. // Copyright Joyent, Inc. and other Node contributors.
  29443. //
  29444. // Permission is hereby granted, free of charge, to any person obtaining a
  29445. // copy of this software and associated documentation files (the
  29446. // "Software"), to deal in the Software without restriction, including
  29447. // without limitation the rights to use, copy, modify, merge, publish,
  29448. // distribute, sublicense, and/or sell copies of the Software, and to permit
  29449. // persons to whom the Software is furnished to do so, subject to the
  29450. // following conditions:
  29451. //
  29452. // The above copyright notice and this permission notice shall be included
  29453. // in all copies or substantial portions of the Software.
  29454. //
  29455. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  29456. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  29457. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  29458. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  29459. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  29460. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  29461. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  29462. // resolves . and .. elements in a path array with directory names there
  29463. // must be no slashes, empty elements, or device names (c:\) in the array
  29464. // (so also no leading and trailing slashes - it does not distinguish
  29465. // relative and absolute paths)
  29466. function normalizeArray(parts, allowAboveRoot) {
  29467. // if the path tries to go above the root, `up` ends up > 0
  29468. var up = 0;
  29469. for (var i = parts.length - 1; i >= 0; i--) {
  29470. var last = parts[i];
  29471. if (last === '.') {
  29472. parts.splice(i, 1);
  29473. } else if (last === '..') {
  29474. parts.splice(i, 1);
  29475. up++;
  29476. } else if (up) {
  29477. parts.splice(i, 1);
  29478. up--;
  29479. }
  29480. }
  29481. // if the path is allowed to go above the root, restore leading ..s
  29482. if (allowAboveRoot) {
  29483. for (; up--; up) {
  29484. parts.unshift('..');
  29485. }
  29486. }
  29487. return parts;
  29488. }
  29489. // path.resolve([from ...], to)
  29490. // posix version
  29491. exports.resolve = function() {
  29492. var resolvedPath = '',
  29493. resolvedAbsolute = false;
  29494. for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) {
  29495. var path = (i >= 0) ? arguments[i] : process.cwd();
  29496. // Skip empty and invalid entries
  29497. if (typeof path !== 'string') {
  29498. throw new TypeError('Arguments to path.resolve must be strings');
  29499. } else if (!path) {
  29500. continue;
  29501. }
  29502. resolvedPath = path + '/' + resolvedPath;
  29503. resolvedAbsolute = path.charAt(0) === '/';
  29504. }
  29505. // At this point the path should be resolved to a full absolute path, but
  29506. // handle relative paths to be safe (might happen when process.cwd() fails)
  29507. // Normalize the path
  29508. resolvedPath = normalizeArray(filter(resolvedPath.split('/'), function(p) {
  29509. return !!p;
  29510. }), !resolvedAbsolute).join('/');
  29511. return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.';
  29512. };
  29513. // path.normalize(path)
  29514. // posix version
  29515. exports.normalize = function(path) {
  29516. var isAbsolute = exports.isAbsolute(path),
  29517. trailingSlash = substr(path, -1) === '/';
  29518. // Normalize the path
  29519. path = normalizeArray(filter(path.split('/'), function(p) {
  29520. return !!p;
  29521. }), !isAbsolute).join('/');
  29522. if (!path && !isAbsolute) {
  29523. path = '.';
  29524. }
  29525. if (path && trailingSlash) {
  29526. path += '/';
  29527. }
  29528. return (isAbsolute ? '/' : '') + path;
  29529. };
  29530. // posix version
  29531. exports.isAbsolute = function(path) {
  29532. return path.charAt(0) === '/';
  29533. };
  29534. // posix version
  29535. exports.join = function() {
  29536. var paths = Array.prototype.slice.call(arguments, 0);
  29537. return exports.normalize(filter(paths, function(p, index) {
  29538. if (typeof p !== 'string') {
  29539. throw new TypeError('Arguments to path.join must be strings');
  29540. }
  29541. return p;
  29542. }).join('/'));
  29543. };
  29544. // path.relative(from, to)
  29545. // posix version
  29546. exports.relative = function(from, to) {
  29547. from = exports.resolve(from).substr(1);
  29548. to = exports.resolve(to).substr(1);
  29549. function trim(arr) {
  29550. var start = 0;
  29551. for (; start < arr.length; start++) {
  29552. if (arr[start] !== '') break;
  29553. }
  29554. var end = arr.length - 1;
  29555. for (; end >= 0; end--) {
  29556. if (arr[end] !== '') break;
  29557. }
  29558. if (start > end) return [];
  29559. return arr.slice(start, end - start + 1);
  29560. }
  29561. var fromParts = trim(from.split('/'));
  29562. var toParts = trim(to.split('/'));
  29563. var length = Math.min(fromParts.length, toParts.length);
  29564. var samePartsLength = length;
  29565. for (var i = 0; i < length; i++) {
  29566. if (fromParts[i] !== toParts[i]) {
  29567. samePartsLength = i;
  29568. break;
  29569. }
  29570. }
  29571. var outputParts = [];
  29572. for (var i = samePartsLength; i < fromParts.length; i++) {
  29573. outputParts.push('..');
  29574. }
  29575. outputParts = outputParts.concat(toParts.slice(samePartsLength));
  29576. return outputParts.join('/');
  29577. };
  29578. exports.sep = '/';
  29579. exports.delimiter = ':';
  29580. exports.dirname = function (path) {
  29581. if (typeof path !== 'string') path = path + '';
  29582. if (path.length === 0) return '.';
  29583. var code = path.charCodeAt(0);
  29584. var hasRoot = code === 47 /*/*/;
  29585. var end = -1;
  29586. var matchedSlash = true;
  29587. for (var i = path.length - 1; i >= 1; --i) {
  29588. code = path.charCodeAt(i);
  29589. if (code === 47 /*/*/) {
  29590. if (!matchedSlash) {
  29591. end = i;
  29592. break;
  29593. }
  29594. } else {
  29595. // We saw the first non-path separator
  29596. matchedSlash = false;
  29597. }
  29598. }
  29599. if (end === -1) return hasRoot ? '/' : '.';
  29600. if (hasRoot && end === 1) {
  29601. // return '//';
  29602. // Backwards-compat fix:
  29603. return '/';
  29604. }
  29605. return path.slice(0, end);
  29606. };
  29607. function basename(path) {
  29608. if (typeof path !== 'string') path = path + '';
  29609. var start = 0;
  29610. var end = -1;
  29611. var matchedSlash = true;
  29612. var i;
  29613. for (i = path.length - 1; i >= 0; --i) {
  29614. if (path.charCodeAt(i) === 47 /*/*/) {
  29615. // If we reached a path separator that was not part of a set of path
  29616. // separators at the end of the string, stop now
  29617. if (!matchedSlash) {
  29618. start = i + 1;
  29619. break;
  29620. }
  29621. } else if (end === -1) {
  29622. // We saw the first non-path separator, mark this as the end of our
  29623. // path component
  29624. matchedSlash = false;
  29625. end = i + 1;
  29626. }
  29627. }
  29628. if (end === -1) return '';
  29629. return path.slice(start, end);
  29630. }
  29631. // Uses a mixed approach for backwards-compatibility, as ext behavior changed
  29632. // in new Node.js versions, so only basename() above is backported here
  29633. exports.basename = function (path, ext) {
  29634. var f = basename(path);
  29635. if (ext && f.substr(-1 * ext.length) === ext) {
  29636. f = f.substr(0, f.length - ext.length);
  29637. }
  29638. return f;
  29639. };
  29640. exports.extname = function (path) {
  29641. if (typeof path !== 'string') path = path + '';
  29642. var startDot = -1;
  29643. var startPart = 0;
  29644. var end = -1;
  29645. var matchedSlash = true;
  29646. // Track the state of characters (if any) we see before our first dot and
  29647. // after any path separator we find
  29648. var preDotState = 0;
  29649. for (var i = path.length - 1; i >= 0; --i) {
  29650. var code = path.charCodeAt(i);
  29651. if (code === 47 /*/*/) {
  29652. // If we reached a path separator that was not part of a set of path
  29653. // separators at the end of the string, stop now
  29654. if (!matchedSlash) {
  29655. startPart = i + 1;
  29656. break;
  29657. }
  29658. continue;
  29659. }
  29660. if (end === -1) {
  29661. // We saw the first non-path separator, mark this as the end of our
  29662. // extension
  29663. matchedSlash = false;
  29664. end = i + 1;
  29665. }
  29666. if (code === 46 /*.*/) {
  29667. // If this is our first dot, mark it as the start of our extension
  29668. if (startDot === -1)
  29669. startDot = i;
  29670. else if (preDotState !== 1)
  29671. preDotState = 1;
  29672. } else if (startDot !== -1) {
  29673. // We saw a non-dot and non-path separator before our dot, so we should
  29674. // have a good chance at having a non-empty extension
  29675. preDotState = -1;
  29676. }
  29677. }
  29678. if (startDot === -1 || end === -1 ||
  29679. // We saw a non-dot character immediately before the dot
  29680. preDotState === 0 ||
  29681. // The (right-most) trimmed path component is exactly '..'
  29682. preDotState === 1 && startDot === end - 1 && startDot === startPart + 1) {
  29683. return '';
  29684. }
  29685. return path.slice(startDot, end);
  29686. };
  29687. function filter (xs, f) {
  29688. if (xs.filter) return xs.filter(f);
  29689. var res = [];
  29690. for (var i = 0; i < xs.length; i++) {
  29691. if (f(xs[i], i, xs)) res.push(xs[i]);
  29692. }
  29693. return res;
  29694. }
  29695. // String.prototype.substr - negative index don't work in IE8
  29696. var substr = 'ab'.substr(-1) === 'b'
  29697. ? function (str, start, len) { return str.substr(start, len) }
  29698. : function (str, start, len) {
  29699. if (start < 0) start = str.length + start;
  29700. return str.substr(start, len);
  29701. }
  29702. ;
  29703. },{"process":"../node_modules/process/browser.js"}],"../src/utilities/LRUCache.js":[function(require,module,exports) {
  29704. "use strict";
  29705. Object.defineProperty(exports, "__esModule", {
  29706. value: true
  29707. });
  29708. exports.LRUCache = void 0;
  29709. // TODO: can we remove the use of `indexOf` here because it's potentially slow? Possibly use time and sort as needed?
  29710. class LRUCache {
  29711. constructor() {
  29712. // options
  29713. this.maxSize = 800;
  29714. this.minSize = 600;
  29715. this.unloadPercent = 0.2;
  29716. this.usedSet = new Set();
  29717. this.itemSet = new Set();
  29718. this.itemList = [];
  29719. this.callbacks = new Map();
  29720. } // Returns whether or not the cache has reached the maximum size
  29721. isFull() {
  29722. return this.itemSet.size >= this.maxSize;
  29723. }
  29724. add(item, removeCb) {
  29725. const itemSet = this.itemSet;
  29726. if (itemSet.has(item)) {
  29727. return false;
  29728. }
  29729. if (this.isFull()) {
  29730. return false;
  29731. }
  29732. const usedSet = this.usedSet;
  29733. const itemList = this.itemList;
  29734. const callbacks = this.callbacks;
  29735. itemList.push(item);
  29736. usedSet.add(item);
  29737. itemSet.add(item);
  29738. callbacks.set(item, removeCb);
  29739. return true;
  29740. }
  29741. remove(item) {
  29742. const usedSet = this.usedSet;
  29743. const itemSet = this.itemSet;
  29744. const itemList = this.itemList;
  29745. const callbacks = this.callbacks;
  29746. if (itemSet.has(item)) {
  29747. callbacks.get(item)(item);
  29748. const index = itemList.indexOf(item);
  29749. itemList.splice(index, 1);
  29750. usedSet.delete(item);
  29751. itemSet.delete(item);
  29752. callbacks.delete(item);
  29753. return true;
  29754. }
  29755. return false;
  29756. }
  29757. markUsed(item) {
  29758. const itemSet = this.itemSet;
  29759. const usedSet = this.usedSet;
  29760. if (itemSet.has(item) && !usedSet.has(item)) {
  29761. const itemList = this.itemList;
  29762. const index = itemList.indexOf(item);
  29763. itemList.splice(index, 1);
  29764. itemList.push(item);
  29765. usedSet.add(item);
  29766. }
  29767. }
  29768. markAllUnused() {
  29769. this.usedSet.clear();
  29770. } // TODO: this should be renamed because it's not necessarily unloading all unused content
  29771. // Maybe call it "cleanup" or "unloadToMinSize"
  29772. unloadUnusedContent(prioritySortCb) {
  29773. const unloadPercent = this.unloadPercent;
  29774. const targetSize = this.minSize;
  29775. const itemList = this.itemList;
  29776. const itemSet = this.itemSet;
  29777. const usedSet = this.usedSet;
  29778. const callbacks = this.callbacks;
  29779. const unused = itemList.length - usedSet.size;
  29780. if (itemList.length > targetSize && unused > 0) {
  29781. // TODO: sort by priority
  29782. let nodesToUnload = Math.max(itemList.length - targetSize, targetSize) * unloadPercent;
  29783. nodesToUnload = Math.ceil(nodesToUnload);
  29784. nodesToUnload = Math.min(unused, nodesToUnload);
  29785. const removedItems = itemList.splice(0, nodesToUnload);
  29786. for (let i = 0, l = removedItems.length; i < l; i++) {
  29787. const item = removedItems[i];
  29788. callbacks.get(item)(item);
  29789. itemSet.delete(item);
  29790. callbacks.delete(item);
  29791. }
  29792. }
  29793. }
  29794. scheduleUnload(prioritySortCb, markAllUnused = true) {
  29795. if (!this.scheduled) {
  29796. this.scheduled = true;
  29797. Promise.resolve().then(() => {
  29798. this.scheduled = false;
  29799. this.unloadUnusedContent(prioritySortCb);
  29800. if (markAllUnused) {
  29801. this.markAllUnused();
  29802. }
  29803. });
  29804. }
  29805. }
  29806. }
  29807. exports.LRUCache = LRUCache;
  29808. },{}],"../src/utilities/PriorityQueue.js":[function(require,module,exports) {
  29809. "use strict";
  29810. Object.defineProperty(exports, "__esModule", {
  29811. value: true
  29812. });
  29813. exports.PriorityQueue = void 0;
  29814. class PriorityQueue {
  29815. constructor(maxJobs = 6) {
  29816. // options
  29817. this.maxJobs = maxJobs;
  29818. this.items = [];
  29819. this.currJobs = 0;
  29820. this.scheduled = false;
  29821. }
  29822. add(item, priority, callback) {
  29823. return new Promise((resolve, reject) => {
  29824. const prCallback = (...args) => callback(...args).then(resolve).catch(reject);
  29825. const items = this.items;
  29826. for (let i = 0, l = items.length; i < l; i++) {
  29827. const thisItem = items[i];
  29828. if (thisItem.priority > priority) {
  29829. items.splice(i, 0, {
  29830. priority,
  29831. item,
  29832. callback: prCallback
  29833. });
  29834. this.scheduleJobRun();
  29835. return;
  29836. }
  29837. }
  29838. items.push({
  29839. priority,
  29840. item,
  29841. callback: prCallback
  29842. });
  29843. this.scheduleJobRun();
  29844. });
  29845. }
  29846. remove(item) {
  29847. const items = this.items;
  29848. for (let i = 0, l = items.length; i < l; i++) {
  29849. const thisItem = items[i];
  29850. if (thisItem.item === item) {
  29851. items.splice(i, 1);
  29852. break;
  29853. }
  29854. }
  29855. }
  29856. tryRunJobs() {
  29857. const items = this.items;
  29858. const maxJobs = this.maxJobs;
  29859. while (maxJobs > this.currJobs && items.length > 0) {
  29860. this.currJobs++;
  29861. const {
  29862. item,
  29863. priority,
  29864. callback
  29865. } = items.pop();
  29866. callback(item, priority).then(() => {
  29867. this.currJobs--;
  29868. this.scheduleJobRun();
  29869. }).catch(() => {
  29870. this.currJobs--;
  29871. this.scheduleJobRun();
  29872. });
  29873. }
  29874. }
  29875. scheduleJobRun() {
  29876. if (!this.scheduled) {
  29877. Promise.resolve().then(() => {
  29878. this.tryRunJobs();
  29879. this.scheduled = false;
  29880. });
  29881. this.scheduled = true;
  29882. }
  29883. }
  29884. }
  29885. exports.PriorityQueue = PriorityQueue;
  29886. },{}],"../src/base/constants.js":[function(require,module,exports) {
  29887. "use strict";
  29888. Object.defineProperty(exports, "__esModule", {
  29889. value: true
  29890. });
  29891. exports.FAILED = exports.LOADED = exports.PARSING = exports.LOADING = exports.UNLOADED = void 0;
  29892. const UNLOADED = 0;
  29893. exports.UNLOADED = UNLOADED;
  29894. const LOADING = 1;
  29895. exports.LOADING = LOADING;
  29896. const PARSING = 2;
  29897. exports.PARSING = PARSING;
  29898. const LOADED = 3;
  29899. exports.LOADED = LOADED;
  29900. const FAILED = 4;
  29901. exports.FAILED = FAILED;
  29902. },{}],"../src/base/traverseFunctions.js":[function(require,module,exports) {
  29903. "use strict";
  29904. Object.defineProperty(exports, "__esModule", {
  29905. value: true
  29906. });
  29907. exports.traverseSet = traverseSet;
  29908. exports.determineFrustumSet = determineFrustumSet;
  29909. exports.markUsedSetLeaves = markUsedSetLeaves;
  29910. exports.skipTraversal = skipTraversal;
  29911. exports.toggleTiles = toggleTiles;
  29912. var _constants = require("./constants.js");
  29913. function isUsedThisFrame(tile, frameCount) {
  29914. return tile.__lastFrameVisited === frameCount && tile.__used;
  29915. }
  29916. function resetFrameState(tile, frameCount) {
  29917. if (tile.__lastFrameVisited !== frameCount) {
  29918. tile.__lastFrameVisited = frameCount;
  29919. tile.__used = false;
  29920. tile.__inFrustum = false;
  29921. tile.__isLeaf = false;
  29922. tile.__visible = false;
  29923. tile.__active = false;
  29924. tile.__error = 0;
  29925. }
  29926. }
  29927. function recursivelyMarkUsed(tile, frameCount, lruCache) {
  29928. resetFrameState(tile, frameCount);
  29929. tile.__used = true;
  29930. lruCache.markUsed(tile);
  29931. if (tile.__contentEmpty) {
  29932. const children = tile.children;
  29933. for (let i = 0, l = children.length; i < l; i++) {
  29934. recursivelyMarkUsed(children[i], frameCount, lruCache);
  29935. }
  29936. }
  29937. }
  29938. function traverseSet(tile, beforeCb = null, afterCb = null, parent = null, depth = 0) {
  29939. if (beforeCb && beforeCb(tile, parent, depth)) {
  29940. if (afterCb) {
  29941. afterCb(tile, parent, depth);
  29942. }
  29943. return;
  29944. }
  29945. const children = tile.children;
  29946. for (let i = 0, l = children.length; i < l; i++) {
  29947. traverseSet(children[i], beforeCb, afterCb, tile, depth + 1);
  29948. }
  29949. if (afterCb) {
  29950. afterCb(tile, parent, depth);
  29951. }
  29952. } // TODO: include frustum mask here?
  29953. function determineFrustumSet(tile, renderer) {
  29954. const stats = renderer.stats;
  29955. const frameCount = renderer.frameCount;
  29956. const errorTarget = renderer.errorTarget;
  29957. const maxDepth = renderer.maxDepth;
  29958. const loadSiblings = renderer.loadSiblings;
  29959. const lruCache = renderer.lruCache;
  29960. resetFrameState(tile, frameCount);
  29961. const inFrustum = renderer.tileInView(tile);
  29962. if (inFrustum === false) {
  29963. return false;
  29964. }
  29965. tile.__used = true;
  29966. lruCache.markUsed(tile);
  29967. tile.__inFrustum = true;
  29968. stats.inFrustum++;
  29969. if (!tile.__contentEmpty) {
  29970. const error = renderer.calculateError(tile);
  29971. tile.__error = error;
  29972. if (error <= errorTarget) {
  29973. return true;
  29974. }
  29975. }
  29976. if (renderer.maxDepth > 0 && tile.__depth + 1 >= maxDepth) {
  29977. return true;
  29978. }
  29979. let anyChildrenUsed = false;
  29980. const children = tile.children;
  29981. for (let i = 0, l = children.length; i < l; i++) {
  29982. const c = children[i];
  29983. const r = determineFrustumSet(c, renderer);
  29984. anyChildrenUsed = anyChildrenUsed || r;
  29985. }
  29986. if (anyChildrenUsed && loadSiblings) {
  29987. for (let i = 0, l = children.length; i < l; i++) {
  29988. recursivelyMarkUsed(tile, frameCount, lruCache);
  29989. }
  29990. }
  29991. return true;
  29992. }
  29993. function markUsedSetLeaves(tile, renderer) {
  29994. const stats = renderer.stats;
  29995. const frameCount = renderer.frameCount;
  29996. if (!isUsedThisFrame(tile, frameCount)) {
  29997. return;
  29998. }
  29999. stats.used++;
  30000. const children = tile.children;
  30001. let anyChildrenUsed = false;
  30002. for (let i = 0, l = children.length; i < l; i++) {
  30003. const c = children[i];
  30004. anyChildrenUsed = anyChildrenUsed || isUsedThisFrame(c, frameCount);
  30005. }
  30006. if (!anyChildrenUsed) {
  30007. tile.__isLeaf = true; // TODO: stats
  30008. } else {
  30009. for (let i = 0, l = children.length; i < l; i++) {
  30010. const c = children[i];
  30011. markUsedSetLeaves(c, renderer);
  30012. }
  30013. }
  30014. }
  30015. function skipTraversal(tile, renderer) {
  30016. const stats = renderer.stats;
  30017. const frameCount = renderer.frameCount;
  30018. if (!isUsedThisFrame(tile, frameCount)) {
  30019. return;
  30020. }
  30021. const lruCache = renderer.lruCache;
  30022. if (tile.__isLeaf) {
  30023. if (tile.__loadingState === _constants.LOADED) {
  30024. if (tile.__inFrustum) {
  30025. tile.__visible = true;
  30026. stats.visible++;
  30027. }
  30028. tile.__active = true;
  30029. stats.active++;
  30030. } else if (!lruCache.isFull()) {
  30031. renderer.requestTileContents(tile);
  30032. }
  30033. return;
  30034. }
  30035. const errorRequirement = renderer.errorTarget * renderer.errorThreshold;
  30036. const meetsSSE = tile.__error < errorRequirement;
  30037. const hasContent = tile.__loadingState === _constants.LOADED && !tile.__contentEmpty;
  30038. const children = tile.children;
  30039. let allChildrenHaveContent = true;
  30040. for (let i = 0, l = children.length; i < l; i++) {
  30041. const c = children[i];
  30042. if (isUsedThisFrame(c, frameCount)) {
  30043. const childContent = c.__loadingState === _constants.LOADED || tile.__contentEmpty;
  30044. allChildrenHaveContent = allChildrenHaveContent && childContent;
  30045. }
  30046. }
  30047. if (meetsSSE && !hasContent && !lruCache.isFull()) {
  30048. renderer.requestTileContents(tile);
  30049. }
  30050. if (meetsSSE && hasContent && !allChildrenHaveContent) {
  30051. if (tile.__inFrustum) {
  30052. tile.__visible = true;
  30053. stats.visible++;
  30054. }
  30055. tile.__active = true;
  30056. stats.active++;
  30057. for (let i = 0, l = children.length; i < l; i++) {
  30058. const c = children[i];
  30059. if (isUsedThisFrame(c, frameCount) && !lruCache.isFull()) {
  30060. renderer.requestTileContents(c);
  30061. }
  30062. }
  30063. return;
  30064. }
  30065. for (let i = 0, l = children.length; i < l; i++) {
  30066. const c = children[i];
  30067. if (isUsedThisFrame(c, frameCount)) {
  30068. skipTraversal(c, renderer);
  30069. }
  30070. }
  30071. }
  30072. function toggleTiles(tile, renderer) {
  30073. const frameCount = renderer.frameCount;
  30074. const isUsed = isUsedThisFrame(tile, frameCount);
  30075. if (isUsed || tile.__usedLastFrame) {
  30076. if (!isUsed) {
  30077. if (!tile.__contentEmpty && tile.__loadingState === _constants.LOADED) {
  30078. renderer.setTileVisible(tile, false);
  30079. renderer.setTileActive(tile, false);
  30080. }
  30081. tile.__usedLastFrame = false;
  30082. } else {
  30083. if (!tile.__contentEmpty && tile.__loadingState === _constants.LOADED) {
  30084. // enable visibility if active due to shadows
  30085. renderer.setTileActive(tile, tile.__active);
  30086. renderer.setTileVisible(tile, tile.__active || tile.__visible);
  30087. }
  30088. tile.__usedLastFrame = true;
  30089. }
  30090. const children = tile.children;
  30091. for (let i = 0, l = children.length; i < l; i++) {
  30092. const c = children[i];
  30093. toggleTiles(c, renderer);
  30094. }
  30095. }
  30096. }
  30097. },{"./constants.js":"../src/base/constants.js"}],"../src/base/TilesRendererBase.js":[function(require,module,exports) {
  30098. "use strict";
  30099. Object.defineProperty(exports, "__esModule", {
  30100. value: true
  30101. });
  30102. exports.TilesRendererBase = void 0;
  30103. var _path = _interopRequireDefault(require("path"));
  30104. var _LRUCache = require("../utilities/LRUCache.js");
  30105. var _PriorityQueue = require("../utilities/PriorityQueue.js");
  30106. var _traverseFunctions = require("./traverseFunctions.js");
  30107. var _constants = require("./constants.js");
  30108. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  30109. // TODO: find out why tiles are left dangling in the hierarchy
  30110. // TODO: Address the issue of too many promises, garbage collection
  30111. // TODO: remove more redundant computation
  30112. // TODO: See if using classes improves performance
  30113. // TODO: See if declaring function inline improves performance
  30114. // TODO: Make sure active state works as expected
  30115. class TilesRendererBase {
  30116. get root() {
  30117. const tileSet = this.tileSets[this.rootSet];
  30118. if (!tileSet || tileSet instanceof Promise) {
  30119. return null;
  30120. } else {
  30121. return tileSet.root;
  30122. }
  30123. }
  30124. constructor(url, cache = new _LRUCache.LRUCache(), downloadQueue = new _PriorityQueue.PriorityQueue(6), parseQueue = new _PriorityQueue.PriorityQueue(1)) {
  30125. // state
  30126. this.tileSets = {};
  30127. this.rootSet = url;
  30128. this.lruCache = cache;
  30129. this.fetchOptions = {};
  30130. this.downloadQueue = downloadQueue;
  30131. this.parseQueue = parseQueue;
  30132. this.stats = {
  30133. parsing: 0,
  30134. downloading: 0,
  30135. inFrustum: 0,
  30136. used: 0,
  30137. active: 0,
  30138. visible: 0
  30139. };
  30140. this.frameCount = 0; // options
  30141. this.errorTarget = 6.0;
  30142. this.errorThreshold = 6.0;
  30143. this.loadSiblings = true;
  30144. this.maxDepth = Infinity;
  30145. }
  30146. traverse(cb) {
  30147. const tileSets = this.tileSets;
  30148. const rootTileSet = tileSets[this.rootSet];
  30149. if (!rootTileSet || !rootTileSet.root) return;
  30150. (0, _traverseFunctions.traverseSet)(rootTileSet.root, cb);
  30151. } // Public API
  30152. update() {
  30153. const stats = this.stats;
  30154. const lruCache = this.lruCache;
  30155. const tileSets = this.tileSets;
  30156. const rootTileSet = tileSets[this.rootSet];
  30157. if (!(this.rootSet in tileSets)) {
  30158. this.loadTileSet(this.rootSet);
  30159. return;
  30160. } else if (!rootTileSet || !rootTileSet.root) {
  30161. return;
  30162. }
  30163. const root = rootTileSet.root;
  30164. stats.inFrustum = 0, stats.used = 0, stats.active = 0, stats.visible = 0, this.frameCount++;
  30165. (0, _traverseFunctions.determineFrustumSet)(root, this);
  30166. (0, _traverseFunctions.markUsedSetLeaves)(root, this);
  30167. (0, _traverseFunctions.skipTraversal)(root, this);
  30168. (0, _traverseFunctions.toggleTiles)(root, this); // TODO: We may want to add this function in the requestTileContents function
  30169. lruCache.scheduleUnload(null);
  30170. } // Overrideable
  30171. parseTile(buffer, tile) {
  30172. return null;
  30173. }
  30174. disposeTile(tile) {}
  30175. preprocessNode(tile, parentTile, tileSetDir) {
  30176. if (tile.content) {
  30177. if (!('uri' in tile.content) && 'url' in tile.content) {
  30178. tile.content.uri = tile.content.url;
  30179. delete tile.content.url;
  30180. }
  30181. if (tile.content.uri) {
  30182. tile.content.uri = _path.default.join(tileSetDir, tile.content.uri);
  30183. } // TODO: fix for some cases where tilesets provide the bounding volume
  30184. // but volumes are not present. See
  30185. if (tile.content.boundingVolume && !('box' in tile.content.boundingVolume || 'sphere' in tile.content.boundingVolume || 'region' in tile.content.boundingVolume)) {
  30186. delete tile.content.boundingVolume;
  30187. }
  30188. }
  30189. tile.parent = parentTile;
  30190. tile.children = tile.children || [];
  30191. tile.__contentEmpty = !tile.content || !tile.content.uri;
  30192. tile.__error = 0.0;
  30193. tile.__inFrustum = false;
  30194. tile.__isLeaf = false;
  30195. tile.__wasUsed = false;
  30196. tile.__used = false;
  30197. tile.__wasVisible = false;
  30198. tile.__visible = false;
  30199. tile.__wasActive = false;
  30200. tile.__active = false;
  30201. tile.__childrenActive = false;
  30202. tile.__loadingState = _constants.UNLOADED;
  30203. tile.__loadIndex = 0;
  30204. tile.__loadAbort = null;
  30205. if (parentTile === null) {
  30206. tile.__depth = 0;
  30207. } else {
  30208. tile.__depth = parentTile.__depth + 1;
  30209. }
  30210. }
  30211. setTileActive(tile, state) {}
  30212. setTileVisible(tile, state) {}
  30213. calculateError(tile) {
  30214. return 0;
  30215. }
  30216. tileInView(tile) {
  30217. return true;
  30218. } // Private Functions
  30219. loadTileSet(url) {
  30220. const tileSets = this.tileSets;
  30221. if (!(url in tileSets)) {
  30222. const pr = fetch(url, this.fetchOptions).then(res => {
  30223. if (res.ok) {
  30224. return res.json();
  30225. } else {
  30226. throw new Error(`Status ${res.status} (${res.statusText})`);
  30227. }
  30228. }).then(json => {
  30229. // TODO: Add version query?
  30230. const version = json.asset.version;
  30231. console.assert(version === '1.0' || version === '0.0');
  30232. const basePath = _path.default.dirname(url);
  30233. (0, _traverseFunctions.traverseSet)(json.root, (node, parent) => this.preprocessNode(node, parent, basePath));
  30234. tileSets[url] = json; // TODO: schedule an update to avoid doing this too many times
  30235. this.update();
  30236. });
  30237. pr.catch(e => {
  30238. console.error(`TilesLoader: Failed to load tile set json "${url}"`);
  30239. console.error(e);
  30240. delete tileSets[url];
  30241. });
  30242. tileSets[url] = pr;
  30243. }
  30244. return Promise.resolve(tileSets[url]);
  30245. }
  30246. requestTileContents(tile) {
  30247. // If the tile is already being loaded then don't
  30248. // start it again.
  30249. if (tile.__loadingState !== _constants.UNLOADED) {
  30250. return;
  30251. } // TODO: reuse the functions created here?
  30252. const lruCache = this.lruCache;
  30253. const downloadQueue = this.downloadQueue;
  30254. const parseQueue = this.parseQueue;
  30255. lruCache.add(tile, t => {
  30256. if (t.__loadingState === _constants.LOADING) {
  30257. t.__loadAbort.abort();
  30258. t.__loadAbort = null;
  30259. } else {
  30260. this.disposeTile(t);
  30261. }
  30262. if (t.__loadingState === _constants.LOADING) {
  30263. stats.downloading--;
  30264. } else if (t.__loadingState === _constants.PARSING) {
  30265. stats.parsing--;
  30266. }
  30267. t.__loadingState = _constants.UNLOADED;
  30268. t.__loadIndex++; // TODO: Removing from the queues here is slow
  30269. // parseQueue.remove( t );
  30270. // downloadQueue.remove( t );
  30271. });
  30272. tile.__loadIndex++;
  30273. const loadIndex = tile.__loadIndex;
  30274. const priority = 1 / (tile.__depth + 1);
  30275. const stats = this.stats;
  30276. const controller = new AbortController();
  30277. const signal = controller.signal;
  30278. stats.downloading++;
  30279. tile.__loadAbort = controller;
  30280. tile.__loadingState = _constants.LOADING;
  30281. downloadQueue.add(tile, priority, tile => {
  30282. if (tile.__loadIndex !== loadIndex) {
  30283. return Promise.resolve();
  30284. }
  30285. return fetch(tile.content.uri, Object.assign({
  30286. signal
  30287. }, this.fetchOptions));
  30288. }).then(res => {
  30289. if (tile.__loadIndex !== loadIndex) {
  30290. return;
  30291. }
  30292. if (res.ok) {
  30293. return res.arrayBuffer();
  30294. } else {
  30295. throw new Error(`Failed to load model with error code ${res.status}`);
  30296. }
  30297. }).then(buffer => {
  30298. if (tile.__loadIndex !== loadIndex) {
  30299. return;
  30300. }
  30301. stats.downloading--;
  30302. stats.parsing++;
  30303. tile.__loadAbort = null;
  30304. tile.__loadingState = _constants.PARSING;
  30305. return parseQueue.add(buffer, priority, buffer => {
  30306. if (tile.__loadIndex !== loadIndex) {
  30307. return Promise.resolve();
  30308. }
  30309. return this.parseTile(buffer, tile);
  30310. });
  30311. }).then(() => {
  30312. if (tile.__loadIndex !== loadIndex) {
  30313. return;
  30314. }
  30315. stats.parsing--;
  30316. tile.__loadingState = _constants.LOADED;
  30317. this.setTileActive(tile, tile.__active);
  30318. this.setTileVisible(tile, tile.__visible);
  30319. }).catch(e => {
  30320. // if it has been unloaded then the tile has been disposed
  30321. if (tile.__loadIndex !== loadIndex) {
  30322. return;
  30323. }
  30324. if (e.name !== 'AbortError') {
  30325. console.error('TilesRenderer : Failed to load tile.');
  30326. console.error(e);
  30327. tile.__loadingState = _constants.FAILED;
  30328. } else {
  30329. lruCache.remove(tile);
  30330. }
  30331. });
  30332. }
  30333. }
  30334. exports.TilesRendererBase = TilesRendererBase;
  30335. },{"path":"../node_modules/path-browserify/index.js","../utilities/LRUCache.js":"../src/utilities/LRUCache.js","../utilities/PriorityQueue.js":"../src/utilities/PriorityQueue.js","./traverseFunctions.js":"../src/base/traverseFunctions.js","./constants.js":"../src/base/constants.js"}],"../src/base/B3DMLoaderBase.js":[function(require,module,exports) {
  30336. "use strict";
  30337. Object.defineProperty(exports, "__esModule", {
  30338. value: true
  30339. });
  30340. exports.B3DMLoaderBase = void 0;
  30341. // https://github.com/AnalyticalGraphicsInc/3d-tiles/blob/master/specification/TileFormats/Batched3DModel/README.md
  30342. // convert an array of numbers to a string
  30343. function arrayToString(array) {
  30344. let str = '';
  30345. for (let i = 0, l = array.length; i < l; i++) {
  30346. str += String.fromCharCode(array[i]);
  30347. }
  30348. return str;
  30349. }
  30350. class B3DMLoaderBase {
  30351. constructor() {
  30352. this.fetchOptions = {};
  30353. }
  30354. load(url) {
  30355. return fetch(url, this.fetchOptions).then(res => res.arrayBuffer()).then(buffer => this.parse(buffer));
  30356. }
  30357. parse(buffer) {
  30358. const dataView = new DataView(buffer); // 28-byte header
  30359. // 4 bytes
  30360. const magic = String.fromCharCode(dataView.getUint8(0)) + String.fromCharCode(dataView.getUint8(1)) + String.fromCharCode(dataView.getUint8(2)) + String.fromCharCode(dataView.getUint8(3));
  30361. console.assert(magic === 'b3dm'); // 4 bytes
  30362. const version = dataView.getUint32(4, true);
  30363. console.assert(version === 1); // 4 bytes
  30364. const byteLength = dataView.getUint32(8, true);
  30365. console.assert(byteLength === buffer.byteLength); // 4 bytes
  30366. const featureTableJSONByteLength = dataView.getUint32(12, true); // 4 bytes
  30367. const featureTableBinaryByteLength = dataView.getUint32(16, true); // 4 bytes
  30368. const batchTableJSONByteLength = dataView.getUint32(20, true); // 4 bytes
  30369. const batchTableBinaryByteLength = dataView.getUint32(24, true); // Feature Table
  30370. const featureTableStart = 28;
  30371. const jsonFeatureTableData = new Uint8Array(buffer, featureTableStart, featureTableJSONByteLength);
  30372. const jsonFeatureTable = featureTableJSONByteLength === 0 ? {} : JSON.parse(arrayToString(jsonFeatureTableData)); // const binFeatureTableData = new Uint8Array( buffer, featureTableStart + featureTableJSONByteLength, featureTableBinaryByteLength );
  30373. // TODO: dereference the json feature table data in to the binary array.
  30374. // https://github.com/AnalyticalGraphicsInc/3d-tiles/blob/master/specification/TileFormats/FeatureTable/README.md#json-header
  30375. // Batch Table
  30376. const batchTableStart = featureTableStart + featureTableJSONByteLength + featureTableBinaryByteLength;
  30377. const jsonBatchTableData = new Uint8Array(buffer, batchTableStart, batchTableJSONByteLength);
  30378. const jsonBatchTable = batchTableJSONByteLength === 0 ? {} : JSON.parse(arrayToString(jsonBatchTableData)); // const binBatchTableData = new Uint8Array( buffer, batchTableStart + batchTableJSONByteLength, batchTableBinaryByteLength );
  30379. // TODO: dereference the json batch table data in to the binary array.
  30380. // https://github.com/AnalyticalGraphicsInc/3d-tiles/blob/master/specification/TileFormats/FeatureTable/README.md#json-header
  30381. const glbStart = batchTableStart + batchTableJSONByteLength + batchTableBinaryByteLength;
  30382. const glbBytes = new Uint8Array(buffer, glbStart, byteLength - glbStart); // TODO: Understand how to apply the batchId semantics
  30383. // https://github.com/AnalyticalGraphicsInc/3d-tiles/blob/master/specification/TileFormats/Batched3DModel/README.md#binary-gltf
  30384. return {
  30385. version,
  30386. featureTable: jsonFeatureTable,
  30387. batchTable: jsonBatchTable,
  30388. glbBytes
  30389. };
  30390. }
  30391. }
  30392. exports.B3DMLoaderBase = B3DMLoaderBase;
  30393. },{}],"../node_modules/three/examples/jsm/loaders/GLTFLoader.js":[function(require,module,exports) {
  30394. "use strict";
  30395. Object.defineProperty(exports, "__esModule", {
  30396. value: true
  30397. });
  30398. exports.GLTFLoader = void 0;
  30399. var _threeModule = require("../../../build/three.module.js");
  30400. /**
  30401. * @author Rich Tibbett / https://github.com/richtr
  30402. * @author mrdoob / http://mrdoob.com/
  30403. * @author Tony Parisi / http://www.tonyparisi.com/
  30404. * @author Takahiro / https://github.com/takahirox
  30405. * @author Don McCurdy / https://www.donmccurdy.com
  30406. */
  30407. var GLTFLoader = function () {
  30408. function GLTFLoader(manager) {
  30409. _threeModule.Loader.call(this, manager);
  30410. this.dracoLoader = null;
  30411. this.ddsLoader = null;
  30412. }
  30413. GLTFLoader.prototype = Object.assign(Object.create(_threeModule.Loader.prototype), {
  30414. constructor: GLTFLoader,
  30415. load: function (url, onLoad, onProgress, onError) {
  30416. var scope = this;
  30417. var resourcePath;
  30418. if (this.resourcePath !== '') {
  30419. resourcePath = this.resourcePath;
  30420. } else if (this.path !== '') {
  30421. resourcePath = this.path;
  30422. } else {
  30423. resourcePath = _threeModule.LoaderUtils.extractUrlBase(url);
  30424. } // Tells the LoadingManager to track an extra item, which resolves after
  30425. // the model is fully loaded. This means the count of items loaded will
  30426. // be incorrect, but ensures manager.onLoad() does not fire early.
  30427. scope.manager.itemStart(url);
  30428. var _onError = function (e) {
  30429. if (onError) {
  30430. onError(e);
  30431. } else {
  30432. console.error(e);
  30433. }
  30434. scope.manager.itemError(url);
  30435. scope.manager.itemEnd(url);
  30436. };
  30437. var loader = new _threeModule.FileLoader(scope.manager);
  30438. loader.setPath(this.path);
  30439. loader.setResponseType('arraybuffer');
  30440. if (scope.crossOrigin === 'use-credentials') {
  30441. loader.setWithCredentials(true);
  30442. }
  30443. loader.load(url, function (data) {
  30444. try {
  30445. scope.parse(data, resourcePath, function (gltf) {
  30446. onLoad(gltf);
  30447. scope.manager.itemEnd(url);
  30448. }, _onError);
  30449. } catch (e) {
  30450. _onError(e);
  30451. }
  30452. }, onProgress, _onError);
  30453. },
  30454. setDRACOLoader: function (dracoLoader) {
  30455. this.dracoLoader = dracoLoader;
  30456. return this;
  30457. },
  30458. setDDSLoader: function (ddsLoader) {
  30459. this.ddsLoader = ddsLoader;
  30460. return this;
  30461. },
  30462. parse: function (data, path, onLoad, onError) {
  30463. var content;
  30464. var extensions = {};
  30465. if (typeof data === 'string') {
  30466. content = data;
  30467. } else {
  30468. var magic = _threeModule.LoaderUtils.decodeText(new Uint8Array(data, 0, 4));
  30469. if (magic === BINARY_EXTENSION_HEADER_MAGIC) {
  30470. try {
  30471. extensions[EXTENSIONS.KHR_BINARY_GLTF] = new GLTFBinaryExtension(data);
  30472. } catch (error) {
  30473. if (onError) onError(error);
  30474. return;
  30475. }
  30476. content = extensions[EXTENSIONS.KHR_BINARY_GLTF].content;
  30477. } else {
  30478. content = _threeModule.LoaderUtils.decodeText(new Uint8Array(data));
  30479. }
  30480. }
  30481. var json = JSON.parse(content);
  30482. if (json.asset === undefined || json.asset.version[0] < 2) {
  30483. if (onError) onError(new Error('THREE.GLTFLoader: Unsupported asset. glTF versions >=2.0 are supported. Use LegacyGLTFLoader instead.'));
  30484. return;
  30485. }
  30486. if (json.extensionsUsed) {
  30487. for (var i = 0; i < json.extensionsUsed.length; ++i) {
  30488. var extensionName = json.extensionsUsed[i];
  30489. var extensionsRequired = json.extensionsRequired || [];
  30490. switch (extensionName) {
  30491. case EXTENSIONS.KHR_LIGHTS_PUNCTUAL:
  30492. extensions[extensionName] = new GLTFLightsExtension(json);
  30493. break;
  30494. case EXTENSIONS.KHR_MATERIALS_UNLIT:
  30495. extensions[extensionName] = new GLTFMaterialsUnlitExtension();
  30496. break;
  30497. case EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS:
  30498. extensions[extensionName] = new GLTFMaterialsPbrSpecularGlossinessExtension();
  30499. break;
  30500. case EXTENSIONS.KHR_DRACO_MESH_COMPRESSION:
  30501. extensions[extensionName] = new GLTFDracoMeshCompressionExtension(json, this.dracoLoader);
  30502. break;
  30503. case EXTENSIONS.MSFT_TEXTURE_DDS:
  30504. extensions[EXTENSIONS.MSFT_TEXTURE_DDS] = new GLTFTextureDDSExtension(this.ddsLoader);
  30505. break;
  30506. case EXTENSIONS.KHR_TEXTURE_TRANSFORM:
  30507. extensions[EXTENSIONS.KHR_TEXTURE_TRANSFORM] = new GLTFTextureTransformExtension();
  30508. break;
  30509. default:
  30510. if (extensionsRequired.indexOf(extensionName) >= 0) {
  30511. console.warn('THREE.GLTFLoader: Unknown extension "' + extensionName + '".');
  30512. }
  30513. }
  30514. }
  30515. }
  30516. var parser = new GLTFParser(json, extensions, {
  30517. path: path || this.resourcePath || '',
  30518. crossOrigin: this.crossOrigin,
  30519. manager: this.manager
  30520. });
  30521. parser.parse(onLoad, onError);
  30522. }
  30523. });
  30524. /* GLTFREGISTRY */
  30525. function GLTFRegistry() {
  30526. var objects = {};
  30527. return {
  30528. get: function (key) {
  30529. return objects[key];
  30530. },
  30531. add: function (key, object) {
  30532. objects[key] = object;
  30533. },
  30534. remove: function (key) {
  30535. delete objects[key];
  30536. },
  30537. removeAll: function () {
  30538. objects = {};
  30539. }
  30540. };
  30541. }
  30542. /*********************************/
  30543. /********** EXTENSIONS ***********/
  30544. /*********************************/
  30545. var EXTENSIONS = {
  30546. KHR_BINARY_GLTF: 'KHR_binary_glTF',
  30547. KHR_DRACO_MESH_COMPRESSION: 'KHR_draco_mesh_compression',
  30548. KHR_LIGHTS_PUNCTUAL: 'KHR_lights_punctual',
  30549. KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS: 'KHR_materials_pbrSpecularGlossiness',
  30550. KHR_MATERIALS_UNLIT: 'KHR_materials_unlit',
  30551. KHR_TEXTURE_TRANSFORM: 'KHR_texture_transform',
  30552. MSFT_TEXTURE_DDS: 'MSFT_texture_dds'
  30553. };
  30554. /**
  30555. * DDS Texture Extension
  30556. *
  30557. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/MSFT_texture_dds
  30558. *
  30559. */
  30560. function GLTFTextureDDSExtension(ddsLoader) {
  30561. if (!ddsLoader) {
  30562. throw new Error('THREE.GLTFLoader: Attempting to load .dds texture without importing DDSLoader');
  30563. }
  30564. this.name = EXTENSIONS.MSFT_TEXTURE_DDS;
  30565. this.ddsLoader = ddsLoader;
  30566. }
  30567. /**
  30568. * Punctual Lights Extension
  30569. *
  30570. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_lights_punctual
  30571. */
  30572. function GLTFLightsExtension(json) {
  30573. this.name = EXTENSIONS.KHR_LIGHTS_PUNCTUAL;
  30574. var extension = json.extensions && json.extensions[EXTENSIONS.KHR_LIGHTS_PUNCTUAL] || {};
  30575. this.lightDefs = extension.lights || [];
  30576. }
  30577. GLTFLightsExtension.prototype.loadLight = function (lightIndex) {
  30578. var lightDef = this.lightDefs[lightIndex];
  30579. var lightNode;
  30580. var color = new _threeModule.Color(0xffffff);
  30581. if (lightDef.color !== undefined) color.fromArray(lightDef.color);
  30582. var range = lightDef.range !== undefined ? lightDef.range : 0;
  30583. switch (lightDef.type) {
  30584. case 'directional':
  30585. lightNode = new _threeModule.DirectionalLight(color);
  30586. lightNode.target.position.set(0, 0, -1);
  30587. lightNode.add(lightNode.target);
  30588. break;
  30589. case 'point':
  30590. lightNode = new _threeModule.PointLight(color);
  30591. lightNode.distance = range;
  30592. break;
  30593. case 'spot':
  30594. lightNode = new _threeModule.SpotLight(color);
  30595. lightNode.distance = range; // Handle spotlight properties.
  30596. lightDef.spot = lightDef.spot || {};
  30597. lightDef.spot.innerConeAngle = lightDef.spot.innerConeAngle !== undefined ? lightDef.spot.innerConeAngle : 0;
  30598. lightDef.spot.outerConeAngle = lightDef.spot.outerConeAngle !== undefined ? lightDef.spot.outerConeAngle : Math.PI / 4.0;
  30599. lightNode.angle = lightDef.spot.outerConeAngle;
  30600. lightNode.penumbra = 1.0 - lightDef.spot.innerConeAngle / lightDef.spot.outerConeAngle;
  30601. lightNode.target.position.set(0, 0, -1);
  30602. lightNode.add(lightNode.target);
  30603. break;
  30604. default:
  30605. throw new Error('THREE.GLTFLoader: Unexpected light type, "' + lightDef.type + '".');
  30606. } // Some lights (e.g. spot) default to a position other than the origin. Reset the position
  30607. // here, because node-level parsing will only override position if explicitly specified.
  30608. lightNode.position.set(0, 0, 0);
  30609. lightNode.decay = 2;
  30610. if (lightDef.intensity !== undefined) lightNode.intensity = lightDef.intensity;
  30611. lightNode.name = lightDef.name || 'light_' + lightIndex;
  30612. return Promise.resolve(lightNode);
  30613. };
  30614. /**
  30615. * Unlit Materials Extension
  30616. *
  30617. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_unlit
  30618. */
  30619. function GLTFMaterialsUnlitExtension() {
  30620. this.name = EXTENSIONS.KHR_MATERIALS_UNLIT;
  30621. }
  30622. GLTFMaterialsUnlitExtension.prototype.getMaterialType = function () {
  30623. return _threeModule.MeshBasicMaterial;
  30624. };
  30625. GLTFMaterialsUnlitExtension.prototype.extendParams = function (materialParams, materialDef, parser) {
  30626. var pending = [];
  30627. materialParams.color = new _threeModule.Color(1.0, 1.0, 1.0);
  30628. materialParams.opacity = 1.0;
  30629. var metallicRoughness = materialDef.pbrMetallicRoughness;
  30630. if (metallicRoughness) {
  30631. if (Array.isArray(metallicRoughness.baseColorFactor)) {
  30632. var array = metallicRoughness.baseColorFactor;
  30633. materialParams.color.fromArray(array);
  30634. materialParams.opacity = array[3];
  30635. }
  30636. if (metallicRoughness.baseColorTexture !== undefined) {
  30637. pending.push(parser.assignTexture(materialParams, 'map', metallicRoughness.baseColorTexture));
  30638. }
  30639. }
  30640. return Promise.all(pending);
  30641. };
  30642. /* BINARY EXTENSION */
  30643. var BINARY_EXTENSION_HEADER_MAGIC = 'glTF';
  30644. var BINARY_EXTENSION_HEADER_LENGTH = 12;
  30645. var BINARY_EXTENSION_CHUNK_TYPES = {
  30646. JSON: 0x4E4F534A,
  30647. BIN: 0x004E4942
  30648. };
  30649. function GLTFBinaryExtension(data) {
  30650. this.name = EXTENSIONS.KHR_BINARY_GLTF;
  30651. this.content = null;
  30652. this.body = null;
  30653. var headerView = new DataView(data, 0, BINARY_EXTENSION_HEADER_LENGTH);
  30654. this.header = {
  30655. magic: _threeModule.LoaderUtils.decodeText(new Uint8Array(data.slice(0, 4))),
  30656. version: headerView.getUint32(4, true),
  30657. length: headerView.getUint32(8, true)
  30658. };
  30659. if (this.header.magic !== BINARY_EXTENSION_HEADER_MAGIC) {
  30660. throw new Error('THREE.GLTFLoader: Unsupported glTF-Binary header.');
  30661. } else if (this.header.version < 2.0) {
  30662. throw new Error('THREE.GLTFLoader: Legacy binary file detected. Use LegacyGLTFLoader instead.');
  30663. }
  30664. var chunkView = new DataView(data, BINARY_EXTENSION_HEADER_LENGTH);
  30665. var chunkIndex = 0;
  30666. while (chunkIndex < chunkView.byteLength) {
  30667. var chunkLength = chunkView.getUint32(chunkIndex, true);
  30668. chunkIndex += 4;
  30669. var chunkType = chunkView.getUint32(chunkIndex, true);
  30670. chunkIndex += 4;
  30671. if (chunkType === BINARY_EXTENSION_CHUNK_TYPES.JSON) {
  30672. var contentArray = new Uint8Array(data, BINARY_EXTENSION_HEADER_LENGTH + chunkIndex, chunkLength);
  30673. this.content = _threeModule.LoaderUtils.decodeText(contentArray);
  30674. } else if (chunkType === BINARY_EXTENSION_CHUNK_TYPES.BIN) {
  30675. var byteOffset = BINARY_EXTENSION_HEADER_LENGTH + chunkIndex;
  30676. this.body = data.slice(byteOffset, byteOffset + chunkLength);
  30677. } // Clients must ignore chunks with unknown types.
  30678. chunkIndex += chunkLength;
  30679. }
  30680. if (this.content === null) {
  30681. throw new Error('THREE.GLTFLoader: JSON content not found.');
  30682. }
  30683. }
  30684. /**
  30685. * DRACO Mesh Compression Extension
  30686. *
  30687. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_draco_mesh_compression
  30688. */
  30689. function GLTFDracoMeshCompressionExtension(json, dracoLoader) {
  30690. if (!dracoLoader) {
  30691. throw new Error('THREE.GLTFLoader: No DRACOLoader instance provided.');
  30692. }
  30693. this.name = EXTENSIONS.KHR_DRACO_MESH_COMPRESSION;
  30694. this.json = json;
  30695. this.dracoLoader = dracoLoader;
  30696. }
  30697. GLTFDracoMeshCompressionExtension.prototype.decodePrimitive = function (primitive, parser) {
  30698. var json = this.json;
  30699. var dracoLoader = this.dracoLoader;
  30700. var bufferViewIndex = primitive.extensions[this.name].bufferView;
  30701. var gltfAttributeMap = primitive.extensions[this.name].attributes;
  30702. var threeAttributeMap = {};
  30703. var attributeNormalizedMap = {};
  30704. var attributeTypeMap = {};
  30705. for (var attributeName in gltfAttributeMap) {
  30706. var threeAttributeName = ATTRIBUTES[attributeName] || attributeName.toLowerCase();
  30707. threeAttributeMap[threeAttributeName] = gltfAttributeMap[attributeName];
  30708. }
  30709. for (attributeName in primitive.attributes) {
  30710. var threeAttributeName = ATTRIBUTES[attributeName] || attributeName.toLowerCase();
  30711. if (gltfAttributeMap[attributeName] !== undefined) {
  30712. var accessorDef = json.accessors[primitive.attributes[attributeName]];
  30713. var componentType = WEBGL_COMPONENT_TYPES[accessorDef.componentType];
  30714. attributeTypeMap[threeAttributeName] = componentType;
  30715. attributeNormalizedMap[threeAttributeName] = accessorDef.normalized === true;
  30716. }
  30717. }
  30718. return parser.getDependency('bufferView', bufferViewIndex).then(function (bufferView) {
  30719. return new Promise(function (resolve) {
  30720. dracoLoader.decodeDracoFile(bufferView, function (geometry) {
  30721. for (var attributeName in geometry.attributes) {
  30722. var attribute = geometry.attributes[attributeName];
  30723. var normalized = attributeNormalizedMap[attributeName];
  30724. if (normalized !== undefined) attribute.normalized = normalized;
  30725. }
  30726. resolve(geometry);
  30727. }, threeAttributeMap, attributeTypeMap);
  30728. });
  30729. });
  30730. };
  30731. /**
  30732. * Texture Transform Extension
  30733. *
  30734. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_texture_transform
  30735. */
  30736. function GLTFTextureTransformExtension() {
  30737. this.name = EXTENSIONS.KHR_TEXTURE_TRANSFORM;
  30738. }
  30739. GLTFTextureTransformExtension.prototype.extendTexture = function (texture, transform) {
  30740. texture = texture.clone();
  30741. if (transform.offset !== undefined) {
  30742. texture.offset.fromArray(transform.offset);
  30743. }
  30744. if (transform.rotation !== undefined) {
  30745. texture.rotation = transform.rotation;
  30746. }
  30747. if (transform.scale !== undefined) {
  30748. texture.repeat.fromArray(transform.scale);
  30749. }
  30750. if (transform.texCoord !== undefined) {
  30751. console.warn('THREE.GLTFLoader: Custom UV sets in "' + this.name + '" extension not yet supported.');
  30752. }
  30753. texture.needsUpdate = true;
  30754. return texture;
  30755. };
  30756. /**
  30757. * Specular-Glossiness Extension
  30758. *
  30759. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_pbrSpecularGlossiness
  30760. */
  30761. function GLTFMaterialsPbrSpecularGlossinessExtension() {
  30762. return {
  30763. name: EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS,
  30764. specularGlossinessParams: ['color', 'map', 'lightMap', 'lightMapIntensity', 'aoMap', 'aoMapIntensity', 'emissive', 'emissiveIntensity', 'emissiveMap', 'bumpMap', 'bumpScale', 'normalMap', 'displacementMap', 'displacementScale', 'displacementBias', 'specularMap', 'specular', 'glossinessMap', 'glossiness', 'alphaMap', 'envMap', 'envMapIntensity', 'refractionRatio'],
  30765. getMaterialType: function () {
  30766. return _threeModule.ShaderMaterial;
  30767. },
  30768. extendParams: function (materialParams, materialDef, parser) {
  30769. var pbrSpecularGlossiness = materialDef.extensions[this.name];
  30770. var shader = _threeModule.ShaderLib['standard'];
  30771. var uniforms = _threeModule.UniformsUtils.clone(shader.uniforms);
  30772. var specularMapParsFragmentChunk = ['#ifdef USE_SPECULARMAP', ' uniform sampler2D specularMap;', '#endif'].join('\n');
  30773. var glossinessMapParsFragmentChunk = ['#ifdef USE_GLOSSINESSMAP', ' uniform sampler2D glossinessMap;', '#endif'].join('\n');
  30774. 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');
  30775. 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');
  30776. var lightPhysicalFragmentChunk = ['PhysicalMaterial material;', 'material.diffuseColor = diffuseColor.rgb;', 'material.specularRoughness = clamp( 1.0 - glossinessFactor, 0.04, 1.0 );', 'material.specularColor = specularFactor.rgb;'].join('\n');
  30777. 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);
  30778. delete uniforms.roughness;
  30779. delete uniforms.metalness;
  30780. delete uniforms.roughnessMap;
  30781. delete uniforms.metalnessMap;
  30782. uniforms.specular = {
  30783. value: new _threeModule.Color().setHex(0x111111)
  30784. };
  30785. uniforms.glossiness = {
  30786. value: 0.5
  30787. };
  30788. uniforms.specularMap = {
  30789. value: null
  30790. };
  30791. uniforms.glossinessMap = {
  30792. value: null
  30793. };
  30794. materialParams.vertexShader = shader.vertexShader;
  30795. materialParams.fragmentShader = fragmentShader;
  30796. materialParams.uniforms = uniforms;
  30797. materialParams.defines = {
  30798. 'STANDARD': ''
  30799. };
  30800. materialParams.color = new _threeModule.Color(1.0, 1.0, 1.0);
  30801. materialParams.opacity = 1.0;
  30802. var pending = [];
  30803. if (Array.isArray(pbrSpecularGlossiness.diffuseFactor)) {
  30804. var array = pbrSpecularGlossiness.diffuseFactor;
  30805. materialParams.color.fromArray(array);
  30806. materialParams.opacity = array[3];
  30807. }
  30808. if (pbrSpecularGlossiness.diffuseTexture !== undefined) {
  30809. pending.push(parser.assignTexture(materialParams, 'map', pbrSpecularGlossiness.diffuseTexture));
  30810. }
  30811. materialParams.emissive = new _threeModule.Color(0.0, 0.0, 0.0);
  30812. materialParams.glossiness = pbrSpecularGlossiness.glossinessFactor !== undefined ? pbrSpecularGlossiness.glossinessFactor : 1.0;
  30813. materialParams.specular = new _threeModule.Color(1.0, 1.0, 1.0);
  30814. if (Array.isArray(pbrSpecularGlossiness.specularFactor)) {
  30815. materialParams.specular.fromArray(pbrSpecularGlossiness.specularFactor);
  30816. }
  30817. if (pbrSpecularGlossiness.specularGlossinessTexture !== undefined) {
  30818. var specGlossMapDef = pbrSpecularGlossiness.specularGlossinessTexture;
  30819. pending.push(parser.assignTexture(materialParams, 'glossinessMap', specGlossMapDef));
  30820. pending.push(parser.assignTexture(materialParams, 'specularMap', specGlossMapDef));
  30821. }
  30822. return Promise.all(pending);
  30823. },
  30824. createMaterial: function (params) {
  30825. // setup material properties based on MeshStandardMaterial for Specular-Glossiness
  30826. var material = new _threeModule.ShaderMaterial({
  30827. defines: params.defines,
  30828. vertexShader: params.vertexShader,
  30829. fragmentShader: params.fragmentShader,
  30830. uniforms: params.uniforms,
  30831. fog: true,
  30832. lights: true,
  30833. opacity: params.opacity,
  30834. transparent: params.transparent
  30835. });
  30836. material.isGLTFSpecularGlossinessMaterial = true;
  30837. material.color = params.color;
  30838. material.map = params.map === undefined ? null : params.map;
  30839. material.lightMap = null;
  30840. material.lightMapIntensity = 1.0;
  30841. material.aoMap = params.aoMap === undefined ? null : params.aoMap;
  30842. material.aoMapIntensity = 1.0;
  30843. material.emissive = params.emissive;
  30844. material.emissiveIntensity = 1.0;
  30845. material.emissiveMap = params.emissiveMap === undefined ? null : params.emissiveMap;
  30846. material.bumpMap = params.bumpMap === undefined ? null : params.bumpMap;
  30847. material.bumpScale = 1;
  30848. material.normalMap = params.normalMap === undefined ? null : params.normalMap;
  30849. if (params.normalScale) material.normalScale = params.normalScale;
  30850. material.displacementMap = null;
  30851. material.displacementScale = 1;
  30852. material.displacementBias = 0;
  30853. material.specularMap = params.specularMap === undefined ? null : params.specularMap;
  30854. material.specular = params.specular;
  30855. material.glossinessMap = params.glossinessMap === undefined ? null : params.glossinessMap;
  30856. material.glossiness = params.glossiness;
  30857. material.alphaMap = null;
  30858. material.envMap = params.envMap === undefined ? null : params.envMap;
  30859. material.envMapIntensity = 1.0;
  30860. material.refractionRatio = 0.98;
  30861. material.extensions.derivatives = true;
  30862. return material;
  30863. },
  30864. /**
  30865. * Clones a GLTFSpecularGlossinessMaterial instance. The ShaderMaterial.copy() method can
  30866. * copy only properties it knows about or inherits, and misses many properties that would
  30867. * normally be defined by MeshStandardMaterial.
  30868. *
  30869. * This method allows GLTFSpecularGlossinessMaterials to be cloned in the process of
  30870. * loading a glTF model, but cloning later (e.g. by the user) would require these changes
  30871. * AND also updating `.onBeforeRender` on the parent mesh.
  30872. *
  30873. * @param {ShaderMaterial} source
  30874. * @return {ShaderMaterial}
  30875. */
  30876. cloneMaterial: function (source) {
  30877. var target = source.clone();
  30878. target.isGLTFSpecularGlossinessMaterial = true;
  30879. var params = this.specularGlossinessParams;
  30880. for (var i = 0, il = params.length; i < il; i++) {
  30881. var value = source[params[i]];
  30882. target[params[i]] = value && value.isColor ? value.clone() : value;
  30883. }
  30884. return target;
  30885. },
  30886. // Here's based on refreshUniformsCommon() and refreshUniformsStandard() in WebGLRenderer.
  30887. refreshUniforms: function (renderer, scene, camera, geometry, material) {
  30888. if (material.isGLTFSpecularGlossinessMaterial !== true) {
  30889. return;
  30890. }
  30891. var uniforms = material.uniforms;
  30892. var defines = material.defines;
  30893. uniforms.opacity.value = material.opacity;
  30894. uniforms.diffuse.value.copy(material.color);
  30895. uniforms.emissive.value.copy(material.emissive).multiplyScalar(material.emissiveIntensity);
  30896. uniforms.map.value = material.map;
  30897. uniforms.specularMap.value = material.specularMap;
  30898. uniforms.alphaMap.value = material.alphaMap;
  30899. uniforms.lightMap.value = material.lightMap;
  30900. uniforms.lightMapIntensity.value = material.lightMapIntensity;
  30901. uniforms.aoMap.value = material.aoMap;
  30902. uniforms.aoMapIntensity.value = material.aoMapIntensity; // uv repeat and offset setting priorities
  30903. // 1. color map
  30904. // 2. specular map
  30905. // 3. normal map
  30906. // 4. bump map
  30907. // 5. alpha map
  30908. // 6. emissive map
  30909. var uvScaleMap;
  30910. if (material.map) {
  30911. uvScaleMap = material.map;
  30912. } else if (material.specularMap) {
  30913. uvScaleMap = material.specularMap;
  30914. } else if (material.displacementMap) {
  30915. uvScaleMap = material.displacementMap;
  30916. } else if (material.normalMap) {
  30917. uvScaleMap = material.normalMap;
  30918. } else if (material.bumpMap) {
  30919. uvScaleMap = material.bumpMap;
  30920. } else if (material.glossinessMap) {
  30921. uvScaleMap = material.glossinessMap;
  30922. } else if (material.alphaMap) {
  30923. uvScaleMap = material.alphaMap;
  30924. } else if (material.emissiveMap) {
  30925. uvScaleMap = material.emissiveMap;
  30926. }
  30927. if (uvScaleMap !== undefined) {
  30928. // backwards compatibility
  30929. if (uvScaleMap.isWebGLRenderTarget) {
  30930. uvScaleMap = uvScaleMap.texture;
  30931. }
  30932. if (uvScaleMap.matrixAutoUpdate === true) {
  30933. uvScaleMap.updateMatrix();
  30934. }
  30935. uniforms.uvTransform.value.copy(uvScaleMap.matrix);
  30936. }
  30937. if (material.envMap) {
  30938. uniforms.envMap.value = material.envMap;
  30939. uniforms.envMapIntensity.value = material.envMapIntensity; // don't flip CubeTexture envMaps, flip everything else:
  30940. // WebGLRenderTargetCube will be flipped for backwards compatibility
  30941. // WebGLRenderTargetCube.texture will be flipped because it's a Texture and NOT a CubeTexture
  30942. // this check must be handled differently, or removed entirely, if WebGLRenderTargetCube uses a CubeTexture in the future
  30943. uniforms.flipEnvMap.value = material.envMap.isCubeTexture ? -1 : 1;
  30944. uniforms.reflectivity.value = material.reflectivity;
  30945. uniforms.refractionRatio.value = material.refractionRatio;
  30946. uniforms.maxMipLevel.value = renderer.properties.get(material.envMap).__maxMipLevel;
  30947. }
  30948. uniforms.specular.value.copy(material.specular);
  30949. uniforms.glossiness.value = material.glossiness;
  30950. uniforms.glossinessMap.value = material.glossinessMap;
  30951. uniforms.emissiveMap.value = material.emissiveMap;
  30952. uniforms.bumpMap.value = material.bumpMap;
  30953. uniforms.normalMap.value = material.normalMap;
  30954. uniforms.displacementMap.value = material.displacementMap;
  30955. uniforms.displacementScale.value = material.displacementScale;
  30956. uniforms.displacementBias.value = material.displacementBias;
  30957. if (uniforms.glossinessMap.value !== null && defines.USE_GLOSSINESSMAP === undefined) {
  30958. defines.USE_GLOSSINESSMAP = ''; // set USE_ROUGHNESSMAP to enable vUv
  30959. defines.USE_ROUGHNESSMAP = '';
  30960. }
  30961. if (uniforms.glossinessMap.value === null && defines.USE_GLOSSINESSMAP !== undefined) {
  30962. delete defines.USE_GLOSSINESSMAP;
  30963. delete defines.USE_ROUGHNESSMAP;
  30964. }
  30965. }
  30966. };
  30967. }
  30968. /*********************************/
  30969. /********** INTERPOLATION ********/
  30970. /*********************************/
  30971. // Spline Interpolation
  30972. // Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#appendix-c-spline-interpolation
  30973. function GLTFCubicSplineInterpolant(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  30974. _threeModule.Interpolant.call(this, parameterPositions, sampleValues, sampleSize, resultBuffer);
  30975. }
  30976. GLTFCubicSplineInterpolant.prototype = Object.create(_threeModule.Interpolant.prototype);
  30977. GLTFCubicSplineInterpolant.prototype.constructor = GLTFCubicSplineInterpolant;
  30978. GLTFCubicSplineInterpolant.prototype.copySampleValue_ = function (index) {
  30979. // Copies a sample value to the result buffer. See description of glTF
  30980. // CUBICSPLINE values layout in interpolate_() function below.
  30981. var result = this.resultBuffer,
  30982. values = this.sampleValues,
  30983. valueSize = this.valueSize,
  30984. offset = index * valueSize * 3 + valueSize;
  30985. for (var i = 0; i !== valueSize; i++) {
  30986. result[i] = values[offset + i];
  30987. }
  30988. return result;
  30989. };
  30990. GLTFCubicSplineInterpolant.prototype.beforeStart_ = GLTFCubicSplineInterpolant.prototype.copySampleValue_;
  30991. GLTFCubicSplineInterpolant.prototype.afterEnd_ = GLTFCubicSplineInterpolant.prototype.copySampleValue_;
  30992. GLTFCubicSplineInterpolant.prototype.interpolate_ = function (i1, t0, t, t1) {
  30993. var result = this.resultBuffer;
  30994. var values = this.sampleValues;
  30995. var stride = this.valueSize;
  30996. var stride2 = stride * 2;
  30997. var stride3 = stride * 3;
  30998. var td = t1 - t0;
  30999. var p = (t - t0) / td;
  31000. var pp = p * p;
  31001. var ppp = pp * p;
  31002. var offset1 = i1 * stride3;
  31003. var offset0 = offset1 - stride3;
  31004. var s2 = -2 * ppp + 3 * pp;
  31005. var s3 = ppp - pp;
  31006. var s0 = 1 - s2;
  31007. var s1 = s3 - pp + p; // Layout of keyframe output values for CUBICSPLINE animations:
  31008. // [ inTangent_1, splineVertex_1, outTangent_1, inTangent_2, splineVertex_2, ... ]
  31009. for (var i = 0; i !== stride; i++) {
  31010. var p0 = values[offset0 + i + stride]; // splineVertex_k
  31011. var m0 = values[offset0 + i + stride2] * td; // outTangent_k * (t_k+1 - t_k)
  31012. var p1 = values[offset1 + i + stride]; // splineVertex_k+1
  31013. var m1 = values[offset1 + i] * td; // inTangent_k+1 * (t_k+1 - t_k)
  31014. result[i] = s0 * p0 + s1 * m0 + s2 * p1 + s3 * m1;
  31015. }
  31016. return result;
  31017. };
  31018. /*********************************/
  31019. /********** INTERNALS ************/
  31020. /*********************************/
  31021. /* CONSTANTS */
  31022. var WEBGL_CONSTANTS = {
  31023. FLOAT: 5126,
  31024. //FLOAT_MAT2: 35674,
  31025. FLOAT_MAT3: 35675,
  31026. FLOAT_MAT4: 35676,
  31027. FLOAT_VEC2: 35664,
  31028. FLOAT_VEC3: 35665,
  31029. FLOAT_VEC4: 35666,
  31030. LINEAR: 9729,
  31031. REPEAT: 10497,
  31032. SAMPLER_2D: 35678,
  31033. POINTS: 0,
  31034. LINES: 1,
  31035. LINE_LOOP: 2,
  31036. LINE_STRIP: 3,
  31037. TRIANGLES: 4,
  31038. TRIANGLE_STRIP: 5,
  31039. TRIANGLE_FAN: 6,
  31040. UNSIGNED_BYTE: 5121,
  31041. UNSIGNED_SHORT: 5123
  31042. };
  31043. var WEBGL_COMPONENT_TYPES = {
  31044. 5120: Int8Array,
  31045. 5121: Uint8Array,
  31046. 5122: Int16Array,
  31047. 5123: Uint16Array,
  31048. 5125: Uint32Array,
  31049. 5126: Float32Array
  31050. };
  31051. var WEBGL_FILTERS = {
  31052. 9728: _threeModule.NearestFilter,
  31053. 9729: _threeModule.LinearFilter,
  31054. 9984: _threeModule.NearestMipmapNearestFilter,
  31055. 9985: _threeModule.LinearMipmapNearestFilter,
  31056. 9986: _threeModule.NearestMipmapLinearFilter,
  31057. 9987: _threeModule.LinearMipmapLinearFilter
  31058. };
  31059. var WEBGL_WRAPPINGS = {
  31060. 33071: _threeModule.ClampToEdgeWrapping,
  31061. 33648: _threeModule.MirroredRepeatWrapping,
  31062. 10497: _threeModule.RepeatWrapping
  31063. };
  31064. var WEBGL_TYPE_SIZES = {
  31065. 'SCALAR': 1,
  31066. 'VEC2': 2,
  31067. 'VEC3': 3,
  31068. 'VEC4': 4,
  31069. 'MAT2': 4,
  31070. 'MAT3': 9,
  31071. 'MAT4': 16
  31072. };
  31073. var ATTRIBUTES = {
  31074. POSITION: 'position',
  31075. NORMAL: 'normal',
  31076. TANGENT: 'tangent',
  31077. TEXCOORD_0: 'uv',
  31078. TEXCOORD_1: 'uv2',
  31079. COLOR_0: 'color',
  31080. WEIGHTS_0: 'skinWeight',
  31081. JOINTS_0: 'skinIndex'
  31082. };
  31083. var PATH_PROPERTIES = {
  31084. scale: 'scale',
  31085. translation: 'position',
  31086. rotation: 'quaternion',
  31087. weights: 'morphTargetInfluences'
  31088. };
  31089. var INTERPOLATION = {
  31090. CUBICSPLINE: undefined,
  31091. // We use a custom interpolant (GLTFCubicSplineInterpolation) for CUBICSPLINE tracks. Each
  31092. // keyframe track will be initialized with a default interpolation type, then modified.
  31093. LINEAR: _threeModule.InterpolateLinear,
  31094. STEP: _threeModule.InterpolateDiscrete
  31095. };
  31096. var ALPHA_MODES = {
  31097. OPAQUE: 'OPAQUE',
  31098. MASK: 'MASK',
  31099. BLEND: 'BLEND'
  31100. };
  31101. var MIME_TYPE_FORMATS = {
  31102. 'image/png': _threeModule.RGBAFormat,
  31103. 'image/jpeg': _threeModule.RGBFormat
  31104. };
  31105. /* UTILITY FUNCTIONS */
  31106. function resolveURL(url, path) {
  31107. // Invalid URL
  31108. if (typeof url !== 'string' || url === '') return ''; // Host Relative URL
  31109. if (/^https?:\/\//i.test(path) && /^\//.test(url)) {
  31110. path = path.replace(/(^https?:\/\/[^\/]+).*/i, '$1');
  31111. } // Absolute URL http://,https://,//
  31112. if (/^(https?:)?\/\//i.test(url)) return url; // Data URI
  31113. if (/^data:.*,.*$/i.test(url)) return url; // Blob URL
  31114. if (/^blob:.*$/i.test(url)) return url; // Relative URL
  31115. return path + url;
  31116. }
  31117. var defaultMaterial;
  31118. /**
  31119. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#default-material
  31120. */
  31121. function createDefaultMaterial() {
  31122. defaultMaterial = defaultMaterial || new _threeModule.MeshStandardMaterial({
  31123. color: 0xFFFFFF,
  31124. emissive: 0x000000,
  31125. metalness: 1,
  31126. roughness: 1,
  31127. transparent: false,
  31128. depthTest: true,
  31129. side: _threeModule.FrontSide
  31130. });
  31131. return defaultMaterial;
  31132. }
  31133. function addUnknownExtensionsToUserData(knownExtensions, object, objectDef) {
  31134. // Add unknown glTF extensions to an object's userData.
  31135. for (var name in objectDef.extensions) {
  31136. if (knownExtensions[name] === undefined) {
  31137. object.userData.gltfExtensions = object.userData.gltfExtensions || {};
  31138. object.userData.gltfExtensions[name] = objectDef.extensions[name];
  31139. }
  31140. }
  31141. }
  31142. /**
  31143. * @param {Object3D|Material|BufferGeometry} object
  31144. * @param {GLTF.definition} gltfDef
  31145. */
  31146. function assignExtrasToUserData(object, gltfDef) {
  31147. if (gltfDef.extras !== undefined) {
  31148. if (typeof gltfDef.extras === 'object') {
  31149. Object.assign(object.userData, gltfDef.extras);
  31150. } else {
  31151. console.warn('THREE.GLTFLoader: Ignoring primitive type .extras, ' + gltfDef.extras);
  31152. }
  31153. }
  31154. }
  31155. /**
  31156. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#morph-targets
  31157. *
  31158. * @param {BufferGeometry} geometry
  31159. * @param {Array<GLTF.Target>} targets
  31160. * @param {GLTFParser} parser
  31161. * @return {Promise<BufferGeometry>}
  31162. */
  31163. function addMorphTargets(geometry, targets, parser) {
  31164. var hasMorphPosition = false;
  31165. var hasMorphNormal = false;
  31166. for (var i = 0, il = targets.length; i < il; i++) {
  31167. var target = targets[i];
  31168. if (target.POSITION !== undefined) hasMorphPosition = true;
  31169. if (target.NORMAL !== undefined) hasMorphNormal = true;
  31170. if (hasMorphPosition && hasMorphNormal) break;
  31171. }
  31172. if (!hasMorphPosition && !hasMorphNormal) return Promise.resolve(geometry);
  31173. var pendingPositionAccessors = [];
  31174. var pendingNormalAccessors = [];
  31175. for (var i = 0, il = targets.length; i < il; i++) {
  31176. var target = targets[i];
  31177. if (hasMorphPosition) {
  31178. var pendingAccessor = target.POSITION !== undefined ? parser.getDependency('accessor', target.POSITION) : geometry.attributes.position;
  31179. pendingPositionAccessors.push(pendingAccessor);
  31180. }
  31181. if (hasMorphNormal) {
  31182. var pendingAccessor = target.NORMAL !== undefined ? parser.getDependency('accessor', target.NORMAL) : geometry.attributes.normal;
  31183. pendingNormalAccessors.push(pendingAccessor);
  31184. }
  31185. }
  31186. return Promise.all([Promise.all(pendingPositionAccessors), Promise.all(pendingNormalAccessors)]).then(function (accessors) {
  31187. var morphPositions = accessors[0];
  31188. var morphNormals = accessors[1]; // Clone morph target accessors before modifying them.
  31189. for (var i = 0, il = morphPositions.length; i < il; i++) {
  31190. if (geometry.attributes.position === morphPositions[i]) continue;
  31191. morphPositions[i] = cloneBufferAttribute(morphPositions[i]);
  31192. }
  31193. for (var i = 0, il = morphNormals.length; i < il; i++) {
  31194. if (geometry.attributes.normal === morphNormals[i]) continue;
  31195. morphNormals[i] = cloneBufferAttribute(morphNormals[i]);
  31196. }
  31197. for (var i = 0, il = targets.length; i < il; i++) {
  31198. var target = targets[i];
  31199. var attributeName = 'morphTarget' + i;
  31200. if (hasMorphPosition) {
  31201. // Three.js morph position is absolute value. The formula is
  31202. // basePosition
  31203. // + weight0 * ( morphPosition0 - basePosition )
  31204. // + weight1 * ( morphPosition1 - basePosition )
  31205. // ...
  31206. // while the glTF one is relative
  31207. // basePosition
  31208. // + weight0 * glTFmorphPosition0
  31209. // + weight1 * glTFmorphPosition1
  31210. // ...
  31211. // then we need to convert from relative to absolute here.
  31212. if (target.POSITION !== undefined) {
  31213. var positionAttribute = morphPositions[i];
  31214. positionAttribute.name = attributeName;
  31215. var position = geometry.attributes.position;
  31216. for (var j = 0, jl = positionAttribute.count; j < jl; j++) {
  31217. positionAttribute.setXYZ(j, positionAttribute.getX(j) + position.getX(j), positionAttribute.getY(j) + position.getY(j), positionAttribute.getZ(j) + position.getZ(j));
  31218. }
  31219. }
  31220. }
  31221. if (hasMorphNormal) {
  31222. // see target.POSITION's comment
  31223. if (target.NORMAL !== undefined) {
  31224. var normalAttribute = morphNormals[i];
  31225. normalAttribute.name = attributeName;
  31226. var normal = geometry.attributes.normal;
  31227. for (var j = 0, jl = normalAttribute.count; j < jl; j++) {
  31228. normalAttribute.setXYZ(j, normalAttribute.getX(j) + normal.getX(j), normalAttribute.getY(j) + normal.getY(j), normalAttribute.getZ(j) + normal.getZ(j));
  31229. }
  31230. }
  31231. }
  31232. }
  31233. if (hasMorphPosition) geometry.morphAttributes.position = morphPositions;
  31234. if (hasMorphNormal) geometry.morphAttributes.normal = morphNormals;
  31235. return geometry;
  31236. });
  31237. }
  31238. /**
  31239. * @param {Mesh} mesh
  31240. * @param {GLTF.Mesh} meshDef
  31241. */
  31242. function updateMorphTargets(mesh, meshDef) {
  31243. mesh.updateMorphTargets();
  31244. if (meshDef.weights !== undefined) {
  31245. for (var i = 0, il = meshDef.weights.length; i < il; i++) {
  31246. mesh.morphTargetInfluences[i] = meshDef.weights[i];
  31247. }
  31248. } // .extras has user-defined data, so check that .extras.targetNames is an array.
  31249. if (meshDef.extras && Array.isArray(meshDef.extras.targetNames)) {
  31250. var targetNames = meshDef.extras.targetNames;
  31251. if (mesh.morphTargetInfluences.length === targetNames.length) {
  31252. mesh.morphTargetDictionary = {};
  31253. for (var i = 0, il = targetNames.length; i < il; i++) {
  31254. mesh.morphTargetDictionary[targetNames[i]] = i;
  31255. }
  31256. } else {
  31257. console.warn('THREE.GLTFLoader: Invalid extras.targetNames length. Ignoring names.');
  31258. }
  31259. }
  31260. }
  31261. function createPrimitiveKey(primitiveDef) {
  31262. var dracoExtension = primitiveDef.extensions && primitiveDef.extensions[EXTENSIONS.KHR_DRACO_MESH_COMPRESSION];
  31263. var geometryKey;
  31264. if (dracoExtension) {
  31265. geometryKey = 'draco:' + dracoExtension.bufferView + ':' + dracoExtension.indices + ':' + createAttributesKey(dracoExtension.attributes);
  31266. } else {
  31267. geometryKey = primitiveDef.indices + ':' + createAttributesKey(primitiveDef.attributes) + ':' + primitiveDef.mode;
  31268. }
  31269. return geometryKey;
  31270. }
  31271. function createAttributesKey(attributes) {
  31272. var attributesKey = '';
  31273. var keys = Object.keys(attributes).sort();
  31274. for (var i = 0, il = keys.length; i < il; i++) {
  31275. attributesKey += keys[i] + ':' + attributes[keys[i]] + ';';
  31276. }
  31277. return attributesKey;
  31278. }
  31279. function cloneBufferAttribute(attribute) {
  31280. if (attribute.isInterleavedBufferAttribute) {
  31281. var count = attribute.count;
  31282. var itemSize = attribute.itemSize;
  31283. var array = attribute.array.slice(0, count * itemSize);
  31284. for (var i = 0, j = 0; i < count; ++i) {
  31285. array[j++] = attribute.getX(i);
  31286. if (itemSize >= 2) array[j++] = attribute.getY(i);
  31287. if (itemSize >= 3) array[j++] = attribute.getZ(i);
  31288. if (itemSize >= 4) array[j++] = attribute.getW(i);
  31289. }
  31290. return new _threeModule.BufferAttribute(array, itemSize, attribute.normalized);
  31291. }
  31292. return attribute.clone();
  31293. }
  31294. /* GLTF PARSER */
  31295. function GLTFParser(json, extensions, options) {
  31296. this.json = json || {};
  31297. this.extensions = extensions || {};
  31298. this.options = options || {}; // loader object cache
  31299. this.cache = new GLTFRegistry(); // BufferGeometry caching
  31300. this.primitiveCache = {};
  31301. this.textureLoader = new _threeModule.TextureLoader(this.options.manager);
  31302. this.textureLoader.setCrossOrigin(this.options.crossOrigin);
  31303. this.fileLoader = new _threeModule.FileLoader(this.options.manager);
  31304. this.fileLoader.setResponseType('arraybuffer');
  31305. if (this.options.crossOrigin === 'use-credentials') {
  31306. this.fileLoader.setWithCredentials(true);
  31307. }
  31308. }
  31309. GLTFParser.prototype.parse = function (onLoad, onError) {
  31310. var parser = this;
  31311. var json = this.json;
  31312. var extensions = this.extensions; // Clear the loader cache
  31313. this.cache.removeAll(); // Mark the special nodes/meshes in json for efficient parse
  31314. this.markDefs();
  31315. Promise.all([this.getDependencies('scene'), this.getDependencies('animation'), this.getDependencies('camera')]).then(function (dependencies) {
  31316. var result = {
  31317. scene: dependencies[0][json.scene || 0],
  31318. scenes: dependencies[0],
  31319. animations: dependencies[1],
  31320. cameras: dependencies[2],
  31321. asset: json.asset,
  31322. parser: parser,
  31323. userData: {}
  31324. };
  31325. addUnknownExtensionsToUserData(extensions, result, json);
  31326. assignExtrasToUserData(result, json);
  31327. onLoad(result);
  31328. }).catch(onError);
  31329. };
  31330. /**
  31331. * Marks the special nodes/meshes in json for efficient parse.
  31332. */
  31333. GLTFParser.prototype.markDefs = function () {
  31334. var nodeDefs = this.json.nodes || [];
  31335. var skinDefs = this.json.skins || [];
  31336. var meshDefs = this.json.meshes || [];
  31337. var meshReferences = {};
  31338. var meshUses = {}; // Nothing in the node definition indicates whether it is a Bone or an
  31339. // Object3D. Use the skins' joint references to mark bones.
  31340. for (var skinIndex = 0, skinLength = skinDefs.length; skinIndex < skinLength; skinIndex++) {
  31341. var joints = skinDefs[skinIndex].joints;
  31342. for (var i = 0, il = joints.length; i < il; i++) {
  31343. nodeDefs[joints[i]].isBone = true;
  31344. }
  31345. } // Meshes can (and should) be reused by multiple nodes in a glTF asset. To
  31346. // avoid having more than one Mesh with the same name, count
  31347. // references and rename instances below.
  31348. //
  31349. // Example: CesiumMilkTruck sample model reuses "Wheel" meshes.
  31350. for (var nodeIndex = 0, nodeLength = nodeDefs.length; nodeIndex < nodeLength; nodeIndex++) {
  31351. var nodeDef = nodeDefs[nodeIndex];
  31352. if (nodeDef.mesh !== undefined) {
  31353. if (meshReferences[nodeDef.mesh] === undefined) {
  31354. meshReferences[nodeDef.mesh] = meshUses[nodeDef.mesh] = 0;
  31355. }
  31356. meshReferences[nodeDef.mesh]++; // Nothing in the mesh definition indicates whether it is
  31357. // a SkinnedMesh or Mesh. Use the node's mesh reference
  31358. // to mark SkinnedMesh if node has skin.
  31359. if (nodeDef.skin !== undefined) {
  31360. meshDefs[nodeDef.mesh].isSkinnedMesh = true;
  31361. }
  31362. }
  31363. }
  31364. this.json.meshReferences = meshReferences;
  31365. this.json.meshUses = meshUses;
  31366. };
  31367. /**
  31368. * Requests the specified dependency asynchronously, with caching.
  31369. * @param {string} type
  31370. * @param {number} index
  31371. * @return {Promise<Object3D|Material|THREE.Texture|AnimationClip|ArrayBuffer|Object>}
  31372. */
  31373. GLTFParser.prototype.getDependency = function (type, index) {
  31374. var cacheKey = type + ':' + index;
  31375. var dependency = this.cache.get(cacheKey);
  31376. if (!dependency) {
  31377. switch (type) {
  31378. case 'scene':
  31379. dependency = this.loadScene(index);
  31380. break;
  31381. case 'node':
  31382. dependency = this.loadNode(index);
  31383. break;
  31384. case 'mesh':
  31385. dependency = this.loadMesh(index);
  31386. break;
  31387. case 'accessor':
  31388. dependency = this.loadAccessor(index);
  31389. break;
  31390. case 'bufferView':
  31391. dependency = this.loadBufferView(index);
  31392. break;
  31393. case 'buffer':
  31394. dependency = this.loadBuffer(index);
  31395. break;
  31396. case 'material':
  31397. dependency = this.loadMaterial(index);
  31398. break;
  31399. case 'texture':
  31400. dependency = this.loadTexture(index);
  31401. break;
  31402. case 'skin':
  31403. dependency = this.loadSkin(index);
  31404. break;
  31405. case 'animation':
  31406. dependency = this.loadAnimation(index);
  31407. break;
  31408. case 'camera':
  31409. dependency = this.loadCamera(index);
  31410. break;
  31411. case 'light':
  31412. dependency = this.extensions[EXTENSIONS.KHR_LIGHTS_PUNCTUAL].loadLight(index);
  31413. break;
  31414. default:
  31415. throw new Error('Unknown type: ' + type);
  31416. }
  31417. this.cache.add(cacheKey, dependency);
  31418. }
  31419. return dependency;
  31420. };
  31421. /**
  31422. * Requests all dependencies of the specified type asynchronously, with caching.
  31423. * @param {string} type
  31424. * @return {Promise<Array<Object>>}
  31425. */
  31426. GLTFParser.prototype.getDependencies = function (type) {
  31427. var dependencies = this.cache.get(type);
  31428. if (!dependencies) {
  31429. var parser = this;
  31430. var defs = this.json[type + (type === 'mesh' ? 'es' : 's')] || [];
  31431. dependencies = Promise.all(defs.map(function (def, index) {
  31432. return parser.getDependency(type, index);
  31433. }));
  31434. this.cache.add(type, dependencies);
  31435. }
  31436. return dependencies;
  31437. };
  31438. /**
  31439. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#buffers-and-buffer-views
  31440. * @param {number} bufferIndex
  31441. * @return {Promise<ArrayBuffer>}
  31442. */
  31443. GLTFParser.prototype.loadBuffer = function (bufferIndex) {
  31444. var bufferDef = this.json.buffers[bufferIndex];
  31445. var loader = this.fileLoader;
  31446. if (bufferDef.type && bufferDef.type !== 'arraybuffer') {
  31447. throw new Error('THREE.GLTFLoader: ' + bufferDef.type + ' buffer type is not supported.');
  31448. } // If present, GLB container is required to be the first buffer.
  31449. if (bufferDef.uri === undefined && bufferIndex === 0) {
  31450. return Promise.resolve(this.extensions[EXTENSIONS.KHR_BINARY_GLTF].body);
  31451. }
  31452. var options = this.options;
  31453. return new Promise(function (resolve, reject) {
  31454. loader.load(resolveURL(bufferDef.uri, options.path), resolve, undefined, function () {
  31455. reject(new Error('THREE.GLTFLoader: Failed to load buffer "' + bufferDef.uri + '".'));
  31456. });
  31457. });
  31458. };
  31459. /**
  31460. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#buffers-and-buffer-views
  31461. * @param {number} bufferViewIndex
  31462. * @return {Promise<ArrayBuffer>}
  31463. */
  31464. GLTFParser.prototype.loadBufferView = function (bufferViewIndex) {
  31465. var bufferViewDef = this.json.bufferViews[bufferViewIndex];
  31466. return this.getDependency('buffer', bufferViewDef.buffer).then(function (buffer) {
  31467. var byteLength = bufferViewDef.byteLength || 0;
  31468. var byteOffset = bufferViewDef.byteOffset || 0;
  31469. return buffer.slice(byteOffset, byteOffset + byteLength);
  31470. });
  31471. };
  31472. /**
  31473. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#accessors
  31474. * @param {number} accessorIndex
  31475. * @return {Promise<BufferAttribute|InterleavedBufferAttribute>}
  31476. */
  31477. GLTFParser.prototype.loadAccessor = function (accessorIndex) {
  31478. var parser = this;
  31479. var json = this.json;
  31480. var accessorDef = this.json.accessors[accessorIndex];
  31481. if (accessorDef.bufferView === undefined && accessorDef.sparse === undefined) {
  31482. // Ignore empty accessors, which may be used to declare runtime
  31483. // information about attributes coming from another source (e.g. Draco
  31484. // compression extension).
  31485. return Promise.resolve(null);
  31486. }
  31487. var pendingBufferViews = [];
  31488. if (accessorDef.bufferView !== undefined) {
  31489. pendingBufferViews.push(this.getDependency('bufferView', accessorDef.bufferView));
  31490. } else {
  31491. pendingBufferViews.push(null);
  31492. }
  31493. if (accessorDef.sparse !== undefined) {
  31494. pendingBufferViews.push(this.getDependency('bufferView', accessorDef.sparse.indices.bufferView));
  31495. pendingBufferViews.push(this.getDependency('bufferView', accessorDef.sparse.values.bufferView));
  31496. }
  31497. return Promise.all(pendingBufferViews).then(function (bufferViews) {
  31498. var bufferView = bufferViews[0];
  31499. var itemSize = WEBGL_TYPE_SIZES[accessorDef.type];
  31500. var TypedArray = WEBGL_COMPONENT_TYPES[accessorDef.componentType]; // For VEC3: itemSize is 3, elementBytes is 4, itemBytes is 12.
  31501. var elementBytes = TypedArray.BYTES_PER_ELEMENT;
  31502. var itemBytes = elementBytes * itemSize;
  31503. var byteOffset = accessorDef.byteOffset || 0;
  31504. var byteStride = accessorDef.bufferView !== undefined ? json.bufferViews[accessorDef.bufferView].byteStride : undefined;
  31505. var normalized = accessorDef.normalized === true;
  31506. var array, bufferAttribute; // The buffer is not interleaved if the stride is the item size in bytes.
  31507. if (byteStride && byteStride !== itemBytes) {
  31508. // Each "slice" of the buffer, as defined by 'count' elements of 'byteStride' bytes, gets its own InterleavedBuffer
  31509. // This makes sure that IBA.count reflects accessor.count properly
  31510. var ibSlice = Math.floor(byteOffset / byteStride);
  31511. var ibCacheKey = 'InterleavedBuffer:' + accessorDef.bufferView + ':' + accessorDef.componentType + ':' + ibSlice + ':' + accessorDef.count;
  31512. var ib = parser.cache.get(ibCacheKey);
  31513. if (!ib) {
  31514. array = new TypedArray(bufferView, ibSlice * byteStride, accessorDef.count * byteStride / elementBytes); // Integer parameters to IB/IBA are in array elements, not bytes.
  31515. ib = new _threeModule.InterleavedBuffer(array, byteStride / elementBytes);
  31516. parser.cache.add(ibCacheKey, ib);
  31517. }
  31518. bufferAttribute = new _threeModule.InterleavedBufferAttribute(ib, itemSize, byteOffset % byteStride / elementBytes, normalized);
  31519. } else {
  31520. if (bufferView === null) {
  31521. array = new TypedArray(accessorDef.count * itemSize);
  31522. } else {
  31523. array = new TypedArray(bufferView, byteOffset, accessorDef.count * itemSize);
  31524. }
  31525. bufferAttribute = new _threeModule.BufferAttribute(array, itemSize, normalized);
  31526. } // https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#sparse-accessors
  31527. if (accessorDef.sparse !== undefined) {
  31528. var itemSizeIndices = WEBGL_TYPE_SIZES.SCALAR;
  31529. var TypedArrayIndices = WEBGL_COMPONENT_TYPES[accessorDef.sparse.indices.componentType];
  31530. var byteOffsetIndices = accessorDef.sparse.indices.byteOffset || 0;
  31531. var byteOffsetValues = accessorDef.sparse.values.byteOffset || 0;
  31532. var sparseIndices = new TypedArrayIndices(bufferViews[1], byteOffsetIndices, accessorDef.sparse.count * itemSizeIndices);
  31533. var sparseValues = new TypedArray(bufferViews[2], byteOffsetValues, accessorDef.sparse.count * itemSize);
  31534. if (bufferView !== null) {
  31535. // Avoid modifying the original ArrayBuffer, if the bufferView wasn't initialized with zeroes.
  31536. bufferAttribute = new _threeModule.BufferAttribute(bufferAttribute.array.slice(), bufferAttribute.itemSize, bufferAttribute.normalized);
  31537. }
  31538. for (var i = 0, il = sparseIndices.length; i < il; i++) {
  31539. var index = sparseIndices[i];
  31540. bufferAttribute.setX(index, sparseValues[i * itemSize]);
  31541. if (itemSize >= 2) bufferAttribute.setY(index, sparseValues[i * itemSize + 1]);
  31542. if (itemSize >= 3) bufferAttribute.setZ(index, sparseValues[i * itemSize + 2]);
  31543. if (itemSize >= 4) bufferAttribute.setW(index, sparseValues[i * itemSize + 3]);
  31544. if (itemSize >= 5) throw new Error('THREE.GLTFLoader: Unsupported itemSize in sparse BufferAttribute.');
  31545. }
  31546. }
  31547. return bufferAttribute;
  31548. });
  31549. };
  31550. /**
  31551. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#textures
  31552. * @param {number} textureIndex
  31553. * @return {Promise<THREE.Texture>}
  31554. */
  31555. GLTFParser.prototype.loadTexture = function (textureIndex) {
  31556. var parser = this;
  31557. var json = this.json;
  31558. var options = this.options;
  31559. var textureLoader = this.textureLoader;
  31560. var URL = window.URL || window.webkitURL;
  31561. var textureDef = json.textures[textureIndex];
  31562. var textureExtensions = textureDef.extensions || {};
  31563. var source;
  31564. if (textureExtensions[EXTENSIONS.MSFT_TEXTURE_DDS]) {
  31565. source = json.images[textureExtensions[EXTENSIONS.MSFT_TEXTURE_DDS].source];
  31566. } else {
  31567. source = json.images[textureDef.source];
  31568. }
  31569. var sourceURI = source.uri;
  31570. var isObjectURL = false;
  31571. if (source.bufferView !== undefined) {
  31572. // Load binary image data from bufferView, if provided.
  31573. sourceURI = parser.getDependency('bufferView', source.bufferView).then(function (bufferView) {
  31574. isObjectURL = true;
  31575. var blob = new Blob([bufferView], {
  31576. type: source.mimeType
  31577. });
  31578. sourceURI = URL.createObjectURL(blob);
  31579. return sourceURI;
  31580. });
  31581. }
  31582. return Promise.resolve(sourceURI).then(function (sourceURI) {
  31583. // Load Texture resource.
  31584. var loader = options.manager.getHandler(sourceURI);
  31585. if (!loader) {
  31586. loader = textureExtensions[EXTENSIONS.MSFT_TEXTURE_DDS] ? parser.extensions[EXTENSIONS.MSFT_TEXTURE_DDS].ddsLoader : textureLoader;
  31587. }
  31588. return new Promise(function (resolve, reject) {
  31589. loader.load(resolveURL(sourceURI, options.path), resolve, undefined, reject);
  31590. });
  31591. }).then(function (texture) {
  31592. // Clean up resources and configure Texture.
  31593. if (isObjectURL === true) {
  31594. URL.revokeObjectURL(sourceURI);
  31595. }
  31596. texture.flipY = false;
  31597. if (textureDef.name !== undefined) texture.name = textureDef.name; // Ignore unknown mime types, like DDS files.
  31598. if (source.mimeType in MIME_TYPE_FORMATS) {
  31599. texture.format = MIME_TYPE_FORMATS[source.mimeType];
  31600. }
  31601. var samplers = json.samplers || {};
  31602. var sampler = samplers[textureDef.sampler] || {};
  31603. texture.magFilter = WEBGL_FILTERS[sampler.magFilter] || _threeModule.LinearFilter;
  31604. texture.minFilter = WEBGL_FILTERS[sampler.minFilter] || _threeModule.LinearMipmapLinearFilter;
  31605. texture.wrapS = WEBGL_WRAPPINGS[sampler.wrapS] || _threeModule.RepeatWrapping;
  31606. texture.wrapT = WEBGL_WRAPPINGS[sampler.wrapT] || _threeModule.RepeatWrapping;
  31607. return texture;
  31608. });
  31609. };
  31610. /**
  31611. * Asynchronously assigns a texture to the given material parameters.
  31612. * @param {Object} materialParams
  31613. * @param {string} mapName
  31614. * @param {Object} mapDef
  31615. * @return {Promise}
  31616. */
  31617. GLTFParser.prototype.assignTexture = function (materialParams, mapName, mapDef) {
  31618. var parser = this;
  31619. return this.getDependency('texture', mapDef.index).then(function (texture) {
  31620. if (!texture.isCompressedTexture) {
  31621. switch (mapName) {
  31622. case 'aoMap':
  31623. case 'emissiveMap':
  31624. case 'metalnessMap':
  31625. case 'normalMap':
  31626. case 'roughnessMap':
  31627. texture.format = _threeModule.RGBFormat;
  31628. break;
  31629. }
  31630. }
  31631. if (parser.extensions[EXTENSIONS.KHR_TEXTURE_TRANSFORM]) {
  31632. var transform = mapDef.extensions !== undefined ? mapDef.extensions[EXTENSIONS.KHR_TEXTURE_TRANSFORM] : undefined;
  31633. if (transform) {
  31634. texture = parser.extensions[EXTENSIONS.KHR_TEXTURE_TRANSFORM].extendTexture(texture, transform);
  31635. }
  31636. }
  31637. materialParams[mapName] = texture;
  31638. });
  31639. };
  31640. /**
  31641. * Assigns final material to a Mesh, Line, or Points instance. The instance
  31642. * already has a material (generated from the glTF material options alone)
  31643. * but reuse of the same glTF material may require multiple threejs materials
  31644. * to accomodate different primitive types, defines, etc. New materials will
  31645. * be created if necessary, and reused from a cache.
  31646. * @param {Object3D} mesh Mesh, Line, or Points instance.
  31647. */
  31648. GLTFParser.prototype.assignFinalMaterial = function (mesh) {
  31649. var geometry = mesh.geometry;
  31650. var material = mesh.material;
  31651. var extensions = this.extensions;
  31652. var useVertexTangents = geometry.attributes.tangent !== undefined;
  31653. var useVertexColors = geometry.attributes.color !== undefined;
  31654. var useFlatShading = geometry.attributes.normal === undefined;
  31655. var useSkinning = mesh.isSkinnedMesh === true;
  31656. var useMorphTargets = Object.keys(geometry.morphAttributes).length > 0;
  31657. var useMorphNormals = useMorphTargets && geometry.morphAttributes.normal !== undefined;
  31658. if (mesh.isPoints) {
  31659. var cacheKey = 'PointsMaterial:' + material.uuid;
  31660. var pointsMaterial = this.cache.get(cacheKey);
  31661. if (!pointsMaterial) {
  31662. pointsMaterial = new _threeModule.PointsMaterial();
  31663. _threeModule.Material.prototype.copy.call(pointsMaterial, material);
  31664. pointsMaterial.color.copy(material.color);
  31665. pointsMaterial.map = material.map;
  31666. pointsMaterial.sizeAttenuation = false; // glTF spec says points should be 1px
  31667. this.cache.add(cacheKey, pointsMaterial);
  31668. }
  31669. material = pointsMaterial;
  31670. } else if (mesh.isLine) {
  31671. var cacheKey = 'LineBasicMaterial:' + material.uuid;
  31672. var lineMaterial = this.cache.get(cacheKey);
  31673. if (!lineMaterial) {
  31674. lineMaterial = new _threeModule.LineBasicMaterial();
  31675. _threeModule.Material.prototype.copy.call(lineMaterial, material);
  31676. lineMaterial.color.copy(material.color);
  31677. this.cache.add(cacheKey, lineMaterial);
  31678. }
  31679. material = lineMaterial;
  31680. } // Clone the material if it will be modified
  31681. if (useVertexTangents || useVertexColors || useFlatShading || useSkinning || useMorphTargets) {
  31682. var cacheKey = 'ClonedMaterial:' + material.uuid + ':';
  31683. if (material.isGLTFSpecularGlossinessMaterial) cacheKey += 'specular-glossiness:';
  31684. if (useSkinning) cacheKey += 'skinning:';
  31685. if (useVertexTangents) cacheKey += 'vertex-tangents:';
  31686. if (useVertexColors) cacheKey += 'vertex-colors:';
  31687. if (useFlatShading) cacheKey += 'flat-shading:';
  31688. if (useMorphTargets) cacheKey += 'morph-targets:';
  31689. if (useMorphNormals) cacheKey += 'morph-normals:';
  31690. var cachedMaterial = this.cache.get(cacheKey);
  31691. if (!cachedMaterial) {
  31692. cachedMaterial = material.isGLTFSpecularGlossinessMaterial ? extensions[EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS].cloneMaterial(material) : material.clone();
  31693. if (useSkinning) cachedMaterial.skinning = true;
  31694. if (useVertexTangents) cachedMaterial.vertexTangents = true;
  31695. if (useVertexColors) cachedMaterial.vertexColors = _threeModule.VertexColors;
  31696. if (useFlatShading) cachedMaterial.flatShading = true;
  31697. if (useMorphTargets) cachedMaterial.morphTargets = true;
  31698. if (useMorphNormals) cachedMaterial.morphNormals = true;
  31699. this.cache.add(cacheKey, cachedMaterial);
  31700. }
  31701. material = cachedMaterial;
  31702. } // workarounds for mesh and geometry
  31703. if (material.aoMap && geometry.attributes.uv2 === undefined && geometry.attributes.uv !== undefined) {
  31704. console.log('THREE.GLTFLoader: Duplicating UVs to support aoMap.');
  31705. geometry.addAttribute('uv2', new _threeModule.BufferAttribute(geometry.attributes.uv.array, 2));
  31706. }
  31707. if (material.isGLTFSpecularGlossinessMaterial) {
  31708. // for GLTFSpecularGlossinessMaterial(ShaderMaterial) uniforms runtime update
  31709. mesh.onBeforeRender = extensions[EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS].refreshUniforms;
  31710. }
  31711. mesh.material = material;
  31712. };
  31713. /**
  31714. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#materials
  31715. * @param {number} materialIndex
  31716. * @return {Promise<Material>}
  31717. */
  31718. GLTFParser.prototype.loadMaterial = function (materialIndex) {
  31719. var parser = this;
  31720. var json = this.json;
  31721. var extensions = this.extensions;
  31722. var materialDef = json.materials[materialIndex];
  31723. var materialType;
  31724. var materialParams = {};
  31725. var materialExtensions = materialDef.extensions || {};
  31726. var pending = [];
  31727. if (materialExtensions[EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS]) {
  31728. var sgExtension = extensions[EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS];
  31729. materialType = sgExtension.getMaterialType();
  31730. pending.push(sgExtension.extendParams(materialParams, materialDef, parser));
  31731. } else if (materialExtensions[EXTENSIONS.KHR_MATERIALS_UNLIT]) {
  31732. var kmuExtension = extensions[EXTENSIONS.KHR_MATERIALS_UNLIT];
  31733. materialType = kmuExtension.getMaterialType();
  31734. pending.push(kmuExtension.extendParams(materialParams, materialDef, parser));
  31735. } else {
  31736. // Specification:
  31737. // https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#metallic-roughness-material
  31738. materialType = _threeModule.MeshStandardMaterial;
  31739. var metallicRoughness = materialDef.pbrMetallicRoughness || {};
  31740. materialParams.color = new _threeModule.Color(1.0, 1.0, 1.0);
  31741. materialParams.opacity = 1.0;
  31742. if (Array.isArray(metallicRoughness.baseColorFactor)) {
  31743. var array = metallicRoughness.baseColorFactor;
  31744. materialParams.color.fromArray(array);
  31745. materialParams.opacity = array[3];
  31746. }
  31747. if (metallicRoughness.baseColorTexture !== undefined) {
  31748. pending.push(parser.assignTexture(materialParams, 'map', metallicRoughness.baseColorTexture));
  31749. }
  31750. materialParams.metalness = metallicRoughness.metallicFactor !== undefined ? metallicRoughness.metallicFactor : 1.0;
  31751. materialParams.roughness = metallicRoughness.roughnessFactor !== undefined ? metallicRoughness.roughnessFactor : 1.0;
  31752. if (metallicRoughness.metallicRoughnessTexture !== undefined) {
  31753. pending.push(parser.assignTexture(materialParams, 'metalnessMap', metallicRoughness.metallicRoughnessTexture));
  31754. pending.push(parser.assignTexture(materialParams, 'roughnessMap', metallicRoughness.metallicRoughnessTexture));
  31755. }
  31756. }
  31757. if (materialDef.doubleSided === true) {
  31758. materialParams.side = _threeModule.DoubleSide;
  31759. }
  31760. var alphaMode = materialDef.alphaMode || ALPHA_MODES.OPAQUE;
  31761. if (alphaMode === ALPHA_MODES.BLEND) {
  31762. materialParams.transparent = true;
  31763. } else {
  31764. materialParams.transparent = false;
  31765. if (alphaMode === ALPHA_MODES.MASK) {
  31766. materialParams.alphaTest = materialDef.alphaCutoff !== undefined ? materialDef.alphaCutoff : 0.5;
  31767. }
  31768. }
  31769. if (materialDef.normalTexture !== undefined && materialType !== _threeModule.MeshBasicMaterial) {
  31770. pending.push(parser.assignTexture(materialParams, 'normalMap', materialDef.normalTexture));
  31771. materialParams.normalScale = new _threeModule.Vector2(1, 1);
  31772. if (materialDef.normalTexture.scale !== undefined) {
  31773. materialParams.normalScale.set(materialDef.normalTexture.scale, materialDef.normalTexture.scale);
  31774. }
  31775. }
  31776. if (materialDef.occlusionTexture !== undefined && materialType !== _threeModule.MeshBasicMaterial) {
  31777. pending.push(parser.assignTexture(materialParams, 'aoMap', materialDef.occlusionTexture));
  31778. if (materialDef.occlusionTexture.strength !== undefined) {
  31779. materialParams.aoMapIntensity = materialDef.occlusionTexture.strength;
  31780. }
  31781. }
  31782. if (materialDef.emissiveFactor !== undefined && materialType !== _threeModule.MeshBasicMaterial) {
  31783. materialParams.emissive = new _threeModule.Color().fromArray(materialDef.emissiveFactor);
  31784. }
  31785. if (materialDef.emissiveTexture !== undefined && materialType !== _threeModule.MeshBasicMaterial) {
  31786. pending.push(parser.assignTexture(materialParams, 'emissiveMap', materialDef.emissiveTexture));
  31787. }
  31788. return Promise.all(pending).then(function () {
  31789. var material;
  31790. if (materialType === _threeModule.ShaderMaterial) {
  31791. material = extensions[EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS].createMaterial(materialParams);
  31792. } else {
  31793. material = new materialType(materialParams);
  31794. }
  31795. if (materialDef.name !== undefined) material.name = materialDef.name; // baseColorTexture, emissiveTexture, and specularGlossinessTexture use sRGB encoding.
  31796. if (material.map) material.map.encoding = _threeModule.sRGBEncoding;
  31797. if (material.emissiveMap) material.emissiveMap.encoding = _threeModule.sRGBEncoding;
  31798. if (material.specularMap) material.specularMap.encoding = _threeModule.sRGBEncoding;
  31799. assignExtrasToUserData(material, materialDef);
  31800. if (materialDef.extensions) addUnknownExtensionsToUserData(extensions, material, materialDef);
  31801. return material;
  31802. });
  31803. };
  31804. /**
  31805. * @param {BufferGeometry} geometry
  31806. * @param {GLTF.Primitive} primitiveDef
  31807. * @param {GLTFParser} parser
  31808. * @return {Promise<BufferGeometry>}
  31809. */
  31810. function addPrimitiveAttributes(geometry, primitiveDef, parser) {
  31811. var attributes = primitiveDef.attributes;
  31812. var pending = [];
  31813. function assignAttributeAccessor(accessorIndex, attributeName) {
  31814. return parser.getDependency('accessor', accessorIndex).then(function (accessor) {
  31815. geometry.addAttribute(attributeName, accessor);
  31816. });
  31817. }
  31818. for (var gltfAttributeName in attributes) {
  31819. var threeAttributeName = ATTRIBUTES[gltfAttributeName] || gltfAttributeName.toLowerCase(); // Skip attributes already provided by e.g. Draco extension.
  31820. if (threeAttributeName in geometry.attributes) continue;
  31821. pending.push(assignAttributeAccessor(attributes[gltfAttributeName], threeAttributeName));
  31822. }
  31823. if (primitiveDef.indices !== undefined && !geometry.index) {
  31824. var accessor = parser.getDependency('accessor', primitiveDef.indices).then(function (accessor) {
  31825. geometry.setIndex(accessor);
  31826. });
  31827. pending.push(accessor);
  31828. }
  31829. assignExtrasToUserData(geometry, primitiveDef);
  31830. return Promise.all(pending).then(function () {
  31831. return primitiveDef.targets !== undefined ? addMorphTargets(geometry, primitiveDef.targets, parser) : geometry;
  31832. });
  31833. }
  31834. /**
  31835. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#geometry
  31836. *
  31837. * Creates BufferGeometries from primitives.
  31838. *
  31839. * @param {Array<GLTF.Primitive>} primitives
  31840. * @return {Promise<Array<BufferGeometry>>}
  31841. */
  31842. GLTFParser.prototype.loadGeometries = function (primitives) {
  31843. var parser = this;
  31844. var extensions = this.extensions;
  31845. var cache = this.primitiveCache;
  31846. function createDracoPrimitive(primitive) {
  31847. return extensions[EXTENSIONS.KHR_DRACO_MESH_COMPRESSION].decodePrimitive(primitive, parser).then(function (geometry) {
  31848. return addPrimitiveAttributes(geometry, primitive, parser);
  31849. });
  31850. }
  31851. var pending = [];
  31852. for (var i = 0, il = primitives.length; i < il; i++) {
  31853. var primitive = primitives[i];
  31854. var cacheKey = createPrimitiveKey(primitive); // See if we've already created this geometry
  31855. var cached = cache[cacheKey];
  31856. if (cached) {
  31857. // Use the cached geometry if it exists
  31858. pending.push(cached.promise);
  31859. } else {
  31860. var geometryPromise;
  31861. if (primitive.extensions && primitive.extensions[EXTENSIONS.KHR_DRACO_MESH_COMPRESSION]) {
  31862. // Use DRACO geometry if available
  31863. geometryPromise = createDracoPrimitive(primitive);
  31864. } else {
  31865. // Otherwise create a new geometry
  31866. geometryPromise = addPrimitiveAttributes(new _threeModule.BufferGeometry(), primitive, parser);
  31867. } // Cache this geometry
  31868. cache[cacheKey] = {
  31869. primitive: primitive,
  31870. promise: geometryPromise
  31871. };
  31872. pending.push(geometryPromise);
  31873. }
  31874. }
  31875. return Promise.all(pending);
  31876. };
  31877. /**
  31878. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#meshes
  31879. * @param {number} meshIndex
  31880. * @return {Promise<Group|Mesh|SkinnedMesh>}
  31881. */
  31882. GLTFParser.prototype.loadMesh = function (meshIndex) {
  31883. var parser = this;
  31884. var json = this.json;
  31885. var meshDef = json.meshes[meshIndex];
  31886. var primitives = meshDef.primitives;
  31887. var pending = [];
  31888. for (var i = 0, il = primitives.length; i < il; i++) {
  31889. var material = primitives[i].material === undefined ? createDefaultMaterial() : this.getDependency('material', primitives[i].material);
  31890. pending.push(material);
  31891. }
  31892. return Promise.all(pending).then(function (originalMaterials) {
  31893. return parser.loadGeometries(primitives).then(function (geometries) {
  31894. var meshes = [];
  31895. for (var i = 0, il = geometries.length; i < il; i++) {
  31896. var geometry = geometries[i];
  31897. var primitive = primitives[i]; // 1. create Mesh
  31898. var mesh;
  31899. var material = originalMaterials[i];
  31900. if (primitive.mode === WEBGL_CONSTANTS.TRIANGLES || primitive.mode === WEBGL_CONSTANTS.TRIANGLE_STRIP || primitive.mode === WEBGL_CONSTANTS.TRIANGLE_FAN || primitive.mode === undefined) {
  31901. // .isSkinnedMesh isn't in glTF spec. See .markDefs()
  31902. mesh = meshDef.isSkinnedMesh === true ? new _threeModule.SkinnedMesh(geometry, material) : new _threeModule.Mesh(geometry, material);
  31903. if (mesh.isSkinnedMesh === true && !mesh.geometry.attributes.skinWeight.normalized) {
  31904. // we normalize floating point skin weight array to fix malformed assets (see #15319)
  31905. // it's important to skip this for non-float32 data since normalizeSkinWeights assumes non-normalized inputs
  31906. mesh.normalizeSkinWeights();
  31907. }
  31908. if (primitive.mode === WEBGL_CONSTANTS.TRIANGLE_STRIP) {
  31909. mesh.drawMode = _threeModule.TriangleStripDrawMode;
  31910. } else if (primitive.mode === WEBGL_CONSTANTS.TRIANGLE_FAN) {
  31911. mesh.drawMode = _threeModule.TriangleFanDrawMode;
  31912. }
  31913. } else if (primitive.mode === WEBGL_CONSTANTS.LINES) {
  31914. mesh = new _threeModule.LineSegments(geometry, material);
  31915. } else if (primitive.mode === WEBGL_CONSTANTS.LINE_STRIP) {
  31916. mesh = new _threeModule.Line(geometry, material);
  31917. } else if (primitive.mode === WEBGL_CONSTANTS.LINE_LOOP) {
  31918. mesh = new _threeModule.LineLoop(geometry, material);
  31919. } else if (primitive.mode === WEBGL_CONSTANTS.POINTS) {
  31920. mesh = new _threeModule.Points(geometry, material);
  31921. } else {
  31922. throw new Error('THREE.GLTFLoader: Primitive mode unsupported: ' + primitive.mode);
  31923. }
  31924. if (Object.keys(mesh.geometry.morphAttributes).length > 0) {
  31925. updateMorphTargets(mesh, meshDef);
  31926. }
  31927. mesh.name = meshDef.name || 'mesh_' + meshIndex;
  31928. if (geometries.length > 1) mesh.name += '_' + i;
  31929. assignExtrasToUserData(mesh, meshDef);
  31930. parser.assignFinalMaterial(mesh);
  31931. meshes.push(mesh);
  31932. }
  31933. if (meshes.length === 1) {
  31934. return meshes[0];
  31935. }
  31936. var group = new _threeModule.Group();
  31937. for (var i = 0, il = meshes.length; i < il; i++) {
  31938. group.add(meshes[i]);
  31939. }
  31940. return group;
  31941. });
  31942. });
  31943. };
  31944. /**
  31945. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#cameras
  31946. * @param {number} cameraIndex
  31947. * @return {Promise<THREE.Camera>}
  31948. */
  31949. GLTFParser.prototype.loadCamera = function (cameraIndex) {
  31950. var camera;
  31951. var cameraDef = this.json.cameras[cameraIndex];
  31952. var params = cameraDef[cameraDef.type];
  31953. if (!params) {
  31954. console.warn('THREE.GLTFLoader: Missing camera parameters.');
  31955. return;
  31956. }
  31957. if (cameraDef.type === 'perspective') {
  31958. camera = new _threeModule.PerspectiveCamera(_threeModule.Math.radToDeg(params.yfov), params.aspectRatio || 1, params.znear || 1, params.zfar || 2e6);
  31959. } else if (cameraDef.type === 'orthographic') {
  31960. camera = new _threeModule.OrthographicCamera(params.xmag / -2, params.xmag / 2, params.ymag / 2, params.ymag / -2, params.znear, params.zfar);
  31961. }
  31962. if (cameraDef.name !== undefined) camera.name = cameraDef.name;
  31963. assignExtrasToUserData(camera, cameraDef);
  31964. return Promise.resolve(camera);
  31965. };
  31966. /**
  31967. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins
  31968. * @param {number} skinIndex
  31969. * @return {Promise<Object>}
  31970. */
  31971. GLTFParser.prototype.loadSkin = function (skinIndex) {
  31972. var skinDef = this.json.skins[skinIndex];
  31973. var skinEntry = {
  31974. joints: skinDef.joints
  31975. };
  31976. if (skinDef.inverseBindMatrices === undefined) {
  31977. return Promise.resolve(skinEntry);
  31978. }
  31979. return this.getDependency('accessor', skinDef.inverseBindMatrices).then(function (accessor) {
  31980. skinEntry.inverseBindMatrices = accessor;
  31981. return skinEntry;
  31982. });
  31983. };
  31984. /**
  31985. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#animations
  31986. * @param {number} animationIndex
  31987. * @return {Promise<AnimationClip>}
  31988. */
  31989. GLTFParser.prototype.loadAnimation = function (animationIndex) {
  31990. var json = this.json;
  31991. var animationDef = json.animations[animationIndex];
  31992. var pendingNodes = [];
  31993. var pendingInputAccessors = [];
  31994. var pendingOutputAccessors = [];
  31995. var pendingSamplers = [];
  31996. var pendingTargets = [];
  31997. for (var i = 0, il = animationDef.channels.length; i < il; i++) {
  31998. var channel = animationDef.channels[i];
  31999. var sampler = animationDef.samplers[channel.sampler];
  32000. var target = channel.target;
  32001. var name = target.node !== undefined ? target.node : target.id; // NOTE: target.id is deprecated.
  32002. var input = animationDef.parameters !== undefined ? animationDef.parameters[sampler.input] : sampler.input;
  32003. var output = animationDef.parameters !== undefined ? animationDef.parameters[sampler.output] : sampler.output;
  32004. pendingNodes.push(this.getDependency('node', name));
  32005. pendingInputAccessors.push(this.getDependency('accessor', input));
  32006. pendingOutputAccessors.push(this.getDependency('accessor', output));
  32007. pendingSamplers.push(sampler);
  32008. pendingTargets.push(target);
  32009. }
  32010. return Promise.all([Promise.all(pendingNodes), Promise.all(pendingInputAccessors), Promise.all(pendingOutputAccessors), Promise.all(pendingSamplers), Promise.all(pendingTargets)]).then(function (dependencies) {
  32011. var nodes = dependencies[0];
  32012. var inputAccessors = dependencies[1];
  32013. var outputAccessors = dependencies[2];
  32014. var samplers = dependencies[3];
  32015. var targets = dependencies[4];
  32016. var tracks = [];
  32017. for (var i = 0, il = nodes.length; i < il; i++) {
  32018. var node = nodes[i];
  32019. var inputAccessor = inputAccessors[i];
  32020. var outputAccessor = outputAccessors[i];
  32021. var sampler = samplers[i];
  32022. var target = targets[i];
  32023. if (node === undefined) continue;
  32024. node.updateMatrix();
  32025. node.matrixAutoUpdate = true;
  32026. var TypedKeyframeTrack;
  32027. switch (PATH_PROPERTIES[target.path]) {
  32028. case PATH_PROPERTIES.weights:
  32029. TypedKeyframeTrack = _threeModule.NumberKeyframeTrack;
  32030. break;
  32031. case PATH_PROPERTIES.rotation:
  32032. TypedKeyframeTrack = _threeModule.QuaternionKeyframeTrack;
  32033. break;
  32034. case PATH_PROPERTIES.position:
  32035. case PATH_PROPERTIES.scale:
  32036. default:
  32037. TypedKeyframeTrack = _threeModule.VectorKeyframeTrack;
  32038. break;
  32039. }
  32040. var targetName = node.name ? node.name : node.uuid;
  32041. var interpolation = sampler.interpolation !== undefined ? INTERPOLATION[sampler.interpolation] : _threeModule.InterpolateLinear;
  32042. var targetNames = [];
  32043. if (PATH_PROPERTIES[target.path] === PATH_PROPERTIES.weights) {
  32044. // Node may be a Group (glTF mesh with several primitives) or a Mesh.
  32045. node.traverse(function (object) {
  32046. if (object.isMesh === true && object.morphTargetInfluences) {
  32047. targetNames.push(object.name ? object.name : object.uuid);
  32048. }
  32049. });
  32050. } else {
  32051. targetNames.push(targetName);
  32052. }
  32053. var outputArray = outputAccessor.array;
  32054. if (outputAccessor.normalized) {
  32055. var scale;
  32056. if (outputArray.constructor === Int8Array) {
  32057. scale = 1 / 127;
  32058. } else if (outputArray.constructor === Uint8Array) {
  32059. scale = 1 / 255;
  32060. } else if (outputArray.constructor == Int16Array) {
  32061. scale = 1 / 32767;
  32062. } else if (outputArray.constructor === Uint16Array) {
  32063. scale = 1 / 65535;
  32064. } else {
  32065. throw new Error('THREE.GLTFLoader: Unsupported output accessor component type.');
  32066. }
  32067. var scaled = new Float32Array(outputArray.length);
  32068. for (var j = 0, jl = outputArray.length; j < jl; j++) {
  32069. scaled[j] = outputArray[j] * scale;
  32070. }
  32071. outputArray = scaled;
  32072. }
  32073. for (var j = 0, jl = targetNames.length; j < jl; j++) {
  32074. var track = new TypedKeyframeTrack(targetNames[j] + '.' + PATH_PROPERTIES[target.path], inputAccessor.array, outputArray, interpolation); // Override interpolation with custom factory method.
  32075. if (sampler.interpolation === 'CUBICSPLINE') {
  32076. track.createInterpolant = function InterpolantFactoryMethodGLTFCubicSpline(result) {
  32077. // A CUBICSPLINE keyframe in glTF has three output values for each input value,
  32078. // representing inTangent, splineVertex, and outTangent. As a result, track.getValueSize()
  32079. // must be divided by three to get the interpolant's sampleSize argument.
  32080. return new GLTFCubicSplineInterpolant(this.times, this.values, this.getValueSize() / 3, result);
  32081. }; // Mark as CUBICSPLINE. `track.getInterpolation()` doesn't support custom interpolants.
  32082. track.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline = true;
  32083. }
  32084. tracks.push(track);
  32085. }
  32086. }
  32087. var name = animationDef.name !== undefined ? animationDef.name : 'animation_' + animationIndex;
  32088. return new _threeModule.AnimationClip(name, undefined, tracks);
  32089. });
  32090. };
  32091. /**
  32092. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#nodes-and-hierarchy
  32093. * @param {number} nodeIndex
  32094. * @return {Promise<Object3D>}
  32095. */
  32096. GLTFParser.prototype.loadNode = function (nodeIndex) {
  32097. var json = this.json;
  32098. var extensions = this.extensions;
  32099. var parser = this;
  32100. var meshReferences = json.meshReferences;
  32101. var meshUses = json.meshUses;
  32102. var nodeDef = json.nodes[nodeIndex];
  32103. return function () {
  32104. var pending = [];
  32105. if (nodeDef.mesh !== undefined) {
  32106. pending.push(parser.getDependency('mesh', nodeDef.mesh).then(function (mesh) {
  32107. var node;
  32108. if (meshReferences[nodeDef.mesh] > 1) {
  32109. var instanceNum = meshUses[nodeDef.mesh]++;
  32110. node = mesh.clone();
  32111. node.name += '_instance_' + instanceNum; // onBeforeRender copy for Specular-Glossiness
  32112. node.onBeforeRender = mesh.onBeforeRender;
  32113. for (var i = 0, il = node.children.length; i < il; i++) {
  32114. node.children[i].name += '_instance_' + instanceNum;
  32115. node.children[i].onBeforeRender = mesh.children[i].onBeforeRender;
  32116. }
  32117. } else {
  32118. node = mesh;
  32119. } // if weights are provided on the node, override weights on the mesh.
  32120. if (nodeDef.weights !== undefined) {
  32121. node.traverse(function (o) {
  32122. if (!o.isMesh) return;
  32123. for (var i = 0, il = nodeDef.weights.length; i < il; i++) {
  32124. o.morphTargetInfluences[i] = nodeDef.weights[i];
  32125. }
  32126. });
  32127. }
  32128. return node;
  32129. }));
  32130. }
  32131. if (nodeDef.camera !== undefined) {
  32132. pending.push(parser.getDependency('camera', nodeDef.camera));
  32133. }
  32134. if (nodeDef.extensions && nodeDef.extensions[EXTENSIONS.KHR_LIGHTS_PUNCTUAL] && nodeDef.extensions[EXTENSIONS.KHR_LIGHTS_PUNCTUAL].light !== undefined) {
  32135. pending.push(parser.getDependency('light', nodeDef.extensions[EXTENSIONS.KHR_LIGHTS_PUNCTUAL].light));
  32136. }
  32137. return Promise.all(pending);
  32138. }().then(function (objects) {
  32139. var node; // .isBone isn't in glTF spec. See .markDefs
  32140. if (nodeDef.isBone === true) {
  32141. node = new _threeModule.Bone();
  32142. } else if (objects.length > 1) {
  32143. node = new _threeModule.Group();
  32144. } else if (objects.length === 1) {
  32145. node = objects[0];
  32146. } else {
  32147. node = new _threeModule.Object3D();
  32148. }
  32149. if (node !== objects[0]) {
  32150. for (var i = 0, il = objects.length; i < il; i++) {
  32151. node.add(objects[i]);
  32152. }
  32153. }
  32154. if (nodeDef.name !== undefined) {
  32155. node.userData.name = nodeDef.name;
  32156. node.name = _threeModule.PropertyBinding.sanitizeNodeName(nodeDef.name);
  32157. }
  32158. assignExtrasToUserData(node, nodeDef);
  32159. if (nodeDef.extensions) addUnknownExtensionsToUserData(extensions, node, nodeDef);
  32160. if (nodeDef.matrix !== undefined) {
  32161. var matrix = new _threeModule.Matrix4();
  32162. matrix.fromArray(nodeDef.matrix);
  32163. node.applyMatrix(matrix);
  32164. } else {
  32165. if (nodeDef.translation !== undefined) {
  32166. node.position.fromArray(nodeDef.translation);
  32167. }
  32168. if (nodeDef.rotation !== undefined) {
  32169. node.quaternion.fromArray(nodeDef.rotation);
  32170. }
  32171. if (nodeDef.scale !== undefined) {
  32172. node.scale.fromArray(nodeDef.scale);
  32173. }
  32174. }
  32175. return node;
  32176. });
  32177. };
  32178. /**
  32179. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#scenes
  32180. * @param {number} sceneIndex
  32181. * @return {Promise<Scene>}
  32182. */
  32183. GLTFParser.prototype.loadScene = function () {
  32184. // scene node hierachy builder
  32185. function buildNodeHierachy(nodeId, parentObject, json, parser) {
  32186. var nodeDef = json.nodes[nodeId];
  32187. return parser.getDependency('node', nodeId).then(function (node) {
  32188. if (nodeDef.skin === undefined) return node; // build skeleton here as well
  32189. var skinEntry;
  32190. return parser.getDependency('skin', nodeDef.skin).then(function (skin) {
  32191. skinEntry = skin;
  32192. var pendingJoints = [];
  32193. for (var i = 0, il = skinEntry.joints.length; i < il; i++) {
  32194. pendingJoints.push(parser.getDependency('node', skinEntry.joints[i]));
  32195. }
  32196. return Promise.all(pendingJoints);
  32197. }).then(function (jointNodes) {
  32198. node.traverse(function (mesh) {
  32199. if (!mesh.isMesh) return;
  32200. var bones = [];
  32201. var boneInverses = [];
  32202. for (var j = 0, jl = jointNodes.length; j < jl; j++) {
  32203. var jointNode = jointNodes[j];
  32204. if (jointNode) {
  32205. bones.push(jointNode);
  32206. var mat = new _threeModule.Matrix4();
  32207. if (skinEntry.inverseBindMatrices !== undefined) {
  32208. mat.fromArray(skinEntry.inverseBindMatrices.array, j * 16);
  32209. }
  32210. boneInverses.push(mat);
  32211. } else {
  32212. console.warn('THREE.GLTFLoader: Joint "%s" could not be found.', skinEntry.joints[j]);
  32213. }
  32214. }
  32215. mesh.bind(new _threeModule.Skeleton(bones, boneInverses), mesh.matrixWorld);
  32216. });
  32217. return node;
  32218. });
  32219. }).then(function (node) {
  32220. // build node hierachy
  32221. parentObject.add(node);
  32222. var pending = [];
  32223. if (nodeDef.children) {
  32224. var children = nodeDef.children;
  32225. for (var i = 0, il = children.length; i < il; i++) {
  32226. var child = children[i];
  32227. pending.push(buildNodeHierachy(child, node, json, parser));
  32228. }
  32229. }
  32230. return Promise.all(pending);
  32231. });
  32232. }
  32233. return function loadScene(sceneIndex) {
  32234. var json = this.json;
  32235. var extensions = this.extensions;
  32236. var sceneDef = this.json.scenes[sceneIndex];
  32237. var parser = this;
  32238. var scene = new _threeModule.Scene();
  32239. if (sceneDef.name !== undefined) scene.name = sceneDef.name;
  32240. assignExtrasToUserData(scene, sceneDef);
  32241. if (sceneDef.extensions) addUnknownExtensionsToUserData(extensions, scene, sceneDef);
  32242. var nodeIds = sceneDef.nodes || [];
  32243. var pending = [];
  32244. for (var i = 0, il = nodeIds.length; i < il; i++) {
  32245. pending.push(buildNodeHierachy(nodeIds[i], scene, json, parser));
  32246. }
  32247. return Promise.all(pending).then(function () {
  32248. return scene;
  32249. });
  32250. };
  32251. }();
  32252. return GLTFLoader;
  32253. }();
  32254. exports.GLTFLoader = GLTFLoader;
  32255. },{"../../../build/three.module.js":"../node_modules/three/build/three.module.js"}],"../src/three/B3DMLoader.js":[function(require,module,exports) {
  32256. "use strict";
  32257. Object.defineProperty(exports, "__esModule", {
  32258. value: true
  32259. });
  32260. exports.B3DMLoader = void 0;
  32261. var _B3DMLoaderBase = require("../base/B3DMLoaderBase.js");
  32262. var _GLTFLoader = require("three/examples/jsm/loaders/GLTFLoader.js");
  32263. class B3DMLoader extends _B3DMLoaderBase.B3DMLoaderBase {
  32264. parse(buffer) {
  32265. const b3dm = super.parse(buffer);
  32266. const gltfBuffer = b3dm.glbBytes.slice().buffer;
  32267. return new Promise((resolve, reject) => {
  32268. new _GLTFLoader.GLTFLoader().parse(gltfBuffer, null, resolve, reject);
  32269. });
  32270. }
  32271. }
  32272. exports.B3DMLoader = B3DMLoader;
  32273. },{"../base/B3DMLoaderBase.js":"../src/base/B3DMLoaderBase.js","three/examples/jsm/loaders/GLTFLoader.js":"../node_modules/three/examples/jsm/loaders/GLTFLoader.js"}],"../src/three/TilesGroup.js":[function(require,module,exports) {
  32274. "use strict";
  32275. Object.defineProperty(exports, "__esModule", {
  32276. value: true
  32277. });
  32278. exports.TilesGroup = void 0;
  32279. var _three = require("three");
  32280. // Specialization of "Group" that only updates world matrices of children if
  32281. // the transform has changed since the last update and ignores the "force"
  32282. // parameter under the assumption that the children tiles will not move.
  32283. const tempMat = new _three.Matrix4();
  32284. class TilesGroup extends _three.Group {
  32285. constructor(tilesRenderer) {
  32286. super();
  32287. this.tilesRenderer = tilesRenderer;
  32288. }
  32289. raycast(raycaster, intersects) {
  32290. this.tilesRenderer.raycast(raycaster, intersects);
  32291. }
  32292. updateMatrixWorld(force) {
  32293. if (this.matrixAutoUpdate) {
  32294. this.updateMatrix();
  32295. }
  32296. if (this.matrixWorldNeedsUpdate || force) {
  32297. if (this.parent === null) {
  32298. tempMat.copy(this.matrix);
  32299. } else {
  32300. tempMat.multiplyMatrices(this.parent.matrixWorld, this.matrix);
  32301. }
  32302. this.matrixWorldNeedsUpdate = false;
  32303. const elA = tempMat.elements;
  32304. const elB = this.matrixWorld.elements;
  32305. let isDifferent = false;
  32306. for (let i = 0; i < 16; i++) {
  32307. const itemA = elA[i];
  32308. const itemB = elB[i];
  32309. const diff = Math.abs(itemA - itemB);
  32310. if (diff > Number.EPSILON) {
  32311. isDifferent = true;
  32312. break;
  32313. }
  32314. }
  32315. if (isDifferent) {
  32316. this.matrixWorld.copy(tempMat); // update children
  32317. // the children will not have to change unless the parent group has updated
  32318. const children = this.children;
  32319. for (let i = 0, l = children.length; i < l; i++) {
  32320. children[i].updateMatrixWorld();
  32321. }
  32322. }
  32323. }
  32324. }
  32325. }
  32326. exports.TilesGroup = TilesGroup;
  32327. },{"three":"../node_modules/three/build/three.module.js"}],"../src/three/raycastTraverse.js":[function(require,module,exports) {
  32328. "use strict";
  32329. Object.defineProperty(exports, "__esModule", {
  32330. value: true
  32331. });
  32332. exports.raycastTraverseFirstHit = raycastTraverseFirstHit;
  32333. exports.raycastTraverse = raycastTraverse;
  32334. var _three = require("three");
  32335. const _sphere = new _three.Sphere();
  32336. const _mat = new _three.Matrix4();
  32337. const _vec = new _three.Vector3();
  32338. const _vec2 = new _three.Vector3();
  32339. const _ray = new _three.Ray();
  32340. const _hitArray = [];
  32341. function distanceSort(a, b) {
  32342. return a.distance - b.distance;
  32343. }
  32344. function intersectTileScene(scene, raycaster, intersects) {
  32345. // Don't intersect the box3 helpers because those are used for debugging
  32346. scene.traverse(c => {
  32347. if (!(c instanceof _three.Box3Helper)) {
  32348. Object.getPrototypeOf(c).raycast.call(c, raycaster, intersects);
  32349. }
  32350. });
  32351. } // Returns the closest hit when traversing the tree
  32352. function raycastTraverseFirstHit(root, group, activeSet, raycaster) {
  32353. // If the root is active make sure we've checked it
  32354. if (activeSet.has(root.cached.scene)) {
  32355. intersectTileScene(root.cached.scene, raycaster, _hitArray);
  32356. if (_hitArray.length > 0) {
  32357. if (_hitArray.length > 1) {
  32358. _hitArray.sort(distanceSort);
  32359. }
  32360. _hitArray.length = 0;
  32361. return _hitArray[0];
  32362. } else {
  32363. return null;
  32364. }
  32365. } // TODO: see if we can avoid creating a new array here every time to save on memory
  32366. const array = [];
  32367. const children = root.children;
  32368. for (let i = 0, l = children.length; i < l; i++) {
  32369. const tile = children[i];
  32370. const cached = tile.cached;
  32371. const groupMatrixWorld = group.matrixWorld;
  32372. const transformMat = cached.transform;
  32373. _mat.copy(groupMatrixWorld);
  32374. _mat.multiply(transformMat); // if we don't hit the sphere then early out
  32375. const sphere = cached.sphere;
  32376. if (sphere) {
  32377. _sphere.copy(sphere);
  32378. _sphere.applyMatrix4(_mat);
  32379. if (!raycaster.ray.intersectsSphere(_sphere)) {
  32380. continue;
  32381. }
  32382. } // TODO: check region
  32383. const boundingBox = cached.box;
  32384. const obbMat = cached.boxTransform;
  32385. if (boundingBox) {
  32386. _mat.multiply(obbMat);
  32387. _mat.getInverse(_mat);
  32388. _ray.copy(raycaster.ray).applyMatrix4(_mat);
  32389. if (_ray.intersectBox(boundingBox, _vec)) {
  32390. // account for tile scale
  32391. let invScale;
  32392. _vec2.setFromMatrixScale(_mat);
  32393. invScale = _vec2.x;
  32394. if (Math.abs(Math.max(_vec2.x - _vec2.y, _vec2.x - _vec2.z)) > 1e-6) {
  32395. console.warn('ThreeTilesRenderer : Non uniform scale used for tile which may cause issues when raycasting.');
  32396. } // if we intersect the box save the distance to the tile bounds
  32397. let data = {
  32398. distance: Infinity,
  32399. tile: null
  32400. };
  32401. array.push(data);
  32402. data.distance = _vec.distanceToSquared(_ray.origin) * invScale * invScale;
  32403. data.tile = tile;
  32404. } else {
  32405. continue;
  32406. }
  32407. }
  32408. } // sort them by ascending distance
  32409. array.sort(distanceSort); // traverse until we find the best hit and early out if a tile bounds
  32410. // couldn't possible include a best hit
  32411. let bestDistanceSquared = Infinity;
  32412. let bestHit = null;
  32413. for (let i = 0, l = array.length; i < l; i++) {
  32414. const data = array[i];
  32415. const distanceSquared = data.distance;
  32416. if (distanceSquared > bestDistanceSquared) {
  32417. break;
  32418. } else {
  32419. const tile = data.tile;
  32420. const scene = tile.cached.scene;
  32421. let hit = null;
  32422. if (activeSet.has(scene)) {
  32423. // save the hit if it's closer
  32424. intersectTileScene(scene, raycaster, _hitArray);
  32425. if (_hitArray.length > 0) {
  32426. if (_hitArray.length > 1) {
  32427. _hitArray.sort(distanceSort);
  32428. }
  32429. hit = _hitArray[0];
  32430. }
  32431. } else {
  32432. hit = raycastTraverseFirstHit(tile, group, activeSet, raycaster);
  32433. }
  32434. if (hit) {
  32435. const hitDistanceSquared = hit.distance * hit.distance;
  32436. if (hitDistanceSquared < bestDistanceSquared) {
  32437. bestDistanceSquared = hitDistanceSquared;
  32438. bestHit = hit;
  32439. }
  32440. _hitArray.length = 0;
  32441. }
  32442. }
  32443. }
  32444. return bestHit;
  32445. }
  32446. function raycastTraverse(tile, group, activeSet, raycaster, intersects) {
  32447. const cached = tile.cached;
  32448. const groupMatrixWorld = group.matrixWorld;
  32449. const transformMat = cached.transform;
  32450. _mat.copy(groupMatrixWorld);
  32451. _mat.multiply(transformMat);
  32452. const sphere = cached.sphere;
  32453. if (sphere) {
  32454. _sphere.copy(sphere);
  32455. _sphere.applyMatrix4(_mat);
  32456. if (!raycaster.ray.intersectsSphere(_sphere)) {
  32457. return;
  32458. }
  32459. }
  32460. const boundingBox = cached.box;
  32461. const obbMat = cached.boxTransform;
  32462. if (boundingBox) {
  32463. _mat.multiply(obbMat);
  32464. _mat.getInverse(_mat);
  32465. _ray.copy(raycaster.ray).applyMatrix4(_mat);
  32466. if (!_ray.intersectsBox(boundingBox)) {
  32467. return;
  32468. }
  32469. } // TODO: check region
  32470. const scene = cached.scene;
  32471. if (activeSet.has(scene)) {
  32472. scene.traverse(c => {
  32473. if (!(c instanceof _three.Box3Helper)) {
  32474. Object.getPrototypeOf(c).raycast.call(c, raycaster, intersects);
  32475. }
  32476. });
  32477. return;
  32478. }
  32479. const children = tile.children;
  32480. for (let i = 0, l = children.length; i < l; i++) {
  32481. raycastTraverse(children[i], group, activeSet, raycaster, intersects);
  32482. }
  32483. }
  32484. },{"three":"../node_modules/three/build/three.module.js"}],"../src/three/TilesRenderer.js":[function(require,module,exports) {
  32485. "use strict";
  32486. Object.defineProperty(exports, "__esModule", {
  32487. value: true
  32488. });
  32489. exports.TilesRenderer = void 0;
  32490. var _TilesRendererBase = require("../base/TilesRendererBase.js");
  32491. var _B3DMLoader = require("./B3DMLoader.js");
  32492. var _TilesGroup = require("./TilesGroup.js");
  32493. var _three = require("three");
  32494. var _raycastTraverse = require("./raycastTraverse.js");
  32495. const DEG2RAD = _three.Math.DEG2RAD;
  32496. const tempMat = new _three.Matrix4();
  32497. const tempQuaternion = new _three.Quaternion();
  32498. const tempVector = new _three.Vector3();
  32499. const vecX = new _three.Vector3();
  32500. const vecY = new _three.Vector3();
  32501. const vecZ = new _three.Vector3();
  32502. const _sphere = new _three.Sphere();
  32503. function emptyRaycast() {}
  32504. class TilesRenderer extends _TilesRendererBase.TilesRendererBase {
  32505. get camera() {
  32506. return this.cameras[0];
  32507. }
  32508. set camera(camera) {
  32509. const cameras = this.cameras;
  32510. cameras.length = 1;
  32511. cameras[0] = camera;
  32512. }
  32513. constructor(...args) {
  32514. super(...args);
  32515. this.group = new _TilesGroup.TilesGroup(this);
  32516. this.cameras = [];
  32517. this.resolution = new _three.Vector2();
  32518. this.frustums = [];
  32519. this.activeSet = new Set();
  32520. this.visibleSet = new Set();
  32521. }
  32522. /* Public API */
  32523. getBounds(box) {
  32524. if (!this.root) {
  32525. return false;
  32526. }
  32527. const cached = this.root.cached;
  32528. const boundingBox = cached.box;
  32529. const obbMat = cached.boxTransform;
  32530. const transformMat = cached.transform;
  32531. box.copy(boundingBox);
  32532. tempMat.multiplyMatrices(transformMat, obbMat);
  32533. box.applyMatrix4(tempMat);
  32534. return true;
  32535. }
  32536. raycast(raycaster, intersects) {
  32537. if (!this.root) {
  32538. return;
  32539. }
  32540. if (raycaster.firstHitOnly) {
  32541. const hit = (0, _raycastTraverse.raycastTraverseFirstHit)(this.root, this.group, this.activeSet, raycaster);
  32542. if (hit) {
  32543. intersects.push(hit);
  32544. }
  32545. } else {
  32546. (0, _raycastTraverse.raycastTraverse)(this.root, this.group, this.activeSet, raycaster, intersects);
  32547. }
  32548. }
  32549. setResolutionFromRenderer(renderer) {
  32550. const resolution = this.resolution;
  32551. renderer.getSize(resolution);
  32552. resolution.multiplyScalar(renderer.getPixelRatio());
  32553. }
  32554. /* Overriden */
  32555. update() {
  32556. const group = this.group;
  32557. const cameras = this.cameras;
  32558. const frustums = this.frustums;
  32559. const resolution = this.resolution;
  32560. if (cameras.length === 0) {
  32561. console.warn('TilesRenderer: no cameras to use are defined. Cannot update 3d tiles.');
  32562. return;
  32563. }
  32564. if (resolution.width === 0 || resolution.height === 0) {
  32565. console.warn('TilesRenderer: resolution for error calculation is not set. Cannot updated 3d tiles.');
  32566. return;
  32567. } // automatically scale the array of frustums to match the cameras
  32568. while (frustums.length > cameras.length) {
  32569. frustums.pop();
  32570. }
  32571. while (frustums.length < cameras.length) {
  32572. frustums.push(new _three.Frustum());
  32573. } // store the camera frustums in the 3d tiles root frame
  32574. for (let i = 0, l = frustums.length; i < l; i++) {
  32575. const camera = cameras[i];
  32576. const frustum = frustums[i];
  32577. tempMat.copy(group.matrixWorld);
  32578. tempMat.premultiply(camera.matrixWorldInverse);
  32579. tempMat.premultiply(camera.projectionMatrix);
  32580. frustum.setFromMatrix(tempMat);
  32581. }
  32582. super.update();
  32583. }
  32584. preprocessNode(tile, parentTile, tileSetDir) {
  32585. super.preprocessNode(tile, parentTile, tileSetDir);
  32586. const transform = new _three.Matrix4();
  32587. if (tile.transform) {
  32588. const transformArr = tile.transform;
  32589. for (let i = 0; i < 16; i++) {
  32590. transform.elements[i] = transformArr[i];
  32591. }
  32592. } else {
  32593. transform.identity();
  32594. }
  32595. if (parentTile) {
  32596. transform.multiply(parentTile.cached.transform);
  32597. }
  32598. let box = null;
  32599. let boxTransform = null;
  32600. if ('box' in tile.boundingVolume) {
  32601. const data = tile.boundingVolume.box;
  32602. box = new _three.Box3();
  32603. boxTransform = new _three.Matrix4(); // get the extents of the bounds in each axis
  32604. vecX.set(data[3], data[4], data[5]);
  32605. vecY.set(data[6], data[7], data[8]);
  32606. vecZ.set(data[9], data[10], data[11]);
  32607. const scaleX = vecX.length();
  32608. const scaleY = vecY.length();
  32609. const scaleZ = vecZ.length();
  32610. vecX.normalize();
  32611. vecY.normalize();
  32612. vecZ.normalize(); // create the oriented frame that the box exists in
  32613. 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
  32614. box.min.set(-scaleX, -scaleY, -scaleZ);
  32615. box.max.set(scaleX, scaleY, scaleZ);
  32616. }
  32617. let sphere = null;
  32618. if ('sphere' in tile.boundingVolume) {
  32619. const data = tile.boundingVolume.sphere;
  32620. sphere = new _three.Sphere();
  32621. sphere.center.set(data[0], data[1], data[2]);
  32622. sphere.radius = data[3];
  32623. } else if ('box' in tile.boundingVolume) {
  32624. sphere = new _three.Sphere();
  32625. box.getBoundingSphere(sphere);
  32626. boxTransform.decompose(sphere.center, tempQuaternion, tempVector);
  32627. }
  32628. let region = null;
  32629. if ('region' in tile.boundingVolume) {
  32630. console.warn('ThreeTilesRenderer: region bounding volume not supported.');
  32631. }
  32632. tile.cached = {
  32633. loadIndex: 0,
  32634. transform,
  32635. active: false,
  32636. box,
  32637. boxTransform,
  32638. sphere,
  32639. region,
  32640. scene: null,
  32641. geometry: null,
  32642. material: null,
  32643. distance: Infinity
  32644. };
  32645. }
  32646. parseTile(buffer, tile) {
  32647. tile._loadIndex = tile._loadIndex || 0;
  32648. tile._loadIndex++; // TODO: 90 degree rotation must be applied to GLTF file to resolve "up"
  32649. const loadIndex = tile._loadIndex;
  32650. return new _B3DMLoader.B3DMLoader().parse(buffer).then(res => {
  32651. if (tile._loadIndex !== loadIndex) {
  32652. return;
  32653. }
  32654. const cached = tile.cached;
  32655. const cachedTransform = cached.transform;
  32656. const scene = res.scene;
  32657. cachedTransform.decompose(scene.position, scene.quaternion, scene.scale);
  32658. scene.traverse(c => c.frustumCulled = false);
  32659. cached.scene = scene; // We handle raycasting in a custom way so remove it from here
  32660. scene.traverse(c => {
  32661. c.raycast = emptyRaycast;
  32662. });
  32663. const materials = [];
  32664. const geometry = [];
  32665. scene.traverse(c => {
  32666. if (c.geometry) {
  32667. geometry.push(c.geometry);
  32668. }
  32669. if (c.material) {
  32670. materials.push(c.material);
  32671. }
  32672. });
  32673. cached.materials = materials;
  32674. cached.geometry = geometry;
  32675. });
  32676. }
  32677. disposeTile(tile) {
  32678. const cached = tile.cached;
  32679. if (cached.scene) {
  32680. const scene = cached.scene;
  32681. const materials = cached.materials;
  32682. const geometry = cached.geometry;
  32683. if (scene.parent) {
  32684. scene.parent.remove(scene);
  32685. }
  32686. for (let i = 0, l = geometry.length; i < l; i++) {
  32687. geometry[i].dispose();
  32688. }
  32689. for (let i = 0, l = materials.length; i < l; i++) {
  32690. const material = materials[i];
  32691. for (const key in material) {
  32692. const value = material[key];
  32693. if (value && value.isTexture) {
  32694. value.dispose();
  32695. }
  32696. }
  32697. material.dispose();
  32698. }
  32699. cached.scene = null;
  32700. cached.materials = null;
  32701. cached.geometry = null;
  32702. }
  32703. tile._loadIndex++;
  32704. }
  32705. setTileVisible(tile, visible) {
  32706. // TODO: save the whole tile object in the visible set and active set
  32707. const scene = tile.cached.scene;
  32708. const visibleSet = this.visibleSet;
  32709. const group = this.group;
  32710. if (visible) {
  32711. if (scene && !scene.parent) {
  32712. group.add(scene);
  32713. visibleSet.add(scene);
  32714. scene.updateMatrixWorld(true);
  32715. }
  32716. } else {
  32717. group.remove(scene);
  32718. visibleSet.delete(scene);
  32719. }
  32720. }
  32721. setTileActive(tile, active) {
  32722. const cached = tile.cached;
  32723. const activeSet = this.activeSet;
  32724. if (active !== cached.active) {
  32725. cached.active = active;
  32726. if (active) {
  32727. activeSet.add(cached.scene);
  32728. } else {
  32729. activeSet.delete(cached.scene);
  32730. }
  32731. }
  32732. }
  32733. calculateError(tile) {
  32734. const cached = tile.cached;
  32735. const cameras = this.cameras; // TODO: Use the content bounding volume here?
  32736. const boundingVolume = tile.boundingVolume;
  32737. const transformMat = cached.transform;
  32738. const resolution = this.resolution;
  32739. if ('box' in boundingVolume) {
  32740. const group = this.group;
  32741. const boundingBox = cached.box;
  32742. const obbMat = cached.boxTransform; // TODO: these can likely be cached? Or the world transform mat can be used
  32743. // transformMat can be rolled into oobMat
  32744. tempMat.copy(group.matrixWorld);
  32745. tempMat.multiply(transformMat);
  32746. tempMat.multiply(obbMat);
  32747. tempMat.getInverse(tempMat); // NOTE: scale is inverted here.
  32748. // assume the scales on all axes are uniform.
  32749. let invScale; // account for tile scale.
  32750. tempVector.setFromMatrixScale(tempMat);
  32751. invScale = tempVector.x;
  32752. if (Math.abs(Math.max(tempVector.x - tempVector.y, tempVector.x - tempVector.z)) > 1e-6) {
  32753. console.warn('ThreeTilesRenderer : Non uniform scale used for tile which may cause issues when calculating screen space error.');
  32754. }
  32755. let minError = Infinity;
  32756. for (let i = 0, l = cameras.length; i < l; i++) {
  32757. // transform camera position into local frame of the tile bounding box
  32758. const cam = cameras[i];
  32759. tempVector.copy(cam.position);
  32760. tempVector.applyMatrix4(tempMat);
  32761. let error;
  32762. if (cam.isOrthographicCamera) {
  32763. const w = cam.right - cam.left;
  32764. const h = cam.top - cam.bottom;
  32765. const pixelSize = Math.max(h / resolution.height, w / resolution.width);
  32766. error = tile.geometricError / (pixelSize * invScale);
  32767. } else {
  32768. const distance = boundingBox.distanceToPoint(tempVector);
  32769. const scaledDistance = distance * invScale;
  32770. const sseDenominator = 2 * Math.tan(0.5 * cam.fov * DEG2RAD);
  32771. error = tile.geometricError * resolution.height / (scaledDistance * sseDenominator);
  32772. tile.cached.distance = scaledDistance;
  32773. }
  32774. minError = Math.min(minError, error);
  32775. }
  32776. return minError;
  32777. } else if ('sphere' in boundingVolume) {
  32778. // const sphere = cached.sphere;
  32779. console.warn('ThreeTilesRenderer : Sphere bounds not supported.');
  32780. } else if ('region' in boundingVolume) {
  32781. // unsupported
  32782. console.warn('ThreeTilesRenderer : Region bounds not supported.');
  32783. }
  32784. return Infinity;
  32785. }
  32786. tileInView(tile) {
  32787. // TODO: we should use the more precise bounding volumes here if possible
  32788. // cache the root-space planes
  32789. const sphere = tile.cached.sphere;
  32790. if (sphere) {
  32791. _sphere.copy(sphere);
  32792. _sphere.applyMatrix4(tile.cached.transform);
  32793. const frustums = this.frustums;
  32794. for (let i = 0, l = frustums.length; i < l; i++) {
  32795. const frustum = frustums[i];
  32796. if (frustum.intersectsSphere(_sphere)) {
  32797. return true;
  32798. }
  32799. }
  32800. return false;
  32801. }
  32802. return true;
  32803. }
  32804. }
  32805. exports.TilesRenderer = TilesRenderer;
  32806. },{"../base/TilesRendererBase.js":"../src/base/TilesRendererBase.js","./B3DMLoader.js":"../src/three/B3DMLoader.js","./TilesGroup.js":"../src/three/TilesGroup.js","three":"../node_modules/three/build/three.module.js","./raycastTraverse.js":"../src/three/raycastTraverse.js"}],"../src/three/SphereHelper.js":[function(require,module,exports) {
  32807. "use strict";
  32808. Object.defineProperty(exports, "__esModule", {
  32809. value: true
  32810. });
  32811. exports.SphereHelper = void 0;
  32812. var _three = require("three");
  32813. const _vector = new _three.Vector3();
  32814. const axes = ['x', 'y', 'z'];
  32815. class SphereHelper extends _three.LineSegments {
  32816. constructor(sphere, color = 0xffff00, angleSteps = 40) {
  32817. const geometry = new _three.BufferGeometry();
  32818. const positions = [];
  32819. for (let i = 0; i < 3; i++) {
  32820. const axis1 = axes[i];
  32821. const axis2 = axes[(i + 1) % 3];
  32822. _vector.set(0, 0, 0);
  32823. for (let a = 0; a < angleSteps; a++) {
  32824. let angle;
  32825. angle = 2 * Math.PI * a / (angleSteps - 1);
  32826. _vector[axis1] = Math.sin(angle);
  32827. _vector[axis2] = Math.cos(angle);
  32828. positions.push(_vector.x, _vector.y, _vector.z);
  32829. angle = 2 * Math.PI * (a + 1) / (angleSteps - 1);
  32830. _vector[axis1] = Math.sin(angle);
  32831. _vector[axis2] = Math.cos(angle);
  32832. positions.push(_vector.x, _vector.y, _vector.z);
  32833. }
  32834. }
  32835. geometry.setAttribute('position', new _three.BufferAttribute(new Float32Array(positions), 3));
  32836. geometry.computeBoundingSphere();
  32837. super(geometry, new _three.LineBasicMaterial({
  32838. color: color,
  32839. toneMapped: false
  32840. }));
  32841. this.sphere = sphere;
  32842. this.type = 'SphereHelper';
  32843. }
  32844. updateMatrixWorld(force) {
  32845. // TODO: Why doesn't this radius have to be multiplied by 0.5?
  32846. const sphere = this.sphere;
  32847. this.position.copy(sphere.center);
  32848. this.scale.setScalar(sphere.radius);
  32849. super.updateMatrixWorld(force);
  32850. }
  32851. }
  32852. exports.SphereHelper = SphereHelper;
  32853. },{"three":"../node_modules/three/build/three.module.js"}],"../src/three/DebugTilesRenderer.js":[function(require,module,exports) {
  32854. "use strict";
  32855. Object.defineProperty(exports, "__esModule", {
  32856. value: true
  32857. });
  32858. exports.DebugTilesRenderer = void 0;
  32859. var _three = require("three");
  32860. var _TilesRenderer = require("./TilesRenderer.js");
  32861. var _SphereHelper = require("./SphereHelper.js");
  32862. const ORIGINAL_MATERIAL = Symbol('ORIGINAL_MATERIAL');
  32863. const NONE = 0;
  32864. const SCREEN_ERROR = 1;
  32865. const GEOMETRIC_ERROR = 2;
  32866. const DISTANCE = 3;
  32867. const DEPTH = 4;
  32868. const IS_LEAF = 5;
  32869. class DebugTilesRenderer extends _TilesRenderer.TilesRenderer {
  32870. constructor(...args) {
  32871. super(...args);
  32872. const tilesGroup = this.group;
  32873. const boxGroup = new _three.Group();
  32874. tilesGroup.add(boxGroup);
  32875. const sphereGroup = new _three.Group();
  32876. tilesGroup.add(sphereGroup);
  32877. this.displayBoxBounds = false;
  32878. this.displaySphereBounds = false;
  32879. this.colorMode = NONE;
  32880. this.boxGroup = boxGroup;
  32881. this.sphereGroup = sphereGroup;
  32882. this.maxDepth = -1;
  32883. this.maxDistance = -1;
  32884. this.maxError = -1;
  32885. }
  32886. getTileInformationFromObject(object) {
  32887. let targetTile = null;
  32888. this.traverse(tile => {
  32889. if (targetTile) {
  32890. return true;
  32891. }
  32892. const scene = tile.cached.scene;
  32893. if (scene) {
  32894. scene.traverse(c => {
  32895. if (c === object) {
  32896. targetTile = tile;
  32897. }
  32898. });
  32899. }
  32900. });
  32901. if (targetTile) {
  32902. return {
  32903. distanceToCamera: targetTile.cached.distance,
  32904. geometricError: targetTile.geometricError,
  32905. screenSpaceError: targetTile.__error,
  32906. depth: targetTile.__depth,
  32907. isLeaf: targetTile.__isLeaf
  32908. };
  32909. } else {
  32910. return null;
  32911. }
  32912. }
  32913. update() {
  32914. super.update();
  32915. if (!this.root) {
  32916. return;
  32917. }
  32918. this.boxGroup.visible = this.displayBoxBounds;
  32919. this.sphereGroup.visible = this.displaySphereBounds;
  32920. let maxDepth = -1;
  32921. if (this.maxDepth === -1) {
  32922. this.traverse(tile => {
  32923. maxDepth = Math.max(maxDepth, tile.__depth);
  32924. });
  32925. } else {
  32926. maxDepth = this.maxDepth;
  32927. }
  32928. let maxError = -1;
  32929. if (this.maxError === -1) {
  32930. this.traverse(tile => {
  32931. maxError = Math.max(maxError, tile.geometricError);
  32932. });
  32933. } else {
  32934. maxError = this.maxError;
  32935. }
  32936. let maxDistance = -1;
  32937. if (this.maxDistance === -1) {
  32938. maxDistance = this.root.cached.sphere.radius;
  32939. } else {
  32940. maxDistance = this.maxDistance;
  32941. }
  32942. const errorTarget = this.errorTarget;
  32943. const colorMode = this.colorMode;
  32944. const visibleSet = this.visibleSet;
  32945. this.traverse(tile => {
  32946. const scene = tile.cached.scene;
  32947. if (visibleSet.has(scene)) {
  32948. scene.traverse(c => {
  32949. const currMaterial = c.material;
  32950. if (currMaterial) {
  32951. const originalMaterial = c[ORIGINAL_MATERIAL];
  32952. if (colorMode === NONE && currMaterial !== originalMaterial) {
  32953. c.material.dispose();
  32954. c.material = c[ORIGINAL_MATERIAL];
  32955. } else if (colorMode !== NONE && currMaterial === originalMaterial) {
  32956. c.material = new _three.MeshBasicMaterial();
  32957. }
  32958. switch (colorMode) {
  32959. case DEPTH:
  32960. {
  32961. const val = tile.__depth / maxDepth;
  32962. c.material.color.setRGB(val, val, val);
  32963. break;
  32964. }
  32965. case SCREEN_ERROR:
  32966. {
  32967. const val = tile.__error / errorTarget;
  32968. if (val > 1.0) {
  32969. c.material.color.setRGB(1.0, 0.0, 0.0);
  32970. } else {
  32971. c.material.color.setRGB(val, val, val);
  32972. }
  32973. break;
  32974. }
  32975. case GEOMETRIC_ERROR:
  32976. {
  32977. const val = Math.min(tile.geometricError / maxError, 1);
  32978. c.material.color.setRGB(val, val, val);
  32979. break;
  32980. }
  32981. case DISTANCE:
  32982. {
  32983. // TODO
  32984. // Allow custom scaling
  32985. const val = Math.min(tile.cached.distance / maxDistance, 1);
  32986. c.material.color.setRGB(val, val, val);
  32987. break;
  32988. }
  32989. case IS_LEAF:
  32990. {
  32991. if (!tile.children || tile.children.length === 0) {
  32992. c.material.color.set(0xffffff);
  32993. } else {
  32994. c.material.color.set(0);
  32995. }
  32996. break;
  32997. }
  32998. }
  32999. }
  33000. });
  33001. }
  33002. });
  33003. }
  33004. setTileVisible(tile, visible) {
  33005. super.setTileVisible(tile, visible);
  33006. const cached = tile.cached;
  33007. const sphereGroup = this.sphereGroup;
  33008. const boxGroup = this.boxGroup;
  33009. const boxHelperGroup = cached.boxHelperGroup;
  33010. const sphereHelper = cached.sphereHelper;
  33011. if (!visible && boxHelperGroup.parent) {
  33012. boxGroup.remove(boxHelperGroup);
  33013. sphereGroup.remove(sphereHelper);
  33014. } else if (visible && !boxHelperGroup.parent) {
  33015. boxGroup.add(boxHelperGroup);
  33016. boxHelperGroup.updateMatrixWorld(true);
  33017. sphereGroup.add(sphereHelper);
  33018. sphereHelper.updateMatrixWorld(true);
  33019. }
  33020. }
  33021. parseTile(buffer, tile) {
  33022. return super.parseTile(buffer, tile).then(() => {
  33023. const cached = tile.cached;
  33024. const scene = cached.scene;
  33025. if (scene) {
  33026. const cachedBox = cached.box;
  33027. const cachedBoxMat = cached.boxTransform;
  33028. const cachedTransform = cached.transform;
  33029. const boxHelperGroup = new _three.Group();
  33030. boxHelperGroup.matrix.copy(cachedBoxMat);
  33031. boxHelperGroup.matrix.multiply(cachedTransform);
  33032. boxHelperGroup.matrix.decompose(boxHelperGroup.position, boxHelperGroup.quaternion, boxHelperGroup.scale);
  33033. const boxHelper = new _three.Box3Helper(cachedBox);
  33034. boxHelperGroup.add(boxHelper);
  33035. cached.boxHelperGroup = boxHelperGroup;
  33036. if (this.displayBoxBounds) {
  33037. this.boxGroup.add(boxHelperGroup);
  33038. boxHelperGroup.updateMatrixWorld(true);
  33039. }
  33040. const cachedSphere = cached.sphere;
  33041. const sphereHelper = new _SphereHelper.SphereHelper(cachedSphere);
  33042. cached.sphereHelper = sphereHelper;
  33043. if (this.displaySphereBounds) {
  33044. this.sphereGroup.add(sphereHelper);
  33045. sphereHelper.updateMatrixWorld(true);
  33046. }
  33047. scene.traverse(c => {
  33048. const material = c.material;
  33049. if (material) {
  33050. c[ORIGINAL_MATERIAL] = material;
  33051. }
  33052. });
  33053. }
  33054. });
  33055. }
  33056. disposeTile(tile) {
  33057. super.disposeTile(tile);
  33058. delete tile.cached.boxBounds;
  33059. }
  33060. }
  33061. exports.DebugTilesRenderer = DebugTilesRenderer;
  33062. },{"three":"../node_modules/three/build/three.module.js","./TilesRenderer.js":"../src/three/TilesRenderer.js","./SphereHelper.js":"../src/three/SphereHelper.js"}],"../src/index.js":[function(require,module,exports) {
  33063. "use strict";
  33064. Object.defineProperty(exports, "__esModule", {
  33065. value: true
  33066. });
  33067. Object.defineProperty(exports, "DebugTilesRenderer", {
  33068. enumerable: true,
  33069. get: function () {
  33070. return _DebugTilesRenderer.DebugTilesRenderer;
  33071. }
  33072. });
  33073. Object.defineProperty(exports, "TilesRenderer", {
  33074. enumerable: true,
  33075. get: function () {
  33076. return _TilesRenderer.TilesRenderer;
  33077. }
  33078. });
  33079. Object.defineProperty(exports, "B3DMLoader", {
  33080. enumerable: true,
  33081. get: function () {
  33082. return _B3DMLoader.B3DMLoader;
  33083. }
  33084. });
  33085. Object.defineProperty(exports, "TilesRendererBase", {
  33086. enumerable: true,
  33087. get: function () {
  33088. return _TilesRendererBase.TilesRendererBase;
  33089. }
  33090. });
  33091. Object.defineProperty(exports, "B3DMLoaderBase", {
  33092. enumerable: true,
  33093. get: function () {
  33094. return _B3DMLoaderBase.B3DMLoaderBase;
  33095. }
  33096. });
  33097. Object.defineProperty(exports, "LRUCache", {
  33098. enumerable: true,
  33099. get: function () {
  33100. return _LRUCache.LRUCache;
  33101. }
  33102. });
  33103. Object.defineProperty(exports, "PriorityQueue", {
  33104. enumerable: true,
  33105. get: function () {
  33106. return _PriorityQueue.PriorityQueue;
  33107. }
  33108. });
  33109. var _DebugTilesRenderer = require("./three/DebugTilesRenderer.js");
  33110. var _TilesRenderer = require("./three/TilesRenderer.js");
  33111. var _B3DMLoader = require("./three/B3DMLoader.js");
  33112. var _TilesRendererBase = require("./base/TilesRendererBase.js");
  33113. var _B3DMLoaderBase = require("./base/B3DMLoaderBase.js");
  33114. var _LRUCache = require("./utilities/LRUCache.js");
  33115. var _PriorityQueue = require("./utilities/PriorityQueue.js");
  33116. },{"./three/DebugTilesRenderer.js":"../src/three/DebugTilesRenderer.js","./three/TilesRenderer.js":"../src/three/TilesRenderer.js","./three/B3DMLoader.js":"../src/three/B3DMLoader.js","./base/TilesRendererBase.js":"../src/base/TilesRendererBase.js","./base/B3DMLoaderBase.js":"../src/base/B3DMLoaderBase.js","./utilities/LRUCache.js":"../src/utilities/LRUCache.js","./utilities/PriorityQueue.js":"../src/utilities/PriorityQueue.js"}],"../node_modules/three/examples/jsm/controls/OrbitControls.js":[function(require,module,exports) {
  33117. "use strict";
  33118. Object.defineProperty(exports, "__esModule", {
  33119. value: true
  33120. });
  33121. exports.MapControls = exports.OrbitControls = void 0;
  33122. var _threeModule = require("../../../build/three.module.js");
  33123. /**
  33124. * @author qiao / https://github.com/qiao
  33125. * @author mrdoob / http://mrdoob.com
  33126. * @author alteredq / http://alteredqualia.com/
  33127. * @author WestLangley / http://github.com/WestLangley
  33128. * @author erich666 / http://erichaines.com
  33129. * @author ScieCode / http://github.com/sciecode
  33130. */
  33131. // This set of controls performs orbiting, dollying (zooming), and panning.
  33132. // Unlike TrackballControls, it maintains the "up" direction object.up (+Y by default).
  33133. //
  33134. // Orbit - left mouse / touch: one-finger move
  33135. // Zoom - middle mouse, or mousewheel / touch: two-finger spread or squish
  33136. // Pan - right mouse, or left mouse + ctrl/meta/shiftKey, or arrow keys / touch: two-finger move
  33137. var OrbitControls = function (object, domElement) {
  33138. this.object = object;
  33139. this.domElement = domElement !== undefined ? domElement : document; // Set to false to disable this control
  33140. this.enabled = true; // "target" sets the location of focus, where the object orbits around
  33141. this.target = new _threeModule.Vector3(); // How far you can dolly in and out ( PerspectiveCamera only )
  33142. this.minDistance = 0;
  33143. this.maxDistance = Infinity; // How far you can zoom in and out ( OrthographicCamera only )
  33144. this.minZoom = 0;
  33145. this.maxZoom = Infinity; // How far you can orbit vertically, upper and lower limits.
  33146. // Range is 0 to Math.PI radians.
  33147. this.minPolarAngle = 0; // radians
  33148. this.maxPolarAngle = Math.PI; // radians
  33149. // How far you can orbit horizontally, upper and lower limits.
  33150. // If set, must be a sub-interval of the interval [ - Math.PI, Math.PI ].
  33151. this.minAzimuthAngle = -Infinity; // radians
  33152. this.maxAzimuthAngle = Infinity; // radians
  33153. // Set to true to enable damping (inertia)
  33154. // If damping is enabled, you must call controls.update() in your animation loop
  33155. this.enableDamping = false;
  33156. this.dampingFactor = 0.05; // This option actually enables dollying in and out; left as "zoom" for backwards compatibility.
  33157. // Set to false to disable zooming
  33158. this.enableZoom = true;
  33159. this.zoomSpeed = 1.0; // Set to false to disable rotating
  33160. this.enableRotate = true;
  33161. this.rotateSpeed = 1.0; // Set to false to disable panning
  33162. this.enablePan = true;
  33163. this.panSpeed = 1.0;
  33164. this.screenSpacePanning = false; // if true, pan in screen-space
  33165. this.keyPanSpeed = 7.0; // pixels moved per arrow key push
  33166. // Set to true to automatically rotate around the target
  33167. // If auto-rotate is enabled, you must call controls.update() in your animation loop
  33168. this.autoRotate = false;
  33169. this.autoRotateSpeed = 2.0; // 30 seconds per round when fps is 60
  33170. // Set to false to disable use of the keys
  33171. this.enableKeys = true; // The four arrow keys
  33172. this.keys = {
  33173. LEFT: 37,
  33174. UP: 38,
  33175. RIGHT: 39,
  33176. BOTTOM: 40
  33177. }; // Mouse buttons
  33178. this.mouseButtons = {
  33179. LEFT: _threeModule.MOUSE.ROTATE,
  33180. MIDDLE: _threeModule.MOUSE.DOLLY,
  33181. RIGHT: _threeModule.MOUSE.PAN
  33182. }; // Touch fingers
  33183. this.touches = {
  33184. ONE: _threeModule.TOUCH.ROTATE,
  33185. TWO: _threeModule.TOUCH.DOLLY_PAN
  33186. }; // for reset
  33187. this.target0 = this.target.clone();
  33188. this.position0 = this.object.position.clone();
  33189. this.zoom0 = this.object.zoom; //
  33190. // public methods
  33191. //
  33192. this.getPolarAngle = function () {
  33193. return spherical.phi;
  33194. };
  33195. this.getAzimuthalAngle = function () {
  33196. return spherical.theta;
  33197. };
  33198. this.saveState = function () {
  33199. scope.target0.copy(scope.target);
  33200. scope.position0.copy(scope.object.position);
  33201. scope.zoom0 = scope.object.zoom;
  33202. };
  33203. this.reset = function () {
  33204. scope.target.copy(scope.target0);
  33205. scope.object.position.copy(scope.position0);
  33206. scope.object.zoom = scope.zoom0;
  33207. scope.object.updateProjectionMatrix();
  33208. scope.dispatchEvent(changeEvent);
  33209. scope.update();
  33210. state = STATE.NONE;
  33211. }; // this method is exposed, but perhaps it would be better if we can make it private...
  33212. this.update = function () {
  33213. var offset = new _threeModule.Vector3(); // so camera.up is the orbit axis
  33214. var quat = new _threeModule.Quaternion().setFromUnitVectors(object.up, new _threeModule.Vector3(0, 1, 0));
  33215. var quatInverse = quat.clone().inverse();
  33216. var lastPosition = new _threeModule.Vector3();
  33217. var lastQuaternion = new _threeModule.Quaternion();
  33218. return function update() {
  33219. var position = scope.object.position;
  33220. offset.copy(position).sub(scope.target); // rotate offset to "y-axis-is-up" space
  33221. offset.applyQuaternion(quat); // angle from z-axis around y-axis
  33222. spherical.setFromVector3(offset);
  33223. if (scope.autoRotate && state === STATE.NONE) {
  33224. rotateLeft(getAutoRotationAngle());
  33225. }
  33226. if (scope.enableDamping) {
  33227. spherical.theta += sphericalDelta.theta * scope.dampingFactor;
  33228. spherical.phi += sphericalDelta.phi * scope.dampingFactor;
  33229. } else {
  33230. spherical.theta += sphericalDelta.theta;
  33231. spherical.phi += sphericalDelta.phi;
  33232. } // restrict theta to be between desired limits
  33233. spherical.theta = Math.max(scope.minAzimuthAngle, Math.min(scope.maxAzimuthAngle, spherical.theta)); // restrict phi to be between desired limits
  33234. spherical.phi = Math.max(scope.minPolarAngle, Math.min(scope.maxPolarAngle, spherical.phi));
  33235. spherical.makeSafe();
  33236. spherical.radius *= scale; // restrict radius to be between desired limits
  33237. spherical.radius = Math.max(scope.minDistance, Math.min(scope.maxDistance, spherical.radius)); // move target to panned location
  33238. if (scope.enableDamping === true) {
  33239. scope.target.addScaledVector(panOffset, scope.dampingFactor);
  33240. } else {
  33241. scope.target.add(panOffset);
  33242. }
  33243. offset.setFromSpherical(spherical); // rotate offset back to "camera-up-vector-is-up" space
  33244. offset.applyQuaternion(quatInverse);
  33245. position.copy(scope.target).add(offset);
  33246. scope.object.lookAt(scope.target);
  33247. if (scope.enableDamping === true) {
  33248. sphericalDelta.theta *= 1 - scope.dampingFactor;
  33249. sphericalDelta.phi *= 1 - scope.dampingFactor;
  33250. panOffset.multiplyScalar(1 - scope.dampingFactor);
  33251. } else {
  33252. sphericalDelta.set(0, 0, 0);
  33253. panOffset.set(0, 0, 0);
  33254. }
  33255. scale = 1; // update condition is:
  33256. // min(camera displacement, camera rotation in radians)^2 > EPS
  33257. // using small-angle approximation cos(x/2) = 1 - x^2 / 8
  33258. if (zoomChanged || lastPosition.distanceToSquared(scope.object.position) > EPS || 8 * (1 - lastQuaternion.dot(scope.object.quaternion)) > EPS) {
  33259. scope.dispatchEvent(changeEvent);
  33260. lastPosition.copy(scope.object.position);
  33261. lastQuaternion.copy(scope.object.quaternion);
  33262. zoomChanged = false;
  33263. return true;
  33264. }
  33265. return false;
  33266. };
  33267. }();
  33268. this.dispose = function () {
  33269. scope.domElement.removeEventListener('contextmenu', onContextMenu, false);
  33270. scope.domElement.removeEventListener('mousedown', onMouseDown, false);
  33271. scope.domElement.removeEventListener('wheel', onMouseWheel, false);
  33272. scope.domElement.removeEventListener('touchstart', onTouchStart, false);
  33273. scope.domElement.removeEventListener('touchend', onTouchEnd, false);
  33274. scope.domElement.removeEventListener('touchmove', onTouchMove, false);
  33275. document.removeEventListener('mousemove', onMouseMove, false);
  33276. document.removeEventListener('mouseup', onMouseUp, false);
  33277. window.removeEventListener('keydown', onKeyDown, false); //scope.dispatchEvent( { type: 'dispose' } ); // should this be added here?
  33278. }; //
  33279. // internals
  33280. //
  33281. var scope = this;
  33282. var changeEvent = {
  33283. type: 'change'
  33284. };
  33285. var startEvent = {
  33286. type: 'start'
  33287. };
  33288. var endEvent = {
  33289. type: 'end'
  33290. };
  33291. var STATE = {
  33292. NONE: -1,
  33293. ROTATE: 0,
  33294. DOLLY: 1,
  33295. PAN: 2,
  33296. TOUCH_ROTATE: 3,
  33297. TOUCH_PAN: 4,
  33298. TOUCH_DOLLY_PAN: 5,
  33299. TOUCH_DOLLY_ROTATE: 6
  33300. };
  33301. var state = STATE.NONE;
  33302. var EPS = 0.000001; // current position in spherical coordinates
  33303. var spherical = new _threeModule.Spherical();
  33304. var sphericalDelta = new _threeModule.Spherical();
  33305. var scale = 1;
  33306. var panOffset = new _threeModule.Vector3();
  33307. var zoomChanged = false;
  33308. var rotateStart = new _threeModule.Vector2();
  33309. var rotateEnd = new _threeModule.Vector2();
  33310. var rotateDelta = new _threeModule.Vector2();
  33311. var panStart = new _threeModule.Vector2();
  33312. var panEnd = new _threeModule.Vector2();
  33313. var panDelta = new _threeModule.Vector2();
  33314. var dollyStart = new _threeModule.Vector2();
  33315. var dollyEnd = new _threeModule.Vector2();
  33316. var dollyDelta = new _threeModule.Vector2();
  33317. function getAutoRotationAngle() {
  33318. return 2 * Math.PI / 60 / 60 * scope.autoRotateSpeed;
  33319. }
  33320. function getZoomScale() {
  33321. return Math.pow(0.95, scope.zoomSpeed);
  33322. }
  33323. function rotateLeft(angle) {
  33324. sphericalDelta.theta -= angle;
  33325. }
  33326. function rotateUp(angle) {
  33327. sphericalDelta.phi -= angle;
  33328. }
  33329. var panLeft = function () {
  33330. var v = new _threeModule.Vector3();
  33331. return function panLeft(distance, objectMatrix) {
  33332. v.setFromMatrixColumn(objectMatrix, 0); // get X column of objectMatrix
  33333. v.multiplyScalar(-distance);
  33334. panOffset.add(v);
  33335. };
  33336. }();
  33337. var panUp = function () {
  33338. var v = new _threeModule.Vector3();
  33339. return function panUp(distance, objectMatrix) {
  33340. if (scope.screenSpacePanning === true) {
  33341. v.setFromMatrixColumn(objectMatrix, 1);
  33342. } else {
  33343. v.setFromMatrixColumn(objectMatrix, 0);
  33344. v.crossVectors(scope.object.up, v);
  33345. }
  33346. v.multiplyScalar(distance);
  33347. panOffset.add(v);
  33348. };
  33349. }(); // deltaX and deltaY are in pixels; right and down are positive
  33350. var pan = function () {
  33351. var offset = new _threeModule.Vector3();
  33352. return function pan(deltaX, deltaY) {
  33353. var element = scope.domElement === document ? scope.domElement.body : scope.domElement;
  33354. if (scope.object.isPerspectiveCamera) {
  33355. // perspective
  33356. var position = scope.object.position;
  33357. offset.copy(position).sub(scope.target);
  33358. var targetDistance = offset.length(); // half of the fov is center to top of screen
  33359. targetDistance *= Math.tan(scope.object.fov / 2 * Math.PI / 180.0); // we use only clientHeight here so aspect ratio does not distort speed
  33360. panLeft(2 * deltaX * targetDistance / element.clientHeight, scope.object.matrix);
  33361. panUp(2 * deltaY * targetDistance / element.clientHeight, scope.object.matrix);
  33362. } else if (scope.object.isOrthographicCamera) {
  33363. // orthographic
  33364. panLeft(deltaX * (scope.object.right - scope.object.left) / scope.object.zoom / element.clientWidth, scope.object.matrix);
  33365. panUp(deltaY * (scope.object.top - scope.object.bottom) / scope.object.zoom / element.clientHeight, scope.object.matrix);
  33366. } else {
  33367. // camera neither orthographic nor perspective
  33368. console.warn('WARNING: OrbitControls.js encountered an unknown camera type - pan disabled.');
  33369. scope.enablePan = false;
  33370. }
  33371. };
  33372. }();
  33373. function dollyIn(dollyScale) {
  33374. if (scope.object.isPerspectiveCamera) {
  33375. scale /= dollyScale;
  33376. } else if (scope.object.isOrthographicCamera) {
  33377. scope.object.zoom = Math.max(scope.minZoom, Math.min(scope.maxZoom, scope.object.zoom * dollyScale));
  33378. scope.object.updateProjectionMatrix();
  33379. zoomChanged = true;
  33380. } else {
  33381. console.warn('WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled.');
  33382. scope.enableZoom = false;
  33383. }
  33384. }
  33385. function dollyOut(dollyScale) {
  33386. if (scope.object.isPerspectiveCamera) {
  33387. scale *= dollyScale;
  33388. } else if (scope.object.isOrthographicCamera) {
  33389. scope.object.zoom = Math.max(scope.minZoom, Math.min(scope.maxZoom, scope.object.zoom / dollyScale));
  33390. scope.object.updateProjectionMatrix();
  33391. zoomChanged = true;
  33392. } else {
  33393. console.warn('WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled.');
  33394. scope.enableZoom = false;
  33395. }
  33396. } //
  33397. // event callbacks - update the object state
  33398. //
  33399. function handleMouseDownRotate(event) {
  33400. rotateStart.set(event.clientX, event.clientY);
  33401. }
  33402. function handleMouseDownDolly(event) {
  33403. dollyStart.set(event.clientX, event.clientY);
  33404. }
  33405. function handleMouseDownPan(event) {
  33406. panStart.set(event.clientX, event.clientY);
  33407. }
  33408. function handleMouseMoveRotate(event) {
  33409. rotateEnd.set(event.clientX, event.clientY);
  33410. rotateDelta.subVectors(rotateEnd, rotateStart).multiplyScalar(scope.rotateSpeed);
  33411. var element = scope.domElement === document ? scope.domElement.body : scope.domElement;
  33412. rotateLeft(2 * Math.PI * rotateDelta.x / element.clientHeight); // yes, height
  33413. rotateUp(2 * Math.PI * rotateDelta.y / element.clientHeight);
  33414. rotateStart.copy(rotateEnd);
  33415. scope.update();
  33416. }
  33417. function handleMouseMoveDolly(event) {
  33418. dollyEnd.set(event.clientX, event.clientY);
  33419. dollyDelta.subVectors(dollyEnd, dollyStart);
  33420. if (dollyDelta.y > 0) {
  33421. dollyIn(getZoomScale());
  33422. } else if (dollyDelta.y < 0) {
  33423. dollyOut(getZoomScale());
  33424. }
  33425. dollyStart.copy(dollyEnd);
  33426. scope.update();
  33427. }
  33428. function handleMouseMovePan(event) {
  33429. panEnd.set(event.clientX, event.clientY);
  33430. panDelta.subVectors(panEnd, panStart).multiplyScalar(scope.panSpeed);
  33431. pan(panDelta.x, panDelta.y);
  33432. panStart.copy(panEnd);
  33433. scope.update();
  33434. }
  33435. function handleMouseUp()
  33436. /*event*/
  33437. {// no-op
  33438. }
  33439. function handleMouseWheel(event) {
  33440. if (event.deltaY < 0) {
  33441. dollyOut(getZoomScale());
  33442. } else if (event.deltaY > 0) {
  33443. dollyIn(getZoomScale());
  33444. }
  33445. scope.update();
  33446. }
  33447. function handleKeyDown(event) {
  33448. var needsUpdate = false;
  33449. switch (event.keyCode) {
  33450. case scope.keys.UP:
  33451. pan(0, scope.keyPanSpeed);
  33452. needsUpdate = true;
  33453. break;
  33454. case scope.keys.BOTTOM:
  33455. pan(0, -scope.keyPanSpeed);
  33456. needsUpdate = true;
  33457. break;
  33458. case scope.keys.LEFT:
  33459. pan(scope.keyPanSpeed, 0);
  33460. needsUpdate = true;
  33461. break;
  33462. case scope.keys.RIGHT:
  33463. pan(-scope.keyPanSpeed, 0);
  33464. needsUpdate = true;
  33465. break;
  33466. }
  33467. if (needsUpdate) {
  33468. // prevent the browser from scrolling on cursor keys
  33469. event.preventDefault();
  33470. scope.update();
  33471. }
  33472. }
  33473. function handleTouchStartRotate(event) {
  33474. if (event.touches.length == 1) {
  33475. rotateStart.set(event.touches[0].pageX, event.touches[0].pageY);
  33476. } else {
  33477. var x = 0.5 * (event.touches[0].pageX + event.touches[1].pageX);
  33478. var y = 0.5 * (event.touches[0].pageY + event.touches[1].pageY);
  33479. rotateStart.set(x, y);
  33480. }
  33481. }
  33482. function handleTouchStartPan(event) {
  33483. if (event.touches.length == 1) {
  33484. panStart.set(event.touches[0].pageX, event.touches[0].pageY);
  33485. } else {
  33486. var x = 0.5 * (event.touches[0].pageX + event.touches[1].pageX);
  33487. var y = 0.5 * (event.touches[0].pageY + event.touches[1].pageY);
  33488. panStart.set(x, y);
  33489. }
  33490. }
  33491. function handleTouchStartDolly(event) {
  33492. var dx = event.touches[0].pageX - event.touches[1].pageX;
  33493. var dy = event.touches[0].pageY - event.touches[1].pageY;
  33494. var distance = Math.sqrt(dx * dx + dy * dy);
  33495. dollyStart.set(0, distance);
  33496. }
  33497. function handleTouchStartDollyPan(event) {
  33498. if (scope.enableZoom) handleTouchStartDolly(event);
  33499. if (scope.enablePan) handleTouchStartPan(event);
  33500. }
  33501. function handleTouchStartDollyRotate(event) {
  33502. if (scope.enableZoom) handleTouchStartDolly(event);
  33503. if (scope.enableRotate) handleTouchStartRotate(event);
  33504. }
  33505. function handleTouchMoveRotate(event) {
  33506. if (event.touches.length == 1) {
  33507. rotateEnd.set(event.touches[0].pageX, event.touches[0].pageY);
  33508. } else {
  33509. var x = 0.5 * (event.touches[0].pageX + event.touches[1].pageX);
  33510. var y = 0.5 * (event.touches[0].pageY + event.touches[1].pageY);
  33511. rotateEnd.set(x, y);
  33512. }
  33513. rotateDelta.subVectors(rotateEnd, rotateStart).multiplyScalar(scope.rotateSpeed);
  33514. var element = scope.domElement === document ? scope.domElement.body : scope.domElement;
  33515. rotateLeft(2 * Math.PI * rotateDelta.x / element.clientHeight); // yes, height
  33516. rotateUp(2 * Math.PI * rotateDelta.y / element.clientHeight);
  33517. rotateStart.copy(rotateEnd);
  33518. }
  33519. function handleTouchMovePan(event) {
  33520. if (event.touches.length == 1) {
  33521. panEnd.set(event.touches[0].pageX, event.touches[0].pageY);
  33522. } else {
  33523. var x = 0.5 * (event.touches[0].pageX + event.touches[1].pageX);
  33524. var y = 0.5 * (event.touches[0].pageY + event.touches[1].pageY);
  33525. panEnd.set(x, y);
  33526. }
  33527. panDelta.subVectors(panEnd, panStart).multiplyScalar(scope.panSpeed);
  33528. pan(panDelta.x, panDelta.y);
  33529. panStart.copy(panEnd);
  33530. }
  33531. function handleTouchMoveDolly(event) {
  33532. var dx = event.touches[0].pageX - event.touches[1].pageX;
  33533. var dy = event.touches[0].pageY - event.touches[1].pageY;
  33534. var distance = Math.sqrt(dx * dx + dy * dy);
  33535. dollyEnd.set(0, distance);
  33536. dollyDelta.set(0, Math.pow(dollyEnd.y / dollyStart.y, scope.zoomSpeed));
  33537. dollyIn(dollyDelta.y);
  33538. dollyStart.copy(dollyEnd);
  33539. }
  33540. function handleTouchMoveDollyPan(event) {
  33541. if (scope.enableZoom) handleTouchMoveDolly(event);
  33542. if (scope.enablePan) handleTouchMovePan(event);
  33543. }
  33544. function handleTouchMoveDollyRotate(event) {
  33545. if (scope.enableZoom) handleTouchMoveDolly(event);
  33546. if (scope.enableRotate) handleTouchMoveRotate(event);
  33547. }
  33548. function handleTouchEnd()
  33549. /*event*/
  33550. {} // no-op
  33551. //
  33552. // event handlers - FSM: listen for events and reset state
  33553. //
  33554. function onMouseDown(event) {
  33555. if (scope.enabled === false) return; // Prevent the browser from scrolling.
  33556. event.preventDefault(); // Manually set the focus since calling preventDefault above
  33557. // prevents the browser from setting it automatically.
  33558. scope.domElement.focus ? scope.domElement.focus() : window.focus();
  33559. switch (event.button) {
  33560. case 0:
  33561. switch (scope.mouseButtons.LEFT) {
  33562. case _threeModule.MOUSE.ROTATE:
  33563. if (event.ctrlKey || event.metaKey || event.shiftKey) {
  33564. if (scope.enablePan === false) return;
  33565. handleMouseDownPan(event);
  33566. state = STATE.PAN;
  33567. } else {
  33568. if (scope.enableRotate === false) return;
  33569. handleMouseDownRotate(event);
  33570. state = STATE.ROTATE;
  33571. }
  33572. break;
  33573. case _threeModule.MOUSE.PAN:
  33574. if (event.ctrlKey || event.metaKey || event.shiftKey) {
  33575. if (scope.enableRotate === false) return;
  33576. handleMouseDownRotate(event);
  33577. state = STATE.ROTATE;
  33578. } else {
  33579. if (scope.enablePan === false) return;
  33580. handleMouseDownPan(event);
  33581. state = STATE.PAN;
  33582. }
  33583. break;
  33584. default:
  33585. state = STATE.NONE;
  33586. }
  33587. break;
  33588. case 1:
  33589. switch (scope.mouseButtons.MIDDLE) {
  33590. case _threeModule.MOUSE.DOLLY:
  33591. if (scope.enableZoom === false) return;
  33592. handleMouseDownDolly(event);
  33593. state = STATE.DOLLY;
  33594. break;
  33595. default:
  33596. state = STATE.NONE;
  33597. }
  33598. break;
  33599. case 2:
  33600. switch (scope.mouseButtons.RIGHT) {
  33601. case _threeModule.MOUSE.ROTATE:
  33602. if (scope.enableRotate === false) return;
  33603. handleMouseDownRotate(event);
  33604. state = STATE.ROTATE;
  33605. break;
  33606. case _threeModule.MOUSE.PAN:
  33607. if (scope.enablePan === false) return;
  33608. handleMouseDownPan(event);
  33609. state = STATE.PAN;
  33610. break;
  33611. default:
  33612. state = STATE.NONE;
  33613. }
  33614. break;
  33615. }
  33616. if (state !== STATE.NONE) {
  33617. document.addEventListener('mousemove', onMouseMove, false);
  33618. document.addEventListener('mouseup', onMouseUp, false);
  33619. scope.dispatchEvent(startEvent);
  33620. }
  33621. }
  33622. function onMouseMove(event) {
  33623. if (scope.enabled === false) return;
  33624. event.preventDefault();
  33625. switch (state) {
  33626. case STATE.ROTATE:
  33627. if (scope.enableRotate === false) return;
  33628. handleMouseMoveRotate(event);
  33629. break;
  33630. case STATE.DOLLY:
  33631. if (scope.enableZoom === false) return;
  33632. handleMouseMoveDolly(event);
  33633. break;
  33634. case STATE.PAN:
  33635. if (scope.enablePan === false) return;
  33636. handleMouseMovePan(event);
  33637. break;
  33638. }
  33639. }
  33640. function onMouseUp(event) {
  33641. if (scope.enabled === false) return;
  33642. handleMouseUp(event);
  33643. document.removeEventListener('mousemove', onMouseMove, false);
  33644. document.removeEventListener('mouseup', onMouseUp, false);
  33645. scope.dispatchEvent(endEvent);
  33646. state = STATE.NONE;
  33647. }
  33648. function onMouseWheel(event) {
  33649. if (scope.enabled === false || scope.enableZoom === false || state !== STATE.NONE && state !== STATE.ROTATE) return;
  33650. event.preventDefault();
  33651. event.stopPropagation();
  33652. scope.dispatchEvent(startEvent);
  33653. handleMouseWheel(event);
  33654. scope.dispatchEvent(endEvent);
  33655. }
  33656. function onKeyDown(event) {
  33657. if (scope.enabled === false || scope.enableKeys === false || scope.enablePan === false) return;
  33658. handleKeyDown(event);
  33659. }
  33660. function onTouchStart(event) {
  33661. if (scope.enabled === false) return;
  33662. event.preventDefault();
  33663. switch (event.touches.length) {
  33664. case 1:
  33665. switch (scope.touches.ONE) {
  33666. case _threeModule.TOUCH.ROTATE:
  33667. if (scope.enableRotate === false) return;
  33668. handleTouchStartRotate(event);
  33669. state = STATE.TOUCH_ROTATE;
  33670. break;
  33671. case _threeModule.TOUCH.PAN:
  33672. if (scope.enablePan === false) return;
  33673. handleTouchStartPan(event);
  33674. state = STATE.TOUCH_PAN;
  33675. break;
  33676. default:
  33677. state = STATE.NONE;
  33678. }
  33679. break;
  33680. case 2:
  33681. switch (scope.touches.TWO) {
  33682. case _threeModule.TOUCH.DOLLY_PAN:
  33683. if (scope.enableZoom === false && scope.enablePan === false) return;
  33684. handleTouchStartDollyPan(event);
  33685. state = STATE.TOUCH_DOLLY_PAN;
  33686. break;
  33687. case _threeModule.TOUCH.DOLLY_ROTATE:
  33688. if (scope.enableZoom === false && scope.enableRotate === false) return;
  33689. handleTouchStartDollyRotate(event);
  33690. state = STATE.TOUCH_DOLLY_ROTATE;
  33691. break;
  33692. default:
  33693. state = STATE.NONE;
  33694. }
  33695. break;
  33696. default:
  33697. state = STATE.NONE;
  33698. }
  33699. if (state !== STATE.NONE) {
  33700. scope.dispatchEvent(startEvent);
  33701. }
  33702. }
  33703. function onTouchMove(event) {
  33704. if (scope.enabled === false) return;
  33705. event.preventDefault();
  33706. event.stopPropagation();
  33707. switch (state) {
  33708. case STATE.TOUCH_ROTATE:
  33709. if (scope.enableRotate === false) return;
  33710. handleTouchMoveRotate(event);
  33711. scope.update();
  33712. break;
  33713. case STATE.TOUCH_PAN:
  33714. if (scope.enablePan === false) return;
  33715. handleTouchMovePan(event);
  33716. scope.update();
  33717. break;
  33718. case STATE.TOUCH_DOLLY_PAN:
  33719. if (scope.enableZoom === false && scope.enablePan === false) return;
  33720. handleTouchMoveDollyPan(event);
  33721. scope.update();
  33722. break;
  33723. case STATE.TOUCH_DOLLY_ROTATE:
  33724. if (scope.enableZoom === false && scope.enableRotate === false) return;
  33725. handleTouchMoveDollyRotate(event);
  33726. scope.update();
  33727. break;
  33728. default:
  33729. state = STATE.NONE;
  33730. }
  33731. }
  33732. function onTouchEnd(event) {
  33733. if (scope.enabled === false) return;
  33734. handleTouchEnd(event);
  33735. scope.dispatchEvent(endEvent);
  33736. state = STATE.NONE;
  33737. }
  33738. function onContextMenu(event) {
  33739. if (scope.enabled === false) return;
  33740. event.preventDefault();
  33741. } //
  33742. scope.domElement.addEventListener('contextmenu', onContextMenu, false);
  33743. scope.domElement.addEventListener('mousedown', onMouseDown, false);
  33744. scope.domElement.addEventListener('wheel', onMouseWheel, false);
  33745. scope.domElement.addEventListener('touchstart', onTouchStart, false);
  33746. scope.domElement.addEventListener('touchend', onTouchEnd, false);
  33747. scope.domElement.addEventListener('touchmove', onTouchMove, false);
  33748. window.addEventListener('keydown', onKeyDown, false); // force an update at start
  33749. this.update();
  33750. };
  33751. exports.OrbitControls = OrbitControls;
  33752. OrbitControls.prototype = Object.create(_threeModule.EventDispatcher.prototype);
  33753. OrbitControls.prototype.constructor = OrbitControls; // This set of controls performs orbiting, dollying (zooming), and panning.
  33754. // Unlike TrackballControls, it maintains the "up" direction object.up (+Y by default).
  33755. // This is very similar to OrbitControls, another set of touch behavior
  33756. //
  33757. // Orbit - right mouse, or left mouse + ctrl/meta/shiftKey / touch: two-finger rotate
  33758. // Zoom - middle mouse, or mousewheel / touch: two-finger spread or squish
  33759. // Pan - left mouse, or arrow keys / touch: one-finger move
  33760. var MapControls = function (object, domElement) {
  33761. OrbitControls.call(this, object, domElement);
  33762. this.mouseButtons.LEFT = _threeModule.MOUSE.PAN;
  33763. this.mouseButtons.RIGHT = _threeModule.MOUSE.ROTATE;
  33764. this.touches.ONE = _threeModule.TOUCH.PAN;
  33765. this.touches.TWO = _threeModule.TOUCH.DOLLY_ROTATE;
  33766. };
  33767. exports.MapControls = MapControls;
  33768. MapControls.prototype = Object.create(_threeModule.EventDispatcher.prototype);
  33769. MapControls.prototype.constructor = MapControls;
  33770. },{"../../../build/three.module.js":"../node_modules/three/build/three.module.js"}],"../node_modules/three/examples/jsm/utils/BufferGeometryUtils.js":[function(require,module,exports) {
  33771. "use strict";
  33772. Object.defineProperty(exports, "__esModule", {
  33773. value: true
  33774. });
  33775. exports.BufferGeometryUtils = void 0;
  33776. var _threeModule = require("../../../build/three.module.js");
  33777. /**
  33778. * @author mrdoob / http://mrdoob.com/
  33779. */
  33780. var BufferGeometryUtils = {
  33781. computeTangents: function (geometry) {
  33782. var index = geometry.index;
  33783. var attributes = geometry.attributes; // based on http://www.terathon.com/code/tangent.html
  33784. // (per vertex tangents)
  33785. if (index === null || attributes.position === undefined || attributes.normal === undefined || attributes.uv === undefined) {
  33786. console.warn('THREE.BufferGeometry: Missing required attributes (index, position, normal or uv) in BufferGeometry.computeTangents()');
  33787. return;
  33788. }
  33789. var indices = index.array;
  33790. var positions = attributes.position.array;
  33791. var normals = attributes.normal.array;
  33792. var uvs = attributes.uv.array;
  33793. var nVertices = positions.length / 3;
  33794. if (attributes.tangent === undefined) {
  33795. geometry.addAttribute('tangent', new _threeModule.BufferAttribute(new Float32Array(4 * nVertices), 4));
  33796. }
  33797. var tangents = attributes.tangent.array;
  33798. var tan1 = [],
  33799. tan2 = [];
  33800. for (var i = 0; i < nVertices; i++) {
  33801. tan1[i] = new _threeModule.Vector3();
  33802. tan2[i] = new _threeModule.Vector3();
  33803. }
  33804. var vA = new _threeModule.Vector3(),
  33805. vB = new _threeModule.Vector3(),
  33806. vC = new _threeModule.Vector3(),
  33807. uvA = new _threeModule.Vector2(),
  33808. uvB = new _threeModule.Vector2(),
  33809. uvC = new _threeModule.Vector2(),
  33810. sdir = new _threeModule.Vector3(),
  33811. tdir = new _threeModule.Vector3();
  33812. function handleTriangle(a, b, c) {
  33813. vA.fromArray(positions, a * 3);
  33814. vB.fromArray(positions, b * 3);
  33815. vC.fromArray(positions, c * 3);
  33816. uvA.fromArray(uvs, a * 2);
  33817. uvB.fromArray(uvs, b * 2);
  33818. uvC.fromArray(uvs, c * 2);
  33819. var x1 = vB.x - vA.x;
  33820. var x2 = vC.x - vA.x;
  33821. var y1 = vB.y - vA.y;
  33822. var y2 = vC.y - vA.y;
  33823. var z1 = vB.z - vA.z;
  33824. var z2 = vC.z - vA.z;
  33825. var s1 = uvB.x - uvA.x;
  33826. var s2 = uvC.x - uvA.x;
  33827. var t1 = uvB.y - uvA.y;
  33828. var t2 = uvC.y - uvA.y;
  33829. var r = 1.0 / (s1 * t2 - s2 * t1);
  33830. sdir.set((t2 * x1 - t1 * x2) * r, (t2 * y1 - t1 * y2) * r, (t2 * z1 - t1 * z2) * r);
  33831. tdir.set((s1 * x2 - s2 * x1) * r, (s1 * y2 - s2 * y1) * r, (s1 * z2 - s2 * z1) * r);
  33832. tan1[a].add(sdir);
  33833. tan1[b].add(sdir);
  33834. tan1[c].add(sdir);
  33835. tan2[a].add(tdir);
  33836. tan2[b].add(tdir);
  33837. tan2[c].add(tdir);
  33838. }
  33839. var groups = geometry.groups;
  33840. if (groups.length === 0) {
  33841. groups = [{
  33842. start: 0,
  33843. count: indices.length
  33844. }];
  33845. }
  33846. for (var i = 0, il = groups.length; i < il; ++i) {
  33847. var group = groups[i];
  33848. var start = group.start;
  33849. var count = group.count;
  33850. for (var j = start, jl = start + count; j < jl; j += 3) {
  33851. handleTriangle(indices[j + 0], indices[j + 1], indices[j + 2]);
  33852. }
  33853. }
  33854. var tmp = new _threeModule.Vector3(),
  33855. tmp2 = new _threeModule.Vector3();
  33856. var n = new _threeModule.Vector3(),
  33857. n2 = new _threeModule.Vector3();
  33858. var w, t, test;
  33859. function handleVertex(v) {
  33860. n.fromArray(normals, v * 3);
  33861. n2.copy(n);
  33862. t = tan1[v]; // Gram-Schmidt orthogonalize
  33863. tmp.copy(t);
  33864. tmp.sub(n.multiplyScalar(n.dot(t))).normalize(); // Calculate handedness
  33865. tmp2.crossVectors(n2, t);
  33866. test = tmp2.dot(tan2[v]);
  33867. w = test < 0.0 ? -1.0 : 1.0;
  33868. tangents[v * 4] = tmp.x;
  33869. tangents[v * 4 + 1] = tmp.y;
  33870. tangents[v * 4 + 2] = tmp.z;
  33871. tangents[v * 4 + 3] = w;
  33872. }
  33873. for (var i = 0, il = groups.length; i < il; ++i) {
  33874. var group = groups[i];
  33875. var start = group.start;
  33876. var count = group.count;
  33877. for (var j = start, jl = start + count; j < jl; j += 3) {
  33878. handleVertex(indices[j + 0]);
  33879. handleVertex(indices[j + 1]);
  33880. handleVertex(indices[j + 2]);
  33881. }
  33882. }
  33883. },
  33884. /**
  33885. * @param {Array<BufferGeometry>} geometries
  33886. * @param {Boolean} useGroups
  33887. * @return {BufferGeometry}
  33888. */
  33889. mergeBufferGeometries: function (geometries, useGroups) {
  33890. var isIndexed = geometries[0].index !== null;
  33891. var attributesUsed = new Set(Object.keys(geometries[0].attributes));
  33892. var morphAttributesUsed = new Set(Object.keys(geometries[0].morphAttributes));
  33893. var attributes = {};
  33894. var morphAttributes = {};
  33895. var mergedGeometry = new _threeModule.BufferGeometry();
  33896. var offset = 0;
  33897. for (var i = 0; i < geometries.length; ++i) {
  33898. var geometry = geometries[i]; // ensure that all geometries are indexed, or none
  33899. if (isIndexed !== (geometry.index !== null)) return null; // gather attributes, exit early if they're different
  33900. for (var name in geometry.attributes) {
  33901. if (!attributesUsed.has(name)) return null;
  33902. if (attributes[name] === undefined) attributes[name] = [];
  33903. attributes[name].push(geometry.attributes[name]);
  33904. } // gather morph attributes, exit early if they're different
  33905. for (var name in geometry.morphAttributes) {
  33906. if (!morphAttributesUsed.has(name)) return null;
  33907. if (morphAttributes[name] === undefined) morphAttributes[name] = [];
  33908. morphAttributes[name].push(geometry.morphAttributes[name]);
  33909. } // gather .userData
  33910. mergedGeometry.userData.mergedUserData = mergedGeometry.userData.mergedUserData || [];
  33911. mergedGeometry.userData.mergedUserData.push(geometry.userData);
  33912. if (useGroups) {
  33913. var count;
  33914. if (isIndexed) {
  33915. count = geometry.index.count;
  33916. } else if (geometry.attributes.position !== undefined) {
  33917. count = geometry.attributes.position.count;
  33918. } else {
  33919. return null;
  33920. }
  33921. mergedGeometry.addGroup(offset, count, i);
  33922. offset += count;
  33923. }
  33924. } // merge indices
  33925. if (isIndexed) {
  33926. var indexOffset = 0;
  33927. var mergedIndex = [];
  33928. for (var i = 0; i < geometries.length; ++i) {
  33929. var index = geometries[i].index;
  33930. for (var j = 0; j < index.count; ++j) {
  33931. mergedIndex.push(index.getX(j) + indexOffset);
  33932. }
  33933. indexOffset += geometries[i].attributes.position.count;
  33934. }
  33935. mergedGeometry.setIndex(mergedIndex);
  33936. } // merge attributes
  33937. for (var name in attributes) {
  33938. var mergedAttribute = this.mergeBufferAttributes(attributes[name]);
  33939. if (!mergedAttribute) return null;
  33940. mergedGeometry.addAttribute(name, mergedAttribute);
  33941. } // merge morph attributes
  33942. for (var name in morphAttributes) {
  33943. var numMorphTargets = morphAttributes[name][0].length;
  33944. if (numMorphTargets === 0) break;
  33945. mergedGeometry.morphAttributes = mergedGeometry.morphAttributes || {};
  33946. mergedGeometry.morphAttributes[name] = [];
  33947. for (var i = 0; i < numMorphTargets; ++i) {
  33948. var morphAttributesToMerge = [];
  33949. for (var j = 0; j < morphAttributes[name].length; ++j) {
  33950. morphAttributesToMerge.push(morphAttributes[name][j][i]);
  33951. }
  33952. var mergedMorphAttribute = this.mergeBufferAttributes(morphAttributesToMerge);
  33953. if (!mergedMorphAttribute) return null;
  33954. mergedGeometry.morphAttributes[name].push(mergedMorphAttribute);
  33955. }
  33956. }
  33957. return mergedGeometry;
  33958. },
  33959. /**
  33960. * @param {Array<BufferAttribute>} attributes
  33961. * @return {BufferAttribute}
  33962. */
  33963. mergeBufferAttributes: function (attributes) {
  33964. var TypedArray;
  33965. var itemSize;
  33966. var normalized;
  33967. var arrayLength = 0;
  33968. for (var i = 0; i < attributes.length; ++i) {
  33969. var attribute = attributes[i];
  33970. if (attribute.isInterleavedBufferAttribute) return null;
  33971. if (TypedArray === undefined) TypedArray = attribute.array.constructor;
  33972. if (TypedArray !== attribute.array.constructor) return null;
  33973. if (itemSize === undefined) itemSize = attribute.itemSize;
  33974. if (itemSize !== attribute.itemSize) return null;
  33975. if (normalized === undefined) normalized = attribute.normalized;
  33976. if (normalized !== attribute.normalized) return null;
  33977. arrayLength += attribute.array.length;
  33978. }
  33979. var array = new TypedArray(arrayLength);
  33980. var offset = 0;
  33981. for (var i = 0; i < attributes.length; ++i) {
  33982. array.set(attributes[i].array, offset);
  33983. offset += attributes[i].array.length;
  33984. }
  33985. return new _threeModule.BufferAttribute(array, itemSize, normalized);
  33986. },
  33987. /**
  33988. * @param {Array<BufferAttribute>} attributes
  33989. * @return {Array<InterleavedBufferAttribute>}
  33990. */
  33991. interleaveAttributes: function (attributes) {
  33992. // Interleaves the provided attributes into an InterleavedBuffer and returns
  33993. // a set of InterleavedBufferAttributes for each attribute
  33994. var TypedArray;
  33995. var arrayLength = 0;
  33996. var stride = 0; // calculate the the length and type of the interleavedBuffer
  33997. for (var i = 0, l = attributes.length; i < l; ++i) {
  33998. var attribute = attributes[i];
  33999. if (TypedArray === undefined) TypedArray = attribute.array.constructor;
  34000. if (TypedArray !== attribute.array.constructor) {
  34001. console.warn('AttributeBuffers of different types cannot be interleaved');
  34002. return null;
  34003. }
  34004. arrayLength += attribute.array.length;
  34005. stride += attribute.itemSize;
  34006. } // Create the set of buffer attributes
  34007. var interleavedBuffer = new _threeModule.InterleavedBuffer(new TypedArray(arrayLength), stride);
  34008. var offset = 0;
  34009. var res = [];
  34010. var getters = ['getX', 'getY', 'getZ', 'getW'];
  34011. var setters = ['setX', 'setY', 'setZ', 'setW'];
  34012. for (var j = 0, l = attributes.length; j < l; j++) {
  34013. var attribute = attributes[j];
  34014. var itemSize = attribute.itemSize;
  34015. var count = attribute.count;
  34016. var iba = new _threeModule.InterleavedBufferAttribute(interleavedBuffer, itemSize, offset, attribute.normalized);
  34017. res.push(iba);
  34018. offset += itemSize; // Move the data for each attribute into the new interleavedBuffer
  34019. // at the appropriate offset
  34020. for (var c = 0; c < count; c++) {
  34021. for (var k = 0; k < itemSize; k++) {
  34022. iba[setters[k]](c, attribute[getters[k]](c));
  34023. }
  34024. }
  34025. }
  34026. return res;
  34027. },
  34028. /**
  34029. * @param {Array<BufferGeometry>} geometry
  34030. * @return {number}
  34031. */
  34032. estimateBytesUsed: function (geometry) {
  34033. // Return the estimated memory used by this geometry in bytes
  34034. // Calculate using itemSize, count, and BYTES_PER_ELEMENT to account
  34035. // for InterleavedBufferAttributes.
  34036. var mem = 0;
  34037. for (var name in geometry.attributes) {
  34038. var attr = geometry.getAttribute(name);
  34039. mem += attr.count * attr.itemSize * attr.array.BYTES_PER_ELEMENT;
  34040. }
  34041. var indices = geometry.getIndex();
  34042. mem += indices ? indices.count * indices.itemSize * indices.array.BYTES_PER_ELEMENT : 0;
  34043. return mem;
  34044. },
  34045. /**
  34046. * @param {BufferGeometry} geometry
  34047. * @param {number} tolerance
  34048. * @return {BufferGeometry>}
  34049. */
  34050. mergeVertices: function (geometry, tolerance = 1e-4) {
  34051. tolerance = Math.max(tolerance, Number.EPSILON); // Generate an index buffer if the geometry doesn't have one, or optimize it
  34052. // if it's already available.
  34053. var hashToIndex = {};
  34054. var indices = geometry.getIndex();
  34055. var positions = geometry.getAttribute('position');
  34056. var vertexCount = indices ? indices.count : positions.count; // next value for triangle indices
  34057. var nextIndex = 0; // attributes and new attribute arrays
  34058. var attributeNames = Object.keys(geometry.attributes);
  34059. var attrArrays = {};
  34060. var morphAttrsArrays = {};
  34061. var newIndices = [];
  34062. var getters = ['getX', 'getY', 'getZ', 'getW']; // initialize the arrays
  34063. for (var i = 0, l = attributeNames.length; i < l; i++) {
  34064. var name = attributeNames[i];
  34065. attrArrays[name] = [];
  34066. var morphAttr = geometry.morphAttributes[name];
  34067. if (morphAttr) {
  34068. morphAttrsArrays[name] = new Array(morphAttr.length).fill().map(() => []);
  34069. }
  34070. } // convert the error tolerance to an amount of decimal places to truncate to
  34071. var decimalShift = Math.log10(1 / tolerance);
  34072. var shiftMultiplier = Math.pow(10, decimalShift);
  34073. for (var i = 0; i < vertexCount; i++) {
  34074. var index = indices ? indices.getX(i) : i; // Generate a hash for the vertex attributes at the current index 'i'
  34075. var hash = '';
  34076. for (var j = 0, l = attributeNames.length; j < l; j++) {
  34077. var name = attributeNames[j];
  34078. var attribute = geometry.getAttribute(name);
  34079. var itemSize = attribute.itemSize;
  34080. for (var k = 0; k < itemSize; k++) {
  34081. // double tilde truncates the decimal value
  34082. hash += `${~~(attribute[getters[k]](index) * shiftMultiplier)},`;
  34083. }
  34084. } // Add another reference to the vertex if it's already
  34085. // used by another index
  34086. if (hash in hashToIndex) {
  34087. newIndices.push(hashToIndex[hash]);
  34088. } else {
  34089. // copy data to the new index in the attribute arrays
  34090. for (var j = 0, l = attributeNames.length; j < l; j++) {
  34091. var name = attributeNames[j];
  34092. var attribute = geometry.getAttribute(name);
  34093. var morphAttr = geometry.morphAttributes[name];
  34094. var itemSize = attribute.itemSize;
  34095. var newarray = attrArrays[name];
  34096. var newMorphArrays = morphAttrsArrays[name];
  34097. for (var k = 0; k < itemSize; k++) {
  34098. var getterFunc = getters[k];
  34099. newarray.push(attribute[getterFunc](index));
  34100. if (morphAttr) {
  34101. for (var m = 0, ml = morphAttr.length; m < ml; m++) {
  34102. newMorphArrays[m].push(morphAttr[m][getterFunc](index));
  34103. }
  34104. }
  34105. }
  34106. }
  34107. hashToIndex[hash] = nextIndex;
  34108. newIndices.push(nextIndex);
  34109. nextIndex++;
  34110. }
  34111. } // Generate typed arrays from new attribute arrays and update
  34112. // the attributeBuffers
  34113. const result = geometry.clone();
  34114. for (var i = 0, l = attributeNames.length; i < l; i++) {
  34115. var name = attributeNames[i];
  34116. var oldAttribute = geometry.getAttribute(name);
  34117. var buffer = new oldAttribute.array.constructor(attrArrays[name]);
  34118. var attribute = new _threeModule.BufferAttribute(buffer, oldAttribute.itemSize, oldAttribute.normalized);
  34119. result.addAttribute(name, attribute); // Update the attribute arrays
  34120. if (name in morphAttrsArrays) {
  34121. for (var j = 0; j < morphAttrsArrays[name].length; j++) {
  34122. var oldMorphAttribute = geometry.morphAttributes[name][j];
  34123. var buffer = new oldMorphAttribute.array.constructor(morphAttrsArrays[name][j]);
  34124. var morphAttribute = new _threeModule.BufferAttribute(buffer, oldMorphAttribute.itemSize, oldMorphAttribute.normalized);
  34125. result.morphAttributes[name][j] = morphAttribute;
  34126. }
  34127. }
  34128. } // indices
  34129. result.setIndex(newIndices);
  34130. return result;
  34131. }
  34132. };
  34133. exports.BufferGeometryUtils = BufferGeometryUtils;
  34134. },{"../../../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) {
  34135. "use strict";
  34136. Object.defineProperty(exports, "__esModule", {
  34137. value: true
  34138. });
  34139. exports.default = exports.GUI = exports.gui = exports.dom = exports.controllers = exports.color = void 0;
  34140. /**
  34141. * dat-gui JavaScript Controller Library
  34142. * http://code.google.com/p/dat-gui
  34143. *
  34144. * Copyright 2011 Data Arts Team, Google Creative Lab
  34145. *
  34146. * Licensed under the Apache License, Version 2.0 (the "License");
  34147. * you may not use this file except in compliance with the License.
  34148. * You may obtain a copy of the License at
  34149. *
  34150. * http://www.apache.org/licenses/LICENSE-2.0
  34151. */
  34152. function ___$insertStyle(css) {
  34153. if (!css) {
  34154. return;
  34155. }
  34156. if (typeof window === 'undefined') {
  34157. return;
  34158. }
  34159. var style = document.createElement('style');
  34160. style.setAttribute('type', 'text/css');
  34161. style.innerHTML = css;
  34162. document.head.appendChild(style);
  34163. return css;
  34164. }
  34165. function colorToString(color, forceCSSHex) {
  34166. var colorFormat = color.__state.conversionName.toString();
  34167. var r = Math.round(color.r);
  34168. var g = Math.round(color.g);
  34169. var b = Math.round(color.b);
  34170. var a = color.a;
  34171. var h = Math.round(color.h);
  34172. var s = color.s.toFixed(1);
  34173. var v = color.v.toFixed(1);
  34174. if (forceCSSHex || colorFormat === 'THREE_CHAR_HEX' || colorFormat === 'SIX_CHAR_HEX') {
  34175. var str = color.hex.toString(16);
  34176. while (str.length < 6) {
  34177. str = '0' + str;
  34178. }
  34179. return '#' + str;
  34180. } else if (colorFormat === 'CSS_RGB') {
  34181. return 'rgb(' + r + ',' + g + ',' + b + ')';
  34182. } else if (colorFormat === 'CSS_RGBA') {
  34183. return 'rgba(' + r + ',' + g + ',' + b + ',' + a + ')';
  34184. } else if (colorFormat === 'HEX') {
  34185. return '0x' + color.hex.toString(16);
  34186. } else if (colorFormat === 'RGB_ARRAY') {
  34187. return '[' + r + ',' + g + ',' + b + ']';
  34188. } else if (colorFormat === 'RGBA_ARRAY') {
  34189. return '[' + r + ',' + g + ',' + b + ',' + a + ']';
  34190. } else if (colorFormat === 'RGB_OBJ') {
  34191. return '{r:' + r + ',g:' + g + ',b:' + b + '}';
  34192. } else if (colorFormat === 'RGBA_OBJ') {
  34193. return '{r:' + r + ',g:' + g + ',b:' + b + ',a:' + a + '}';
  34194. } else if (colorFormat === 'HSV_OBJ') {
  34195. return '{h:' + h + ',s:' + s + ',v:' + v + '}';
  34196. } else if (colorFormat === 'HSVA_OBJ') {
  34197. return '{h:' + h + ',s:' + s + ',v:' + v + ',a:' + a + '}';
  34198. }
  34199. return 'unknown format';
  34200. }
  34201. var ARR_EACH = Array.prototype.forEach;
  34202. var ARR_SLICE = Array.prototype.slice;
  34203. var Common = {
  34204. BREAK: {},
  34205. extend: function extend(target) {
  34206. this.each(ARR_SLICE.call(arguments, 1), function (obj) {
  34207. var keys = this.isObject(obj) ? Object.keys(obj) : [];
  34208. keys.forEach(function (key) {
  34209. if (!this.isUndefined(obj[key])) {
  34210. target[key] = obj[key];
  34211. }
  34212. }.bind(this));
  34213. }, this);
  34214. return target;
  34215. },
  34216. defaults: function defaults(target) {
  34217. this.each(ARR_SLICE.call(arguments, 1), function (obj) {
  34218. var keys = this.isObject(obj) ? Object.keys(obj) : [];
  34219. keys.forEach(function (key) {
  34220. if (this.isUndefined(target[key])) {
  34221. target[key] = obj[key];
  34222. }
  34223. }.bind(this));
  34224. }, this);
  34225. return target;
  34226. },
  34227. compose: function compose() {
  34228. var toCall = ARR_SLICE.call(arguments);
  34229. return function () {
  34230. var args = ARR_SLICE.call(arguments);
  34231. for (var i = toCall.length - 1; i >= 0; i--) {
  34232. args = [toCall[i].apply(this, args)];
  34233. }
  34234. return args[0];
  34235. };
  34236. },
  34237. each: function each(obj, itr, scope) {
  34238. if (!obj) {
  34239. return;
  34240. }
  34241. if (ARR_EACH && obj.forEach && obj.forEach === ARR_EACH) {
  34242. obj.forEach(itr, scope);
  34243. } else if (obj.length === obj.length + 0) {
  34244. var key = void 0;
  34245. var l = void 0;
  34246. for (key = 0, l = obj.length; key < l; key++) {
  34247. if (key in obj && itr.call(scope, obj[key], key) === this.BREAK) {
  34248. return;
  34249. }
  34250. }
  34251. } else {
  34252. for (var _key in obj) {
  34253. if (itr.call(scope, obj[_key], _key) === this.BREAK) {
  34254. return;
  34255. }
  34256. }
  34257. }
  34258. },
  34259. defer: function defer(fnc) {
  34260. setTimeout(fnc, 0);
  34261. },
  34262. debounce: function debounce(func, threshold, callImmediately) {
  34263. var timeout = void 0;
  34264. return function () {
  34265. var obj = this;
  34266. var args = arguments;
  34267. function delayed() {
  34268. timeout = null;
  34269. if (!callImmediately) func.apply(obj, args);
  34270. }
  34271. var callNow = callImmediately || !timeout;
  34272. clearTimeout(timeout);
  34273. timeout = setTimeout(delayed, threshold);
  34274. if (callNow) {
  34275. func.apply(obj, args);
  34276. }
  34277. };
  34278. },
  34279. toArray: function toArray(obj) {
  34280. if (obj.toArray) return obj.toArray();
  34281. return ARR_SLICE.call(obj);
  34282. },
  34283. isUndefined: function isUndefined(obj) {
  34284. return obj === undefined;
  34285. },
  34286. isNull: function isNull(obj) {
  34287. return obj === null;
  34288. },
  34289. isNaN: function (_isNaN) {
  34290. function isNaN() {
  34291. return _isNaN.apply(this, arguments);
  34292. }
  34293. isNaN.toString = function () {
  34294. return _isNaN.toString();
  34295. };
  34296. return isNaN;
  34297. }(function (obj) {
  34298. return isNaN(obj);
  34299. }),
  34300. isArray: Array.isArray || function (obj) {
  34301. return obj.constructor === Array;
  34302. },
  34303. isObject: function isObject(obj) {
  34304. return obj === Object(obj);
  34305. },
  34306. isNumber: function isNumber(obj) {
  34307. return obj === obj + 0;
  34308. },
  34309. isString: function isString(obj) {
  34310. return obj === obj + '';
  34311. },
  34312. isBoolean: function isBoolean(obj) {
  34313. return obj === false || obj === true;
  34314. },
  34315. isFunction: function isFunction(obj) {
  34316. return Object.prototype.toString.call(obj) === '[object Function]';
  34317. }
  34318. };
  34319. var INTERPRETATIONS = [{
  34320. litmus: Common.isString,
  34321. conversions: {
  34322. THREE_CHAR_HEX: {
  34323. read: function read(original) {
  34324. var test = original.match(/^#([A-F0-9])([A-F0-9])([A-F0-9])$/i);
  34325. if (test === null) {
  34326. return false;
  34327. }
  34328. return {
  34329. space: 'HEX',
  34330. hex: parseInt('0x' + test[1].toString() + test[1].toString() + test[2].toString() + test[2].toString() + test[3].toString() + test[3].toString(), 0)
  34331. };
  34332. },
  34333. write: colorToString
  34334. },
  34335. SIX_CHAR_HEX: {
  34336. read: function read(original) {
  34337. var test = original.match(/^#([A-F0-9]{6})$/i);
  34338. if (test === null) {
  34339. return false;
  34340. }
  34341. return {
  34342. space: 'HEX',
  34343. hex: parseInt('0x' + test[1].toString(), 0)
  34344. };
  34345. },
  34346. write: colorToString
  34347. },
  34348. CSS_RGB: {
  34349. read: function read(original) {
  34350. var test = original.match(/^rgb\(\s*(.+)\s*,\s*(.+)\s*,\s*(.+)\s*\)/);
  34351. if (test === null) {
  34352. return false;
  34353. }
  34354. return {
  34355. space: 'RGB',
  34356. r: parseFloat(test[1]),
  34357. g: parseFloat(test[2]),
  34358. b: parseFloat(test[3])
  34359. };
  34360. },
  34361. write: colorToString
  34362. },
  34363. CSS_RGBA: {
  34364. read: function read(original) {
  34365. var test = original.match(/^rgba\(\s*(.+)\s*,\s*(.+)\s*,\s*(.+)\s*,\s*(.+)\s*\)/);
  34366. if (test === null) {
  34367. return false;
  34368. }
  34369. return {
  34370. space: 'RGB',
  34371. r: parseFloat(test[1]),
  34372. g: parseFloat(test[2]),
  34373. b: parseFloat(test[3]),
  34374. a: parseFloat(test[4])
  34375. };
  34376. },
  34377. write: colorToString
  34378. }
  34379. }
  34380. }, {
  34381. litmus: Common.isNumber,
  34382. conversions: {
  34383. HEX: {
  34384. read: function read(original) {
  34385. return {
  34386. space: 'HEX',
  34387. hex: original,
  34388. conversionName: 'HEX'
  34389. };
  34390. },
  34391. write: function write(color) {
  34392. return color.hex;
  34393. }
  34394. }
  34395. }
  34396. }, {
  34397. litmus: Common.isArray,
  34398. conversions: {
  34399. RGB_ARRAY: {
  34400. read: function read(original) {
  34401. if (original.length !== 3) {
  34402. return false;
  34403. }
  34404. return {
  34405. space: 'RGB',
  34406. r: original[0],
  34407. g: original[1],
  34408. b: original[2]
  34409. };
  34410. },
  34411. write: function write(color) {
  34412. return [color.r, color.g, color.b];
  34413. }
  34414. },
  34415. RGBA_ARRAY: {
  34416. read: function read(original) {
  34417. if (original.length !== 4) return false;
  34418. return {
  34419. space: 'RGB',
  34420. r: original[0],
  34421. g: original[1],
  34422. b: original[2],
  34423. a: original[3]
  34424. };
  34425. },
  34426. write: function write(color) {
  34427. return [color.r, color.g, color.b, color.a];
  34428. }
  34429. }
  34430. }
  34431. }, {
  34432. litmus: Common.isObject,
  34433. conversions: {
  34434. RGBA_OBJ: {
  34435. read: function read(original) {
  34436. if (Common.isNumber(original.r) && Common.isNumber(original.g) && Common.isNumber(original.b) && Common.isNumber(original.a)) {
  34437. return {
  34438. space: 'RGB',
  34439. r: original.r,
  34440. g: original.g,
  34441. b: original.b,
  34442. a: original.a
  34443. };
  34444. }
  34445. return false;
  34446. },
  34447. write: function write(color) {
  34448. return {
  34449. r: color.r,
  34450. g: color.g,
  34451. b: color.b,
  34452. a: color.a
  34453. };
  34454. }
  34455. },
  34456. RGB_OBJ: {
  34457. read: function read(original) {
  34458. if (Common.isNumber(original.r) && Common.isNumber(original.g) && Common.isNumber(original.b)) {
  34459. return {
  34460. space: 'RGB',
  34461. r: original.r,
  34462. g: original.g,
  34463. b: original.b
  34464. };
  34465. }
  34466. return false;
  34467. },
  34468. write: function write(color) {
  34469. return {
  34470. r: color.r,
  34471. g: color.g,
  34472. b: color.b
  34473. };
  34474. }
  34475. },
  34476. HSVA_OBJ: {
  34477. read: function read(original) {
  34478. if (Common.isNumber(original.h) && Common.isNumber(original.s) && Common.isNumber(original.v) && Common.isNumber(original.a)) {
  34479. return {
  34480. space: 'HSV',
  34481. h: original.h,
  34482. s: original.s,
  34483. v: original.v,
  34484. a: original.a
  34485. };
  34486. }
  34487. return false;
  34488. },
  34489. write: function write(color) {
  34490. return {
  34491. h: color.h,
  34492. s: color.s,
  34493. v: color.v,
  34494. a: color.a
  34495. };
  34496. }
  34497. },
  34498. HSV_OBJ: {
  34499. read: function read(original) {
  34500. if (Common.isNumber(original.h) && Common.isNumber(original.s) && Common.isNumber(original.v)) {
  34501. return {
  34502. space: 'HSV',
  34503. h: original.h,
  34504. s: original.s,
  34505. v: original.v
  34506. };
  34507. }
  34508. return false;
  34509. },
  34510. write: function write(color) {
  34511. return {
  34512. h: color.h,
  34513. s: color.s,
  34514. v: color.v
  34515. };
  34516. }
  34517. }
  34518. }
  34519. }];
  34520. var result = void 0;
  34521. var toReturn = void 0;
  34522. var interpret = function interpret() {
  34523. toReturn = false;
  34524. var original = arguments.length > 1 ? Common.toArray(arguments) : arguments[0];
  34525. Common.each(INTERPRETATIONS, function (family) {
  34526. if (family.litmus(original)) {
  34527. Common.each(family.conversions, function (conversion, conversionName) {
  34528. result = conversion.read(original);
  34529. if (toReturn === false && result !== false) {
  34530. toReturn = result;
  34531. result.conversionName = conversionName;
  34532. result.conversion = conversion;
  34533. return Common.BREAK;
  34534. }
  34535. });
  34536. return Common.BREAK;
  34537. }
  34538. });
  34539. return toReturn;
  34540. };
  34541. var tmpComponent = void 0;
  34542. var ColorMath = {
  34543. hsv_to_rgb: function hsv_to_rgb(h, s, v) {
  34544. var hi = Math.floor(h / 60) % 6;
  34545. var f = h / 60 - Math.floor(h / 60);
  34546. var p = v * (1.0 - s);
  34547. var q = v * (1.0 - f * s);
  34548. var t = v * (1.0 - (1.0 - f) * s);
  34549. var c = [[v, t, p], [q, v, p], [p, v, t], [p, q, v], [t, p, v], [v, p, q]][hi];
  34550. return {
  34551. r: c[0] * 255,
  34552. g: c[1] * 255,
  34553. b: c[2] * 255
  34554. };
  34555. },
  34556. rgb_to_hsv: function rgb_to_hsv(r, g, b) {
  34557. var min = Math.min(r, g, b);
  34558. var max = Math.max(r, g, b);
  34559. var delta = max - min;
  34560. var h = void 0;
  34561. var s = void 0;
  34562. if (max !== 0) {
  34563. s = delta / max;
  34564. } else {
  34565. return {
  34566. h: NaN,
  34567. s: 0,
  34568. v: 0
  34569. };
  34570. }
  34571. if (r === max) {
  34572. h = (g - b) / delta;
  34573. } else if (g === max) {
  34574. h = 2 + (b - r) / delta;
  34575. } else {
  34576. h = 4 + (r - g) / delta;
  34577. }
  34578. h /= 6;
  34579. if (h < 0) {
  34580. h += 1;
  34581. }
  34582. return {
  34583. h: h * 360,
  34584. s: s,
  34585. v: max / 255
  34586. };
  34587. },
  34588. rgb_to_hex: function rgb_to_hex(r, g, b) {
  34589. var hex = this.hex_with_component(0, 2, r);
  34590. hex = this.hex_with_component(hex, 1, g);
  34591. hex = this.hex_with_component(hex, 0, b);
  34592. return hex;
  34593. },
  34594. component_from_hex: function component_from_hex(hex, componentIndex) {
  34595. return hex >> componentIndex * 8 & 0xFF;
  34596. },
  34597. hex_with_component: function hex_with_component(hex, componentIndex, value) {
  34598. return value << (tmpComponent = componentIndex * 8) | hex & ~(0xFF << tmpComponent);
  34599. }
  34600. };
  34601. var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) {
  34602. return typeof obj;
  34603. } : function (obj) {
  34604. return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
  34605. };
  34606. var classCallCheck = function (instance, Constructor) {
  34607. if (!(instance instanceof Constructor)) {
  34608. throw new TypeError("Cannot call a class as a function");
  34609. }
  34610. };
  34611. var createClass = function () {
  34612. function defineProperties(target, props) {
  34613. for (var i = 0; i < props.length; i++) {
  34614. var descriptor = props[i];
  34615. descriptor.enumerable = descriptor.enumerable || false;
  34616. descriptor.configurable = true;
  34617. if ("value" in descriptor) descriptor.writable = true;
  34618. Object.defineProperty(target, descriptor.key, descriptor);
  34619. }
  34620. }
  34621. return function (Constructor, protoProps, staticProps) {
  34622. if (protoProps) defineProperties(Constructor.prototype, protoProps);
  34623. if (staticProps) defineProperties(Constructor, staticProps);
  34624. return Constructor;
  34625. };
  34626. }();
  34627. var get = function get(object, property, receiver) {
  34628. if (object === null) object = Function.prototype;
  34629. var desc = Object.getOwnPropertyDescriptor(object, property);
  34630. if (desc === undefined) {
  34631. var parent = Object.getPrototypeOf(object);
  34632. if (parent === null) {
  34633. return undefined;
  34634. } else {
  34635. return get(parent, property, receiver);
  34636. }
  34637. } else if ("value" in desc) {
  34638. return desc.value;
  34639. } else {
  34640. var getter = desc.get;
  34641. if (getter === undefined) {
  34642. return undefined;
  34643. }
  34644. return getter.call(receiver);
  34645. }
  34646. };
  34647. var inherits = function (subClass, superClass) {
  34648. if (typeof superClass !== "function" && superClass !== null) {
  34649. throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);
  34650. }
  34651. subClass.prototype = Object.create(superClass && superClass.prototype, {
  34652. constructor: {
  34653. value: subClass,
  34654. enumerable: false,
  34655. writable: true,
  34656. configurable: true
  34657. }
  34658. });
  34659. if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
  34660. };
  34661. var possibleConstructorReturn = function (self, call) {
  34662. if (!self) {
  34663. throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  34664. }
  34665. return call && (typeof call === "object" || typeof call === "function") ? call : self;
  34666. };
  34667. var Color = function () {
  34668. function Color() {
  34669. classCallCheck(this, Color);
  34670. this.__state = interpret.apply(this, arguments);
  34671. if (this.__state === false) {
  34672. throw new Error('Failed to interpret color arguments');
  34673. }
  34674. this.__state.a = this.__state.a || 1;
  34675. }
  34676. createClass(Color, [{
  34677. key: 'toString',
  34678. value: function toString() {
  34679. return colorToString(this);
  34680. }
  34681. }, {
  34682. key: 'toHexString',
  34683. value: function toHexString() {
  34684. return colorToString(this, true);
  34685. }
  34686. }, {
  34687. key: 'toOriginal',
  34688. value: function toOriginal() {
  34689. return this.__state.conversion.write(this);
  34690. }
  34691. }]);
  34692. return Color;
  34693. }();
  34694. function defineRGBComponent(target, component, componentHexIndex) {
  34695. Object.defineProperty(target, component, {
  34696. get: function get$$1() {
  34697. if (this.__state.space === 'RGB') {
  34698. return this.__state[component];
  34699. }
  34700. Color.recalculateRGB(this, component, componentHexIndex);
  34701. return this.__state[component];
  34702. },
  34703. set: function set$$1(v) {
  34704. if (this.__state.space !== 'RGB') {
  34705. Color.recalculateRGB(this, component, componentHexIndex);
  34706. this.__state.space = 'RGB';
  34707. }
  34708. this.__state[component] = v;
  34709. }
  34710. });
  34711. }
  34712. function defineHSVComponent(target, component) {
  34713. Object.defineProperty(target, component, {
  34714. get: function get$$1() {
  34715. if (this.__state.space === 'HSV') {
  34716. return this.__state[component];
  34717. }
  34718. Color.recalculateHSV(this);
  34719. return this.__state[component];
  34720. },
  34721. set: function set$$1(v) {
  34722. if (this.__state.space !== 'HSV') {
  34723. Color.recalculateHSV(this);
  34724. this.__state.space = 'HSV';
  34725. }
  34726. this.__state[component] = v;
  34727. }
  34728. });
  34729. }
  34730. Color.recalculateRGB = function (color, component, componentHexIndex) {
  34731. if (color.__state.space === 'HEX') {
  34732. color.__state[component] = ColorMath.component_from_hex(color.__state.hex, componentHexIndex);
  34733. } else if (color.__state.space === 'HSV') {
  34734. Common.extend(color.__state, ColorMath.hsv_to_rgb(color.__state.h, color.__state.s, color.__state.v));
  34735. } else {
  34736. throw new Error('Corrupted color state');
  34737. }
  34738. };
  34739. Color.recalculateHSV = function (color) {
  34740. var result = ColorMath.rgb_to_hsv(color.r, color.g, color.b);
  34741. Common.extend(color.__state, {
  34742. s: result.s,
  34743. v: result.v
  34744. });
  34745. if (!Common.isNaN(result.h)) {
  34746. color.__state.h = result.h;
  34747. } else if (Common.isUndefined(color.__state.h)) {
  34748. color.__state.h = 0;
  34749. }
  34750. };
  34751. Color.COMPONENTS = ['r', 'g', 'b', 'h', 's', 'v', 'hex', 'a'];
  34752. defineRGBComponent(Color.prototype, 'r', 2);
  34753. defineRGBComponent(Color.prototype, 'g', 1);
  34754. defineRGBComponent(Color.prototype, 'b', 0);
  34755. defineHSVComponent(Color.prototype, 'h');
  34756. defineHSVComponent(Color.prototype, 's');
  34757. defineHSVComponent(Color.prototype, 'v');
  34758. Object.defineProperty(Color.prototype, 'a', {
  34759. get: function get$$1() {
  34760. return this.__state.a;
  34761. },
  34762. set: function set$$1(v) {
  34763. this.__state.a = v;
  34764. }
  34765. });
  34766. Object.defineProperty(Color.prototype, 'hex', {
  34767. get: function get$$1() {
  34768. if (!this.__state.space !== 'HEX') {
  34769. this.__state.hex = ColorMath.rgb_to_hex(this.r, this.g, this.b);
  34770. }
  34771. return this.__state.hex;
  34772. },
  34773. set: function set$$1(v) {
  34774. this.__state.space = 'HEX';
  34775. this.__state.hex = v;
  34776. }
  34777. });
  34778. var Controller = function () {
  34779. function Controller(object, property) {
  34780. classCallCheck(this, Controller);
  34781. this.initialValue = object[property];
  34782. this.domElement = document.createElement('div');
  34783. this.object = object;
  34784. this.property = property;
  34785. this.__onChange = undefined;
  34786. this.__onFinishChange = undefined;
  34787. }
  34788. createClass(Controller, [{
  34789. key: 'onChange',
  34790. value: function onChange(fnc) {
  34791. this.__onChange = fnc;
  34792. return this;
  34793. }
  34794. }, {
  34795. key: 'onFinishChange',
  34796. value: function onFinishChange(fnc) {
  34797. this.__onFinishChange = fnc;
  34798. return this;
  34799. }
  34800. }, {
  34801. key: 'setValue',
  34802. value: function setValue(newValue) {
  34803. this.object[this.property] = newValue;
  34804. if (this.__onChange) {
  34805. this.__onChange.call(this, newValue);
  34806. }
  34807. this.updateDisplay();
  34808. return this;
  34809. }
  34810. }, {
  34811. key: 'getValue',
  34812. value: function getValue() {
  34813. return this.object[this.property];
  34814. }
  34815. }, {
  34816. key: 'updateDisplay',
  34817. value: function updateDisplay() {
  34818. return this;
  34819. }
  34820. }, {
  34821. key: 'isModified',
  34822. value: function isModified() {
  34823. return this.initialValue !== this.getValue();
  34824. }
  34825. }]);
  34826. return Controller;
  34827. }();
  34828. var EVENT_MAP = {
  34829. HTMLEvents: ['change'],
  34830. MouseEvents: ['click', 'mousemove', 'mousedown', 'mouseup', 'mouseover'],
  34831. KeyboardEvents: ['keydown']
  34832. };
  34833. var EVENT_MAP_INV = {};
  34834. Common.each(EVENT_MAP, function (v, k) {
  34835. Common.each(v, function (e) {
  34836. EVENT_MAP_INV[e] = k;
  34837. });
  34838. });
  34839. var CSS_VALUE_PIXELS = /(\d+(\.\d+)?)px/;
  34840. function cssValueToPixels(val) {
  34841. if (val === '0' || Common.isUndefined(val)) {
  34842. return 0;
  34843. }
  34844. var match = val.match(CSS_VALUE_PIXELS);
  34845. if (!Common.isNull(match)) {
  34846. return parseFloat(match[1]);
  34847. }
  34848. return 0;
  34849. }
  34850. var dom = {
  34851. makeSelectable: function makeSelectable(elem, selectable) {
  34852. if (elem === undefined || elem.style === undefined) return;
  34853. elem.onselectstart = selectable ? function () {
  34854. return false;
  34855. } : function () {};
  34856. elem.style.MozUserSelect = selectable ? 'auto' : 'none';
  34857. elem.style.KhtmlUserSelect = selectable ? 'auto' : 'none';
  34858. elem.unselectable = selectable ? 'on' : 'off';
  34859. },
  34860. makeFullscreen: function makeFullscreen(elem, hor, vert) {
  34861. var vertical = vert;
  34862. var horizontal = hor;
  34863. if (Common.isUndefined(horizontal)) {
  34864. horizontal = true;
  34865. }
  34866. if (Common.isUndefined(vertical)) {
  34867. vertical = true;
  34868. }
  34869. elem.style.position = 'absolute';
  34870. if (horizontal) {
  34871. elem.style.left = 0;
  34872. elem.style.right = 0;
  34873. }
  34874. if (vertical) {
  34875. elem.style.top = 0;
  34876. elem.style.bottom = 0;
  34877. }
  34878. },
  34879. fakeEvent: function fakeEvent(elem, eventType, pars, aux) {
  34880. var params = pars || {};
  34881. var className = EVENT_MAP_INV[eventType];
  34882. if (!className) {
  34883. throw new Error('Event type ' + eventType + ' not supported.');
  34884. }
  34885. var evt = document.createEvent(className);
  34886. switch (className) {
  34887. case 'MouseEvents':
  34888. {
  34889. var clientX = params.x || params.clientX || 0;
  34890. var clientY = params.y || params.clientY || 0;
  34891. evt.initMouseEvent(eventType, params.bubbles || false, params.cancelable || true, window, params.clickCount || 1, 0, 0, clientX, clientY, false, false, false, false, 0, null);
  34892. break;
  34893. }
  34894. case 'KeyboardEvents':
  34895. {
  34896. var init = evt.initKeyboardEvent || evt.initKeyEvent;
  34897. Common.defaults(params, {
  34898. cancelable: true,
  34899. ctrlKey: false,
  34900. altKey: false,
  34901. shiftKey: false,
  34902. metaKey: false,
  34903. keyCode: undefined,
  34904. charCode: undefined
  34905. });
  34906. init(eventType, params.bubbles || false, params.cancelable, window, params.ctrlKey, params.altKey, params.shiftKey, params.metaKey, params.keyCode, params.charCode);
  34907. break;
  34908. }
  34909. default:
  34910. {
  34911. evt.initEvent(eventType, params.bubbles || false, params.cancelable || true);
  34912. break;
  34913. }
  34914. }
  34915. Common.defaults(evt, aux);
  34916. elem.dispatchEvent(evt);
  34917. },
  34918. bind: function bind(elem, event, func, newBool) {
  34919. var bool = newBool || false;
  34920. if (elem.addEventListener) {
  34921. elem.addEventListener(event, func, bool);
  34922. } else if (elem.attachEvent) {
  34923. elem.attachEvent('on' + event, func);
  34924. }
  34925. return dom;
  34926. },
  34927. unbind: function unbind(elem, event, func, newBool) {
  34928. var bool = newBool || false;
  34929. if (elem.removeEventListener) {
  34930. elem.removeEventListener(event, func, bool);
  34931. } else if (elem.detachEvent) {
  34932. elem.detachEvent('on' + event, func);
  34933. }
  34934. return dom;
  34935. },
  34936. addClass: function addClass(elem, className) {
  34937. if (elem.className === undefined) {
  34938. elem.className = className;
  34939. } else if (elem.className !== className) {
  34940. var classes = elem.className.split(/ +/);
  34941. if (classes.indexOf(className) === -1) {
  34942. classes.push(className);
  34943. elem.className = classes.join(' ').replace(/^\s+/, '').replace(/\s+$/, '');
  34944. }
  34945. }
  34946. return dom;
  34947. },
  34948. removeClass: function removeClass(elem, className) {
  34949. if (className) {
  34950. if (elem.className === className) {
  34951. elem.removeAttribute('class');
  34952. } else {
  34953. var classes = elem.className.split(/ +/);
  34954. var index = classes.indexOf(className);
  34955. if (index !== -1) {
  34956. classes.splice(index, 1);
  34957. elem.className = classes.join(' ');
  34958. }
  34959. }
  34960. } else {
  34961. elem.className = undefined;
  34962. }
  34963. return dom;
  34964. },
  34965. hasClass: function hasClass(elem, className) {
  34966. return new RegExp('(?:^|\\s+)' + className + '(?:\\s+|$)').test(elem.className) || false;
  34967. },
  34968. getWidth: function getWidth(elem) {
  34969. var style = getComputedStyle(elem);
  34970. return cssValueToPixels(style['border-left-width']) + cssValueToPixels(style['border-right-width']) + cssValueToPixels(style['padding-left']) + cssValueToPixels(style['padding-right']) + cssValueToPixels(style.width);
  34971. },
  34972. getHeight: function getHeight(elem) {
  34973. var style = getComputedStyle(elem);
  34974. return cssValueToPixels(style['border-top-width']) + cssValueToPixels(style['border-bottom-width']) + cssValueToPixels(style['padding-top']) + cssValueToPixels(style['padding-bottom']) + cssValueToPixels(style.height);
  34975. },
  34976. getOffset: function getOffset(el) {
  34977. var elem = el;
  34978. var offset = {
  34979. left: 0,
  34980. top: 0
  34981. };
  34982. if (elem.offsetParent) {
  34983. do {
  34984. offset.left += elem.offsetLeft;
  34985. offset.top += elem.offsetTop;
  34986. elem = elem.offsetParent;
  34987. } while (elem);
  34988. }
  34989. return offset;
  34990. },
  34991. isActive: function isActive(elem) {
  34992. return elem === document.activeElement && (elem.type || elem.href);
  34993. }
  34994. };
  34995. var BooleanController = function (_Controller) {
  34996. inherits(BooleanController, _Controller);
  34997. function BooleanController(object, property) {
  34998. classCallCheck(this, BooleanController);
  34999. var _this2 = possibleConstructorReturn(this, (BooleanController.__proto__ || Object.getPrototypeOf(BooleanController)).call(this, object, property));
  35000. var _this = _this2;
  35001. _this2.__prev = _this2.getValue();
  35002. _this2.__checkbox = document.createElement('input');
  35003. _this2.__checkbox.setAttribute('type', 'checkbox');
  35004. function onChange() {
  35005. _this.setValue(!_this.__prev);
  35006. }
  35007. dom.bind(_this2.__checkbox, 'change', onChange, false);
  35008. _this2.domElement.appendChild(_this2.__checkbox);
  35009. _this2.updateDisplay();
  35010. return _this2;
  35011. }
  35012. createClass(BooleanController, [{
  35013. key: 'setValue',
  35014. value: function setValue(v) {
  35015. var toReturn = get(BooleanController.prototype.__proto__ || Object.getPrototypeOf(BooleanController.prototype), 'setValue', this).call(this, v);
  35016. if (this.__onFinishChange) {
  35017. this.__onFinishChange.call(this, this.getValue());
  35018. }
  35019. this.__prev = this.getValue();
  35020. return toReturn;
  35021. }
  35022. }, {
  35023. key: 'updateDisplay',
  35024. value: function updateDisplay() {
  35025. if (this.getValue() === true) {
  35026. this.__checkbox.setAttribute('checked', 'checked');
  35027. this.__checkbox.checked = true;
  35028. this.__prev = true;
  35029. } else {
  35030. this.__checkbox.checked = false;
  35031. this.__prev = false;
  35032. }
  35033. return get(BooleanController.prototype.__proto__ || Object.getPrototypeOf(BooleanController.prototype), 'updateDisplay', this).call(this);
  35034. }
  35035. }]);
  35036. return BooleanController;
  35037. }(Controller);
  35038. var OptionController = function (_Controller) {
  35039. inherits(OptionController, _Controller);
  35040. function OptionController(object, property, opts) {
  35041. classCallCheck(this, OptionController);
  35042. var _this2 = possibleConstructorReturn(this, (OptionController.__proto__ || Object.getPrototypeOf(OptionController)).call(this, object, property));
  35043. var options = opts;
  35044. var _this = _this2;
  35045. _this2.__select = document.createElement('select');
  35046. if (Common.isArray(options)) {
  35047. var map = {};
  35048. Common.each(options, function (element) {
  35049. map[element] = element;
  35050. });
  35051. options = map;
  35052. }
  35053. Common.each(options, function (value, key) {
  35054. var opt = document.createElement('option');
  35055. opt.innerHTML = key;
  35056. opt.setAttribute('value', value);
  35057. _this.__select.appendChild(opt);
  35058. });
  35059. _this2.updateDisplay();
  35060. dom.bind(_this2.__select, 'change', function () {
  35061. var desiredValue = this.options[this.selectedIndex].value;
  35062. _this.setValue(desiredValue);
  35063. });
  35064. _this2.domElement.appendChild(_this2.__select);
  35065. return _this2;
  35066. }
  35067. createClass(OptionController, [{
  35068. key: 'setValue',
  35069. value: function setValue(v) {
  35070. var toReturn = get(OptionController.prototype.__proto__ || Object.getPrototypeOf(OptionController.prototype), 'setValue', this).call(this, v);
  35071. if (this.__onFinishChange) {
  35072. this.__onFinishChange.call(this, this.getValue());
  35073. }
  35074. return toReturn;
  35075. }
  35076. }, {
  35077. key: 'updateDisplay',
  35078. value: function updateDisplay() {
  35079. if (dom.isActive(this.__select)) return this;
  35080. this.__select.value = this.getValue();
  35081. return get(OptionController.prototype.__proto__ || Object.getPrototypeOf(OptionController.prototype), 'updateDisplay', this).call(this);
  35082. }
  35083. }]);
  35084. return OptionController;
  35085. }(Controller);
  35086. var StringController = function (_Controller) {
  35087. inherits(StringController, _Controller);
  35088. function StringController(object, property) {
  35089. classCallCheck(this, StringController);
  35090. var _this2 = possibleConstructorReturn(this, (StringController.__proto__ || Object.getPrototypeOf(StringController)).call(this, object, property));
  35091. var _this = _this2;
  35092. function onChange() {
  35093. _this.setValue(_this.__input.value);
  35094. }
  35095. function onBlur() {
  35096. if (_this.__onFinishChange) {
  35097. _this.__onFinishChange.call(_this, _this.getValue());
  35098. }
  35099. }
  35100. _this2.__input = document.createElement('input');
  35101. _this2.__input.setAttribute('type', 'text');
  35102. dom.bind(_this2.__input, 'keyup', onChange);
  35103. dom.bind(_this2.__input, 'change', onChange);
  35104. dom.bind(_this2.__input, 'blur', onBlur);
  35105. dom.bind(_this2.__input, 'keydown', function (e) {
  35106. if (e.keyCode === 13) {
  35107. this.blur();
  35108. }
  35109. });
  35110. _this2.updateDisplay();
  35111. _this2.domElement.appendChild(_this2.__input);
  35112. return _this2;
  35113. }
  35114. createClass(StringController, [{
  35115. key: 'updateDisplay',
  35116. value: function updateDisplay() {
  35117. if (!dom.isActive(this.__input)) {
  35118. this.__input.value = this.getValue();
  35119. }
  35120. return get(StringController.prototype.__proto__ || Object.getPrototypeOf(StringController.prototype), 'updateDisplay', this).call(this);
  35121. }
  35122. }]);
  35123. return StringController;
  35124. }(Controller);
  35125. function numDecimals(x) {
  35126. var _x = x.toString();
  35127. if (_x.indexOf('.') > -1) {
  35128. return _x.length - _x.indexOf('.') - 1;
  35129. }
  35130. return 0;
  35131. }
  35132. var NumberController = function (_Controller) {
  35133. inherits(NumberController, _Controller);
  35134. function NumberController(object, property, params) {
  35135. classCallCheck(this, NumberController);
  35136. var _this = possibleConstructorReturn(this, (NumberController.__proto__ || Object.getPrototypeOf(NumberController)).call(this, object, property));
  35137. var _params = params || {};
  35138. _this.__min = _params.min;
  35139. _this.__max = _params.max;
  35140. _this.__step = _params.step;
  35141. if (Common.isUndefined(_this.__step)) {
  35142. if (_this.initialValue === 0) {
  35143. _this.__impliedStep = 1;
  35144. } else {
  35145. _this.__impliedStep = Math.pow(10, Math.floor(Math.log(Math.abs(_this.initialValue)) / Math.LN10)) / 10;
  35146. }
  35147. } else {
  35148. _this.__impliedStep = _this.__step;
  35149. }
  35150. _this.__precision = numDecimals(_this.__impliedStep);
  35151. return _this;
  35152. }
  35153. createClass(NumberController, [{
  35154. key: 'setValue',
  35155. value: function setValue(v) {
  35156. var _v = v;
  35157. if (this.__min !== undefined && _v < this.__min) {
  35158. _v = this.__min;
  35159. } else if (this.__max !== undefined && _v > this.__max) {
  35160. _v = this.__max;
  35161. }
  35162. if (this.__step !== undefined && _v % this.__step !== 0) {
  35163. _v = Math.round(_v / this.__step) * this.__step;
  35164. }
  35165. return get(NumberController.prototype.__proto__ || Object.getPrototypeOf(NumberController.prototype), 'setValue', this).call(this, _v);
  35166. }
  35167. }, {
  35168. key: 'min',
  35169. value: function min(minValue) {
  35170. this.__min = minValue;
  35171. return this;
  35172. }
  35173. }, {
  35174. key: 'max',
  35175. value: function max(maxValue) {
  35176. this.__max = maxValue;
  35177. return this;
  35178. }
  35179. }, {
  35180. key: 'step',
  35181. value: function step(stepValue) {
  35182. this.__step = stepValue;
  35183. this.__impliedStep = stepValue;
  35184. this.__precision = numDecimals(stepValue);
  35185. return this;
  35186. }
  35187. }]);
  35188. return NumberController;
  35189. }(Controller);
  35190. function roundToDecimal(value, decimals) {
  35191. var tenTo = Math.pow(10, decimals);
  35192. return Math.round(value * tenTo) / tenTo;
  35193. }
  35194. var NumberControllerBox = function (_NumberController) {
  35195. inherits(NumberControllerBox, _NumberController);
  35196. function NumberControllerBox(object, property, params) {
  35197. classCallCheck(this, NumberControllerBox);
  35198. var _this2 = possibleConstructorReturn(this, (NumberControllerBox.__proto__ || Object.getPrototypeOf(NumberControllerBox)).call(this, object, property, params));
  35199. _this2.__truncationSuspended = false;
  35200. var _this = _this2;
  35201. var prevY = void 0;
  35202. function onChange() {
  35203. var attempted = parseFloat(_this.__input.value);
  35204. if (!Common.isNaN(attempted)) {
  35205. _this.setValue(attempted);
  35206. }
  35207. }
  35208. function onFinish() {
  35209. if (_this.__onFinishChange) {
  35210. _this.__onFinishChange.call(_this, _this.getValue());
  35211. }
  35212. }
  35213. function onBlur() {
  35214. onFinish();
  35215. }
  35216. function onMouseDrag(e) {
  35217. var diff = prevY - e.clientY;
  35218. _this.setValue(_this.getValue() + diff * _this.__impliedStep);
  35219. prevY = e.clientY;
  35220. }
  35221. function onMouseUp() {
  35222. dom.unbind(window, 'mousemove', onMouseDrag);
  35223. dom.unbind(window, 'mouseup', onMouseUp);
  35224. onFinish();
  35225. }
  35226. function onMouseDown(e) {
  35227. dom.bind(window, 'mousemove', onMouseDrag);
  35228. dom.bind(window, 'mouseup', onMouseUp);
  35229. prevY = e.clientY;
  35230. }
  35231. _this2.__input = document.createElement('input');
  35232. _this2.__input.setAttribute('type', 'text');
  35233. dom.bind(_this2.__input, 'change', onChange);
  35234. dom.bind(_this2.__input, 'blur', onBlur);
  35235. dom.bind(_this2.__input, 'mousedown', onMouseDown);
  35236. dom.bind(_this2.__input, 'keydown', function (e) {
  35237. if (e.keyCode === 13) {
  35238. _this.__truncationSuspended = true;
  35239. this.blur();
  35240. _this.__truncationSuspended = false;
  35241. onFinish();
  35242. }
  35243. });
  35244. _this2.updateDisplay();
  35245. _this2.domElement.appendChild(_this2.__input);
  35246. return _this2;
  35247. }
  35248. createClass(NumberControllerBox, [{
  35249. key: 'updateDisplay',
  35250. value: function updateDisplay() {
  35251. this.__input.value = this.__truncationSuspended ? this.getValue() : roundToDecimal(this.getValue(), this.__precision);
  35252. return get(NumberControllerBox.prototype.__proto__ || Object.getPrototypeOf(NumberControllerBox.prototype), 'updateDisplay', this).call(this);
  35253. }
  35254. }]);
  35255. return NumberControllerBox;
  35256. }(NumberController);
  35257. function map(v, i1, i2, o1, o2) {
  35258. return o1 + (o2 - o1) * ((v - i1) / (i2 - i1));
  35259. }
  35260. var NumberControllerSlider = function (_NumberController) {
  35261. inherits(NumberControllerSlider, _NumberController);
  35262. function NumberControllerSlider(object, property, min, max, step) {
  35263. classCallCheck(this, NumberControllerSlider);
  35264. var _this2 = possibleConstructorReturn(this, (NumberControllerSlider.__proto__ || Object.getPrototypeOf(NumberControllerSlider)).call(this, object, property, {
  35265. min: min,
  35266. max: max,
  35267. step: step
  35268. }));
  35269. var _this = _this2;
  35270. _this2.__background = document.createElement('div');
  35271. _this2.__foreground = document.createElement('div');
  35272. dom.bind(_this2.__background, 'mousedown', onMouseDown);
  35273. dom.bind(_this2.__background, 'touchstart', onTouchStart);
  35274. dom.addClass(_this2.__background, 'slider');
  35275. dom.addClass(_this2.__foreground, 'slider-fg');
  35276. function onMouseDown(e) {
  35277. document.activeElement.blur();
  35278. dom.bind(window, 'mousemove', onMouseDrag);
  35279. dom.bind(window, 'mouseup', onMouseUp);
  35280. onMouseDrag(e);
  35281. }
  35282. function onMouseDrag(e) {
  35283. e.preventDefault();
  35284. var bgRect = _this.__background.getBoundingClientRect();
  35285. _this.setValue(map(e.clientX, bgRect.left, bgRect.right, _this.__min, _this.__max));
  35286. return false;
  35287. }
  35288. function onMouseUp() {
  35289. dom.unbind(window, 'mousemove', onMouseDrag);
  35290. dom.unbind(window, 'mouseup', onMouseUp);
  35291. if (_this.__onFinishChange) {
  35292. _this.__onFinishChange.call(_this, _this.getValue());
  35293. }
  35294. }
  35295. function onTouchStart(e) {
  35296. if (e.touches.length !== 1) {
  35297. return;
  35298. }
  35299. dom.bind(window, 'touchmove', onTouchMove);
  35300. dom.bind(window, 'touchend', onTouchEnd);
  35301. onTouchMove(e);
  35302. }
  35303. function onTouchMove(e) {
  35304. var clientX = e.touches[0].clientX;
  35305. var bgRect = _this.__background.getBoundingClientRect();
  35306. _this.setValue(map(clientX, bgRect.left, bgRect.right, _this.__min, _this.__max));
  35307. }
  35308. function onTouchEnd() {
  35309. dom.unbind(window, 'touchmove', onTouchMove);
  35310. dom.unbind(window, 'touchend', onTouchEnd);
  35311. if (_this.__onFinishChange) {
  35312. _this.__onFinishChange.call(_this, _this.getValue());
  35313. }
  35314. }
  35315. _this2.updateDisplay();
  35316. _this2.__background.appendChild(_this2.__foreground);
  35317. _this2.domElement.appendChild(_this2.__background);
  35318. return _this2;
  35319. }
  35320. createClass(NumberControllerSlider, [{
  35321. key: 'updateDisplay',
  35322. value: function updateDisplay() {
  35323. var pct = (this.getValue() - this.__min) / (this.__max - this.__min);
  35324. this.__foreground.style.width = pct * 100 + '%';
  35325. return get(NumberControllerSlider.prototype.__proto__ || Object.getPrototypeOf(NumberControllerSlider.prototype), 'updateDisplay', this).call(this);
  35326. }
  35327. }]);
  35328. return NumberControllerSlider;
  35329. }(NumberController);
  35330. var FunctionController = function (_Controller) {
  35331. inherits(FunctionController, _Controller);
  35332. function FunctionController(object, property, text) {
  35333. classCallCheck(this, FunctionController);
  35334. var _this2 = possibleConstructorReturn(this, (FunctionController.__proto__ || Object.getPrototypeOf(FunctionController)).call(this, object, property));
  35335. var _this = _this2;
  35336. _this2.__button = document.createElement('div');
  35337. _this2.__button.innerHTML = text === undefined ? 'Fire' : text;
  35338. dom.bind(_this2.__button, 'click', function (e) {
  35339. e.preventDefault();
  35340. _this.fire();
  35341. return false;
  35342. });
  35343. dom.addClass(_this2.__button, 'button');
  35344. _this2.domElement.appendChild(_this2.__button);
  35345. return _this2;
  35346. }
  35347. createClass(FunctionController, [{
  35348. key: 'fire',
  35349. value: function fire() {
  35350. if (this.__onChange) {
  35351. this.__onChange.call(this);
  35352. }
  35353. this.getValue().call(this.object);
  35354. if (this.__onFinishChange) {
  35355. this.__onFinishChange.call(this, this.getValue());
  35356. }
  35357. }
  35358. }]);
  35359. return FunctionController;
  35360. }(Controller);
  35361. var ColorController = function (_Controller) {
  35362. inherits(ColorController, _Controller);
  35363. function ColorController(object, property) {
  35364. classCallCheck(this, ColorController);
  35365. var _this2 = possibleConstructorReturn(this, (ColorController.__proto__ || Object.getPrototypeOf(ColorController)).call(this, object, property));
  35366. _this2.__color = new Color(_this2.getValue());
  35367. _this2.__temp = new Color(0);
  35368. var _this = _this2;
  35369. _this2.domElement = document.createElement('div');
  35370. dom.makeSelectable(_this2.domElement, false);
  35371. _this2.__selector = document.createElement('div');
  35372. _this2.__selector.className = 'selector';
  35373. _this2.__saturation_field = document.createElement('div');
  35374. _this2.__saturation_field.className = 'saturation-field';
  35375. _this2.__field_knob = document.createElement('div');
  35376. _this2.__field_knob.className = 'field-knob';
  35377. _this2.__field_knob_border = '2px solid ';
  35378. _this2.__hue_knob = document.createElement('div');
  35379. _this2.__hue_knob.className = 'hue-knob';
  35380. _this2.__hue_field = document.createElement('div');
  35381. _this2.__hue_field.className = 'hue-field';
  35382. _this2.__input = document.createElement('input');
  35383. _this2.__input.type = 'text';
  35384. _this2.__input_textShadow = '0 1px 1px ';
  35385. dom.bind(_this2.__input, 'keydown', function (e) {
  35386. if (e.keyCode === 13) {
  35387. onBlur.call(this);
  35388. }
  35389. });
  35390. dom.bind(_this2.__input, 'blur', onBlur);
  35391. dom.bind(_this2.__selector, 'mousedown', function () {
  35392. dom.addClass(this, 'drag').bind(window, 'mouseup', function () {
  35393. dom.removeClass(_this.__selector, 'drag');
  35394. });
  35395. });
  35396. dom.bind(_this2.__selector, 'touchstart', function () {
  35397. dom.addClass(this, 'drag').bind(window, 'touchend', function () {
  35398. dom.removeClass(_this.__selector, 'drag');
  35399. });
  35400. });
  35401. var valueField = document.createElement('div');
  35402. Common.extend(_this2.__selector.style, {
  35403. width: '122px',
  35404. height: '102px',
  35405. padding: '3px',
  35406. backgroundColor: '#222',
  35407. boxShadow: '0px 1px 3px rgba(0,0,0,0.3)'
  35408. });
  35409. Common.extend(_this2.__field_knob.style, {
  35410. position: 'absolute',
  35411. width: '12px',
  35412. height: '12px',
  35413. border: _this2.__field_knob_border + (_this2.__color.v < 0.5 ? '#fff' : '#000'),
  35414. boxShadow: '0px 1px 3px rgba(0,0,0,0.5)',
  35415. borderRadius: '12px',
  35416. zIndex: 1
  35417. });
  35418. Common.extend(_this2.__hue_knob.style, {
  35419. position: 'absolute',
  35420. width: '15px',
  35421. height: '2px',
  35422. borderRight: '4px solid #fff',
  35423. zIndex: 1
  35424. });
  35425. Common.extend(_this2.__saturation_field.style, {
  35426. width: '100px',
  35427. height: '100px',
  35428. border: '1px solid #555',
  35429. marginRight: '3px',
  35430. display: 'inline-block',
  35431. cursor: 'pointer'
  35432. });
  35433. Common.extend(valueField.style, {
  35434. width: '100%',
  35435. height: '100%',
  35436. background: 'none'
  35437. });
  35438. linearGradient(valueField, 'top', 'rgba(0,0,0,0)', '#000');
  35439. Common.extend(_this2.__hue_field.style, {
  35440. width: '15px',
  35441. height: '100px',
  35442. border: '1px solid #555',
  35443. cursor: 'ns-resize',
  35444. position: 'absolute',
  35445. top: '3px',
  35446. right: '3px'
  35447. });
  35448. hueGradient(_this2.__hue_field);
  35449. Common.extend(_this2.__input.style, {
  35450. outline: 'none',
  35451. textAlign: 'center',
  35452. color: '#fff',
  35453. border: 0,
  35454. fontWeight: 'bold',
  35455. textShadow: _this2.__input_textShadow + 'rgba(0,0,0,0.7)'
  35456. });
  35457. dom.bind(_this2.__saturation_field, 'mousedown', fieldDown);
  35458. dom.bind(_this2.__saturation_field, 'touchstart', fieldDown);
  35459. dom.bind(_this2.__field_knob, 'mousedown', fieldDown);
  35460. dom.bind(_this2.__field_knob, 'touchstart', fieldDown);
  35461. dom.bind(_this2.__hue_field, 'mousedown', fieldDownH);
  35462. dom.bind(_this2.__hue_field, 'touchstart', fieldDownH);
  35463. function fieldDown(e) {
  35464. setSV(e);
  35465. dom.bind(window, 'mousemove', setSV);
  35466. dom.bind(window, 'touchmove', setSV);
  35467. dom.bind(window, 'mouseup', fieldUpSV);
  35468. dom.bind(window, 'touchend', fieldUpSV);
  35469. }
  35470. function fieldDownH(e) {
  35471. setH(e);
  35472. dom.bind(window, 'mousemove', setH);
  35473. dom.bind(window, 'touchmove', setH);
  35474. dom.bind(window, 'mouseup', fieldUpH);
  35475. dom.bind(window, 'touchend', fieldUpH);
  35476. }
  35477. function fieldUpSV() {
  35478. dom.unbind(window, 'mousemove', setSV);
  35479. dom.unbind(window, 'touchmove', setSV);
  35480. dom.unbind(window, 'mouseup', fieldUpSV);
  35481. dom.unbind(window, 'touchend', fieldUpSV);
  35482. onFinish();
  35483. }
  35484. function fieldUpH() {
  35485. dom.unbind(window, 'mousemove', setH);
  35486. dom.unbind(window, 'touchmove', setH);
  35487. dom.unbind(window, 'mouseup', fieldUpH);
  35488. dom.unbind(window, 'touchend', fieldUpH);
  35489. onFinish();
  35490. }
  35491. function onBlur() {
  35492. var i = interpret(this.value);
  35493. if (i !== false) {
  35494. _this.__color.__state = i;
  35495. _this.setValue(_this.__color.toOriginal());
  35496. } else {
  35497. this.value = _this.__color.toString();
  35498. }
  35499. }
  35500. function onFinish() {
  35501. if (_this.__onFinishChange) {
  35502. _this.__onFinishChange.call(_this, _this.__color.toOriginal());
  35503. }
  35504. }
  35505. _this2.__saturation_field.appendChild(valueField);
  35506. _this2.__selector.appendChild(_this2.__field_knob);
  35507. _this2.__selector.appendChild(_this2.__saturation_field);
  35508. _this2.__selector.appendChild(_this2.__hue_field);
  35509. _this2.__hue_field.appendChild(_this2.__hue_knob);
  35510. _this2.domElement.appendChild(_this2.__input);
  35511. _this2.domElement.appendChild(_this2.__selector);
  35512. _this2.updateDisplay();
  35513. function setSV(e) {
  35514. if (e.type.indexOf('touch') === -1) {
  35515. e.preventDefault();
  35516. }
  35517. var fieldRect = _this.__saturation_field.getBoundingClientRect();
  35518. var _ref = e.touches && e.touches[0] || e,
  35519. clientX = _ref.clientX,
  35520. clientY = _ref.clientY;
  35521. var s = (clientX - fieldRect.left) / (fieldRect.right - fieldRect.left);
  35522. var v = 1 - (clientY - fieldRect.top) / (fieldRect.bottom - fieldRect.top);
  35523. if (v > 1) {
  35524. v = 1;
  35525. } else if (v < 0) {
  35526. v = 0;
  35527. }
  35528. if (s > 1) {
  35529. s = 1;
  35530. } else if (s < 0) {
  35531. s = 0;
  35532. }
  35533. _this.__color.v = v;
  35534. _this.__color.s = s;
  35535. _this.setValue(_this.__color.toOriginal());
  35536. return false;
  35537. }
  35538. function setH(e) {
  35539. if (e.type.indexOf('touch') === -1) {
  35540. e.preventDefault();
  35541. }
  35542. var fieldRect = _this.__hue_field.getBoundingClientRect();
  35543. var _ref2 = e.touches && e.touches[0] || e,
  35544. clientY = _ref2.clientY;
  35545. var h = 1 - (clientY - fieldRect.top) / (fieldRect.bottom - fieldRect.top);
  35546. if (h > 1) {
  35547. h = 1;
  35548. } else if (h < 0) {
  35549. h = 0;
  35550. }
  35551. _this.__color.h = h * 360;
  35552. _this.setValue(_this.__color.toOriginal());
  35553. return false;
  35554. }
  35555. return _this2;
  35556. }
  35557. createClass(ColorController, [{
  35558. key: 'updateDisplay',
  35559. value: function updateDisplay() {
  35560. var i = interpret(this.getValue());
  35561. if (i !== false) {
  35562. var mismatch = false;
  35563. Common.each(Color.COMPONENTS, function (component) {
  35564. if (!Common.isUndefined(i[component]) && !Common.isUndefined(this.__color.__state[component]) && i[component] !== this.__color.__state[component]) {
  35565. mismatch = true;
  35566. return {};
  35567. }
  35568. }, this);
  35569. if (mismatch) {
  35570. Common.extend(this.__color.__state, i);
  35571. }
  35572. }
  35573. Common.extend(this.__temp.__state, this.__color.__state);
  35574. this.__temp.a = 1;
  35575. var flip = this.__color.v < 0.5 || this.__color.s > 0.5 ? 255 : 0;
  35576. var _flip = 255 - flip;
  35577. Common.extend(this.__field_knob.style, {
  35578. marginLeft: 100 * this.__color.s - 7 + 'px',
  35579. marginTop: 100 * (1 - this.__color.v) - 7 + 'px',
  35580. backgroundColor: this.__temp.toHexString(),
  35581. border: this.__field_knob_border + 'rgb(' + flip + ',' + flip + ',' + flip + ')'
  35582. });
  35583. this.__hue_knob.style.marginTop = (1 - this.__color.h / 360) * 100 + 'px';
  35584. this.__temp.s = 1;
  35585. this.__temp.v = 1;
  35586. linearGradient(this.__saturation_field, 'left', '#fff', this.__temp.toHexString());
  35587. this.__input.value = this.__color.toString();
  35588. Common.extend(this.__input.style, {
  35589. backgroundColor: this.__color.toHexString(),
  35590. color: 'rgb(' + flip + ',' + flip + ',' + flip + ')',
  35591. textShadow: this.__input_textShadow + 'rgba(' + _flip + ',' + _flip + ',' + _flip + ',.7)'
  35592. });
  35593. }
  35594. }]);
  35595. return ColorController;
  35596. }(Controller);
  35597. var vendors = ['-moz-', '-o-', '-webkit-', '-ms-', ''];
  35598. function linearGradient(elem, x, a, b) {
  35599. elem.style.background = '';
  35600. Common.each(vendors, function (vendor) {
  35601. elem.style.cssText += 'background: ' + vendor + 'linear-gradient(' + x + ', ' + a + ' 0%, ' + b + ' 100%); ';
  35602. });
  35603. }
  35604. function hueGradient(elem) {
  35605. elem.style.background = '';
  35606. elem.style.cssText += 'background: -moz-linear-gradient(top, #ff0000 0%, #ff00ff 17%, #0000ff 34%, #00ffff 50%, #00ff00 67%, #ffff00 84%, #ff0000 100%);';
  35607. elem.style.cssText += 'background: -webkit-linear-gradient(top, #ff0000 0%,#ff00ff 17%,#0000ff 34%,#00ffff 50%,#00ff00 67%,#ffff00 84%,#ff0000 100%);';
  35608. elem.style.cssText += 'background: -o-linear-gradient(top, #ff0000 0%,#ff00ff 17%,#0000ff 34%,#00ffff 50%,#00ff00 67%,#ffff00 84%,#ff0000 100%);';
  35609. elem.style.cssText += 'background: -ms-linear-gradient(top, #ff0000 0%,#ff00ff 17%,#0000ff 34%,#00ffff 50%,#00ff00 67%,#ffff00 84%,#ff0000 100%);';
  35610. elem.style.cssText += 'background: linear-gradient(top, #ff0000 0%,#ff00ff 17%,#0000ff 34%,#00ffff 50%,#00ff00 67%,#ffff00 84%,#ff0000 100%);';
  35611. }
  35612. var css = {
  35613. load: function load(url, indoc) {
  35614. var doc = indoc || document;
  35615. var link = doc.createElement('link');
  35616. link.type = 'text/css';
  35617. link.rel = 'stylesheet';
  35618. link.href = url;
  35619. doc.getElementsByTagName('head')[0].appendChild(link);
  35620. },
  35621. inject: function inject(cssContent, indoc) {
  35622. var doc = indoc || document;
  35623. var injected = document.createElement('style');
  35624. injected.type = 'text/css';
  35625. injected.innerHTML = cssContent;
  35626. var head = doc.getElementsByTagName('head')[0];
  35627. try {
  35628. head.appendChild(injected);
  35629. } catch (e) {}
  35630. }
  35631. };
  35632. 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>";
  35633. var ControllerFactory = function ControllerFactory(object, property) {
  35634. var initialValue = object[property];
  35635. if (Common.isArray(arguments[2]) || Common.isObject(arguments[2])) {
  35636. return new OptionController(object, property, arguments[2]);
  35637. }
  35638. if (Common.isNumber(initialValue)) {
  35639. if (Common.isNumber(arguments[2]) && Common.isNumber(arguments[3])) {
  35640. if (Common.isNumber(arguments[4])) {
  35641. return new NumberControllerSlider(object, property, arguments[2], arguments[3], arguments[4]);
  35642. }
  35643. return new NumberControllerSlider(object, property, arguments[2], arguments[3]);
  35644. }
  35645. if (Common.isNumber(arguments[4])) {
  35646. return new NumberControllerBox(object, property, {
  35647. min: arguments[2],
  35648. max: arguments[3],
  35649. step: arguments[4]
  35650. });
  35651. }
  35652. return new NumberControllerBox(object, property, {
  35653. min: arguments[2],
  35654. max: arguments[3]
  35655. });
  35656. }
  35657. if (Common.isString(initialValue)) {
  35658. return new StringController(object, property);
  35659. }
  35660. if (Common.isFunction(initialValue)) {
  35661. return new FunctionController(object, property, '');
  35662. }
  35663. if (Common.isBoolean(initialValue)) {
  35664. return new BooleanController(object, property);
  35665. }
  35666. return null;
  35667. };
  35668. function requestAnimationFrame(callback) {
  35669. setTimeout(callback, 1000 / 60);
  35670. }
  35671. var requestAnimationFrame$1 = window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || requestAnimationFrame;
  35672. var CenteredDiv = function () {
  35673. function CenteredDiv() {
  35674. classCallCheck(this, CenteredDiv);
  35675. this.backgroundElement = document.createElement('div');
  35676. Common.extend(this.backgroundElement.style, {
  35677. backgroundColor: 'rgba(0,0,0,0.8)',
  35678. top: 0,
  35679. left: 0,
  35680. display: 'none',
  35681. zIndex: '1000',
  35682. opacity: 0,
  35683. WebkitTransition: 'opacity 0.2s linear',
  35684. transition: 'opacity 0.2s linear'
  35685. });
  35686. dom.makeFullscreen(this.backgroundElement);
  35687. this.backgroundElement.style.position = 'fixed';
  35688. this.domElement = document.createElement('div');
  35689. Common.extend(this.domElement.style, {
  35690. position: 'fixed',
  35691. display: 'none',
  35692. zIndex: '1001',
  35693. opacity: 0,
  35694. WebkitTransition: '-webkit-transform 0.2s ease-out, opacity 0.2s linear',
  35695. transition: 'transform 0.2s ease-out, opacity 0.2s linear'
  35696. });
  35697. document.body.appendChild(this.backgroundElement);
  35698. document.body.appendChild(this.domElement);
  35699. var _this = this;
  35700. dom.bind(this.backgroundElement, 'click', function () {
  35701. _this.hide();
  35702. });
  35703. }
  35704. createClass(CenteredDiv, [{
  35705. key: 'show',
  35706. value: function show() {
  35707. var _this = this;
  35708. this.backgroundElement.style.display = 'block';
  35709. this.domElement.style.display = 'block';
  35710. this.domElement.style.opacity = 0;
  35711. this.domElement.style.webkitTransform = 'scale(1.1)';
  35712. this.layout();
  35713. Common.defer(function () {
  35714. _this.backgroundElement.style.opacity = 1;
  35715. _this.domElement.style.opacity = 1;
  35716. _this.domElement.style.webkitTransform = 'scale(1)';
  35717. });
  35718. }
  35719. }, {
  35720. key: 'hide',
  35721. value: function hide() {
  35722. var _this = this;
  35723. var hide = function hide() {
  35724. _this.domElement.style.display = 'none';
  35725. _this.backgroundElement.style.display = 'none';
  35726. dom.unbind(_this.domElement, 'webkitTransitionEnd', hide);
  35727. dom.unbind(_this.domElement, 'transitionend', hide);
  35728. dom.unbind(_this.domElement, 'oTransitionEnd', hide);
  35729. };
  35730. dom.bind(this.domElement, 'webkitTransitionEnd', hide);
  35731. dom.bind(this.domElement, 'transitionend', hide);
  35732. dom.bind(this.domElement, 'oTransitionEnd', hide);
  35733. this.backgroundElement.style.opacity = 0;
  35734. this.domElement.style.opacity = 0;
  35735. this.domElement.style.webkitTransform = 'scale(1.1)';
  35736. }
  35737. }, {
  35738. key: 'layout',
  35739. value: function layout() {
  35740. this.domElement.style.left = window.innerWidth / 2 - dom.getWidth(this.domElement) / 2 + 'px';
  35741. this.domElement.style.top = window.innerHeight / 2 - dom.getHeight(this.domElement) / 2 + 'px';
  35742. }
  35743. }]);
  35744. return CenteredDiv;
  35745. }();
  35746. 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");
  35747. css.inject(styleSheet);
  35748. var CSS_NAMESPACE = 'dg';
  35749. var HIDE_KEY_CODE = 72;
  35750. var CLOSE_BUTTON_HEIGHT = 20;
  35751. var DEFAULT_DEFAULT_PRESET_NAME = 'Default';
  35752. var SUPPORTS_LOCAL_STORAGE = function () {
  35753. try {
  35754. return !!window.localStorage;
  35755. } catch (e) {
  35756. return false;
  35757. }
  35758. }();
  35759. var SAVE_DIALOGUE = void 0;
  35760. var autoPlaceVirgin = true;
  35761. var autoPlaceContainer = void 0;
  35762. var hide = false;
  35763. var hideableGuis = [];
  35764. var GUI = function GUI(pars) {
  35765. var _this = this;
  35766. var params = pars || {};
  35767. this.domElement = document.createElement('div');
  35768. this.__ul = document.createElement('ul');
  35769. this.domElement.appendChild(this.__ul);
  35770. dom.addClass(this.domElement, CSS_NAMESPACE);
  35771. this.__folders = {};
  35772. this.__controllers = [];
  35773. this.__rememberedObjects = [];
  35774. this.__rememberedObjectIndecesToControllers = [];
  35775. this.__listening = [];
  35776. params = Common.defaults(params, {
  35777. closeOnTop: false,
  35778. autoPlace: true,
  35779. width: GUI.DEFAULT_WIDTH
  35780. });
  35781. params = Common.defaults(params, {
  35782. resizable: params.autoPlace,
  35783. hideable: params.autoPlace
  35784. });
  35785. if (!Common.isUndefined(params.load)) {
  35786. if (params.preset) {
  35787. params.load.preset = params.preset;
  35788. }
  35789. } else {
  35790. params.load = {
  35791. preset: DEFAULT_DEFAULT_PRESET_NAME
  35792. };
  35793. }
  35794. if (Common.isUndefined(params.parent) && params.hideable) {
  35795. hideableGuis.push(this);
  35796. }
  35797. params.resizable = Common.isUndefined(params.parent) && params.resizable;
  35798. if (params.autoPlace && Common.isUndefined(params.scrollable)) {
  35799. params.scrollable = true;
  35800. }
  35801. var useLocalStorage = SUPPORTS_LOCAL_STORAGE && localStorage.getItem(getLocalStorageHash(this, 'isLocal')) === 'true';
  35802. var saveToLocalStorage = void 0;
  35803. var titleRow = void 0;
  35804. Object.defineProperties(this, {
  35805. parent: {
  35806. get: function get$$1() {
  35807. return params.parent;
  35808. }
  35809. },
  35810. scrollable: {
  35811. get: function get$$1() {
  35812. return params.scrollable;
  35813. }
  35814. },
  35815. autoPlace: {
  35816. get: function get$$1() {
  35817. return params.autoPlace;
  35818. }
  35819. },
  35820. closeOnTop: {
  35821. get: function get$$1() {
  35822. return params.closeOnTop;
  35823. }
  35824. },
  35825. preset: {
  35826. get: function get$$1() {
  35827. if (_this.parent) {
  35828. return _this.getRoot().preset;
  35829. }
  35830. return params.load.preset;
  35831. },
  35832. set: function set$$1(v) {
  35833. if (_this.parent) {
  35834. _this.getRoot().preset = v;
  35835. } else {
  35836. params.load.preset = v;
  35837. }
  35838. setPresetSelectIndex(this);
  35839. _this.revert();
  35840. }
  35841. },
  35842. width: {
  35843. get: function get$$1() {
  35844. return params.width;
  35845. },
  35846. set: function set$$1(v) {
  35847. params.width = v;
  35848. setWidth(_this, v);
  35849. }
  35850. },
  35851. name: {
  35852. get: function get$$1() {
  35853. return params.name;
  35854. },
  35855. set: function set$$1(v) {
  35856. params.name = v;
  35857. if (titleRow) {
  35858. titleRow.innerHTML = params.name;
  35859. }
  35860. }
  35861. },
  35862. closed: {
  35863. get: function get$$1() {
  35864. return params.closed;
  35865. },
  35866. set: function set$$1(v) {
  35867. params.closed = v;
  35868. if (params.closed) {
  35869. dom.addClass(_this.__ul, GUI.CLASS_CLOSED);
  35870. } else {
  35871. dom.removeClass(_this.__ul, GUI.CLASS_CLOSED);
  35872. }
  35873. this.onResize();
  35874. if (_this.__closeButton) {
  35875. _this.__closeButton.innerHTML = v ? GUI.TEXT_OPEN : GUI.TEXT_CLOSED;
  35876. }
  35877. }
  35878. },
  35879. load: {
  35880. get: function get$$1() {
  35881. return params.load;
  35882. }
  35883. },
  35884. useLocalStorage: {
  35885. get: function get$$1() {
  35886. return useLocalStorage;
  35887. },
  35888. set: function set$$1(bool) {
  35889. if (SUPPORTS_LOCAL_STORAGE) {
  35890. useLocalStorage = bool;
  35891. if (bool) {
  35892. dom.bind(window, 'unload', saveToLocalStorage);
  35893. } else {
  35894. dom.unbind(window, 'unload', saveToLocalStorage);
  35895. }
  35896. localStorage.setItem(getLocalStorageHash(_this, 'isLocal'), bool);
  35897. }
  35898. }
  35899. }
  35900. });
  35901. if (Common.isUndefined(params.parent)) {
  35902. this.closed = params.closed || false;
  35903. dom.addClass(this.domElement, GUI.CLASS_MAIN);
  35904. dom.makeSelectable(this.domElement, false);
  35905. if (SUPPORTS_LOCAL_STORAGE) {
  35906. if (useLocalStorage) {
  35907. _this.useLocalStorage = true;
  35908. var savedGui = localStorage.getItem(getLocalStorageHash(this, 'gui'));
  35909. if (savedGui) {
  35910. params.load = JSON.parse(savedGui);
  35911. }
  35912. }
  35913. }
  35914. this.__closeButton = document.createElement('div');
  35915. this.__closeButton.innerHTML = GUI.TEXT_CLOSED;
  35916. dom.addClass(this.__closeButton, GUI.CLASS_CLOSE_BUTTON);
  35917. if (params.closeOnTop) {
  35918. dom.addClass(this.__closeButton, GUI.CLASS_CLOSE_TOP);
  35919. this.domElement.insertBefore(this.__closeButton, this.domElement.childNodes[0]);
  35920. } else {
  35921. dom.addClass(this.__closeButton, GUI.CLASS_CLOSE_BOTTOM);
  35922. this.domElement.appendChild(this.__closeButton);
  35923. }
  35924. dom.bind(this.__closeButton, 'click', function () {
  35925. _this.closed = !_this.closed;
  35926. });
  35927. } else {
  35928. if (params.closed === undefined) {
  35929. params.closed = true;
  35930. }
  35931. var titleRowName = document.createTextNode(params.name);
  35932. dom.addClass(titleRowName, 'controller-name');
  35933. titleRow = addRow(_this, titleRowName);
  35934. var onClickTitle = function onClickTitle(e) {
  35935. e.preventDefault();
  35936. _this.closed = !_this.closed;
  35937. return false;
  35938. };
  35939. dom.addClass(this.__ul, GUI.CLASS_CLOSED);
  35940. dom.addClass(titleRow, 'title');
  35941. dom.bind(titleRow, 'click', onClickTitle);
  35942. if (!params.closed) {
  35943. this.closed = false;
  35944. }
  35945. }
  35946. if (params.autoPlace) {
  35947. if (Common.isUndefined(params.parent)) {
  35948. if (autoPlaceVirgin) {
  35949. autoPlaceContainer = document.createElement('div');
  35950. dom.addClass(autoPlaceContainer, CSS_NAMESPACE);
  35951. dom.addClass(autoPlaceContainer, GUI.CLASS_AUTO_PLACE_CONTAINER);
  35952. document.body.appendChild(autoPlaceContainer);
  35953. autoPlaceVirgin = false;
  35954. }
  35955. autoPlaceContainer.appendChild(this.domElement);
  35956. dom.addClass(this.domElement, GUI.CLASS_AUTO_PLACE);
  35957. }
  35958. if (!this.parent) {
  35959. setWidth(_this, params.width);
  35960. }
  35961. }
  35962. this.__resizeHandler = function () {
  35963. _this.onResizeDebounced();
  35964. };
  35965. dom.bind(window, 'resize', this.__resizeHandler);
  35966. dom.bind(this.__ul, 'webkitTransitionEnd', this.__resizeHandler);
  35967. dom.bind(this.__ul, 'transitionend', this.__resizeHandler);
  35968. dom.bind(this.__ul, 'oTransitionEnd', this.__resizeHandler);
  35969. this.onResize();
  35970. if (params.resizable) {
  35971. addResizeHandle(this);
  35972. }
  35973. saveToLocalStorage = function saveToLocalStorage() {
  35974. if (SUPPORTS_LOCAL_STORAGE && localStorage.getItem(getLocalStorageHash(_this, 'isLocal')) === 'true') {
  35975. localStorage.setItem(getLocalStorageHash(_this, 'gui'), JSON.stringify(_this.getSaveObject()));
  35976. }
  35977. };
  35978. this.saveToLocalStorageIfPossible = saveToLocalStorage;
  35979. function resetWidth() {
  35980. var root = _this.getRoot();
  35981. root.width += 1;
  35982. Common.defer(function () {
  35983. root.width -= 1;
  35984. });
  35985. }
  35986. if (!params.parent) {
  35987. resetWidth();
  35988. }
  35989. };
  35990. GUI.toggleHide = function () {
  35991. hide = !hide;
  35992. Common.each(hideableGuis, function (gui) {
  35993. gui.domElement.style.display = hide ? 'none' : '';
  35994. });
  35995. };
  35996. GUI.CLASS_AUTO_PLACE = 'a';
  35997. GUI.CLASS_AUTO_PLACE_CONTAINER = 'ac';
  35998. GUI.CLASS_MAIN = 'main';
  35999. GUI.CLASS_CONTROLLER_ROW = 'cr';
  36000. GUI.CLASS_TOO_TALL = 'taller-than-window';
  36001. GUI.CLASS_CLOSED = 'closed';
  36002. GUI.CLASS_CLOSE_BUTTON = 'close-button';
  36003. GUI.CLASS_CLOSE_TOP = 'close-top';
  36004. GUI.CLASS_CLOSE_BOTTOM = 'close-bottom';
  36005. GUI.CLASS_DRAG = 'drag';
  36006. GUI.DEFAULT_WIDTH = 245;
  36007. GUI.TEXT_CLOSED = 'Close Controls';
  36008. GUI.TEXT_OPEN = 'Open Controls';
  36009. GUI._keydownHandler = function (e) {
  36010. if (document.activeElement.type !== 'text' && (e.which === HIDE_KEY_CODE || e.keyCode === HIDE_KEY_CODE)) {
  36011. GUI.toggleHide();
  36012. }
  36013. };
  36014. dom.bind(window, 'keydown', GUI._keydownHandler, false);
  36015. Common.extend(GUI.prototype, {
  36016. add: function add(object, property) {
  36017. return _add(this, object, property, {
  36018. factoryArgs: Array.prototype.slice.call(arguments, 2)
  36019. });
  36020. },
  36021. addColor: function addColor(object, property) {
  36022. return _add(this, object, property, {
  36023. color: true
  36024. });
  36025. },
  36026. remove: function remove(controller) {
  36027. this.__ul.removeChild(controller.__li);
  36028. this.__controllers.splice(this.__controllers.indexOf(controller), 1);
  36029. var _this = this;
  36030. Common.defer(function () {
  36031. _this.onResize();
  36032. });
  36033. },
  36034. destroy: function destroy() {
  36035. if (this.parent) {
  36036. throw new Error('Only the root GUI should be removed with .destroy(). ' + 'For subfolders, use gui.removeFolder(folder) instead.');
  36037. }
  36038. if (this.autoPlace) {
  36039. autoPlaceContainer.removeChild(this.domElement);
  36040. }
  36041. var _this = this;
  36042. Common.each(this.__folders, function (subfolder) {
  36043. _this.removeFolder(subfolder);
  36044. });
  36045. dom.unbind(window, 'keydown', GUI._keydownHandler, false);
  36046. removeListeners(this);
  36047. },
  36048. addFolder: function addFolder(name) {
  36049. if (this.__folders[name] !== undefined) {
  36050. throw new Error('You already have a folder in this GUI by the' + ' name "' + name + '"');
  36051. }
  36052. var newGuiParams = {
  36053. name: name,
  36054. parent: this
  36055. };
  36056. newGuiParams.autoPlace = this.autoPlace;
  36057. if (this.load && this.load.folders && this.load.folders[name]) {
  36058. newGuiParams.closed = this.load.folders[name].closed;
  36059. newGuiParams.load = this.load.folders[name];
  36060. }
  36061. var gui = new GUI(newGuiParams);
  36062. this.__folders[name] = gui;
  36063. var li = addRow(this, gui.domElement);
  36064. dom.addClass(li, 'folder');
  36065. return gui;
  36066. },
  36067. removeFolder: function removeFolder(folder) {
  36068. this.__ul.removeChild(folder.domElement.parentElement);
  36069. delete this.__folders[folder.name];
  36070. if (this.load && this.load.folders && this.load.folders[folder.name]) {
  36071. delete this.load.folders[folder.name];
  36072. }
  36073. removeListeners(folder);
  36074. var _this = this;
  36075. Common.each(folder.__folders, function (subfolder) {
  36076. folder.removeFolder(subfolder);
  36077. });
  36078. Common.defer(function () {
  36079. _this.onResize();
  36080. });
  36081. },
  36082. open: function open() {
  36083. this.closed = false;
  36084. },
  36085. close: function close() {
  36086. this.closed = true;
  36087. },
  36088. hide: function hide() {
  36089. this.domElement.style.display = 'none';
  36090. },
  36091. show: function show() {
  36092. this.domElement.style.display = '';
  36093. },
  36094. onResize: function onResize() {
  36095. var root = this.getRoot();
  36096. if (root.scrollable) {
  36097. var top = dom.getOffset(root.__ul).top;
  36098. var h = 0;
  36099. Common.each(root.__ul.childNodes, function (node) {
  36100. if (!(root.autoPlace && node === root.__save_row)) {
  36101. h += dom.getHeight(node);
  36102. }
  36103. });
  36104. if (window.innerHeight - top - CLOSE_BUTTON_HEIGHT < h) {
  36105. dom.addClass(root.domElement, GUI.CLASS_TOO_TALL);
  36106. root.__ul.style.height = window.innerHeight - top - CLOSE_BUTTON_HEIGHT + 'px';
  36107. } else {
  36108. dom.removeClass(root.domElement, GUI.CLASS_TOO_TALL);
  36109. root.__ul.style.height = 'auto';
  36110. }
  36111. }
  36112. if (root.__resize_handle) {
  36113. Common.defer(function () {
  36114. root.__resize_handle.style.height = root.__ul.offsetHeight + 'px';
  36115. });
  36116. }
  36117. if (root.__closeButton) {
  36118. root.__closeButton.style.width = root.width + 'px';
  36119. }
  36120. },
  36121. onResizeDebounced: Common.debounce(function () {
  36122. this.onResize();
  36123. }, 50),
  36124. remember: function remember() {
  36125. if (Common.isUndefined(SAVE_DIALOGUE)) {
  36126. SAVE_DIALOGUE = new CenteredDiv();
  36127. SAVE_DIALOGUE.domElement.innerHTML = saveDialogContents;
  36128. }
  36129. if (this.parent) {
  36130. throw new Error('You can only call remember on a top level GUI.');
  36131. }
  36132. var _this = this;
  36133. Common.each(Array.prototype.slice.call(arguments), function (object) {
  36134. if (_this.__rememberedObjects.length === 0) {
  36135. addSaveMenu(_this);
  36136. }
  36137. if (_this.__rememberedObjects.indexOf(object) === -1) {
  36138. _this.__rememberedObjects.push(object);
  36139. }
  36140. });
  36141. if (this.autoPlace) {
  36142. setWidth(this, this.width);
  36143. }
  36144. },
  36145. getRoot: function getRoot() {
  36146. var gui = this;
  36147. while (gui.parent) {
  36148. gui = gui.parent;
  36149. }
  36150. return gui;
  36151. },
  36152. getSaveObject: function getSaveObject() {
  36153. var toReturn = this.load;
  36154. toReturn.closed = this.closed;
  36155. if (this.__rememberedObjects.length > 0) {
  36156. toReturn.preset = this.preset;
  36157. if (!toReturn.remembered) {
  36158. toReturn.remembered = {};
  36159. }
  36160. toReturn.remembered[this.preset] = getCurrentPreset(this);
  36161. }
  36162. toReturn.folders = {};
  36163. Common.each(this.__folders, function (element, key) {
  36164. toReturn.folders[key] = element.getSaveObject();
  36165. });
  36166. return toReturn;
  36167. },
  36168. save: function save() {
  36169. if (!this.load.remembered) {
  36170. this.load.remembered = {};
  36171. }
  36172. this.load.remembered[this.preset] = getCurrentPreset(this);
  36173. markPresetModified(this, false);
  36174. this.saveToLocalStorageIfPossible();
  36175. },
  36176. saveAs: function saveAs(presetName) {
  36177. if (!this.load.remembered) {
  36178. this.load.remembered = {};
  36179. this.load.remembered[DEFAULT_DEFAULT_PRESET_NAME] = getCurrentPreset(this, true);
  36180. }
  36181. this.load.remembered[presetName] = getCurrentPreset(this);
  36182. this.preset = presetName;
  36183. addPresetOption(this, presetName, true);
  36184. this.saveToLocalStorageIfPossible();
  36185. },
  36186. revert: function revert(gui) {
  36187. Common.each(this.__controllers, function (controller) {
  36188. if (!this.getRoot().load.remembered) {
  36189. controller.setValue(controller.initialValue);
  36190. } else {
  36191. recallSavedValue(gui || this.getRoot(), controller);
  36192. }
  36193. if (controller.__onFinishChange) {
  36194. controller.__onFinishChange.call(controller, controller.getValue());
  36195. }
  36196. }, this);
  36197. Common.each(this.__folders, function (folder) {
  36198. folder.revert(folder);
  36199. });
  36200. if (!gui) {
  36201. markPresetModified(this.getRoot(), false);
  36202. }
  36203. },
  36204. listen: function listen(controller) {
  36205. var init = this.__listening.length === 0;
  36206. this.__listening.push(controller);
  36207. if (init) {
  36208. updateDisplays(this.__listening);
  36209. }
  36210. },
  36211. updateDisplay: function updateDisplay() {
  36212. Common.each(this.__controllers, function (controller) {
  36213. controller.updateDisplay();
  36214. });
  36215. Common.each(this.__folders, function (folder) {
  36216. folder.updateDisplay();
  36217. });
  36218. }
  36219. });
  36220. function addRow(gui, newDom, liBefore) {
  36221. var li = document.createElement('li');
  36222. if (newDom) {
  36223. li.appendChild(newDom);
  36224. }
  36225. if (liBefore) {
  36226. gui.__ul.insertBefore(li, liBefore);
  36227. } else {
  36228. gui.__ul.appendChild(li);
  36229. }
  36230. gui.onResize();
  36231. return li;
  36232. }
  36233. function removeListeners(gui) {
  36234. dom.unbind(window, 'resize', gui.__resizeHandler);
  36235. if (gui.saveToLocalStorageIfPossible) {
  36236. dom.unbind(window, 'unload', gui.saveToLocalStorageIfPossible);
  36237. }
  36238. }
  36239. function markPresetModified(gui, modified) {
  36240. var opt = gui.__preset_select[gui.__preset_select.selectedIndex];
  36241. if (modified) {
  36242. opt.innerHTML = opt.value + '*';
  36243. } else {
  36244. opt.innerHTML = opt.value;
  36245. }
  36246. }
  36247. function augmentController(gui, li, controller) {
  36248. controller.__li = li;
  36249. controller.__gui = gui;
  36250. Common.extend(controller, {
  36251. options: function options(_options) {
  36252. if (arguments.length > 1) {
  36253. var nextSibling = controller.__li.nextElementSibling;
  36254. controller.remove();
  36255. return _add(gui, controller.object, controller.property, {
  36256. before: nextSibling,
  36257. factoryArgs: [Common.toArray(arguments)]
  36258. });
  36259. }
  36260. if (Common.isArray(_options) || Common.isObject(_options)) {
  36261. var _nextSibling = controller.__li.nextElementSibling;
  36262. controller.remove();
  36263. return _add(gui, controller.object, controller.property, {
  36264. before: _nextSibling,
  36265. factoryArgs: [_options]
  36266. });
  36267. }
  36268. },
  36269. name: function name(_name) {
  36270. controller.__li.firstElementChild.firstElementChild.innerHTML = _name;
  36271. return controller;
  36272. },
  36273. listen: function listen() {
  36274. controller.__gui.listen(controller);
  36275. return controller;
  36276. },
  36277. remove: function remove() {
  36278. controller.__gui.remove(controller);
  36279. return controller;
  36280. }
  36281. });
  36282. if (controller instanceof NumberControllerSlider) {
  36283. var box = new NumberControllerBox(controller.object, controller.property, {
  36284. min: controller.__min,
  36285. max: controller.__max,
  36286. step: controller.__step
  36287. });
  36288. Common.each(['updateDisplay', 'onChange', 'onFinishChange', 'step', 'min', 'max'], function (method) {
  36289. var pc = controller[method];
  36290. var pb = box[method];
  36291. controller[method] = box[method] = function () {
  36292. var args = Array.prototype.slice.call(arguments);
  36293. pb.apply(box, args);
  36294. return pc.apply(controller, args);
  36295. };
  36296. });
  36297. dom.addClass(li, 'has-slider');
  36298. controller.domElement.insertBefore(box.domElement, controller.domElement.firstElementChild);
  36299. } else if (controller instanceof NumberControllerBox) {
  36300. var r = function r(returned) {
  36301. if (Common.isNumber(controller.__min) && Common.isNumber(controller.__max)) {
  36302. var oldName = controller.__li.firstElementChild.firstElementChild.innerHTML;
  36303. var wasListening = controller.__gui.__listening.indexOf(controller) > -1;
  36304. controller.remove();
  36305. var newController = _add(gui, controller.object, controller.property, {
  36306. before: controller.__li.nextElementSibling,
  36307. factoryArgs: [controller.__min, controller.__max, controller.__step]
  36308. });
  36309. newController.name(oldName);
  36310. if (wasListening) newController.listen();
  36311. return newController;
  36312. }
  36313. return returned;
  36314. };
  36315. controller.min = Common.compose(r, controller.min);
  36316. controller.max = Common.compose(r, controller.max);
  36317. } else if (controller instanceof BooleanController) {
  36318. dom.bind(li, 'click', function () {
  36319. dom.fakeEvent(controller.__checkbox, 'click');
  36320. });
  36321. dom.bind(controller.__checkbox, 'click', function (e) {
  36322. e.stopPropagation();
  36323. });
  36324. } else if (controller instanceof FunctionController) {
  36325. dom.bind(li, 'click', function () {
  36326. dom.fakeEvent(controller.__button, 'click');
  36327. });
  36328. dom.bind(li, 'mouseover', function () {
  36329. dom.addClass(controller.__button, 'hover');
  36330. });
  36331. dom.bind(li, 'mouseout', function () {
  36332. dom.removeClass(controller.__button, 'hover');
  36333. });
  36334. } else if (controller instanceof ColorController) {
  36335. dom.addClass(li, 'color');
  36336. controller.updateDisplay = Common.compose(function (val) {
  36337. li.style.borderLeftColor = controller.__color.toString();
  36338. return val;
  36339. }, controller.updateDisplay);
  36340. controller.updateDisplay();
  36341. }
  36342. controller.setValue = Common.compose(function (val) {
  36343. if (gui.getRoot().__preset_select && controller.isModified()) {
  36344. markPresetModified(gui.getRoot(), true);
  36345. }
  36346. return val;
  36347. }, controller.setValue);
  36348. }
  36349. function recallSavedValue(gui, controller) {
  36350. var root = gui.getRoot();
  36351. var matchedIndex = root.__rememberedObjects.indexOf(controller.object);
  36352. if (matchedIndex !== -1) {
  36353. var controllerMap = root.__rememberedObjectIndecesToControllers[matchedIndex];
  36354. if (controllerMap === undefined) {
  36355. controllerMap = {};
  36356. root.__rememberedObjectIndecesToControllers[matchedIndex] = controllerMap;
  36357. }
  36358. controllerMap[controller.property] = controller;
  36359. if (root.load && root.load.remembered) {
  36360. var presetMap = root.load.remembered;
  36361. var preset = void 0;
  36362. if (presetMap[gui.preset]) {
  36363. preset = presetMap[gui.preset];
  36364. } else if (presetMap[DEFAULT_DEFAULT_PRESET_NAME]) {
  36365. preset = presetMap[DEFAULT_DEFAULT_PRESET_NAME];
  36366. } else {
  36367. return;
  36368. }
  36369. if (preset[matchedIndex] && preset[matchedIndex][controller.property] !== undefined) {
  36370. var value = preset[matchedIndex][controller.property];
  36371. controller.initialValue = value;
  36372. controller.setValue(value);
  36373. }
  36374. }
  36375. }
  36376. }
  36377. function _add(gui, object, property, params) {
  36378. if (object[property] === undefined) {
  36379. throw new Error('Object "' + object + '" has no property "' + property + '"');
  36380. }
  36381. var controller = void 0;
  36382. if (params.color) {
  36383. controller = new ColorController(object, property);
  36384. } else {
  36385. var factoryArgs = [object, property].concat(params.factoryArgs);
  36386. controller = ControllerFactory.apply(gui, factoryArgs);
  36387. }
  36388. if (params.before instanceof Controller) {
  36389. params.before = params.before.__li;
  36390. }
  36391. recallSavedValue(gui, controller);
  36392. dom.addClass(controller.domElement, 'c');
  36393. var name = document.createElement('span');
  36394. dom.addClass(name, 'property-name');
  36395. name.innerHTML = controller.property;
  36396. var container = document.createElement('div');
  36397. container.appendChild(name);
  36398. container.appendChild(controller.domElement);
  36399. var li = addRow(gui, container, params.before);
  36400. dom.addClass(li, GUI.CLASS_CONTROLLER_ROW);
  36401. if (controller instanceof ColorController) {
  36402. dom.addClass(li, 'color');
  36403. } else {
  36404. dom.addClass(li, _typeof(controller.getValue()));
  36405. }
  36406. augmentController(gui, li, controller);
  36407. gui.__controllers.push(controller);
  36408. return controller;
  36409. }
  36410. function getLocalStorageHash(gui, key) {
  36411. return document.location.href + '.' + key;
  36412. }
  36413. function addPresetOption(gui, name, setSelected) {
  36414. var opt = document.createElement('option');
  36415. opt.innerHTML = name;
  36416. opt.value = name;
  36417. gui.__preset_select.appendChild(opt);
  36418. if (setSelected) {
  36419. gui.__preset_select.selectedIndex = gui.__preset_select.length - 1;
  36420. }
  36421. }
  36422. function showHideExplain(gui, explain) {
  36423. explain.style.display = gui.useLocalStorage ? 'block' : 'none';
  36424. }
  36425. function addSaveMenu(gui) {
  36426. var div = gui.__save_row = document.createElement('li');
  36427. dom.addClass(gui.domElement, 'has-save');
  36428. gui.__ul.insertBefore(div, gui.__ul.firstChild);
  36429. dom.addClass(div, 'save-row');
  36430. var gears = document.createElement('span');
  36431. gears.innerHTML = '&nbsp;';
  36432. dom.addClass(gears, 'button gears');
  36433. var button = document.createElement('span');
  36434. button.innerHTML = 'Save';
  36435. dom.addClass(button, 'button');
  36436. dom.addClass(button, 'save');
  36437. var button2 = document.createElement('span');
  36438. button2.innerHTML = 'New';
  36439. dom.addClass(button2, 'button');
  36440. dom.addClass(button2, 'save-as');
  36441. var button3 = document.createElement('span');
  36442. button3.innerHTML = 'Revert';
  36443. dom.addClass(button3, 'button');
  36444. dom.addClass(button3, 'revert');
  36445. var select = gui.__preset_select = document.createElement('select');
  36446. if (gui.load && gui.load.remembered) {
  36447. Common.each(gui.load.remembered, function (value, key) {
  36448. addPresetOption(gui, key, key === gui.preset);
  36449. });
  36450. } else {
  36451. addPresetOption(gui, DEFAULT_DEFAULT_PRESET_NAME, false);
  36452. }
  36453. dom.bind(select, 'change', function () {
  36454. for (var index = 0; index < gui.__preset_select.length; index++) {
  36455. gui.__preset_select[index].innerHTML = gui.__preset_select[index].value;
  36456. }
  36457. gui.preset = this.value;
  36458. });
  36459. div.appendChild(select);
  36460. div.appendChild(gears);
  36461. div.appendChild(button);
  36462. div.appendChild(button2);
  36463. div.appendChild(button3);
  36464. if (SUPPORTS_LOCAL_STORAGE) {
  36465. var explain = document.getElementById('dg-local-explain');
  36466. var localStorageCheckBox = document.getElementById('dg-local-storage');
  36467. var saveLocally = document.getElementById('dg-save-locally');
  36468. saveLocally.style.display = 'block';
  36469. if (localStorage.getItem(getLocalStorageHash(gui, 'isLocal')) === 'true') {
  36470. localStorageCheckBox.setAttribute('checked', 'checked');
  36471. }
  36472. showHideExplain(gui, explain);
  36473. dom.bind(localStorageCheckBox, 'change', function () {
  36474. gui.useLocalStorage = !gui.useLocalStorage;
  36475. showHideExplain(gui, explain);
  36476. });
  36477. }
  36478. var newConstructorTextArea = document.getElementById('dg-new-constructor');
  36479. dom.bind(newConstructorTextArea, 'keydown', function (e) {
  36480. if (e.metaKey && (e.which === 67 || e.keyCode === 67)) {
  36481. SAVE_DIALOGUE.hide();
  36482. }
  36483. });
  36484. dom.bind(gears, 'click', function () {
  36485. newConstructorTextArea.innerHTML = JSON.stringify(gui.getSaveObject(), undefined, 2);
  36486. SAVE_DIALOGUE.show();
  36487. newConstructorTextArea.focus();
  36488. newConstructorTextArea.select();
  36489. });
  36490. dom.bind(button, 'click', function () {
  36491. gui.save();
  36492. });
  36493. dom.bind(button2, 'click', function () {
  36494. var presetName = prompt('Enter a new preset name.');
  36495. if (presetName) {
  36496. gui.saveAs(presetName);
  36497. }
  36498. });
  36499. dom.bind(button3, 'click', function () {
  36500. gui.revert();
  36501. });
  36502. }
  36503. function addResizeHandle(gui) {
  36504. var pmouseX = void 0;
  36505. gui.__resize_handle = document.createElement('div');
  36506. Common.extend(gui.__resize_handle.style, {
  36507. width: '6px',
  36508. marginLeft: '-3px',
  36509. height: '200px',
  36510. cursor: 'ew-resize',
  36511. position: 'absolute'
  36512. });
  36513. function drag(e) {
  36514. e.preventDefault();
  36515. gui.width += pmouseX - e.clientX;
  36516. gui.onResize();
  36517. pmouseX = e.clientX;
  36518. return false;
  36519. }
  36520. function dragStop() {
  36521. dom.removeClass(gui.__closeButton, GUI.CLASS_DRAG);
  36522. dom.unbind(window, 'mousemove', drag);
  36523. dom.unbind(window, 'mouseup', dragStop);
  36524. }
  36525. function dragStart(e) {
  36526. e.preventDefault();
  36527. pmouseX = e.clientX;
  36528. dom.addClass(gui.__closeButton, GUI.CLASS_DRAG);
  36529. dom.bind(window, 'mousemove', drag);
  36530. dom.bind(window, 'mouseup', dragStop);
  36531. return false;
  36532. }
  36533. dom.bind(gui.__resize_handle, 'mousedown', dragStart);
  36534. dom.bind(gui.__closeButton, 'mousedown', dragStart);
  36535. gui.domElement.insertBefore(gui.__resize_handle, gui.domElement.firstElementChild);
  36536. }
  36537. function setWidth(gui, w) {
  36538. gui.domElement.style.width = w + 'px';
  36539. if (gui.__save_row && gui.autoPlace) {
  36540. gui.__save_row.style.width = w + 'px';
  36541. }
  36542. if (gui.__closeButton) {
  36543. gui.__closeButton.style.width = w + 'px';
  36544. }
  36545. }
  36546. function getCurrentPreset(gui, useInitialValues) {
  36547. var toReturn = {};
  36548. Common.each(gui.__rememberedObjects, function (val, index) {
  36549. var savedValues = {};
  36550. var controllerMap = gui.__rememberedObjectIndecesToControllers[index];
  36551. Common.each(controllerMap, function (controller, property) {
  36552. savedValues[property] = useInitialValues ? controller.initialValue : controller.getValue();
  36553. });
  36554. toReturn[index] = savedValues;
  36555. });
  36556. return toReturn;
  36557. }
  36558. function setPresetSelectIndex(gui) {
  36559. for (var index = 0; index < gui.__preset_select.length; index++) {
  36560. if (gui.__preset_select[index].value === gui.preset) {
  36561. gui.__preset_select.selectedIndex = index;
  36562. }
  36563. }
  36564. }
  36565. function updateDisplays(controllerArray) {
  36566. if (controllerArray.length !== 0) {
  36567. requestAnimationFrame$1.call(window, function () {
  36568. updateDisplays(controllerArray);
  36569. });
  36570. }
  36571. Common.each(controllerArray, function (c) {
  36572. c.updateDisplay();
  36573. });
  36574. }
  36575. var color = {
  36576. Color: Color,
  36577. math: ColorMath,
  36578. interpret: interpret
  36579. };
  36580. exports.color = color;
  36581. var controllers = {
  36582. Controller: Controller,
  36583. BooleanController: BooleanController,
  36584. OptionController: OptionController,
  36585. StringController: StringController,
  36586. NumberController: NumberController,
  36587. NumberControllerBox: NumberControllerBox,
  36588. NumberControllerSlider: NumberControllerSlider,
  36589. FunctionController: FunctionController,
  36590. ColorController: ColorController
  36591. };
  36592. exports.controllers = controllers;
  36593. var dom$1 = {
  36594. dom: dom
  36595. };
  36596. exports.dom = dom$1;
  36597. var gui = {
  36598. GUI: GUI
  36599. };
  36600. exports.gui = gui;
  36601. var GUI$1 = GUI;
  36602. exports.GUI = GUI$1;
  36603. var index = {
  36604. color: color,
  36605. controllers: controllers,
  36606. dom: dom$1,
  36607. gui: gui,
  36608. GUI: GUI$1
  36609. };
  36610. var _default = index;
  36611. exports.default = _default;
  36612. },{}],"../node_modules/three/examples/jsm/libs/stats.module.js":[function(require,module,exports) {
  36613. "use strict";
  36614. Object.defineProperty(exports, "__esModule", {
  36615. value: true
  36616. });
  36617. exports.default = void 0;
  36618. /**
  36619. * @author mrdoob / http://mrdoob.com/
  36620. */
  36621. var Stats = function () {
  36622. var mode = 0;
  36623. var container = document.createElement('div');
  36624. container.style.cssText = 'position:fixed;top:0;left:0;cursor:pointer;opacity:0.9;z-index:10000';
  36625. container.addEventListener('click', function (event) {
  36626. event.preventDefault();
  36627. showPanel(++mode % container.children.length);
  36628. }, false); //
  36629. function addPanel(panel) {
  36630. container.appendChild(panel.dom);
  36631. return panel;
  36632. }
  36633. function showPanel(id) {
  36634. for (var i = 0; i < container.children.length; i++) {
  36635. container.children[i].style.display = i === id ? 'block' : 'none';
  36636. }
  36637. mode = id;
  36638. } //
  36639. var beginTime = (performance || Date).now(),
  36640. prevTime = beginTime,
  36641. frames = 0;
  36642. var fpsPanel = addPanel(new Stats.Panel('FPS', '#0ff', '#002'));
  36643. var msPanel = addPanel(new Stats.Panel('MS', '#0f0', '#020'));
  36644. if (self.performance && self.performance.memory) {
  36645. var memPanel = addPanel(new Stats.Panel('MB', '#f08', '#201'));
  36646. }
  36647. showPanel(0);
  36648. return {
  36649. REVISION: 16,
  36650. dom: container,
  36651. addPanel: addPanel,
  36652. showPanel: showPanel,
  36653. begin: function () {
  36654. beginTime = (performance || Date).now();
  36655. },
  36656. end: function () {
  36657. frames++;
  36658. var time = (performance || Date).now();
  36659. msPanel.update(time - beginTime, 200);
  36660. if (time >= prevTime + 1000) {
  36661. fpsPanel.update(frames * 1000 / (time - prevTime), 100);
  36662. prevTime = time;
  36663. frames = 0;
  36664. if (memPanel) {
  36665. var memory = performance.memory;
  36666. memPanel.update(memory.usedJSHeapSize / 1048576, memory.jsHeapSizeLimit / 1048576);
  36667. }
  36668. }
  36669. return time;
  36670. },
  36671. update: function () {
  36672. beginTime = this.end();
  36673. },
  36674. // Backwards Compatibility
  36675. domElement: container,
  36676. setMode: showPanel
  36677. };
  36678. };
  36679. Stats.Panel = function (name, fg, bg) {
  36680. var min = Infinity,
  36681. max = 0,
  36682. round = Math.round;
  36683. var PR = round(window.devicePixelRatio || 1);
  36684. var WIDTH = 80 * PR,
  36685. HEIGHT = 48 * PR,
  36686. TEXT_X = 3 * PR,
  36687. TEXT_Y = 2 * PR,
  36688. GRAPH_X = 3 * PR,
  36689. GRAPH_Y = 15 * PR,
  36690. GRAPH_WIDTH = 74 * PR,
  36691. GRAPH_HEIGHT = 30 * PR;
  36692. var canvas = document.createElement('canvas');
  36693. canvas.width = WIDTH;
  36694. canvas.height = HEIGHT;
  36695. canvas.style.cssText = 'width:80px;height:48px';
  36696. var context = canvas.getContext('2d');
  36697. context.font = 'bold ' + 9 * PR + 'px Helvetica,Arial,sans-serif';
  36698. context.textBaseline = 'top';
  36699. context.fillStyle = bg;
  36700. context.fillRect(0, 0, WIDTH, HEIGHT);
  36701. context.fillStyle = fg;
  36702. context.fillText(name, TEXT_X, TEXT_Y);
  36703. context.fillRect(GRAPH_X, GRAPH_Y, GRAPH_WIDTH, GRAPH_HEIGHT);
  36704. context.fillStyle = bg;
  36705. context.globalAlpha = 0.9;
  36706. context.fillRect(GRAPH_X, GRAPH_Y, GRAPH_WIDTH, GRAPH_HEIGHT);
  36707. return {
  36708. dom: canvas,
  36709. update: function (value, maxValue) {
  36710. min = Math.min(min, value);
  36711. max = Math.max(max, value);
  36712. context.fillStyle = bg;
  36713. context.globalAlpha = 1;
  36714. context.fillRect(0, 0, WIDTH, GRAPH_Y);
  36715. context.fillStyle = fg;
  36716. context.fillText(round(value) + ' ' + name + ' (' + round(min) + '-' + round(max) + ')', TEXT_X, TEXT_Y);
  36717. context.drawImage(canvas, GRAPH_X + PR, GRAPH_Y, GRAPH_WIDTH - PR, GRAPH_HEIGHT, GRAPH_X, GRAPH_Y, GRAPH_WIDTH - PR, GRAPH_HEIGHT);
  36718. context.fillRect(GRAPH_X + GRAPH_WIDTH - PR, GRAPH_Y, PR, GRAPH_HEIGHT);
  36719. context.fillStyle = bg;
  36720. context.globalAlpha = 0.9;
  36721. context.fillRect(GRAPH_X + GRAPH_WIDTH - PR, GRAPH_Y, PR, round((1 - value / maxValue) * GRAPH_HEIGHT));
  36722. }
  36723. };
  36724. };
  36725. var _default = Stats;
  36726. exports.default = _default;
  36727. },{}],"index.js":[function(require,module,exports) {
  36728. "use strict";
  36729. var _index = require("../src/index.js");
  36730. var _three = require("three");
  36731. var _OrbitControls = require("three/examples/jsm/controls/OrbitControls.js");
  36732. var _BufferGeometryUtils = require("three/examples/jsm/utils/BufferGeometryUtils.js");
  36733. var dat = _interopRequireWildcard(require("three/examples/jsm/libs/dat.gui.module.js"));
  36734. var _statsModule = _interopRequireDefault(require("three/examples/jsm/libs/stats.module.js"));
  36735. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  36736. function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; }
  36737. 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; }
  36738. let camera, controls, scene, renderer, tiles, cameraHelper;
  36739. let thirdPersonCamera, thirdPersonRenderer, thirdPersonControls;
  36740. let orthoCamera, orthoCameraHelper;
  36741. let box;
  36742. let raycaster, mouse, rayIntersect;
  36743. let offsetParent;
  36744. let statsContainer, stats;
  36745. let params = {
  36746. 'orthographic': false,
  36747. 'errorTarget': 6,
  36748. 'errorThreshold': 60,
  36749. 'maxDepth': 15,
  36750. 'loadSiblings': true,
  36751. 'up': '+Y',
  36752. 'displayBoxBounds': false,
  36753. 'colorMode': 0,
  36754. 'showThirdPerson': true,
  36755. 'reload': reinstantiateTiles
  36756. };
  36757. init();
  36758. animate();
  36759. function reinstantiateTiles() {
  36760. const url = window.location.hash.replace(/^#/, '') || './SampleTileset/tileset.json';
  36761. if (tiles) {
  36762. offsetParent.remove(tiles.group);
  36763. }
  36764. tiles = new _index.DebugTilesRenderer(url);
  36765. tiles.camera = camera;
  36766. tiles.setResolutionFromRenderer(renderer);
  36767. offsetParent.add(tiles.group);
  36768. }
  36769. function init() {
  36770. // Third person camera view
  36771. thirdPersonCamera = new _three.PerspectiveCamera(60, window.innerWidth / window.innerHeight, 1, 3000);
  36772. thirdPersonCamera.position.set(50, 40, 40);
  36773. thirdPersonCamera.lookAt(0, 0, 0);
  36774. thirdPersonRenderer = new _three.WebGLRenderer({
  36775. antialias: true
  36776. });
  36777. thirdPersonRenderer.setPixelRatio(window.devicePixelRatio);
  36778. thirdPersonRenderer.setSize(window.innerWidth, window.innerHeight);
  36779. thirdPersonRenderer.setClearColor(0x0f1416);
  36780. document.body.appendChild(thirdPersonRenderer.domElement);
  36781. thirdPersonRenderer.domElement.style.position = 'fixed';
  36782. thirdPersonRenderer.domElement.style.left = '5px';
  36783. thirdPersonRenderer.domElement.style.bottom = '5px';
  36784. thirdPersonControls = new _OrbitControls.OrbitControls(thirdPersonCamera, thirdPersonRenderer.domElement);
  36785. thirdPersonControls.screenSpacePanning = false;
  36786. thirdPersonControls.minDistance = 1;
  36787. thirdPersonControls.maxDistance = 2000; // primary camera view
  36788. scene = new _three.Scene();
  36789. renderer = new _three.WebGLRenderer({
  36790. antialias: true
  36791. });
  36792. renderer.setPixelRatio(window.devicePixelRatio);
  36793. renderer.setSize(window.innerWidth, window.innerHeight);
  36794. renderer.setClearColor(0x151c1f);
  36795. renderer.gammaInput = true;
  36796. renderer.gameOutput = true;
  36797. document.body.appendChild(renderer.domElement);
  36798. camera = new _three.PerspectiveCamera(60, window.innerWidth / window.innerHeight, 1, 2000);
  36799. camera.position.set(400, 400, 400);
  36800. cameraHelper = new _three.CameraHelper(camera);
  36801. scene.add(cameraHelper);
  36802. orthoCamera = new _three.OrthographicCamera();
  36803. orthoCameraHelper = new _three.CameraHelper(orthoCamera);
  36804. scene.add(orthoCameraHelper); // controls
  36805. controls = new _OrbitControls.OrbitControls(camera, renderer.domElement);
  36806. controls.screenSpacePanning = false;
  36807. controls.minDistance = 1;
  36808. controls.maxDistance = 2000; // lights
  36809. var dirLight = new _three.DirectionalLight(0xffffff);
  36810. dirLight.position.set(1, 2, 3);
  36811. scene.add(dirLight);
  36812. var ambLight = new _three.AmbientLight(0xffffff, 0.2);
  36813. scene.add(ambLight);
  36814. box = new _three.Box3();
  36815. offsetParent = new _three.Group();
  36816. scene.add(offsetParent); // Raycasting init
  36817. raycaster = new _three.Raycaster();
  36818. mouse = new _three.Vector2();
  36819. rayIntersect = new _three.Group();
  36820. const rayIntersectMat = new _three.MeshBasicMaterial({
  36821. color: 0xe91e63
  36822. });
  36823. const rayMesh = new _three.Mesh(new _three.CylinderBufferGeometry(0.25, 0.25, 6), rayIntersectMat);
  36824. rayMesh.rotation.x = Math.PI / 2;
  36825. rayMesh.position.z += 3;
  36826. rayIntersect.add(rayMesh);
  36827. const rayRing = new _three.Mesh(new _three.TorusBufferGeometry(1.5, 0.2, 16, 100), rayIntersectMat);
  36828. rayIntersect.add(rayRing);
  36829. scene.add(rayIntersect);
  36830. rayIntersect.visible = false;
  36831. reinstantiateTiles();
  36832. onWindowResize();
  36833. window.addEventListener('resize', onWindowResize, false);
  36834. window.addEventListener('mousemove', onMouseMove, false);
  36835. window.addEventListener('mousedown', onMouseDown, false);
  36836. window.addEventListener('mouseup', onMouseUp, false); // GUI
  36837. const gui = new dat.GUI();
  36838. gui.width = 300;
  36839. const tileOptions = gui.addFolder('Tiles Options');
  36840. tileOptions.add(params, 'orthographic');
  36841. tileOptions.add(params, 'loadSiblings');
  36842. tileOptions.add(params, 'errorTarget').min(0).max(50);
  36843. tileOptions.add(params, 'errorThreshold').min(0).max(1000);
  36844. tileOptions.add(params, 'maxDepth').min(1).max(100);
  36845. tileOptions.add(params, 'up', ['+Y', '-Z']);
  36846. tileOptions.open();
  36847. const debug = gui.addFolder('Debug Options');
  36848. debug.add(params, 'displayBoxBounds');
  36849. debug.add(params, 'colorMode', {
  36850. DEFAULT: 0,
  36851. SCREEN_ERROR: 1,
  36852. GEOMETRIC_ERROR: 2,
  36853. DISTANCE: 3,
  36854. DEPTH: 4,
  36855. IS_LEAF: 5.
  36856. }).onChange(function (v) {
  36857. tiles.colorMode = parseFloat(v);
  36858. if (this._lastController) {
  36859. this._lastController.remove();
  36860. }
  36861. switch (v) {
  36862. // GEOMETRIC_ERROR
  36863. case 2:
  36864. break;
  36865. // DISTANCE
  36866. case 3:
  36867. break;
  36868. // DEPTH
  36869. case 2:
  36870. break;
  36871. }
  36872. });
  36873. debug.open();
  36874. gui.add(params, 'showThirdPerson');
  36875. gui.add(params, 'reload');
  36876. gui.open();
  36877. statsContainer = document.createElement('div');
  36878. statsContainer.style.position = 'absolute';
  36879. statsContainer.style.top = 0;
  36880. statsContainer.style.left = 0;
  36881. statsContainer.style.color = 'white';
  36882. statsContainer.style.width = '100%';
  36883. statsContainer.style.textAlign = 'center';
  36884. statsContainer.style.padding = '5px';
  36885. statsContainer.style.pointerEvents = 'none';
  36886. statsContainer.style.lineHeight = '1.5em';
  36887. document.body.appendChild(statsContainer); // Stats
  36888. stats = new _statsModule.default();
  36889. stats.showPanel(0);
  36890. document.body.appendChild(stats.dom);
  36891. }
  36892. function onWindowResize() {
  36893. thirdPersonCamera.aspect = window.innerWidth / window.innerHeight;
  36894. thirdPersonCamera.updateProjectionMatrix();
  36895. thirdPersonRenderer.setSize(Math.floor(window.innerWidth / 3), Math.floor(window.innerHeight / 3));
  36896. camera.aspect = window.innerWidth / window.innerHeight;
  36897. camera.updateProjectionMatrix();
  36898. renderer.setSize(window.innerWidth, window.innerHeight);
  36899. updateOrthoCamera();
  36900. }
  36901. function onMouseMove(e) {
  36902. mouse.x = e.clientX / window.innerWidth * 2 - 1;
  36903. mouse.y = -(e.clientY / window.innerHeight) * 2 + 1;
  36904. }
  36905. const startPos = new _three.Vector2();
  36906. const endPos = new _three.Vector2();
  36907. function onMouseDown(e) {
  36908. startPos.set(e.clientX, e.clientY);
  36909. }
  36910. function onMouseUp(e) {
  36911. endPos.set(e.clientX, e.clientY);
  36912. if (startPos.distanceTo(endPos) > 2) {
  36913. return;
  36914. }
  36915. raycaster.setFromCamera(mouse, params.orthographic ? orthoCamera : camera);
  36916. raycaster.firstHitOnly = true;
  36917. const results = raycaster.intersectObject(tiles.group, true);
  36918. if (results.length) {
  36919. const object = results[0].object;
  36920. const info = tiles.getTileInformationFromObject(object);
  36921. let str = '';
  36922. for (const key in info) {
  36923. let val = info[key];
  36924. if (typeof val === 'number') {
  36925. val = Math.floor(val * 1e5) / 1e5;
  36926. }
  36927. let name = key;
  36928. while (name.length < 20) {
  36929. name += ' ';
  36930. }
  36931. str += `${name} : ${val}\n`;
  36932. }
  36933. console.log(str);
  36934. }
  36935. }
  36936. function updateOrthoCamera() {
  36937. orthoCamera.position.copy(camera.position);
  36938. orthoCamera.rotation.copy(camera.rotation);
  36939. const scale = camera.position.distanceTo(controls.target) / 2.0;
  36940. const aspect = window.innerWidth / window.innerHeight;
  36941. orthoCamera.left = -aspect * scale;
  36942. orthoCamera.right = aspect * scale;
  36943. orthoCamera.bottom = -scale;
  36944. orthoCamera.top = scale;
  36945. orthoCamera.near = camera.near;
  36946. orthoCamera.far = camera.far;
  36947. orthoCamera.updateProjectionMatrix();
  36948. }
  36949. function animate() {
  36950. // update options
  36951. tiles.errorTarget = params.errorTarget;
  36952. tiles.errorThreshold = params.errorThreshold;
  36953. tiles.loadSiblings = params.loadSiblings;
  36954. tiles.maxDepth = params.maxDepth;
  36955. tiles.camera = params.orthographic ? orthoCamera : camera;
  36956. tiles.displayBoxBounds = params.displayBoxBounds;
  36957. tiles.setResolutionFromRenderer(renderer); // update tiles
  36958. tiles.update();
  36959. window.tiles = tiles;
  36960. offsetParent.rotation.set(0, 0, 0);
  36961. if (params.up === '-Z') {
  36962. offsetParent.rotation.x = Math.PI / 2;
  36963. } // update tiles center
  36964. if (tiles.getBounds(box)) {
  36965. box.getCenter(tiles.group.position);
  36966. tiles.group.position.multiplyScalar(-1);
  36967. }
  36968. raycaster.setFromCamera(mouse, params.orthographic ? orthoCamera : camera);
  36969. raycaster.firstHitOnly = true;
  36970. const results = raycaster.intersectObject(tiles.group, true);
  36971. if (results.length) {
  36972. const closestHit = results[0];
  36973. const point = closestHit.point;
  36974. rayIntersect.position.copy(point); // If the display bounds are visible they get intersected
  36975. if (closestHit.face) {
  36976. const normal = closestHit.face.normal;
  36977. normal.transformDirection(closestHit.object.matrixWorld);
  36978. rayIntersect.lookAt(point.x + normal.x, point.y + normal.y, point.z + normal.z);
  36979. }
  36980. if (params.orthographic) {
  36981. rayIntersect.scale.setScalar(closestHit.distance / 150);
  36982. } else {
  36983. rayIntersect.scale.setScalar(closestHit.distance * camera.fov / 6000);
  36984. }
  36985. rayIntersect.visible = true;
  36986. } else {
  36987. rayIntersect.visible = false;
  36988. }
  36989. stats.begin();
  36990. render();
  36991. stats.end();
  36992. requestAnimationFrame(animate);
  36993. }
  36994. function render() {
  36995. updateOrthoCamera(); // render primary view
  36996. cameraHelper.visible = false;
  36997. orthoCameraHelper.visible = false;
  36998. renderer.render(scene, params.orthographic ? orthoCamera : camera); // render third person view
  36999. thirdPersonRenderer.domElement.style.visibility = params.showThirdPerson ? 'visible' : 'hidden';
  37000. if (params.showThirdPerson) {
  37001. cameraHelper.update();
  37002. cameraHelper.visible = !params.orthographic;
  37003. orthoCameraHelper.update();
  37004. orthoCameraHelper.visible = params.orthographic;
  37005. thirdPersonRenderer.render(scene, thirdPersonCamera);
  37006. }
  37007. const geomSet = new Set();
  37008. tiles.traverse(tile => {
  37009. const scene = tile.cached.scene;
  37010. if (scene) {
  37011. scene.traverse(c => {
  37012. if (c.geometry) {
  37013. geomSet.add(c.geometry);
  37014. }
  37015. });
  37016. }
  37017. });
  37018. let count = 0;
  37019. geomSet.forEach(g => {
  37020. count += _BufferGeometryUtils.BufferGeometryUtils.estimateBytesUsed(g);
  37021. });
  37022. const cacheFullness = tiles.lruCache.itemList.length / tiles.lruCache.minSize;
  37023. statsContainer.innerHTML = `
  37024. Downloading: ${tiles.stats.downloading} Parsing: ${tiles.stats.parsing} Visible: ${tiles.group.children.length}
  37025. <br/>
  37026. Cache: ${(100 * cacheFullness).toFixed(2)}% ~${(count / 1000 / 1000).toFixed(2)}mb
  37027. `;
  37028. }
  37029. },{"../src/index.js":"../src/index.js","three":"../node_modules/three/build/three.module.js","three/examples/jsm/controls/OrbitControls.js":"../node_modules/three/examples/jsm/controls/OrbitControls.js","three/examples/jsm/utils/BufferGeometryUtils.js":"../node_modules/three/examples/jsm/utils/BufferGeometryUtils.js","three/examples/jsm/libs/dat.gui.module.js":"../node_modules/three/examples/jsm/libs/dat.gui.module.js","three/examples/jsm/libs/stats.module.js":"../node_modules/three/examples/jsm/libs/stats.module.js"}],"../node_modules/parcel-bundler/src/builtins/hmr-runtime.js":[function(require,module,exports) {
  37030. var global = arguments[3];
  37031. var OVERLAY_ID = '__parcel__error__overlay__';
  37032. var OldModule = module.bundle.Module;
  37033. function Module(moduleName) {
  37034. OldModule.call(this, moduleName);
  37035. this.hot = {
  37036. data: module.bundle.hotData,
  37037. _acceptCallbacks: [],
  37038. _disposeCallbacks: [],
  37039. accept: function (fn) {
  37040. this._acceptCallbacks.push(fn || function () {});
  37041. },
  37042. dispose: function (fn) {
  37043. this._disposeCallbacks.push(fn);
  37044. }
  37045. };
  37046. module.bundle.hotData = null;
  37047. }
  37048. module.bundle.Module = Module;
  37049. var checkedAssets, assetsToAccept;
  37050. var parent = module.bundle.parent;
  37051. if ((!parent || !parent.isParcelRequire) && typeof WebSocket !== 'undefined') {
  37052. var hostname = "" || location.hostname;
  37053. var protocol = location.protocol === 'https:' ? 'wss' : 'ws';
  37054. var ws = new WebSocket(protocol + '://' + hostname + ':' + "58930" + '/');
  37055. ws.onmessage = function (event) {
  37056. checkedAssets = {};
  37057. assetsToAccept = [];
  37058. var data = JSON.parse(event.data);
  37059. if (data.type === 'update') {
  37060. var handled = false;
  37061. data.assets.forEach(function (asset) {
  37062. if (!asset.isNew) {
  37063. var didAccept = hmrAcceptCheck(global.parcelRequire, asset.id);
  37064. if (didAccept) {
  37065. handled = true;
  37066. }
  37067. }
  37068. }); // Enable HMR for CSS by default.
  37069. handled = handled || data.assets.every(function (asset) {
  37070. return asset.type === 'css' && asset.generated.js;
  37071. });
  37072. if (handled) {
  37073. console.clear();
  37074. data.assets.forEach(function (asset) {
  37075. hmrApply(global.parcelRequire, asset);
  37076. });
  37077. assetsToAccept.forEach(function (v) {
  37078. hmrAcceptRun(v[0], v[1]);
  37079. });
  37080. } else if (location.reload) {
  37081. // `location` global exists in a web worker context but lacks `.reload()` function.
  37082. location.reload();
  37083. }
  37084. }
  37085. if (data.type === 'reload') {
  37086. ws.close();
  37087. ws.onclose = function () {
  37088. location.reload();
  37089. };
  37090. }
  37091. if (data.type === 'error-resolved') {
  37092. console.log('[parcel] ✨ Error resolved');
  37093. removeErrorOverlay();
  37094. }
  37095. if (data.type === 'error') {
  37096. console.error('[parcel] 🚨 ' + data.error.message + '\n' + data.error.stack);
  37097. removeErrorOverlay();
  37098. var overlay = createErrorOverlay(data);
  37099. document.body.appendChild(overlay);
  37100. }
  37101. };
  37102. }
  37103. function removeErrorOverlay() {
  37104. var overlay = document.getElementById(OVERLAY_ID);
  37105. if (overlay) {
  37106. overlay.remove();
  37107. }
  37108. }
  37109. function createErrorOverlay(data) {
  37110. var overlay = document.createElement('div');
  37111. overlay.id = OVERLAY_ID; // html encode message and stack trace
  37112. var message = document.createElement('div');
  37113. var stackTrace = document.createElement('pre');
  37114. message.innerText = data.error.message;
  37115. stackTrace.innerText = data.error.stack;
  37116. 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>';
  37117. return overlay;
  37118. }
  37119. function getParents(bundle, id) {
  37120. var modules = bundle.modules;
  37121. if (!modules) {
  37122. return [];
  37123. }
  37124. var parents = [];
  37125. var k, d, dep;
  37126. for (k in modules) {
  37127. for (d in modules[k][1]) {
  37128. dep = modules[k][1][d];
  37129. if (dep === id || Array.isArray(dep) && dep[dep.length - 1] === id) {
  37130. parents.push(k);
  37131. }
  37132. }
  37133. }
  37134. if (bundle.parent) {
  37135. parents = parents.concat(getParents(bundle.parent, id));
  37136. }
  37137. return parents;
  37138. }
  37139. function hmrApply(bundle, asset) {
  37140. var modules = bundle.modules;
  37141. if (!modules) {
  37142. return;
  37143. }
  37144. if (modules[asset.id] || !bundle.parent) {
  37145. var fn = new Function('require', 'module', 'exports', asset.generated.js);
  37146. asset.isNew = !modules[asset.id];
  37147. modules[asset.id] = [fn, asset.deps];
  37148. } else if (bundle.parent) {
  37149. hmrApply(bundle.parent, asset);
  37150. }
  37151. }
  37152. function hmrAcceptCheck(bundle, id) {
  37153. var modules = bundle.modules;
  37154. if (!modules) {
  37155. return;
  37156. }
  37157. if (!modules[id] && bundle.parent) {
  37158. return hmrAcceptCheck(bundle.parent, id);
  37159. }
  37160. if (checkedAssets[id]) {
  37161. return;
  37162. }
  37163. checkedAssets[id] = true;
  37164. var cached = bundle.cache[id];
  37165. assetsToAccept.push([bundle, id]);
  37166. if (cached && cached.hot && cached.hot._acceptCallbacks.length) {
  37167. return true;
  37168. }
  37169. return getParents(global.parcelRequire, id).some(function (id) {
  37170. return hmrAcceptCheck(global.parcelRequire, id);
  37171. });
  37172. }
  37173. function hmrAcceptRun(bundle, id) {
  37174. var cached = bundle.cache[id];
  37175. bundle.hotData = {};
  37176. if (cached) {
  37177. cached.hot.data = bundle.hotData;
  37178. }
  37179. if (cached && cached.hot && cached.hot._disposeCallbacks.length) {
  37180. cached.hot._disposeCallbacks.forEach(function (cb) {
  37181. cb(bundle.hotData);
  37182. });
  37183. }
  37184. delete bundle.cache[id];
  37185. bundle(id);
  37186. cached = bundle.cache[id];
  37187. if (cached && cached.hot && cached.hot._acceptCallbacks.length) {
  37188. cached.hot._acceptCallbacks.forEach(function (cb) {
  37189. cb();
  37190. });
  37191. return true;
  37192. }
  37193. }
  37194. },{}]},{},["../node_modules/parcel-bundler/src/builtins/hmr-runtime.js","index.js"], null)
  37195. //# sourceMappingURL=example.e31bb0bc.js.map