three.cjs 1.1 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035
  1. /**
  2. * @license
  3. * Copyright 2010-2022 Three.js Authors
  4. * SPDX-License-Identifier: MIT
  5. */
  6. 'use strict';
  7. Object.defineProperty(exports, '__esModule', { value: true });
  8. const REVISION = '146dev';
  9. const MOUSE = {
  10. LEFT: 0,
  11. MIDDLE: 1,
  12. RIGHT: 2,
  13. ROTATE: 0,
  14. DOLLY: 1,
  15. PAN: 2
  16. };
  17. const TOUCH = {
  18. ROTATE: 0,
  19. PAN: 1,
  20. DOLLY_PAN: 2,
  21. DOLLY_ROTATE: 3
  22. };
  23. const CullFaceNone = 0;
  24. const CullFaceBack = 1;
  25. const CullFaceFront = 2;
  26. const CullFaceFrontBack = 3;
  27. const BasicShadowMap = 0;
  28. const PCFShadowMap = 1;
  29. const PCFSoftShadowMap = 2;
  30. const VSMShadowMap = 3;
  31. const FrontSide = 0;
  32. const BackSide = 1;
  33. const DoubleSide = 2;
  34. const NoBlending = 0;
  35. const NormalBlending = 1;
  36. const AdditiveBlending = 2;
  37. const SubtractiveBlending = 3;
  38. const MultiplyBlending = 4;
  39. const CustomBlending = 5;
  40. const AddEquation = 100;
  41. const SubtractEquation = 101;
  42. const ReverseSubtractEquation = 102;
  43. const MinEquation = 103;
  44. const MaxEquation = 104;
  45. const ZeroFactor = 200;
  46. const OneFactor = 201;
  47. const SrcColorFactor = 202;
  48. const OneMinusSrcColorFactor = 203;
  49. const SrcAlphaFactor = 204;
  50. const OneMinusSrcAlphaFactor = 205;
  51. const DstAlphaFactor = 206;
  52. const OneMinusDstAlphaFactor = 207;
  53. const DstColorFactor = 208;
  54. const OneMinusDstColorFactor = 209;
  55. const SrcAlphaSaturateFactor = 210;
  56. const NeverDepth = 0;
  57. const AlwaysDepth = 1;
  58. const LessDepth = 2;
  59. const LessEqualDepth = 3;
  60. const EqualDepth = 4;
  61. const GreaterEqualDepth = 5;
  62. const GreaterDepth = 6;
  63. const NotEqualDepth = 7;
  64. const MultiplyOperation = 0;
  65. const MixOperation = 1;
  66. const AddOperation = 2;
  67. const NoToneMapping = 0;
  68. const LinearToneMapping = 1;
  69. const ReinhardToneMapping = 2;
  70. const CineonToneMapping = 3;
  71. const ACESFilmicToneMapping = 4;
  72. const CustomToneMapping = 5;
  73. const UVMapping = 300;
  74. const CubeReflectionMapping = 301;
  75. const CubeRefractionMapping = 302;
  76. const EquirectangularReflectionMapping = 303;
  77. const EquirectangularRefractionMapping = 304;
  78. const CubeUVReflectionMapping = 306;
  79. const RepeatWrapping = 1000;
  80. const ClampToEdgeWrapping = 1001;
  81. const MirroredRepeatWrapping = 1002;
  82. const NearestFilter = 1003;
  83. const NearestMipmapNearestFilter = 1004;
  84. const NearestMipMapNearestFilter = 1004;
  85. const NearestMipmapLinearFilter = 1005;
  86. const NearestMipMapLinearFilter = 1005;
  87. const LinearFilter = 1006;
  88. const LinearMipmapNearestFilter = 1007;
  89. const LinearMipMapNearestFilter = 1007;
  90. const LinearMipmapLinearFilter = 1008;
  91. const LinearMipMapLinearFilter = 1008;
  92. const UnsignedByteType = 1009;
  93. const ByteType = 1010;
  94. const ShortType = 1011;
  95. const UnsignedShortType = 1012;
  96. const IntType = 1013;
  97. const UnsignedIntType = 1014;
  98. const FloatType = 1015;
  99. const HalfFloatType = 1016;
  100. const UnsignedShort4444Type = 1017;
  101. const UnsignedShort5551Type = 1018;
  102. const UnsignedInt248Type = 1020;
  103. const AlphaFormat = 1021;
  104. const RGBFormat = 1022; // @deprecated since r137
  105. const RGBAFormat = 1023;
  106. const LuminanceFormat = 1024;
  107. const LuminanceAlphaFormat = 1025;
  108. const DepthFormat = 1026;
  109. const DepthStencilFormat = 1027;
  110. const RedFormat = 1028;
  111. const RedIntegerFormat = 1029;
  112. const RGFormat = 1030;
  113. const RGIntegerFormat = 1031;
  114. const RGBAIntegerFormat = 1033;
  115. const RGB_S3TC_DXT1_Format = 33776;
  116. const RGBA_S3TC_DXT1_Format = 33777;
  117. const RGBA_S3TC_DXT3_Format = 33778;
  118. const RGBA_S3TC_DXT5_Format = 33779;
  119. const RGB_PVRTC_4BPPV1_Format = 35840;
  120. const RGB_PVRTC_2BPPV1_Format = 35841;
  121. const RGBA_PVRTC_4BPPV1_Format = 35842;
  122. const RGBA_PVRTC_2BPPV1_Format = 35843;
  123. const RGB_ETC1_Format = 36196;
  124. const RGB_ETC2_Format = 37492;
  125. const RGBA_ETC2_EAC_Format = 37496;
  126. const RGBA_ASTC_4x4_Format = 37808;
  127. const RGBA_ASTC_5x4_Format = 37809;
  128. const RGBA_ASTC_5x5_Format = 37810;
  129. const RGBA_ASTC_6x5_Format = 37811;
  130. const RGBA_ASTC_6x6_Format = 37812;
  131. const RGBA_ASTC_8x5_Format = 37813;
  132. const RGBA_ASTC_8x6_Format = 37814;
  133. const RGBA_ASTC_8x8_Format = 37815;
  134. const RGBA_ASTC_10x5_Format = 37816;
  135. const RGBA_ASTC_10x6_Format = 37817;
  136. const RGBA_ASTC_10x8_Format = 37818;
  137. const RGBA_ASTC_10x10_Format = 37819;
  138. const RGBA_ASTC_12x10_Format = 37820;
  139. const RGBA_ASTC_12x12_Format = 37821;
  140. const RGBA_BPTC_Format = 36492;
  141. const LoopOnce = 2200;
  142. const LoopRepeat = 2201;
  143. const LoopPingPong = 2202;
  144. const InterpolateDiscrete = 2300;
  145. const InterpolateLinear = 2301;
  146. const InterpolateSmooth = 2302;
  147. const ZeroCurvatureEnding = 2400;
  148. const ZeroSlopeEnding = 2401;
  149. const WrapAroundEnding = 2402;
  150. const NormalAnimationBlendMode = 2500;
  151. const AdditiveAnimationBlendMode = 2501;
  152. const TrianglesDrawMode = 0;
  153. const TriangleStripDrawMode = 1;
  154. const TriangleFanDrawMode = 2;
  155. const LinearEncoding = 3000;
  156. const sRGBEncoding = 3001;
  157. const BasicDepthPacking = 3200;
  158. const RGBADepthPacking = 3201;
  159. const TangentSpaceNormalMap = 0;
  160. const ObjectSpaceNormalMap = 1; // Color space string identifiers, matching CSS Color Module Level 4 and WebGPU names where available.
  161. const NoColorSpace = '';
  162. const SRGBColorSpace = 'srgb';
  163. const LinearSRGBColorSpace = 'srgb-linear';
  164. const ZeroStencilOp = 0;
  165. const KeepStencilOp = 7680;
  166. const ReplaceStencilOp = 7681;
  167. const IncrementStencilOp = 7682;
  168. const DecrementStencilOp = 7683;
  169. const IncrementWrapStencilOp = 34055;
  170. const DecrementWrapStencilOp = 34056;
  171. const InvertStencilOp = 5386;
  172. const NeverStencilFunc = 512;
  173. const LessStencilFunc = 513;
  174. const EqualStencilFunc = 514;
  175. const LessEqualStencilFunc = 515;
  176. const GreaterStencilFunc = 516;
  177. const NotEqualStencilFunc = 517;
  178. const GreaterEqualStencilFunc = 518;
  179. const AlwaysStencilFunc = 519;
  180. const StaticDrawUsage = 35044;
  181. const DynamicDrawUsage = 35048;
  182. const StreamDrawUsage = 35040;
  183. const StaticReadUsage = 35045;
  184. const DynamicReadUsage = 35049;
  185. const StreamReadUsage = 35041;
  186. const StaticCopyUsage = 35046;
  187. const DynamicCopyUsage = 35050;
  188. const StreamCopyUsage = 35042;
  189. const GLSL1 = '100';
  190. const GLSL3 = '300 es';
  191. const _SRGBAFormat = 1035; // fallback for WebGL 1
  192. /**
  193. * https://github.com/mrdoob/eventdispatcher.js/
  194. */
  195. class EventDispatcher {
  196. addEventListener(type, listener) {
  197. if (this._listeners === undefined) this._listeners = {};
  198. const listeners = this._listeners;
  199. if (listeners[type] === undefined) {
  200. listeners[type] = [];
  201. }
  202. if (listeners[type].indexOf(listener) === -1) {
  203. listeners[type].push(listener);
  204. }
  205. }
  206. hasEventListener(type, listener) {
  207. if (this._listeners === undefined) return false;
  208. const listeners = this._listeners;
  209. return listeners[type] !== undefined && listeners[type].indexOf(listener) !== -1;
  210. }
  211. removeEventListener(type, listener) {
  212. if (this._listeners === undefined) return;
  213. const listeners = this._listeners;
  214. const listenerArray = listeners[type];
  215. if (listenerArray !== undefined) {
  216. const index = listenerArray.indexOf(listener);
  217. if (index !== -1) {
  218. listenerArray.splice(index, 1);
  219. }
  220. }
  221. }
  222. dispatchEvent(event) {
  223. if (this._listeners === undefined) return;
  224. const listeners = this._listeners;
  225. const listenerArray = listeners[event.type];
  226. if (listenerArray !== undefined) {
  227. event.target = this; // Make a copy, in case listeners are removed while iterating.
  228. const array = listenerArray.slice(0);
  229. for (let i = 0, l = array.length; i < l; i++) {
  230. array[i].call(this, event);
  231. }
  232. event.target = null;
  233. }
  234. }
  235. }
  236. const _lut = ['00', '01', '02', '03', '04', '05', '06', '07', '08', '09', '0a', '0b', '0c', '0d', '0e', '0f', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '1a', '1b', '1c', '1d', '1e', '1f', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '2a', '2b', '2c', '2d', '2e', '2f', '30', '31', '32', '33', '34', '35', '36', '37', '38', '39', '3a', '3b', '3c', '3d', '3e', '3f', '40', '41', '42', '43', '44', '45', '46', '47', '48', '49', '4a', '4b', '4c', '4d', '4e', '4f', '50', '51', '52', '53', '54', '55', '56', '57', '58', '59', '5a', '5b', '5c', '5d', '5e', '5f', '60', '61', '62', '63', '64', '65', '66', '67', '68', '69', '6a', '6b', '6c', '6d', '6e', '6f', '70', '71', '72', '73', '74', '75', '76', '77', '78', '79', '7a', '7b', '7c', '7d', '7e', '7f', '80', '81', '82', '83', '84', '85', '86', '87', '88', '89', '8a', '8b', '8c', '8d', '8e', '8f', '90', '91', '92', '93', '94', '95', '96', '97', '98', '99', '9a', '9b', '9c', '9d', '9e', '9f', 'a0', 'a1', 'a2', 'a3', 'a4', 'a5', 'a6', 'a7', 'a8', 'a9', 'aa', 'ab', 'ac', 'ad', 'ae', 'af', 'b0', 'b1', 'b2', 'b3', 'b4', 'b5', 'b6', 'b7', 'b8', 'b9', 'ba', 'bb', 'bc', 'bd', 'be', 'bf', 'c0', 'c1', 'c2', 'c3', 'c4', 'c5', 'c6', 'c7', 'c8', 'c9', 'ca', 'cb', 'cc', 'cd', 'ce', 'cf', 'd0', 'd1', 'd2', 'd3', 'd4', 'd5', 'd6', 'd7', 'd8', 'd9', 'da', 'db', 'dc', 'dd', 'de', 'df', 'e0', 'e1', 'e2', 'e3', 'e4', 'e5', 'e6', 'e7', 'e8', 'e9', 'ea', 'eb', 'ec', 'ed', 'ee', 'ef', 'f0', 'f1', 'f2', 'f3', 'f4', 'f5', 'f6', 'f7', 'f8', 'f9', 'fa', 'fb', 'fc', 'fd', 'fe', 'ff'];
  237. let _seed = 1234567;
  238. const DEG2RAD = Math.PI / 180;
  239. const RAD2DEG = 180 / Math.PI; // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/21963136#21963136
  240. function generateUUID() {
  241. const d0 = Math.random() * 0xffffffff | 0;
  242. const d1 = Math.random() * 0xffffffff | 0;
  243. const d2 = Math.random() * 0xffffffff | 0;
  244. const d3 = Math.random() * 0xffffffff | 0;
  245. const uuid = _lut[d0 & 0xff] + _lut[d0 >> 8 & 0xff] + _lut[d0 >> 16 & 0xff] + _lut[d0 >> 24 & 0xff] + '-' + _lut[d1 & 0xff] + _lut[d1 >> 8 & 0xff] + '-' + _lut[d1 >> 16 & 0x0f | 0x40] + _lut[d1 >> 24 & 0xff] + '-' + _lut[d2 & 0x3f | 0x80] + _lut[d2 >> 8 & 0xff] + '-' + _lut[d2 >> 16 & 0xff] + _lut[d2 >> 24 & 0xff] + _lut[d3 & 0xff] + _lut[d3 >> 8 & 0xff] + _lut[d3 >> 16 & 0xff] + _lut[d3 >> 24 & 0xff]; // .toLowerCase() here flattens concatenated strings to save heap memory space.
  246. return uuid.toLowerCase();
  247. }
  248. function clamp(value, min, max) {
  249. return Math.max(min, Math.min(max, value));
  250. } // compute euclidean modulo of m % n
  251. // https://en.wikipedia.org/wiki/Modulo_operation
  252. function euclideanModulo(n, m) {
  253. return (n % m + m) % m;
  254. } // Linear mapping from range <a1, a2> to range <b1, b2>
  255. function mapLinear(x, a1, a2, b1, b2) {
  256. return b1 + (x - a1) * (b2 - b1) / (a2 - a1);
  257. } // https://www.gamedev.net/tutorials/programming/general-and-gameplay-programming/inverse-lerp-a-super-useful-yet-often-overlooked-function-r5230/
  258. function inverseLerp(x, y, value) {
  259. if (x !== y) {
  260. return (value - x) / (y - x);
  261. } else {
  262. return 0;
  263. }
  264. } // https://en.wikipedia.org/wiki/Linear_interpolation
  265. function lerp(x, y, t) {
  266. return (1 - t) * x + t * y;
  267. } // http://www.rorydriscoll.com/2016/03/07/frame-rate-independent-damping-using-lerp/
  268. function damp(x, y, lambda, dt) {
  269. return lerp(x, y, 1 - Math.exp(-lambda * dt));
  270. } // https://www.desmos.com/calculator/vcsjnyz7x4
  271. function pingpong(x, length = 1) {
  272. return length - Math.abs(euclideanModulo(x, length * 2) - length);
  273. } // http://en.wikipedia.org/wiki/Smoothstep
  274. function smoothstep(x, min, max) {
  275. if (x <= min) return 0;
  276. if (x >= max) return 1;
  277. x = (x - min) / (max - min);
  278. return x * x * (3 - 2 * x);
  279. }
  280. function smootherstep(x, min, max) {
  281. if (x <= min) return 0;
  282. if (x >= max) return 1;
  283. x = (x - min) / (max - min);
  284. return x * x * x * (x * (x * 6 - 15) + 10);
  285. } // Random integer from <low, high> interval
  286. function randInt(low, high) {
  287. return low + Math.floor(Math.random() * (high - low + 1));
  288. } // Random float from <low, high> interval
  289. function randFloat(low, high) {
  290. return low + Math.random() * (high - low);
  291. } // Random float from <-range/2, range/2> interval
  292. function randFloatSpread(range) {
  293. return range * (0.5 - Math.random());
  294. } // Deterministic pseudo-random float in the interval [ 0, 1 ]
  295. function seededRandom(s) {
  296. if (s !== undefined) _seed = s; // Mulberry32 generator
  297. let t = _seed += 0x6D2B79F5;
  298. t = Math.imul(t ^ t >>> 15, t | 1);
  299. t ^= t + Math.imul(t ^ t >>> 7, t | 61);
  300. return ((t ^ t >>> 14) >>> 0) / 4294967296;
  301. }
  302. function degToRad(degrees) {
  303. return degrees * DEG2RAD;
  304. }
  305. function radToDeg(radians) {
  306. return radians * RAD2DEG;
  307. }
  308. function isPowerOfTwo(value) {
  309. return (value & value - 1) === 0 && value !== 0;
  310. }
  311. function ceilPowerOfTwo(value) {
  312. return Math.pow(2, Math.ceil(Math.log(value) / Math.LN2));
  313. }
  314. function floorPowerOfTwo(value) {
  315. return Math.pow(2, Math.floor(Math.log(value) / Math.LN2));
  316. }
  317. function setQuaternionFromProperEuler(q, a, b, c, order) {
  318. // Intrinsic Proper Euler Angles - see https://en.wikipedia.org/wiki/Euler_angles
  319. // rotations are applied to the axes in the order specified by 'order'
  320. // rotation by angle 'a' is applied first, then by angle 'b', then by angle 'c'
  321. // angles are in radians
  322. const cos = Math.cos;
  323. const sin = Math.sin;
  324. const c2 = cos(b / 2);
  325. const s2 = sin(b / 2);
  326. const c13 = cos((a + c) / 2);
  327. const s13 = sin((a + c) / 2);
  328. const c1_3 = cos((a - c) / 2);
  329. const s1_3 = sin((a - c) / 2);
  330. const c3_1 = cos((c - a) / 2);
  331. const s3_1 = sin((c - a) / 2);
  332. switch (order) {
  333. case 'XYX':
  334. q.set(c2 * s13, s2 * c1_3, s2 * s1_3, c2 * c13);
  335. break;
  336. case 'YZY':
  337. q.set(s2 * s1_3, c2 * s13, s2 * c1_3, c2 * c13);
  338. break;
  339. case 'ZXZ':
  340. q.set(s2 * c1_3, s2 * s1_3, c2 * s13, c2 * c13);
  341. break;
  342. case 'XZX':
  343. q.set(c2 * s13, s2 * s3_1, s2 * c3_1, c2 * c13);
  344. break;
  345. case 'YXY':
  346. q.set(s2 * c3_1, c2 * s13, s2 * s3_1, c2 * c13);
  347. break;
  348. case 'ZYZ':
  349. q.set(s2 * s3_1, s2 * c3_1, c2 * s13, c2 * c13);
  350. break;
  351. default:
  352. console.warn('THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: ' + order);
  353. }
  354. }
  355. function denormalize(value, array) {
  356. switch (array.constructor) {
  357. case Float32Array:
  358. return value;
  359. case Uint16Array:
  360. return value / 65535.0;
  361. case Uint8Array:
  362. return value / 255.0;
  363. case Int16Array:
  364. return Math.max(value / 32767.0, -1.0);
  365. case Int8Array:
  366. return Math.max(value / 127.0, -1.0);
  367. default:
  368. throw new Error('Invalid component type.');
  369. }
  370. }
  371. function normalize(value, array) {
  372. switch (array.constructor) {
  373. case Float32Array:
  374. return value;
  375. case Uint16Array:
  376. return Math.round(value * 65535.0);
  377. case Uint8Array:
  378. return Math.round(value * 255.0);
  379. case Int16Array:
  380. return Math.round(value * 32767.0);
  381. case Int8Array:
  382. return Math.round(value * 127.0);
  383. default:
  384. throw new Error('Invalid component type.');
  385. }
  386. }
  387. var MathUtils = /*#__PURE__*/Object.freeze({
  388. __proto__: null,
  389. DEG2RAD: DEG2RAD,
  390. RAD2DEG: RAD2DEG,
  391. generateUUID: generateUUID,
  392. clamp: clamp,
  393. euclideanModulo: euclideanModulo,
  394. mapLinear: mapLinear,
  395. inverseLerp: inverseLerp,
  396. lerp: lerp,
  397. damp: damp,
  398. pingpong: pingpong,
  399. smoothstep: smoothstep,
  400. smootherstep: smootherstep,
  401. randInt: randInt,
  402. randFloat: randFloat,
  403. randFloatSpread: randFloatSpread,
  404. seededRandom: seededRandom,
  405. degToRad: degToRad,
  406. radToDeg: radToDeg,
  407. isPowerOfTwo: isPowerOfTwo,
  408. ceilPowerOfTwo: ceilPowerOfTwo,
  409. floorPowerOfTwo: floorPowerOfTwo,
  410. setQuaternionFromProperEuler: setQuaternionFromProperEuler,
  411. normalize: normalize,
  412. denormalize: denormalize
  413. });
  414. class Vector2 {
  415. constructor(x = 0, y = 0) {
  416. Vector2.prototype.isVector2 = true;
  417. this.x = x;
  418. this.y = y;
  419. }
  420. get width() {
  421. return this.x;
  422. }
  423. set width(value) {
  424. this.x = value;
  425. }
  426. get height() {
  427. return this.y;
  428. }
  429. set height(value) {
  430. this.y = value;
  431. }
  432. set(x, y) {
  433. this.x = x;
  434. this.y = y;
  435. return this;
  436. }
  437. setScalar(scalar) {
  438. this.x = scalar;
  439. this.y = scalar;
  440. return this;
  441. }
  442. setX(x) {
  443. this.x = x;
  444. return this;
  445. }
  446. setY(y) {
  447. this.y = y;
  448. return this;
  449. }
  450. setComponent(index, value) {
  451. switch (index) {
  452. case 0:
  453. this.x = value;
  454. break;
  455. case 1:
  456. this.y = value;
  457. break;
  458. default:
  459. throw new Error('index is out of range: ' + index);
  460. }
  461. return this;
  462. }
  463. getComponent(index) {
  464. switch (index) {
  465. case 0:
  466. return this.x;
  467. case 1:
  468. return this.y;
  469. default:
  470. throw new Error('index is out of range: ' + index);
  471. }
  472. }
  473. clone() {
  474. return new this.constructor(this.x, this.y);
  475. }
  476. copy(v) {
  477. this.x = v.x;
  478. this.y = v.y;
  479. return this;
  480. }
  481. add(v) {
  482. this.x += v.x;
  483. this.y += v.y;
  484. return this;
  485. }
  486. addScalar(s) {
  487. this.x += s;
  488. this.y += s;
  489. return this;
  490. }
  491. addVectors(a, b) {
  492. this.x = a.x + b.x;
  493. this.y = a.y + b.y;
  494. return this;
  495. }
  496. addScaledVector(v, s) {
  497. this.x += v.x * s;
  498. this.y += v.y * s;
  499. return this;
  500. }
  501. sub(v) {
  502. this.x -= v.x;
  503. this.y -= v.y;
  504. return this;
  505. }
  506. subScalar(s) {
  507. this.x -= s;
  508. this.y -= s;
  509. return this;
  510. }
  511. subVectors(a, b) {
  512. this.x = a.x - b.x;
  513. this.y = a.y - b.y;
  514. return this;
  515. }
  516. multiply(v) {
  517. this.x *= v.x;
  518. this.y *= v.y;
  519. return this;
  520. }
  521. multiplyScalar(scalar) {
  522. this.x *= scalar;
  523. this.y *= scalar;
  524. return this;
  525. }
  526. divide(v) {
  527. this.x /= v.x;
  528. this.y /= v.y;
  529. return this;
  530. }
  531. divideScalar(scalar) {
  532. return this.multiplyScalar(1 / scalar);
  533. }
  534. applyMatrix3(m) {
  535. const x = this.x,
  536. y = this.y;
  537. const e = m.elements;
  538. this.x = e[0] * x + e[3] * y + e[6];
  539. this.y = e[1] * x + e[4] * y + e[7];
  540. return this;
  541. }
  542. min(v) {
  543. this.x = Math.min(this.x, v.x);
  544. this.y = Math.min(this.y, v.y);
  545. return this;
  546. }
  547. max(v) {
  548. this.x = Math.max(this.x, v.x);
  549. this.y = Math.max(this.y, v.y);
  550. return this;
  551. }
  552. clamp(min, max) {
  553. // assumes min < max, componentwise
  554. this.x = Math.max(min.x, Math.min(max.x, this.x));
  555. this.y = Math.max(min.y, Math.min(max.y, this.y));
  556. return this;
  557. }
  558. clampScalar(minVal, maxVal) {
  559. this.x = Math.max(minVal, Math.min(maxVal, this.x));
  560. this.y = Math.max(minVal, Math.min(maxVal, this.y));
  561. return this;
  562. }
  563. clampLength(min, max) {
  564. const length = this.length();
  565. return this.divideScalar(length || 1).multiplyScalar(Math.max(min, Math.min(max, length)));
  566. }
  567. floor() {
  568. this.x = Math.floor(this.x);
  569. this.y = Math.floor(this.y);
  570. return this;
  571. }
  572. ceil() {
  573. this.x = Math.ceil(this.x);
  574. this.y = Math.ceil(this.y);
  575. return this;
  576. }
  577. round() {
  578. this.x = Math.round(this.x);
  579. this.y = Math.round(this.y);
  580. return this;
  581. }
  582. roundToZero() {
  583. this.x = this.x < 0 ? Math.ceil(this.x) : Math.floor(this.x);
  584. this.y = this.y < 0 ? Math.ceil(this.y) : Math.floor(this.y);
  585. return this;
  586. }
  587. negate() {
  588. this.x = -this.x;
  589. this.y = -this.y;
  590. return this;
  591. }
  592. dot(v) {
  593. return this.x * v.x + this.y * v.y;
  594. }
  595. cross(v) {
  596. return this.x * v.y - this.y * v.x;
  597. }
  598. lengthSq() {
  599. return this.x * this.x + this.y * this.y;
  600. }
  601. length() {
  602. return Math.sqrt(this.x * this.x + this.y * this.y);
  603. }
  604. manhattanLength() {
  605. return Math.abs(this.x) + Math.abs(this.y);
  606. }
  607. normalize() {
  608. return this.divideScalar(this.length() || 1);
  609. }
  610. angle() {
  611. // computes the angle in radians with respect to the positive x-axis
  612. const angle = Math.atan2(-this.y, -this.x) + Math.PI;
  613. return angle;
  614. }
  615. distanceTo(v) {
  616. return Math.sqrt(this.distanceToSquared(v));
  617. }
  618. distanceToSquared(v) {
  619. const dx = this.x - v.x,
  620. dy = this.y - v.y;
  621. return dx * dx + dy * dy;
  622. }
  623. manhattanDistanceTo(v) {
  624. return Math.abs(this.x - v.x) + Math.abs(this.y - v.y);
  625. }
  626. setLength(length) {
  627. return this.normalize().multiplyScalar(length);
  628. }
  629. lerp(v, alpha) {
  630. this.x += (v.x - this.x) * alpha;
  631. this.y += (v.y - this.y) * alpha;
  632. return this;
  633. }
  634. lerpVectors(v1, v2, alpha) {
  635. this.x = v1.x + (v2.x - v1.x) * alpha;
  636. this.y = v1.y + (v2.y - v1.y) * alpha;
  637. return this;
  638. }
  639. equals(v) {
  640. return v.x === this.x && v.y === this.y;
  641. }
  642. fromArray(array, offset = 0) {
  643. this.x = array[offset];
  644. this.y = array[offset + 1];
  645. return this;
  646. }
  647. toArray(array = [], offset = 0) {
  648. array[offset] = this.x;
  649. array[offset + 1] = this.y;
  650. return array;
  651. }
  652. fromBufferAttribute(attribute, index) {
  653. this.x = attribute.getX(index);
  654. this.y = attribute.getY(index);
  655. return this;
  656. }
  657. rotateAround(center, angle) {
  658. const c = Math.cos(angle),
  659. s = Math.sin(angle);
  660. const x = this.x - center.x;
  661. const y = this.y - center.y;
  662. this.x = x * c - y * s + center.x;
  663. this.y = x * s + y * c + center.y;
  664. return this;
  665. }
  666. random() {
  667. this.x = Math.random();
  668. this.y = Math.random();
  669. return this;
  670. }
  671. *[Symbol.iterator]() {
  672. yield this.x;
  673. yield this.y;
  674. }
  675. }
  676. class Matrix3 {
  677. constructor() {
  678. Matrix3.prototype.isMatrix3 = true;
  679. this.elements = [1, 0, 0, 0, 1, 0, 0, 0, 1];
  680. }
  681. set(n11, n12, n13, n21, n22, n23, n31, n32, n33) {
  682. const te = this.elements;
  683. te[0] = n11;
  684. te[1] = n21;
  685. te[2] = n31;
  686. te[3] = n12;
  687. te[4] = n22;
  688. te[5] = n32;
  689. te[6] = n13;
  690. te[7] = n23;
  691. te[8] = n33;
  692. return this;
  693. }
  694. identity() {
  695. this.set(1, 0, 0, 0, 1, 0, 0, 0, 1);
  696. return this;
  697. }
  698. copy(m) {
  699. const te = this.elements;
  700. const me = m.elements;
  701. te[0] = me[0];
  702. te[1] = me[1];
  703. te[2] = me[2];
  704. te[3] = me[3];
  705. te[4] = me[4];
  706. te[5] = me[5];
  707. te[6] = me[6];
  708. te[7] = me[7];
  709. te[8] = me[8];
  710. return this;
  711. }
  712. extractBasis(xAxis, yAxis, zAxis) {
  713. xAxis.setFromMatrix3Column(this, 0);
  714. yAxis.setFromMatrix3Column(this, 1);
  715. zAxis.setFromMatrix3Column(this, 2);
  716. return this;
  717. }
  718. setFromMatrix4(m) {
  719. const me = m.elements;
  720. this.set(me[0], me[4], me[8], me[1], me[5], me[9], me[2], me[6], me[10]);
  721. return this;
  722. }
  723. multiply(m) {
  724. return this.multiplyMatrices(this, m);
  725. }
  726. premultiply(m) {
  727. return this.multiplyMatrices(m, this);
  728. }
  729. multiplyMatrices(a, b) {
  730. const ae = a.elements;
  731. const be = b.elements;
  732. const te = this.elements;
  733. const a11 = ae[0],
  734. a12 = ae[3],
  735. a13 = ae[6];
  736. const a21 = ae[1],
  737. a22 = ae[4],
  738. a23 = ae[7];
  739. const a31 = ae[2],
  740. a32 = ae[5],
  741. a33 = ae[8];
  742. const b11 = be[0],
  743. b12 = be[3],
  744. b13 = be[6];
  745. const b21 = be[1],
  746. b22 = be[4],
  747. b23 = be[7];
  748. const b31 = be[2],
  749. b32 = be[5],
  750. b33 = be[8];
  751. te[0] = a11 * b11 + a12 * b21 + a13 * b31;
  752. te[3] = a11 * b12 + a12 * b22 + a13 * b32;
  753. te[6] = a11 * b13 + a12 * b23 + a13 * b33;
  754. te[1] = a21 * b11 + a22 * b21 + a23 * b31;
  755. te[4] = a21 * b12 + a22 * b22 + a23 * b32;
  756. te[7] = a21 * b13 + a22 * b23 + a23 * b33;
  757. te[2] = a31 * b11 + a32 * b21 + a33 * b31;
  758. te[5] = a31 * b12 + a32 * b22 + a33 * b32;
  759. te[8] = a31 * b13 + a32 * b23 + a33 * b33;
  760. return this;
  761. }
  762. multiplyScalar(s) {
  763. const te = this.elements;
  764. te[0] *= s;
  765. te[3] *= s;
  766. te[6] *= s;
  767. te[1] *= s;
  768. te[4] *= s;
  769. te[7] *= s;
  770. te[2] *= s;
  771. te[5] *= s;
  772. te[8] *= s;
  773. return this;
  774. }
  775. determinant() {
  776. const te = this.elements;
  777. const a = te[0],
  778. b = te[1],
  779. c = te[2],
  780. d = te[3],
  781. e = te[4],
  782. f = te[5],
  783. g = te[6],
  784. h = te[7],
  785. i = te[8];
  786. return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g;
  787. }
  788. invert() {
  789. const te = this.elements,
  790. n11 = te[0],
  791. n21 = te[1],
  792. n31 = te[2],
  793. n12 = te[3],
  794. n22 = te[4],
  795. n32 = te[5],
  796. n13 = te[6],
  797. n23 = te[7],
  798. n33 = te[8],
  799. t11 = n33 * n22 - n32 * n23,
  800. t12 = n32 * n13 - n33 * n12,
  801. t13 = n23 * n12 - n22 * n13,
  802. det = n11 * t11 + n21 * t12 + n31 * t13;
  803. if (det === 0) return this.set(0, 0, 0, 0, 0, 0, 0, 0, 0);
  804. const detInv = 1 / det;
  805. te[0] = t11 * detInv;
  806. te[1] = (n31 * n23 - n33 * n21) * detInv;
  807. te[2] = (n32 * n21 - n31 * n22) * detInv;
  808. te[3] = t12 * detInv;
  809. te[4] = (n33 * n11 - n31 * n13) * detInv;
  810. te[5] = (n31 * n12 - n32 * n11) * detInv;
  811. te[6] = t13 * detInv;
  812. te[7] = (n21 * n13 - n23 * n11) * detInv;
  813. te[8] = (n22 * n11 - n21 * n12) * detInv;
  814. return this;
  815. }
  816. transpose() {
  817. let tmp;
  818. const m = this.elements;
  819. tmp = m[1];
  820. m[1] = m[3];
  821. m[3] = tmp;
  822. tmp = m[2];
  823. m[2] = m[6];
  824. m[6] = tmp;
  825. tmp = m[5];
  826. m[5] = m[7];
  827. m[7] = tmp;
  828. return this;
  829. }
  830. getNormalMatrix(matrix4) {
  831. return this.setFromMatrix4(matrix4).invert().transpose();
  832. }
  833. transposeIntoArray(r) {
  834. const m = this.elements;
  835. r[0] = m[0];
  836. r[1] = m[3];
  837. r[2] = m[6];
  838. r[3] = m[1];
  839. r[4] = m[4];
  840. r[5] = m[7];
  841. r[6] = m[2];
  842. r[7] = m[5];
  843. r[8] = m[8];
  844. return this;
  845. }
  846. setUvTransform(tx, ty, sx, sy, rotation, cx, cy) {
  847. const c = Math.cos(rotation);
  848. const s = Math.sin(rotation);
  849. 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);
  850. return this;
  851. }
  852. scale(sx, sy) {
  853. const te = this.elements;
  854. te[0] *= sx;
  855. te[3] *= sx;
  856. te[6] *= sx;
  857. te[1] *= sy;
  858. te[4] *= sy;
  859. te[7] *= sy;
  860. return this;
  861. }
  862. rotate(theta) {
  863. const c = Math.cos(theta);
  864. const s = Math.sin(theta);
  865. const te = this.elements;
  866. const a11 = te[0],
  867. a12 = te[3],
  868. a13 = te[6];
  869. const a21 = te[1],
  870. a22 = te[4],
  871. a23 = te[7];
  872. te[0] = c * a11 + s * a21;
  873. te[3] = c * a12 + s * a22;
  874. te[6] = c * a13 + s * a23;
  875. te[1] = -s * a11 + c * a21;
  876. te[4] = -s * a12 + c * a22;
  877. te[7] = -s * a13 + c * a23;
  878. return this;
  879. }
  880. translate(tx, ty) {
  881. const te = this.elements;
  882. te[0] += tx * te[2];
  883. te[3] += tx * te[5];
  884. te[6] += tx * te[8];
  885. te[1] += ty * te[2];
  886. te[4] += ty * te[5];
  887. te[7] += ty * te[8];
  888. return this;
  889. }
  890. equals(matrix) {
  891. const te = this.elements;
  892. const me = matrix.elements;
  893. for (let i = 0; i < 9; i++) {
  894. if (te[i] !== me[i]) return false;
  895. }
  896. return true;
  897. }
  898. fromArray(array, offset = 0) {
  899. for (let i = 0; i < 9; i++) {
  900. this.elements[i] = array[i + offset];
  901. }
  902. return this;
  903. }
  904. toArray(array = [], offset = 0) {
  905. const te = this.elements;
  906. array[offset] = te[0];
  907. array[offset + 1] = te[1];
  908. array[offset + 2] = te[2];
  909. array[offset + 3] = te[3];
  910. array[offset + 4] = te[4];
  911. array[offset + 5] = te[5];
  912. array[offset + 6] = te[6];
  913. array[offset + 7] = te[7];
  914. array[offset + 8] = te[8];
  915. return array;
  916. }
  917. clone() {
  918. return new this.constructor().fromArray(this.elements);
  919. }
  920. }
  921. function arrayNeedsUint32(array) {
  922. // assumes larger values usually on last
  923. for (let i = array.length - 1; i >= 0; --i) {
  924. if (array[i] >= 65535) return true; // account for PRIMITIVE_RESTART_FIXED_INDEX, #24565
  925. }
  926. return false;
  927. }
  928. const TYPED_ARRAYS = {
  929. Int8Array: Int8Array,
  930. Uint8Array: Uint8Array,
  931. Uint8ClampedArray: Uint8ClampedArray,
  932. Int16Array: Int16Array,
  933. Uint16Array: Uint16Array,
  934. Int32Array: Int32Array,
  935. Uint32Array: Uint32Array,
  936. Float32Array: Float32Array,
  937. Float64Array: Float64Array
  938. };
  939. function getTypedArray(type, buffer) {
  940. return new TYPED_ARRAYS[type](buffer);
  941. }
  942. function createElementNS(name) {
  943. return document.createElementNS('http://www.w3.org/1999/xhtml', name);
  944. }
  945. function SRGBToLinear(c) {
  946. return c < 0.04045 ? c * 0.0773993808 : Math.pow(c * 0.9478672986 + 0.0521327014, 2.4);
  947. }
  948. function LinearToSRGB(c) {
  949. return c < 0.0031308 ? c * 12.92 : 1.055 * Math.pow(c, 0.41666) - 0.055;
  950. } // JavaScript RGB-to-RGB transforms, defined as
  951. // FN[InputColorSpace][OutputColorSpace] callback functions.
  952. const FN = {
  953. [SRGBColorSpace]: {
  954. [LinearSRGBColorSpace]: SRGBToLinear
  955. },
  956. [LinearSRGBColorSpace]: {
  957. [SRGBColorSpace]: LinearToSRGB
  958. }
  959. };
  960. const ColorManagement = {
  961. legacyMode: true,
  962. get workingColorSpace() {
  963. return LinearSRGBColorSpace;
  964. },
  965. set workingColorSpace(colorSpace) {
  966. console.warn('THREE.ColorManagement: .workingColorSpace is readonly.');
  967. },
  968. convert: function (color, sourceColorSpace, targetColorSpace) {
  969. if (this.legacyMode || sourceColorSpace === targetColorSpace || !sourceColorSpace || !targetColorSpace) {
  970. return color;
  971. }
  972. if (FN[sourceColorSpace] && FN[sourceColorSpace][targetColorSpace] !== undefined) {
  973. const fn = FN[sourceColorSpace][targetColorSpace];
  974. color.r = fn(color.r);
  975. color.g = fn(color.g);
  976. color.b = fn(color.b);
  977. return color;
  978. }
  979. throw new Error('Unsupported color space conversion.');
  980. },
  981. fromWorkingColorSpace: function (color, targetColorSpace) {
  982. return this.convert(color, this.workingColorSpace, targetColorSpace);
  983. },
  984. toWorkingColorSpace: function (color, sourceColorSpace) {
  985. return this.convert(color, sourceColorSpace, this.workingColorSpace);
  986. }
  987. };
  988. const _colorKeywords = {
  989. 'aliceblue': 0xF0F8FF,
  990. 'antiquewhite': 0xFAEBD7,
  991. 'aqua': 0x00FFFF,
  992. 'aquamarine': 0x7FFFD4,
  993. 'azure': 0xF0FFFF,
  994. 'beige': 0xF5F5DC,
  995. 'bisque': 0xFFE4C4,
  996. 'black': 0x000000,
  997. 'blanchedalmond': 0xFFEBCD,
  998. 'blue': 0x0000FF,
  999. 'blueviolet': 0x8A2BE2,
  1000. 'brown': 0xA52A2A,
  1001. 'burlywood': 0xDEB887,
  1002. 'cadetblue': 0x5F9EA0,
  1003. 'chartreuse': 0x7FFF00,
  1004. 'chocolate': 0xD2691E,
  1005. 'coral': 0xFF7F50,
  1006. 'cornflowerblue': 0x6495ED,
  1007. 'cornsilk': 0xFFF8DC,
  1008. 'crimson': 0xDC143C,
  1009. 'cyan': 0x00FFFF,
  1010. 'darkblue': 0x00008B,
  1011. 'darkcyan': 0x008B8B,
  1012. 'darkgoldenrod': 0xB8860B,
  1013. 'darkgray': 0xA9A9A9,
  1014. 'darkgreen': 0x006400,
  1015. 'darkgrey': 0xA9A9A9,
  1016. 'darkkhaki': 0xBDB76B,
  1017. 'darkmagenta': 0x8B008B,
  1018. 'darkolivegreen': 0x556B2F,
  1019. 'darkorange': 0xFF8C00,
  1020. 'darkorchid': 0x9932CC,
  1021. 'darkred': 0x8B0000,
  1022. 'darksalmon': 0xE9967A,
  1023. 'darkseagreen': 0x8FBC8F,
  1024. 'darkslateblue': 0x483D8B,
  1025. 'darkslategray': 0x2F4F4F,
  1026. 'darkslategrey': 0x2F4F4F,
  1027. 'darkturquoise': 0x00CED1,
  1028. 'darkviolet': 0x9400D3,
  1029. 'deeppink': 0xFF1493,
  1030. 'deepskyblue': 0x00BFFF,
  1031. 'dimgray': 0x696969,
  1032. 'dimgrey': 0x696969,
  1033. 'dodgerblue': 0x1E90FF,
  1034. 'firebrick': 0xB22222,
  1035. 'floralwhite': 0xFFFAF0,
  1036. 'forestgreen': 0x228B22,
  1037. 'fuchsia': 0xFF00FF,
  1038. 'gainsboro': 0xDCDCDC,
  1039. 'ghostwhite': 0xF8F8FF,
  1040. 'gold': 0xFFD700,
  1041. 'goldenrod': 0xDAA520,
  1042. 'gray': 0x808080,
  1043. 'green': 0x008000,
  1044. 'greenyellow': 0xADFF2F,
  1045. 'grey': 0x808080,
  1046. 'honeydew': 0xF0FFF0,
  1047. 'hotpink': 0xFF69B4,
  1048. 'indianred': 0xCD5C5C,
  1049. 'indigo': 0x4B0082,
  1050. 'ivory': 0xFFFFF0,
  1051. 'khaki': 0xF0E68C,
  1052. 'lavender': 0xE6E6FA,
  1053. 'lavenderblush': 0xFFF0F5,
  1054. 'lawngreen': 0x7CFC00,
  1055. 'lemonchiffon': 0xFFFACD,
  1056. 'lightblue': 0xADD8E6,
  1057. 'lightcoral': 0xF08080,
  1058. 'lightcyan': 0xE0FFFF,
  1059. 'lightgoldenrodyellow': 0xFAFAD2,
  1060. 'lightgray': 0xD3D3D3,
  1061. 'lightgreen': 0x90EE90,
  1062. 'lightgrey': 0xD3D3D3,
  1063. 'lightpink': 0xFFB6C1,
  1064. 'lightsalmon': 0xFFA07A,
  1065. 'lightseagreen': 0x20B2AA,
  1066. 'lightskyblue': 0x87CEFA,
  1067. 'lightslategray': 0x778899,
  1068. 'lightslategrey': 0x778899,
  1069. 'lightsteelblue': 0xB0C4DE,
  1070. 'lightyellow': 0xFFFFE0,
  1071. 'lime': 0x00FF00,
  1072. 'limegreen': 0x32CD32,
  1073. 'linen': 0xFAF0E6,
  1074. 'magenta': 0xFF00FF,
  1075. 'maroon': 0x800000,
  1076. 'mediumaquamarine': 0x66CDAA,
  1077. 'mediumblue': 0x0000CD,
  1078. 'mediumorchid': 0xBA55D3,
  1079. 'mediumpurple': 0x9370DB,
  1080. 'mediumseagreen': 0x3CB371,
  1081. 'mediumslateblue': 0x7B68EE,
  1082. 'mediumspringgreen': 0x00FA9A,
  1083. 'mediumturquoise': 0x48D1CC,
  1084. 'mediumvioletred': 0xC71585,
  1085. 'midnightblue': 0x191970,
  1086. 'mintcream': 0xF5FFFA,
  1087. 'mistyrose': 0xFFE4E1,
  1088. 'moccasin': 0xFFE4B5,
  1089. 'navajowhite': 0xFFDEAD,
  1090. 'navy': 0x000080,
  1091. 'oldlace': 0xFDF5E6,
  1092. 'olive': 0x808000,
  1093. 'olivedrab': 0x6B8E23,
  1094. 'orange': 0xFFA500,
  1095. 'orangered': 0xFF4500,
  1096. 'orchid': 0xDA70D6,
  1097. 'palegoldenrod': 0xEEE8AA,
  1098. 'palegreen': 0x98FB98,
  1099. 'paleturquoise': 0xAFEEEE,
  1100. 'palevioletred': 0xDB7093,
  1101. 'papayawhip': 0xFFEFD5,
  1102. 'peachpuff': 0xFFDAB9,
  1103. 'peru': 0xCD853F,
  1104. 'pink': 0xFFC0CB,
  1105. 'plum': 0xDDA0DD,
  1106. 'powderblue': 0xB0E0E6,
  1107. 'purple': 0x800080,
  1108. 'rebeccapurple': 0x663399,
  1109. 'red': 0xFF0000,
  1110. 'rosybrown': 0xBC8F8F,
  1111. 'royalblue': 0x4169E1,
  1112. 'saddlebrown': 0x8B4513,
  1113. 'salmon': 0xFA8072,
  1114. 'sandybrown': 0xF4A460,
  1115. 'seagreen': 0x2E8B57,
  1116. 'seashell': 0xFFF5EE,
  1117. 'sienna': 0xA0522D,
  1118. 'silver': 0xC0C0C0,
  1119. 'skyblue': 0x87CEEB,
  1120. 'slateblue': 0x6A5ACD,
  1121. 'slategray': 0x708090,
  1122. 'slategrey': 0x708090,
  1123. 'snow': 0xFFFAFA,
  1124. 'springgreen': 0x00FF7F,
  1125. 'steelblue': 0x4682B4,
  1126. 'tan': 0xD2B48C,
  1127. 'teal': 0x008080,
  1128. 'thistle': 0xD8BFD8,
  1129. 'tomato': 0xFF6347,
  1130. 'turquoise': 0x40E0D0,
  1131. 'violet': 0xEE82EE,
  1132. 'wheat': 0xF5DEB3,
  1133. 'white': 0xFFFFFF,
  1134. 'whitesmoke': 0xF5F5F5,
  1135. 'yellow': 0xFFFF00,
  1136. 'yellowgreen': 0x9ACD32
  1137. };
  1138. const _rgb = {
  1139. r: 0,
  1140. g: 0,
  1141. b: 0
  1142. };
  1143. const _hslA = {
  1144. h: 0,
  1145. s: 0,
  1146. l: 0
  1147. };
  1148. const _hslB = {
  1149. h: 0,
  1150. s: 0,
  1151. l: 0
  1152. };
  1153. function hue2rgb(p, q, t) {
  1154. if (t < 0) t += 1;
  1155. if (t > 1) t -= 1;
  1156. if (t < 1 / 6) return p + (q - p) * 6 * t;
  1157. if (t < 1 / 2) return q;
  1158. if (t < 2 / 3) return p + (q - p) * 6 * (2 / 3 - t);
  1159. return p;
  1160. }
  1161. function toComponents(source, target) {
  1162. target.r = source.r;
  1163. target.g = source.g;
  1164. target.b = source.b;
  1165. return target;
  1166. }
  1167. class Color {
  1168. constructor(r, g, b) {
  1169. this.isColor = true;
  1170. this.r = 1;
  1171. this.g = 1;
  1172. this.b = 1;
  1173. if (g === undefined && b === undefined) {
  1174. // r is THREE.Color, hex or string
  1175. return this.set(r);
  1176. }
  1177. return this.setRGB(r, g, b);
  1178. }
  1179. set(value) {
  1180. if (value && value.isColor) {
  1181. this.copy(value);
  1182. } else if (typeof value === 'number') {
  1183. this.setHex(value);
  1184. } else if (typeof value === 'string') {
  1185. this.setStyle(value);
  1186. }
  1187. return this;
  1188. }
  1189. setScalar(scalar) {
  1190. this.r = scalar;
  1191. this.g = scalar;
  1192. this.b = scalar;
  1193. return this;
  1194. }
  1195. setHex(hex, colorSpace = SRGBColorSpace) {
  1196. hex = Math.floor(hex);
  1197. this.r = (hex >> 16 & 255) / 255;
  1198. this.g = (hex >> 8 & 255) / 255;
  1199. this.b = (hex & 255) / 255;
  1200. ColorManagement.toWorkingColorSpace(this, colorSpace);
  1201. return this;
  1202. }
  1203. setRGB(r, g, b, colorSpace = LinearSRGBColorSpace) {
  1204. this.r = r;
  1205. this.g = g;
  1206. this.b = b;
  1207. ColorManagement.toWorkingColorSpace(this, colorSpace);
  1208. return this;
  1209. }
  1210. setHSL(h, s, l, colorSpace = LinearSRGBColorSpace) {
  1211. // h,s,l ranges are in 0.0 - 1.0
  1212. h = euclideanModulo(h, 1);
  1213. s = clamp(s, 0, 1);
  1214. l = clamp(l, 0, 1);
  1215. if (s === 0) {
  1216. this.r = this.g = this.b = l;
  1217. } else {
  1218. const p = l <= 0.5 ? l * (1 + s) : l + s - l * s;
  1219. const q = 2 * l - p;
  1220. this.r = hue2rgb(q, p, h + 1 / 3);
  1221. this.g = hue2rgb(q, p, h);
  1222. this.b = hue2rgb(q, p, h - 1 / 3);
  1223. }
  1224. ColorManagement.toWorkingColorSpace(this, colorSpace);
  1225. return this;
  1226. }
  1227. setStyle(style, colorSpace = SRGBColorSpace) {
  1228. function handleAlpha(string) {
  1229. if (string === undefined) return;
  1230. if (parseFloat(string) < 1) {
  1231. console.warn('THREE.Color: Alpha component of ' + style + ' will be ignored.');
  1232. }
  1233. }
  1234. let m;
  1235. if (m = /^((?:rgb|hsl)a?)\(([^\)]*)\)/.exec(style)) {
  1236. // rgb / hsl
  1237. let color;
  1238. const name = m[1];
  1239. const components = m[2];
  1240. switch (name) {
  1241. case 'rgb':
  1242. case 'rgba':
  1243. if (color = /^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(components)) {
  1244. // rgb(255,0,0) rgba(255,0,0,0.5)
  1245. this.r = Math.min(255, parseInt(color[1], 10)) / 255;
  1246. this.g = Math.min(255, parseInt(color[2], 10)) / 255;
  1247. this.b = Math.min(255, parseInt(color[3], 10)) / 255;
  1248. ColorManagement.toWorkingColorSpace(this, colorSpace);
  1249. handleAlpha(color[4]);
  1250. return this;
  1251. }
  1252. if (color = /^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(components)) {
  1253. // rgb(100%,0%,0%) rgba(100%,0%,0%,0.5)
  1254. this.r = Math.min(100, parseInt(color[1], 10)) / 100;
  1255. this.g = Math.min(100, parseInt(color[2], 10)) / 100;
  1256. this.b = Math.min(100, parseInt(color[3], 10)) / 100;
  1257. ColorManagement.toWorkingColorSpace(this, colorSpace);
  1258. handleAlpha(color[4]);
  1259. return this;
  1260. }
  1261. break;
  1262. case 'hsl':
  1263. case 'hsla':
  1264. if (color = /^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(components)) {
  1265. // hsl(120,50%,50%) hsla(120,50%,50%,0.5)
  1266. const h = parseFloat(color[1]) / 360;
  1267. const s = parseFloat(color[2]) / 100;
  1268. const l = parseFloat(color[3]) / 100;
  1269. handleAlpha(color[4]);
  1270. return this.setHSL(h, s, l, colorSpace);
  1271. }
  1272. break;
  1273. }
  1274. } else if (m = /^\#([A-Fa-f\d]+)$/.exec(style)) {
  1275. // hex color
  1276. const hex = m[1];
  1277. const size = hex.length;
  1278. if (size === 3) {
  1279. // #ff0
  1280. this.r = parseInt(hex.charAt(0) + hex.charAt(0), 16) / 255;
  1281. this.g = parseInt(hex.charAt(1) + hex.charAt(1), 16) / 255;
  1282. this.b = parseInt(hex.charAt(2) + hex.charAt(2), 16) / 255;
  1283. ColorManagement.toWorkingColorSpace(this, colorSpace);
  1284. return this;
  1285. } else if (size === 6) {
  1286. // #ff0000
  1287. this.r = parseInt(hex.charAt(0) + hex.charAt(1), 16) / 255;
  1288. this.g = parseInt(hex.charAt(2) + hex.charAt(3), 16) / 255;
  1289. this.b = parseInt(hex.charAt(4) + hex.charAt(5), 16) / 255;
  1290. ColorManagement.toWorkingColorSpace(this, colorSpace);
  1291. return this;
  1292. }
  1293. }
  1294. if (style && style.length > 0) {
  1295. return this.setColorName(style, colorSpace);
  1296. }
  1297. return this;
  1298. }
  1299. setColorName(style, colorSpace = SRGBColorSpace) {
  1300. // color keywords
  1301. const hex = _colorKeywords[style.toLowerCase()];
  1302. if (hex !== undefined) {
  1303. // red
  1304. this.setHex(hex, colorSpace);
  1305. } else {
  1306. // unknown color
  1307. console.warn('THREE.Color: Unknown color ' + style);
  1308. }
  1309. return this;
  1310. }
  1311. clone() {
  1312. return new this.constructor(this.r, this.g, this.b);
  1313. }
  1314. copy(color) {
  1315. this.r = color.r;
  1316. this.g = color.g;
  1317. this.b = color.b;
  1318. return this;
  1319. }
  1320. copySRGBToLinear(color) {
  1321. this.r = SRGBToLinear(color.r);
  1322. this.g = SRGBToLinear(color.g);
  1323. this.b = SRGBToLinear(color.b);
  1324. return this;
  1325. }
  1326. copyLinearToSRGB(color) {
  1327. this.r = LinearToSRGB(color.r);
  1328. this.g = LinearToSRGB(color.g);
  1329. this.b = LinearToSRGB(color.b);
  1330. return this;
  1331. }
  1332. convertSRGBToLinear() {
  1333. this.copySRGBToLinear(this);
  1334. return this;
  1335. }
  1336. convertLinearToSRGB() {
  1337. this.copyLinearToSRGB(this);
  1338. return this;
  1339. }
  1340. getHex(colorSpace = SRGBColorSpace) {
  1341. ColorManagement.fromWorkingColorSpace(toComponents(this, _rgb), colorSpace);
  1342. return clamp(_rgb.r * 255, 0, 255) << 16 ^ clamp(_rgb.g * 255, 0, 255) << 8 ^ clamp(_rgb.b * 255, 0, 255) << 0;
  1343. }
  1344. getHexString(colorSpace = SRGBColorSpace) {
  1345. return ('000000' + this.getHex(colorSpace).toString(16)).slice(-6);
  1346. }
  1347. getHSL(target, colorSpace = LinearSRGBColorSpace) {
  1348. // h,s,l ranges are in 0.0 - 1.0
  1349. ColorManagement.fromWorkingColorSpace(toComponents(this, _rgb), colorSpace);
  1350. const r = _rgb.r,
  1351. g = _rgb.g,
  1352. b = _rgb.b;
  1353. const max = Math.max(r, g, b);
  1354. const min = Math.min(r, g, b);
  1355. let hue, saturation;
  1356. const lightness = (min + max) / 2.0;
  1357. if (min === max) {
  1358. hue = 0;
  1359. saturation = 0;
  1360. } else {
  1361. const delta = max - min;
  1362. saturation = lightness <= 0.5 ? delta / (max + min) : delta / (2 - max - min);
  1363. switch (max) {
  1364. case r:
  1365. hue = (g - b) / delta + (g < b ? 6 : 0);
  1366. break;
  1367. case g:
  1368. hue = (b - r) / delta + 2;
  1369. break;
  1370. case b:
  1371. hue = (r - g) / delta + 4;
  1372. break;
  1373. }
  1374. hue /= 6;
  1375. }
  1376. target.h = hue;
  1377. target.s = saturation;
  1378. target.l = lightness;
  1379. return target;
  1380. }
  1381. getRGB(target, colorSpace = LinearSRGBColorSpace) {
  1382. ColorManagement.fromWorkingColorSpace(toComponents(this, _rgb), colorSpace);
  1383. target.r = _rgb.r;
  1384. target.g = _rgb.g;
  1385. target.b = _rgb.b;
  1386. return target;
  1387. }
  1388. getStyle(colorSpace = SRGBColorSpace) {
  1389. ColorManagement.fromWorkingColorSpace(toComponents(this, _rgb), colorSpace);
  1390. if (colorSpace !== SRGBColorSpace) {
  1391. // Requires CSS Color Module Level 4 (https://www.w3.org/TR/css-color-4/).
  1392. return `color(${colorSpace} ${_rgb.r} ${_rgb.g} ${_rgb.b})`;
  1393. }
  1394. return `rgb(${_rgb.r * 255 | 0},${_rgb.g * 255 | 0},${_rgb.b * 255 | 0})`;
  1395. }
  1396. offsetHSL(h, s, l) {
  1397. this.getHSL(_hslA);
  1398. _hslA.h += h;
  1399. _hslA.s += s;
  1400. _hslA.l += l;
  1401. this.setHSL(_hslA.h, _hslA.s, _hslA.l);
  1402. return this;
  1403. }
  1404. add(color) {
  1405. this.r += color.r;
  1406. this.g += color.g;
  1407. this.b += color.b;
  1408. return this;
  1409. }
  1410. addColors(color1, color2) {
  1411. this.r = color1.r + color2.r;
  1412. this.g = color1.g + color2.g;
  1413. this.b = color1.b + color2.b;
  1414. return this;
  1415. }
  1416. addScalar(s) {
  1417. this.r += s;
  1418. this.g += s;
  1419. this.b += s;
  1420. return this;
  1421. }
  1422. sub(color) {
  1423. this.r = Math.max(0, this.r - color.r);
  1424. this.g = Math.max(0, this.g - color.g);
  1425. this.b = Math.max(0, this.b - color.b);
  1426. return this;
  1427. }
  1428. multiply(color) {
  1429. this.r *= color.r;
  1430. this.g *= color.g;
  1431. this.b *= color.b;
  1432. return this;
  1433. }
  1434. multiplyScalar(s) {
  1435. this.r *= s;
  1436. this.g *= s;
  1437. this.b *= s;
  1438. return this;
  1439. }
  1440. lerp(color, alpha) {
  1441. this.r += (color.r - this.r) * alpha;
  1442. this.g += (color.g - this.g) * alpha;
  1443. this.b += (color.b - this.b) * alpha;
  1444. return this;
  1445. }
  1446. lerpColors(color1, color2, alpha) {
  1447. this.r = color1.r + (color2.r - color1.r) * alpha;
  1448. this.g = color1.g + (color2.g - color1.g) * alpha;
  1449. this.b = color1.b + (color2.b - color1.b) * alpha;
  1450. return this;
  1451. }
  1452. lerpHSL(color, alpha) {
  1453. this.getHSL(_hslA);
  1454. color.getHSL(_hslB);
  1455. const h = lerp(_hslA.h, _hslB.h, alpha);
  1456. const s = lerp(_hslA.s, _hslB.s, alpha);
  1457. const l = lerp(_hslA.l, _hslB.l, alpha);
  1458. this.setHSL(h, s, l);
  1459. return this;
  1460. }
  1461. equals(c) {
  1462. return c.r === this.r && c.g === this.g && c.b === this.b;
  1463. }
  1464. fromArray(array, offset = 0) {
  1465. this.r = array[offset];
  1466. this.g = array[offset + 1];
  1467. this.b = array[offset + 2];
  1468. return this;
  1469. }
  1470. toArray(array = [], offset = 0) {
  1471. array[offset] = this.r;
  1472. array[offset + 1] = this.g;
  1473. array[offset + 2] = this.b;
  1474. return array;
  1475. }
  1476. fromBufferAttribute(attribute, index) {
  1477. this.r = attribute.getX(index);
  1478. this.g = attribute.getY(index);
  1479. this.b = attribute.getZ(index);
  1480. return this;
  1481. }
  1482. toJSON() {
  1483. return this.getHex();
  1484. }
  1485. *[Symbol.iterator]() {
  1486. yield this.r;
  1487. yield this.g;
  1488. yield this.b;
  1489. }
  1490. }
  1491. Color.NAMES = _colorKeywords;
  1492. let _canvas;
  1493. class ImageUtils {
  1494. static getDataURL(image) {
  1495. if (/^data:/i.test(image.src)) {
  1496. return image.src;
  1497. }
  1498. if (typeof HTMLCanvasElement == 'undefined') {
  1499. return image.src;
  1500. }
  1501. let canvas;
  1502. if (image instanceof HTMLCanvasElement) {
  1503. canvas = image;
  1504. } else {
  1505. if (_canvas === undefined) _canvas = createElementNS('canvas');
  1506. _canvas.width = image.width;
  1507. _canvas.height = image.height;
  1508. const context = _canvas.getContext('2d');
  1509. if (image instanceof ImageData) {
  1510. context.putImageData(image, 0, 0);
  1511. } else {
  1512. context.drawImage(image, 0, 0, image.width, image.height);
  1513. }
  1514. canvas = _canvas;
  1515. }
  1516. if (canvas.width > 2048 || canvas.height > 2048) {
  1517. console.warn('THREE.ImageUtils.getDataURL: Image converted to jpg for performance reasons', image);
  1518. return canvas.toDataURL('image/jpeg', 0.6);
  1519. } else {
  1520. return canvas.toDataURL('image/png');
  1521. }
  1522. }
  1523. static sRGBToLinear(image) {
  1524. if (typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement || typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement || typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap) {
  1525. const canvas = createElementNS('canvas');
  1526. canvas.width = image.width;
  1527. canvas.height = image.height;
  1528. const context = canvas.getContext('2d');
  1529. context.drawImage(image, 0, 0, image.width, image.height);
  1530. const imageData = context.getImageData(0, 0, image.width, image.height);
  1531. const data = imageData.data;
  1532. for (let i = 0; i < data.length; i++) {
  1533. data[i] = SRGBToLinear(data[i] / 255) * 255;
  1534. }
  1535. context.putImageData(imageData, 0, 0);
  1536. return canvas;
  1537. } else if (image.data) {
  1538. const data = image.data.slice(0);
  1539. for (let i = 0; i < data.length; i++) {
  1540. if (data instanceof Uint8Array || data instanceof Uint8ClampedArray) {
  1541. data[i] = Math.floor(SRGBToLinear(data[i] / 255) * 255);
  1542. } else {
  1543. // assuming float
  1544. data[i] = SRGBToLinear(data[i]);
  1545. }
  1546. }
  1547. return {
  1548. data: data,
  1549. width: image.width,
  1550. height: image.height
  1551. };
  1552. } else {
  1553. console.warn('THREE.ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied.');
  1554. return image;
  1555. }
  1556. }
  1557. }
  1558. class Source {
  1559. constructor(data = null) {
  1560. this.isSource = true;
  1561. this.uuid = generateUUID();
  1562. this.data = data;
  1563. this.version = 0;
  1564. }
  1565. set needsUpdate(value) {
  1566. if (value === true) this.version++;
  1567. }
  1568. toJSON(meta) {
  1569. const isRootObject = meta === undefined || typeof meta === 'string';
  1570. if (!isRootObject && meta.images[this.uuid] !== undefined) {
  1571. return meta.images[this.uuid];
  1572. }
  1573. const output = {
  1574. uuid: this.uuid,
  1575. url: ''
  1576. };
  1577. const data = this.data;
  1578. if (data !== null) {
  1579. let url;
  1580. if (Array.isArray(data)) {
  1581. // cube texture
  1582. url = [];
  1583. for (let i = 0, l = data.length; i < l; i++) {
  1584. if (data[i].isDataTexture) {
  1585. url.push(serializeImage(data[i].image));
  1586. } else {
  1587. url.push(serializeImage(data[i]));
  1588. }
  1589. }
  1590. } else {
  1591. // texture
  1592. url = serializeImage(data);
  1593. }
  1594. output.url = url;
  1595. }
  1596. if (!isRootObject) {
  1597. meta.images[this.uuid] = output;
  1598. }
  1599. return output;
  1600. }
  1601. }
  1602. function serializeImage(image) {
  1603. if (typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement || typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement || typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap) {
  1604. // default images
  1605. return ImageUtils.getDataURL(image);
  1606. } else {
  1607. if (image.data) {
  1608. // images of DataTexture
  1609. return {
  1610. data: Array.from(image.data),
  1611. width: image.width,
  1612. height: image.height,
  1613. type: image.data.constructor.name
  1614. };
  1615. } else {
  1616. console.warn('THREE.Texture: Unable to serialize Texture.');
  1617. return {};
  1618. }
  1619. }
  1620. }
  1621. let textureId = 0;
  1622. class Texture extends EventDispatcher {
  1623. constructor(image = Texture.DEFAULT_IMAGE, mapping = Texture.DEFAULT_MAPPING, wrapS = ClampToEdgeWrapping, wrapT = ClampToEdgeWrapping, magFilter = LinearFilter, minFilter = LinearMipmapLinearFilter, format = RGBAFormat, type = UnsignedByteType, anisotropy = 1, encoding = LinearEncoding) {
  1624. super();
  1625. this.isTexture = true;
  1626. Object.defineProperty(this, 'id', {
  1627. value: textureId++
  1628. });
  1629. this.uuid = generateUUID();
  1630. this.name = '';
  1631. this.source = new Source(image);
  1632. this.mipmaps = [];
  1633. this.mapping = mapping;
  1634. this.wrapS = wrapS;
  1635. this.wrapT = wrapT;
  1636. this.magFilter = magFilter;
  1637. this.minFilter = minFilter;
  1638. this.anisotropy = anisotropy;
  1639. this.format = format;
  1640. this.internalFormat = null;
  1641. this.type = type;
  1642. this.offset = new Vector2(0, 0);
  1643. this.repeat = new Vector2(1, 1);
  1644. this.center = new Vector2(0, 0);
  1645. this.rotation = 0;
  1646. this.matrixAutoUpdate = true;
  1647. this.matrix = new Matrix3();
  1648. this.generateMipmaps = true;
  1649. this.premultiplyAlpha = false;
  1650. this.flipY = true;
  1651. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  1652. // Values of encoding !== THREE.LinearEncoding only supported on map, envMap and emissiveMap.
  1653. //
  1654. // Also changing the encoding after already used by a Material will not automatically make the Material
  1655. // update. You need to explicitly call Material.needsUpdate to trigger it to recompile.
  1656. this.encoding = encoding;
  1657. this.userData = {};
  1658. this.version = 0;
  1659. this.onUpdate = null;
  1660. this.isRenderTargetTexture = false; // indicates whether a texture belongs to a render target or not
  1661. this.needsPMREMUpdate = false; // indicates whether this texture should be processed by PMREMGenerator or not (only relevant for render target textures)
  1662. }
  1663. get image() {
  1664. return this.source.data;
  1665. }
  1666. set image(value) {
  1667. this.source.data = value;
  1668. }
  1669. updateMatrix() {
  1670. this.matrix.setUvTransform(this.offset.x, this.offset.y, this.repeat.x, this.repeat.y, this.rotation, this.center.x, this.center.y);
  1671. }
  1672. clone() {
  1673. return new this.constructor().copy(this);
  1674. }
  1675. copy(source) {
  1676. this.name = source.name;
  1677. this.source = source.source;
  1678. this.mipmaps = source.mipmaps.slice(0);
  1679. this.mapping = source.mapping;
  1680. this.wrapS = source.wrapS;
  1681. this.wrapT = source.wrapT;
  1682. this.magFilter = source.magFilter;
  1683. this.minFilter = source.minFilter;
  1684. this.anisotropy = source.anisotropy;
  1685. this.format = source.format;
  1686. this.internalFormat = source.internalFormat;
  1687. this.type = source.type;
  1688. this.offset.copy(source.offset);
  1689. this.repeat.copy(source.repeat);
  1690. this.center.copy(source.center);
  1691. this.rotation = source.rotation;
  1692. this.matrixAutoUpdate = source.matrixAutoUpdate;
  1693. this.matrix.copy(source.matrix);
  1694. this.generateMipmaps = source.generateMipmaps;
  1695. this.premultiplyAlpha = source.premultiplyAlpha;
  1696. this.flipY = source.flipY;
  1697. this.unpackAlignment = source.unpackAlignment;
  1698. this.encoding = source.encoding;
  1699. this.userData = JSON.parse(JSON.stringify(source.userData));
  1700. this.needsUpdate = true;
  1701. return this;
  1702. }
  1703. toJSON(meta) {
  1704. const isRootObject = meta === undefined || typeof meta === 'string';
  1705. if (!isRootObject && meta.textures[this.uuid] !== undefined) {
  1706. return meta.textures[this.uuid];
  1707. }
  1708. const output = {
  1709. metadata: {
  1710. version: 4.5,
  1711. type: 'Texture',
  1712. generator: 'Texture.toJSON'
  1713. },
  1714. uuid: this.uuid,
  1715. name: this.name,
  1716. image: this.source.toJSON(meta).uuid,
  1717. mapping: this.mapping,
  1718. repeat: [this.repeat.x, this.repeat.y],
  1719. offset: [this.offset.x, this.offset.y],
  1720. center: [this.center.x, this.center.y],
  1721. rotation: this.rotation,
  1722. wrap: [this.wrapS, this.wrapT],
  1723. format: this.format,
  1724. type: this.type,
  1725. encoding: this.encoding,
  1726. minFilter: this.minFilter,
  1727. magFilter: this.magFilter,
  1728. anisotropy: this.anisotropy,
  1729. flipY: this.flipY,
  1730. premultiplyAlpha: this.premultiplyAlpha,
  1731. unpackAlignment: this.unpackAlignment
  1732. };
  1733. if (JSON.stringify(this.userData) !== '{}') output.userData = this.userData;
  1734. if (!isRootObject) {
  1735. meta.textures[this.uuid] = output;
  1736. }
  1737. return output;
  1738. }
  1739. dispose() {
  1740. this.dispatchEvent({
  1741. type: 'dispose'
  1742. });
  1743. }
  1744. transformUv(uv) {
  1745. if (this.mapping !== UVMapping) return uv;
  1746. uv.applyMatrix3(this.matrix);
  1747. if (uv.x < 0 || uv.x > 1) {
  1748. switch (this.wrapS) {
  1749. case RepeatWrapping:
  1750. uv.x = uv.x - Math.floor(uv.x);
  1751. break;
  1752. case ClampToEdgeWrapping:
  1753. uv.x = uv.x < 0 ? 0 : 1;
  1754. break;
  1755. case MirroredRepeatWrapping:
  1756. if (Math.abs(Math.floor(uv.x) % 2) === 1) {
  1757. uv.x = Math.ceil(uv.x) - uv.x;
  1758. } else {
  1759. uv.x = uv.x - Math.floor(uv.x);
  1760. }
  1761. break;
  1762. }
  1763. }
  1764. if (uv.y < 0 || uv.y > 1) {
  1765. switch (this.wrapT) {
  1766. case RepeatWrapping:
  1767. uv.y = uv.y - Math.floor(uv.y);
  1768. break;
  1769. case ClampToEdgeWrapping:
  1770. uv.y = uv.y < 0 ? 0 : 1;
  1771. break;
  1772. case MirroredRepeatWrapping:
  1773. if (Math.abs(Math.floor(uv.y) % 2) === 1) {
  1774. uv.y = Math.ceil(uv.y) - uv.y;
  1775. } else {
  1776. uv.y = uv.y - Math.floor(uv.y);
  1777. }
  1778. break;
  1779. }
  1780. }
  1781. if (this.flipY) {
  1782. uv.y = 1 - uv.y;
  1783. }
  1784. return uv;
  1785. }
  1786. set needsUpdate(value) {
  1787. if (value === true) {
  1788. this.version++;
  1789. this.source.needsUpdate = true;
  1790. }
  1791. }
  1792. }
  1793. Texture.DEFAULT_IMAGE = null;
  1794. Texture.DEFAULT_MAPPING = UVMapping;
  1795. class Vector4 {
  1796. constructor(x = 0, y = 0, z = 0, w = 1) {
  1797. Vector4.prototype.isVector4 = true;
  1798. this.x = x;
  1799. this.y = y;
  1800. this.z = z;
  1801. this.w = w;
  1802. }
  1803. get width() {
  1804. return this.z;
  1805. }
  1806. set width(value) {
  1807. this.z = value;
  1808. }
  1809. get height() {
  1810. return this.w;
  1811. }
  1812. set height(value) {
  1813. this.w = value;
  1814. }
  1815. set(x, y, z, w) {
  1816. this.x = x;
  1817. this.y = y;
  1818. this.z = z;
  1819. this.w = w;
  1820. return this;
  1821. }
  1822. setScalar(scalar) {
  1823. this.x = scalar;
  1824. this.y = scalar;
  1825. this.z = scalar;
  1826. this.w = scalar;
  1827. return this;
  1828. }
  1829. setX(x) {
  1830. this.x = x;
  1831. return this;
  1832. }
  1833. setY(y) {
  1834. this.y = y;
  1835. return this;
  1836. }
  1837. setZ(z) {
  1838. this.z = z;
  1839. return this;
  1840. }
  1841. setW(w) {
  1842. this.w = w;
  1843. return this;
  1844. }
  1845. setComponent(index, value) {
  1846. switch (index) {
  1847. case 0:
  1848. this.x = value;
  1849. break;
  1850. case 1:
  1851. this.y = value;
  1852. break;
  1853. case 2:
  1854. this.z = value;
  1855. break;
  1856. case 3:
  1857. this.w = value;
  1858. break;
  1859. default:
  1860. throw new Error('index is out of range: ' + index);
  1861. }
  1862. return this;
  1863. }
  1864. getComponent(index) {
  1865. switch (index) {
  1866. case 0:
  1867. return this.x;
  1868. case 1:
  1869. return this.y;
  1870. case 2:
  1871. return this.z;
  1872. case 3:
  1873. return this.w;
  1874. default:
  1875. throw new Error('index is out of range: ' + index);
  1876. }
  1877. }
  1878. clone() {
  1879. return new this.constructor(this.x, this.y, this.z, this.w);
  1880. }
  1881. copy(v) {
  1882. this.x = v.x;
  1883. this.y = v.y;
  1884. this.z = v.z;
  1885. this.w = v.w !== undefined ? v.w : 1;
  1886. return this;
  1887. }
  1888. add(v) {
  1889. this.x += v.x;
  1890. this.y += v.y;
  1891. this.z += v.z;
  1892. this.w += v.w;
  1893. return this;
  1894. }
  1895. addScalar(s) {
  1896. this.x += s;
  1897. this.y += s;
  1898. this.z += s;
  1899. this.w += s;
  1900. return this;
  1901. }
  1902. addVectors(a, b) {
  1903. this.x = a.x + b.x;
  1904. this.y = a.y + b.y;
  1905. this.z = a.z + b.z;
  1906. this.w = a.w + b.w;
  1907. return this;
  1908. }
  1909. addScaledVector(v, s) {
  1910. this.x += v.x * s;
  1911. this.y += v.y * s;
  1912. this.z += v.z * s;
  1913. this.w += v.w * s;
  1914. return this;
  1915. }
  1916. sub(v) {
  1917. this.x -= v.x;
  1918. this.y -= v.y;
  1919. this.z -= v.z;
  1920. this.w -= v.w;
  1921. return this;
  1922. }
  1923. subScalar(s) {
  1924. this.x -= s;
  1925. this.y -= s;
  1926. this.z -= s;
  1927. this.w -= s;
  1928. return this;
  1929. }
  1930. subVectors(a, b) {
  1931. this.x = a.x - b.x;
  1932. this.y = a.y - b.y;
  1933. this.z = a.z - b.z;
  1934. this.w = a.w - b.w;
  1935. return this;
  1936. }
  1937. multiply(v) {
  1938. this.x *= v.x;
  1939. this.y *= v.y;
  1940. this.z *= v.z;
  1941. this.w *= v.w;
  1942. return this;
  1943. }
  1944. multiplyScalar(scalar) {
  1945. this.x *= scalar;
  1946. this.y *= scalar;
  1947. this.z *= scalar;
  1948. this.w *= scalar;
  1949. return this;
  1950. }
  1951. applyMatrix4(m) {
  1952. const x = this.x,
  1953. y = this.y,
  1954. z = this.z,
  1955. w = this.w;
  1956. const e = m.elements;
  1957. this.x = e[0] * x + e[4] * y + e[8] * z + e[12] * w;
  1958. this.y = e[1] * x + e[5] * y + e[9] * z + e[13] * w;
  1959. this.z = e[2] * x + e[6] * y + e[10] * z + e[14] * w;
  1960. this.w = e[3] * x + e[7] * y + e[11] * z + e[15] * w;
  1961. return this;
  1962. }
  1963. divideScalar(scalar) {
  1964. return this.multiplyScalar(1 / scalar);
  1965. }
  1966. setAxisAngleFromQuaternion(q) {
  1967. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  1968. // q is assumed to be normalized
  1969. this.w = 2 * Math.acos(q.w);
  1970. const s = Math.sqrt(1 - q.w * q.w);
  1971. if (s < 0.0001) {
  1972. this.x = 1;
  1973. this.y = 0;
  1974. this.z = 0;
  1975. } else {
  1976. this.x = q.x / s;
  1977. this.y = q.y / s;
  1978. this.z = q.z / s;
  1979. }
  1980. return this;
  1981. }
  1982. setAxisAngleFromRotationMatrix(m) {
  1983. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  1984. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1985. let angle, x, y, z; // variables for result
  1986. const epsilon = 0.01,
  1987. // margin to allow for rounding errors
  1988. epsilon2 = 0.1,
  1989. // margin to distinguish between 0 and 180 degrees
  1990. te = m.elements,
  1991. m11 = te[0],
  1992. m12 = te[4],
  1993. m13 = te[8],
  1994. m21 = te[1],
  1995. m22 = te[5],
  1996. m23 = te[9],
  1997. m31 = te[2],
  1998. m32 = te[6],
  1999. m33 = te[10];
  2000. if (Math.abs(m12 - m21) < epsilon && Math.abs(m13 - m31) < epsilon && Math.abs(m23 - m32) < epsilon) {
  2001. // singularity found
  2002. // first check for identity matrix which must have +1 for all terms
  2003. // in leading diagonal and zero in other terms
  2004. if (Math.abs(m12 + m21) < epsilon2 && Math.abs(m13 + m31) < epsilon2 && Math.abs(m23 + m32) < epsilon2 && Math.abs(m11 + m22 + m33 - 3) < epsilon2) {
  2005. // this singularity is identity matrix so angle = 0
  2006. this.set(1, 0, 0, 0);
  2007. return this; // zero angle, arbitrary axis
  2008. } // otherwise this singularity is angle = 180
  2009. angle = Math.PI;
  2010. const xx = (m11 + 1) / 2;
  2011. const yy = (m22 + 1) / 2;
  2012. const zz = (m33 + 1) / 2;
  2013. const xy = (m12 + m21) / 4;
  2014. const xz = (m13 + m31) / 4;
  2015. const yz = (m23 + m32) / 4;
  2016. if (xx > yy && xx > zz) {
  2017. // m11 is the largest diagonal term
  2018. if (xx < epsilon) {
  2019. x = 0;
  2020. y = 0.707106781;
  2021. z = 0.707106781;
  2022. } else {
  2023. x = Math.sqrt(xx);
  2024. y = xy / x;
  2025. z = xz / x;
  2026. }
  2027. } else if (yy > zz) {
  2028. // m22 is the largest diagonal term
  2029. if (yy < epsilon) {
  2030. x = 0.707106781;
  2031. y = 0;
  2032. z = 0.707106781;
  2033. } else {
  2034. y = Math.sqrt(yy);
  2035. x = xy / y;
  2036. z = yz / y;
  2037. }
  2038. } else {
  2039. // m33 is the largest diagonal term so base result on this
  2040. if (zz < epsilon) {
  2041. x = 0.707106781;
  2042. y = 0.707106781;
  2043. z = 0;
  2044. } else {
  2045. z = Math.sqrt(zz);
  2046. x = xz / z;
  2047. y = yz / z;
  2048. }
  2049. }
  2050. this.set(x, y, z, angle);
  2051. return this; // return 180 deg rotation
  2052. } // as we have reached here there are no singularities so we can handle normally
  2053. let s = Math.sqrt((m32 - m23) * (m32 - m23) + (m13 - m31) * (m13 - m31) + (m21 - m12) * (m21 - m12)); // used to normalize
  2054. if (Math.abs(s) < 0.001) s = 1; // prevent divide by zero, should not happen if matrix is orthogonal and should be
  2055. // caught by singularity test above, but I've left it in just in case
  2056. this.x = (m32 - m23) / s;
  2057. this.y = (m13 - m31) / s;
  2058. this.z = (m21 - m12) / s;
  2059. this.w = Math.acos((m11 + m22 + m33 - 1) / 2);
  2060. return this;
  2061. }
  2062. min(v) {
  2063. this.x = Math.min(this.x, v.x);
  2064. this.y = Math.min(this.y, v.y);
  2065. this.z = Math.min(this.z, v.z);
  2066. this.w = Math.min(this.w, v.w);
  2067. return this;
  2068. }
  2069. max(v) {
  2070. this.x = Math.max(this.x, v.x);
  2071. this.y = Math.max(this.y, v.y);
  2072. this.z = Math.max(this.z, v.z);
  2073. this.w = Math.max(this.w, v.w);
  2074. return this;
  2075. }
  2076. clamp(min, max) {
  2077. // assumes min < max, componentwise
  2078. this.x = Math.max(min.x, Math.min(max.x, this.x));
  2079. this.y = Math.max(min.y, Math.min(max.y, this.y));
  2080. this.z = Math.max(min.z, Math.min(max.z, this.z));
  2081. this.w = Math.max(min.w, Math.min(max.w, this.w));
  2082. return this;
  2083. }
  2084. clampScalar(minVal, maxVal) {
  2085. this.x = Math.max(minVal, Math.min(maxVal, this.x));
  2086. this.y = Math.max(minVal, Math.min(maxVal, this.y));
  2087. this.z = Math.max(minVal, Math.min(maxVal, this.z));
  2088. this.w = Math.max(minVal, Math.min(maxVal, this.w));
  2089. return this;
  2090. }
  2091. clampLength(min, max) {
  2092. const length = this.length();
  2093. return this.divideScalar(length || 1).multiplyScalar(Math.max(min, Math.min(max, length)));
  2094. }
  2095. floor() {
  2096. this.x = Math.floor(this.x);
  2097. this.y = Math.floor(this.y);
  2098. this.z = Math.floor(this.z);
  2099. this.w = Math.floor(this.w);
  2100. return this;
  2101. }
  2102. ceil() {
  2103. this.x = Math.ceil(this.x);
  2104. this.y = Math.ceil(this.y);
  2105. this.z = Math.ceil(this.z);
  2106. this.w = Math.ceil(this.w);
  2107. return this;
  2108. }
  2109. round() {
  2110. this.x = Math.round(this.x);
  2111. this.y = Math.round(this.y);
  2112. this.z = Math.round(this.z);
  2113. this.w = Math.round(this.w);
  2114. return this;
  2115. }
  2116. roundToZero() {
  2117. this.x = this.x < 0 ? Math.ceil(this.x) : Math.floor(this.x);
  2118. this.y = this.y < 0 ? Math.ceil(this.y) : Math.floor(this.y);
  2119. this.z = this.z < 0 ? Math.ceil(this.z) : Math.floor(this.z);
  2120. this.w = this.w < 0 ? Math.ceil(this.w) : Math.floor(this.w);
  2121. return this;
  2122. }
  2123. negate() {
  2124. this.x = -this.x;
  2125. this.y = -this.y;
  2126. this.z = -this.z;
  2127. this.w = -this.w;
  2128. return this;
  2129. }
  2130. dot(v) {
  2131. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  2132. }
  2133. lengthSq() {
  2134. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  2135. }
  2136. length() {
  2137. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  2138. }
  2139. manhattanLength() {
  2140. return Math.abs(this.x) + Math.abs(this.y) + Math.abs(this.z) + Math.abs(this.w);
  2141. }
  2142. normalize() {
  2143. return this.divideScalar(this.length() || 1);
  2144. }
  2145. setLength(length) {
  2146. return this.normalize().multiplyScalar(length);
  2147. }
  2148. lerp(v, alpha) {
  2149. this.x += (v.x - this.x) * alpha;
  2150. this.y += (v.y - this.y) * alpha;
  2151. this.z += (v.z - this.z) * alpha;
  2152. this.w += (v.w - this.w) * alpha;
  2153. return this;
  2154. }
  2155. lerpVectors(v1, v2, alpha) {
  2156. this.x = v1.x + (v2.x - v1.x) * alpha;
  2157. this.y = v1.y + (v2.y - v1.y) * alpha;
  2158. this.z = v1.z + (v2.z - v1.z) * alpha;
  2159. this.w = v1.w + (v2.w - v1.w) * alpha;
  2160. return this;
  2161. }
  2162. equals(v) {
  2163. return v.x === this.x && v.y === this.y && v.z === this.z && v.w === this.w;
  2164. }
  2165. fromArray(array, offset = 0) {
  2166. this.x = array[offset];
  2167. this.y = array[offset + 1];
  2168. this.z = array[offset + 2];
  2169. this.w = array[offset + 3];
  2170. return this;
  2171. }
  2172. toArray(array = [], offset = 0) {
  2173. array[offset] = this.x;
  2174. array[offset + 1] = this.y;
  2175. array[offset + 2] = this.z;
  2176. array[offset + 3] = this.w;
  2177. return array;
  2178. }
  2179. fromBufferAttribute(attribute, index) {
  2180. this.x = attribute.getX(index);
  2181. this.y = attribute.getY(index);
  2182. this.z = attribute.getZ(index);
  2183. this.w = attribute.getW(index);
  2184. return this;
  2185. }
  2186. random() {
  2187. this.x = Math.random();
  2188. this.y = Math.random();
  2189. this.z = Math.random();
  2190. this.w = Math.random();
  2191. return this;
  2192. }
  2193. *[Symbol.iterator]() {
  2194. yield this.x;
  2195. yield this.y;
  2196. yield this.z;
  2197. yield this.w;
  2198. }
  2199. }
  2200. /*
  2201. In options, we can specify:
  2202. * Texture parameters for an auto-generated target texture
  2203. * depthBuffer/stencilBuffer: Booleans to indicate if we should generate these buffers
  2204. */
  2205. class WebGLRenderTarget extends EventDispatcher {
  2206. constructor(width, height, options = {}) {
  2207. super();
  2208. this.isWebGLRenderTarget = true;
  2209. this.width = width;
  2210. this.height = height;
  2211. this.depth = 1;
  2212. this.scissor = new Vector4(0, 0, width, height);
  2213. this.scissorTest = false;
  2214. this.viewport = new Vector4(0, 0, width, height);
  2215. const image = {
  2216. width: width,
  2217. height: height,
  2218. depth: 1
  2219. };
  2220. this.texture = new Texture(image, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding);
  2221. this.texture.isRenderTargetTexture = true;
  2222. this.texture.flipY = false;
  2223. this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false;
  2224. this.texture.internalFormat = options.internalFormat !== undefined ? options.internalFormat : null;
  2225. this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter;
  2226. this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
  2227. this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : false;
  2228. this.depthTexture = options.depthTexture !== undefined ? options.depthTexture : null;
  2229. this.samples = options.samples !== undefined ? options.samples : 0;
  2230. }
  2231. setSize(width, height, depth = 1) {
  2232. if (this.width !== width || this.height !== height || this.depth !== depth) {
  2233. this.width = width;
  2234. this.height = height;
  2235. this.depth = depth;
  2236. this.texture.image.width = width;
  2237. this.texture.image.height = height;
  2238. this.texture.image.depth = depth;
  2239. this.dispose();
  2240. }
  2241. this.viewport.set(0, 0, width, height);
  2242. this.scissor.set(0, 0, width, height);
  2243. }
  2244. clone() {
  2245. return new this.constructor().copy(this);
  2246. }
  2247. copy(source) {
  2248. this.width = source.width;
  2249. this.height = source.height;
  2250. this.depth = source.depth;
  2251. this.viewport.copy(source.viewport);
  2252. this.texture = source.texture.clone();
  2253. this.texture.isRenderTargetTexture = true; // ensure image object is not shared, see #20328
  2254. const image = Object.assign({}, source.texture.image);
  2255. this.texture.source = new Source(image);
  2256. this.depthBuffer = source.depthBuffer;
  2257. this.stencilBuffer = source.stencilBuffer;
  2258. if (source.depthTexture !== null) this.depthTexture = source.depthTexture.clone();
  2259. this.samples = source.samples;
  2260. return this;
  2261. }
  2262. dispose() {
  2263. this.dispatchEvent({
  2264. type: 'dispose'
  2265. });
  2266. }
  2267. }
  2268. class DataArrayTexture extends Texture {
  2269. constructor(data = null, width = 1, height = 1, depth = 1) {
  2270. super(null);
  2271. this.isDataArrayTexture = true;
  2272. this.image = {
  2273. data,
  2274. width,
  2275. height,
  2276. depth
  2277. };
  2278. this.magFilter = NearestFilter;
  2279. this.minFilter = NearestFilter;
  2280. this.wrapR = ClampToEdgeWrapping;
  2281. this.generateMipmaps = false;
  2282. this.flipY = false;
  2283. this.unpackAlignment = 1;
  2284. }
  2285. }
  2286. class WebGLArrayRenderTarget extends WebGLRenderTarget {
  2287. constructor(width, height, depth) {
  2288. super(width, height);
  2289. this.isWebGLArrayRenderTarget = true;
  2290. this.depth = depth;
  2291. this.texture = new DataArrayTexture(null, width, height, depth);
  2292. this.texture.isRenderTargetTexture = true;
  2293. }
  2294. }
  2295. class Data3DTexture extends Texture {
  2296. constructor(data = null, width = 1, height = 1, depth = 1) {
  2297. // We're going to add .setXXX() methods for setting properties later.
  2298. // Users can still set in DataTexture3D directly.
  2299. //
  2300. // const texture = new THREE.DataTexture3D( data, width, height, depth );
  2301. // texture.anisotropy = 16;
  2302. //
  2303. // See #14839
  2304. super(null);
  2305. this.isData3DTexture = true;
  2306. this.image = {
  2307. data,
  2308. width,
  2309. height,
  2310. depth
  2311. };
  2312. this.magFilter = NearestFilter;
  2313. this.minFilter = NearestFilter;
  2314. this.wrapR = ClampToEdgeWrapping;
  2315. this.generateMipmaps = false;
  2316. this.flipY = false;
  2317. this.unpackAlignment = 1;
  2318. }
  2319. }
  2320. class WebGL3DRenderTarget extends WebGLRenderTarget {
  2321. constructor(width, height, depth) {
  2322. super(width, height);
  2323. this.isWebGL3DRenderTarget = true;
  2324. this.depth = depth;
  2325. this.texture = new Data3DTexture(null, width, height, depth);
  2326. this.texture.isRenderTargetTexture = true;
  2327. }
  2328. }
  2329. class WebGLMultipleRenderTargets extends WebGLRenderTarget {
  2330. constructor(width, height, count, options = {}) {
  2331. super(width, height, options);
  2332. this.isWebGLMultipleRenderTargets = true;
  2333. const texture = this.texture;
  2334. this.texture = [];
  2335. for (let i = 0; i < count; i++) {
  2336. this.texture[i] = texture.clone();
  2337. this.texture[i].isRenderTargetTexture = true;
  2338. }
  2339. }
  2340. setSize(width, height, depth = 1) {
  2341. if (this.width !== width || this.height !== height || this.depth !== depth) {
  2342. this.width = width;
  2343. this.height = height;
  2344. this.depth = depth;
  2345. for (let i = 0, il = this.texture.length; i < il; i++) {
  2346. this.texture[i].image.width = width;
  2347. this.texture[i].image.height = height;
  2348. this.texture[i].image.depth = depth;
  2349. }
  2350. this.dispose();
  2351. }
  2352. this.viewport.set(0, 0, width, height);
  2353. this.scissor.set(0, 0, width, height);
  2354. return this;
  2355. }
  2356. copy(source) {
  2357. this.dispose();
  2358. this.width = source.width;
  2359. this.height = source.height;
  2360. this.depth = source.depth;
  2361. this.viewport.set(0, 0, this.width, this.height);
  2362. this.scissor.set(0, 0, this.width, this.height);
  2363. this.depthBuffer = source.depthBuffer;
  2364. this.stencilBuffer = source.stencilBuffer;
  2365. if (source.depthTexture !== null) this.depthTexture = source.depthTexture.clone();
  2366. this.texture.length = 0;
  2367. for (let i = 0, il = source.texture.length; i < il; i++) {
  2368. this.texture[i] = source.texture[i].clone();
  2369. this.texture[i].isRenderTargetTexture = true;
  2370. }
  2371. return this;
  2372. }
  2373. }
  2374. class Quaternion {
  2375. constructor(x = 0, y = 0, z = 0, w = 1) {
  2376. this.isQuaternion = true;
  2377. this._x = x;
  2378. this._y = y;
  2379. this._z = z;
  2380. this._w = w;
  2381. }
  2382. static slerpFlat(dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t) {
  2383. // fuzz-free, array-based Quaternion SLERP operation
  2384. let x0 = src0[srcOffset0 + 0],
  2385. y0 = src0[srcOffset0 + 1],
  2386. z0 = src0[srcOffset0 + 2],
  2387. w0 = src0[srcOffset0 + 3];
  2388. const x1 = src1[srcOffset1 + 0],
  2389. y1 = src1[srcOffset1 + 1],
  2390. z1 = src1[srcOffset1 + 2],
  2391. w1 = src1[srcOffset1 + 3];
  2392. if (t === 0) {
  2393. dst[dstOffset + 0] = x0;
  2394. dst[dstOffset + 1] = y0;
  2395. dst[dstOffset + 2] = z0;
  2396. dst[dstOffset + 3] = w0;
  2397. return;
  2398. }
  2399. if (t === 1) {
  2400. dst[dstOffset + 0] = x1;
  2401. dst[dstOffset + 1] = y1;
  2402. dst[dstOffset + 2] = z1;
  2403. dst[dstOffset + 3] = w1;
  2404. return;
  2405. }
  2406. if (w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1) {
  2407. let s = 1 - t;
  2408. const cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1,
  2409. dir = cos >= 0 ? 1 : -1,
  2410. sqrSin = 1 - cos * cos; // Skip the Slerp for tiny steps to avoid numeric problems:
  2411. if (sqrSin > Number.EPSILON) {
  2412. const sin = Math.sqrt(sqrSin),
  2413. len = Math.atan2(sin, cos * dir);
  2414. s = Math.sin(s * len) / sin;
  2415. t = Math.sin(t * len) / sin;
  2416. }
  2417. const tDir = t * dir;
  2418. x0 = x0 * s + x1 * tDir;
  2419. y0 = y0 * s + y1 * tDir;
  2420. z0 = z0 * s + z1 * tDir;
  2421. w0 = w0 * s + w1 * tDir; // Normalize in case we just did a lerp:
  2422. if (s === 1 - t) {
  2423. const f = 1 / Math.sqrt(x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0);
  2424. x0 *= f;
  2425. y0 *= f;
  2426. z0 *= f;
  2427. w0 *= f;
  2428. }
  2429. }
  2430. dst[dstOffset] = x0;
  2431. dst[dstOffset + 1] = y0;
  2432. dst[dstOffset + 2] = z0;
  2433. dst[dstOffset + 3] = w0;
  2434. }
  2435. static multiplyQuaternionsFlat(dst, dstOffset, src0, srcOffset0, src1, srcOffset1) {
  2436. const x0 = src0[srcOffset0];
  2437. const y0 = src0[srcOffset0 + 1];
  2438. const z0 = src0[srcOffset0 + 2];
  2439. const w0 = src0[srcOffset0 + 3];
  2440. const x1 = src1[srcOffset1];
  2441. const y1 = src1[srcOffset1 + 1];
  2442. const z1 = src1[srcOffset1 + 2];
  2443. const w1 = src1[srcOffset1 + 3];
  2444. dst[dstOffset] = x0 * w1 + w0 * x1 + y0 * z1 - z0 * y1;
  2445. dst[dstOffset + 1] = y0 * w1 + w0 * y1 + z0 * x1 - x0 * z1;
  2446. dst[dstOffset + 2] = z0 * w1 + w0 * z1 + x0 * y1 - y0 * x1;
  2447. dst[dstOffset + 3] = w0 * w1 - x0 * x1 - y0 * y1 - z0 * z1;
  2448. return dst;
  2449. }
  2450. get x() {
  2451. return this._x;
  2452. }
  2453. set x(value) {
  2454. this._x = value;
  2455. this._onChangeCallback();
  2456. }
  2457. get y() {
  2458. return this._y;
  2459. }
  2460. set y(value) {
  2461. this._y = value;
  2462. this._onChangeCallback();
  2463. }
  2464. get z() {
  2465. return this._z;
  2466. }
  2467. set z(value) {
  2468. this._z = value;
  2469. this._onChangeCallback();
  2470. }
  2471. get w() {
  2472. return this._w;
  2473. }
  2474. set w(value) {
  2475. this._w = value;
  2476. this._onChangeCallback();
  2477. }
  2478. set(x, y, z, w) {
  2479. this._x = x;
  2480. this._y = y;
  2481. this._z = z;
  2482. this._w = w;
  2483. this._onChangeCallback();
  2484. return this;
  2485. }
  2486. clone() {
  2487. return new this.constructor(this._x, this._y, this._z, this._w);
  2488. }
  2489. copy(quaternion) {
  2490. this._x = quaternion.x;
  2491. this._y = quaternion.y;
  2492. this._z = quaternion.z;
  2493. this._w = quaternion.w;
  2494. this._onChangeCallback();
  2495. return this;
  2496. }
  2497. setFromEuler(euler, update) {
  2498. const x = euler._x,
  2499. y = euler._y,
  2500. z = euler._z,
  2501. order = euler._order; // http://www.mathworks.com/matlabcentral/fileexchange/
  2502. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  2503. // content/SpinCalc.m
  2504. const cos = Math.cos;
  2505. const sin = Math.sin;
  2506. const c1 = cos(x / 2);
  2507. const c2 = cos(y / 2);
  2508. const c3 = cos(z / 2);
  2509. const s1 = sin(x / 2);
  2510. const s2 = sin(y / 2);
  2511. const s3 = sin(z / 2);
  2512. switch (order) {
  2513. case 'XYZ':
  2514. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  2515. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  2516. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  2517. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  2518. break;
  2519. case 'YXZ':
  2520. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  2521. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  2522. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  2523. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  2524. break;
  2525. case 'ZXY':
  2526. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  2527. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  2528. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  2529. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  2530. break;
  2531. case 'ZYX':
  2532. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  2533. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  2534. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  2535. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  2536. break;
  2537. case 'YZX':
  2538. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  2539. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  2540. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  2541. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  2542. break;
  2543. case 'XZY':
  2544. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  2545. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  2546. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  2547. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  2548. break;
  2549. default:
  2550. console.warn('THREE.Quaternion: .setFromEuler() encountered an unknown order: ' + order);
  2551. }
  2552. if (update !== false) this._onChangeCallback();
  2553. return this;
  2554. }
  2555. setFromAxisAngle(axis, angle) {
  2556. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  2557. // assumes axis is normalized
  2558. const halfAngle = angle / 2,
  2559. s = Math.sin(halfAngle);
  2560. this._x = axis.x * s;
  2561. this._y = axis.y * s;
  2562. this._z = axis.z * s;
  2563. this._w = Math.cos(halfAngle);
  2564. this._onChangeCallback();
  2565. return this;
  2566. }
  2567. setFromRotationMatrix(m) {
  2568. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  2569. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  2570. const te = m.elements,
  2571. m11 = te[0],
  2572. m12 = te[4],
  2573. m13 = te[8],
  2574. m21 = te[1],
  2575. m22 = te[5],
  2576. m23 = te[9],
  2577. m31 = te[2],
  2578. m32 = te[6],
  2579. m33 = te[10],
  2580. trace = m11 + m22 + m33;
  2581. if (trace > 0) {
  2582. const s = 0.5 / Math.sqrt(trace + 1.0);
  2583. this._w = 0.25 / s;
  2584. this._x = (m32 - m23) * s;
  2585. this._y = (m13 - m31) * s;
  2586. this._z = (m21 - m12) * s;
  2587. } else if (m11 > m22 && m11 > m33) {
  2588. const s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  2589. this._w = (m32 - m23) / s;
  2590. this._x = 0.25 * s;
  2591. this._y = (m12 + m21) / s;
  2592. this._z = (m13 + m31) / s;
  2593. } else if (m22 > m33) {
  2594. const s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  2595. this._w = (m13 - m31) / s;
  2596. this._x = (m12 + m21) / s;
  2597. this._y = 0.25 * s;
  2598. this._z = (m23 + m32) / s;
  2599. } else {
  2600. const s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  2601. this._w = (m21 - m12) / s;
  2602. this._x = (m13 + m31) / s;
  2603. this._y = (m23 + m32) / s;
  2604. this._z = 0.25 * s;
  2605. }
  2606. this._onChangeCallback();
  2607. return this;
  2608. }
  2609. setFromUnitVectors(vFrom, vTo) {
  2610. // assumes direction vectors vFrom and vTo are normalized
  2611. let r = vFrom.dot(vTo) + 1;
  2612. if (r < Number.EPSILON) {
  2613. // vFrom and vTo point in opposite directions
  2614. r = 0;
  2615. if (Math.abs(vFrom.x) > Math.abs(vFrom.z)) {
  2616. this._x = -vFrom.y;
  2617. this._y = vFrom.x;
  2618. this._z = 0;
  2619. this._w = r;
  2620. } else {
  2621. this._x = 0;
  2622. this._y = -vFrom.z;
  2623. this._z = vFrom.y;
  2624. this._w = r;
  2625. }
  2626. } else {
  2627. // crossVectors( vFrom, vTo ); // inlined to avoid cyclic dependency on Vector3
  2628. this._x = vFrom.y * vTo.z - vFrom.z * vTo.y;
  2629. this._y = vFrom.z * vTo.x - vFrom.x * vTo.z;
  2630. this._z = vFrom.x * vTo.y - vFrom.y * vTo.x;
  2631. this._w = r;
  2632. }
  2633. return this.normalize();
  2634. }
  2635. angleTo(q) {
  2636. return 2 * Math.acos(Math.abs(clamp(this.dot(q), -1, 1)));
  2637. }
  2638. rotateTowards(q, step) {
  2639. const angle = this.angleTo(q);
  2640. if (angle === 0) return this;
  2641. const t = Math.min(1, step / angle);
  2642. this.slerp(q, t);
  2643. return this;
  2644. }
  2645. identity() {
  2646. return this.set(0, 0, 0, 1);
  2647. }
  2648. invert() {
  2649. // quaternion is assumed to have unit length
  2650. return this.conjugate();
  2651. }
  2652. conjugate() {
  2653. this._x *= -1;
  2654. this._y *= -1;
  2655. this._z *= -1;
  2656. this._onChangeCallback();
  2657. return this;
  2658. }
  2659. dot(v) {
  2660. return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w;
  2661. }
  2662. lengthSq() {
  2663. return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  2664. }
  2665. length() {
  2666. return Math.sqrt(this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w);
  2667. }
  2668. normalize() {
  2669. let l = this.length();
  2670. if (l === 0) {
  2671. this._x = 0;
  2672. this._y = 0;
  2673. this._z = 0;
  2674. this._w = 1;
  2675. } else {
  2676. l = 1 / l;
  2677. this._x = this._x * l;
  2678. this._y = this._y * l;
  2679. this._z = this._z * l;
  2680. this._w = this._w * l;
  2681. }
  2682. this._onChangeCallback();
  2683. return this;
  2684. }
  2685. multiply(q) {
  2686. return this.multiplyQuaternions(this, q);
  2687. }
  2688. premultiply(q) {
  2689. return this.multiplyQuaternions(q, this);
  2690. }
  2691. multiplyQuaternions(a, b) {
  2692. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  2693. const qax = a._x,
  2694. qay = a._y,
  2695. qaz = a._z,
  2696. qaw = a._w;
  2697. const qbx = b._x,
  2698. qby = b._y,
  2699. qbz = b._z,
  2700. qbw = b._w;
  2701. this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  2702. this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  2703. this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  2704. this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  2705. this._onChangeCallback();
  2706. return this;
  2707. }
  2708. slerp(qb, t) {
  2709. if (t === 0) return this;
  2710. if (t === 1) return this.copy(qb);
  2711. const x = this._x,
  2712. y = this._y,
  2713. z = this._z,
  2714. w = this._w; // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  2715. let cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z;
  2716. if (cosHalfTheta < 0) {
  2717. this._w = -qb._w;
  2718. this._x = -qb._x;
  2719. this._y = -qb._y;
  2720. this._z = -qb._z;
  2721. cosHalfTheta = -cosHalfTheta;
  2722. } else {
  2723. this.copy(qb);
  2724. }
  2725. if (cosHalfTheta >= 1.0) {
  2726. this._w = w;
  2727. this._x = x;
  2728. this._y = y;
  2729. this._z = z;
  2730. return this;
  2731. }
  2732. const sqrSinHalfTheta = 1.0 - cosHalfTheta * cosHalfTheta;
  2733. if (sqrSinHalfTheta <= Number.EPSILON) {
  2734. const s = 1 - t;
  2735. this._w = s * w + t * this._w;
  2736. this._x = s * x + t * this._x;
  2737. this._y = s * y + t * this._y;
  2738. this._z = s * z + t * this._z;
  2739. this.normalize();
  2740. this._onChangeCallback();
  2741. return this;
  2742. }
  2743. const sinHalfTheta = Math.sqrt(sqrSinHalfTheta);
  2744. const halfTheta = Math.atan2(sinHalfTheta, cosHalfTheta);
  2745. const ratioA = Math.sin((1 - t) * halfTheta) / sinHalfTheta,
  2746. ratioB = Math.sin(t * halfTheta) / sinHalfTheta;
  2747. this._w = w * ratioA + this._w * ratioB;
  2748. this._x = x * ratioA + this._x * ratioB;
  2749. this._y = y * ratioA + this._y * ratioB;
  2750. this._z = z * ratioA + this._z * ratioB;
  2751. this._onChangeCallback();
  2752. return this;
  2753. }
  2754. slerpQuaternions(qa, qb, t) {
  2755. return this.copy(qa).slerp(qb, t);
  2756. }
  2757. random() {
  2758. // Derived from http://planning.cs.uiuc.edu/node198.html
  2759. // Note, this source uses w, x, y, z ordering,
  2760. // so we swap the order below.
  2761. const u1 = Math.random();
  2762. const sqrt1u1 = Math.sqrt(1 - u1);
  2763. const sqrtu1 = Math.sqrt(u1);
  2764. const u2 = 2 * Math.PI * Math.random();
  2765. const u3 = 2 * Math.PI * Math.random();
  2766. return this.set(sqrt1u1 * Math.cos(u2), sqrtu1 * Math.sin(u3), sqrtu1 * Math.cos(u3), sqrt1u1 * Math.sin(u2));
  2767. }
  2768. equals(quaternion) {
  2769. return quaternion._x === this._x && quaternion._y === this._y && quaternion._z === this._z && quaternion._w === this._w;
  2770. }
  2771. fromArray(array, offset = 0) {
  2772. this._x = array[offset];
  2773. this._y = array[offset + 1];
  2774. this._z = array[offset + 2];
  2775. this._w = array[offset + 3];
  2776. this._onChangeCallback();
  2777. return this;
  2778. }
  2779. toArray(array = [], offset = 0) {
  2780. array[offset] = this._x;
  2781. array[offset + 1] = this._y;
  2782. array[offset + 2] = this._z;
  2783. array[offset + 3] = this._w;
  2784. return array;
  2785. }
  2786. fromBufferAttribute(attribute, index) {
  2787. this._x = attribute.getX(index);
  2788. this._y = attribute.getY(index);
  2789. this._z = attribute.getZ(index);
  2790. this._w = attribute.getW(index);
  2791. return this;
  2792. }
  2793. _onChange(callback) {
  2794. this._onChangeCallback = callback;
  2795. return this;
  2796. }
  2797. _onChangeCallback() {}
  2798. *[Symbol.iterator]() {
  2799. yield this._x;
  2800. yield this._y;
  2801. yield this._z;
  2802. yield this._w;
  2803. }
  2804. }
  2805. class Vector3 {
  2806. constructor(x = 0, y = 0, z = 0) {
  2807. Vector3.prototype.isVector3 = true;
  2808. this.x = x;
  2809. this.y = y;
  2810. this.z = z;
  2811. }
  2812. set(x, y, z) {
  2813. if (z === undefined) z = this.z; // sprite.scale.set(x,y)
  2814. this.x = x;
  2815. this.y = y;
  2816. this.z = z;
  2817. return this;
  2818. }
  2819. setScalar(scalar) {
  2820. this.x = scalar;
  2821. this.y = scalar;
  2822. this.z = scalar;
  2823. return this;
  2824. }
  2825. setX(x) {
  2826. this.x = x;
  2827. return this;
  2828. }
  2829. setY(y) {
  2830. this.y = y;
  2831. return this;
  2832. }
  2833. setZ(z) {
  2834. this.z = z;
  2835. return this;
  2836. }
  2837. setComponent(index, value) {
  2838. switch (index) {
  2839. case 0:
  2840. this.x = value;
  2841. break;
  2842. case 1:
  2843. this.y = value;
  2844. break;
  2845. case 2:
  2846. this.z = value;
  2847. break;
  2848. default:
  2849. throw new Error('index is out of range: ' + index);
  2850. }
  2851. return this;
  2852. }
  2853. getComponent(index) {
  2854. switch (index) {
  2855. case 0:
  2856. return this.x;
  2857. case 1:
  2858. return this.y;
  2859. case 2:
  2860. return this.z;
  2861. default:
  2862. throw new Error('index is out of range: ' + index);
  2863. }
  2864. }
  2865. clone() {
  2866. return new this.constructor(this.x, this.y, this.z);
  2867. }
  2868. copy(v) {
  2869. this.x = v.x;
  2870. this.y = v.y;
  2871. this.z = v.z;
  2872. return this;
  2873. }
  2874. add(v) {
  2875. this.x += v.x;
  2876. this.y += v.y;
  2877. this.z += v.z;
  2878. return this;
  2879. }
  2880. addScalar(s) {
  2881. this.x += s;
  2882. this.y += s;
  2883. this.z += s;
  2884. return this;
  2885. }
  2886. addVectors(a, b) {
  2887. this.x = a.x + b.x;
  2888. this.y = a.y + b.y;
  2889. this.z = a.z + b.z;
  2890. return this;
  2891. }
  2892. addScaledVector(v, s) {
  2893. this.x += v.x * s;
  2894. this.y += v.y * s;
  2895. this.z += v.z * s;
  2896. return this;
  2897. }
  2898. sub(v) {
  2899. this.x -= v.x;
  2900. this.y -= v.y;
  2901. this.z -= v.z;
  2902. return this;
  2903. }
  2904. subScalar(s) {
  2905. this.x -= s;
  2906. this.y -= s;
  2907. this.z -= s;
  2908. return this;
  2909. }
  2910. subVectors(a, b) {
  2911. this.x = a.x - b.x;
  2912. this.y = a.y - b.y;
  2913. this.z = a.z - b.z;
  2914. return this;
  2915. }
  2916. multiply(v) {
  2917. this.x *= v.x;
  2918. this.y *= v.y;
  2919. this.z *= v.z;
  2920. return this;
  2921. }
  2922. multiplyScalar(scalar) {
  2923. this.x *= scalar;
  2924. this.y *= scalar;
  2925. this.z *= scalar;
  2926. return this;
  2927. }
  2928. multiplyVectors(a, b) {
  2929. this.x = a.x * b.x;
  2930. this.y = a.y * b.y;
  2931. this.z = a.z * b.z;
  2932. return this;
  2933. }
  2934. applyEuler(euler) {
  2935. return this.applyQuaternion(_quaternion$4.setFromEuler(euler));
  2936. }
  2937. applyAxisAngle(axis, angle) {
  2938. return this.applyQuaternion(_quaternion$4.setFromAxisAngle(axis, angle));
  2939. }
  2940. applyMatrix3(m) {
  2941. const x = this.x,
  2942. y = this.y,
  2943. z = this.z;
  2944. const e = m.elements;
  2945. this.x = e[0] * x + e[3] * y + e[6] * z;
  2946. this.y = e[1] * x + e[4] * y + e[7] * z;
  2947. this.z = e[2] * x + e[5] * y + e[8] * z;
  2948. return this;
  2949. }
  2950. applyNormalMatrix(m) {
  2951. return this.applyMatrix3(m).normalize();
  2952. }
  2953. applyMatrix4(m) {
  2954. const x = this.x,
  2955. y = this.y,
  2956. z = this.z;
  2957. const e = m.elements;
  2958. const w = 1 / (e[3] * x + e[7] * y + e[11] * z + e[15]);
  2959. this.x = (e[0] * x + e[4] * y + e[8] * z + e[12]) * w;
  2960. this.y = (e[1] * x + e[5] * y + e[9] * z + e[13]) * w;
  2961. this.z = (e[2] * x + e[6] * y + e[10] * z + e[14]) * w;
  2962. return this;
  2963. }
  2964. applyQuaternion(q) {
  2965. const x = this.x,
  2966. y = this.y,
  2967. z = this.z;
  2968. const qx = q.x,
  2969. qy = q.y,
  2970. qz = q.z,
  2971. qw = q.w; // calculate quat * vector
  2972. const ix = qw * x + qy * z - qz * y;
  2973. const iy = qw * y + qz * x - qx * z;
  2974. const iz = qw * z + qx * y - qy * x;
  2975. const iw = -qx * x - qy * y - qz * z; // calculate result * inverse quat
  2976. this.x = ix * qw + iw * -qx + iy * -qz - iz * -qy;
  2977. this.y = iy * qw + iw * -qy + iz * -qx - ix * -qz;
  2978. this.z = iz * qw + iw * -qz + ix * -qy - iy * -qx;
  2979. return this;
  2980. }
  2981. project(camera) {
  2982. return this.applyMatrix4(camera.matrixWorldInverse).applyMatrix4(camera.projectionMatrix);
  2983. }
  2984. unproject(camera) {
  2985. return this.applyMatrix4(camera.projectionMatrixInverse).applyMatrix4(camera.matrixWorld);
  2986. }
  2987. transformDirection(m) {
  2988. // input: THREE.Matrix4 affine matrix
  2989. // vector interpreted as a direction
  2990. const x = this.x,
  2991. y = this.y,
  2992. z = this.z;
  2993. const e = m.elements;
  2994. this.x = e[0] * x + e[4] * y + e[8] * z;
  2995. this.y = e[1] * x + e[5] * y + e[9] * z;
  2996. this.z = e[2] * x + e[6] * y + e[10] * z;
  2997. return this.normalize();
  2998. }
  2999. divide(v) {
  3000. this.x /= v.x;
  3001. this.y /= v.y;
  3002. this.z /= v.z;
  3003. return this;
  3004. }
  3005. divideScalar(scalar) {
  3006. return this.multiplyScalar(1 / scalar);
  3007. }
  3008. min(v) {
  3009. this.x = Math.min(this.x, v.x);
  3010. this.y = Math.min(this.y, v.y);
  3011. this.z = Math.min(this.z, v.z);
  3012. return this;
  3013. }
  3014. max(v) {
  3015. this.x = Math.max(this.x, v.x);
  3016. this.y = Math.max(this.y, v.y);
  3017. this.z = Math.max(this.z, v.z);
  3018. return this;
  3019. }
  3020. clamp(min, max) {
  3021. // assumes min < max, componentwise
  3022. this.x = Math.max(min.x, Math.min(max.x, this.x));
  3023. this.y = Math.max(min.y, Math.min(max.y, this.y));
  3024. this.z = Math.max(min.z, Math.min(max.z, this.z));
  3025. return this;
  3026. }
  3027. clampScalar(minVal, maxVal) {
  3028. this.x = Math.max(minVal, Math.min(maxVal, this.x));
  3029. this.y = Math.max(minVal, Math.min(maxVal, this.y));
  3030. this.z = Math.max(minVal, Math.min(maxVal, this.z));
  3031. return this;
  3032. }
  3033. clampLength(min, max) {
  3034. const length = this.length();
  3035. return this.divideScalar(length || 1).multiplyScalar(Math.max(min, Math.min(max, length)));
  3036. }
  3037. floor() {
  3038. this.x = Math.floor(this.x);
  3039. this.y = Math.floor(this.y);
  3040. this.z = Math.floor(this.z);
  3041. return this;
  3042. }
  3043. ceil() {
  3044. this.x = Math.ceil(this.x);
  3045. this.y = Math.ceil(this.y);
  3046. this.z = Math.ceil(this.z);
  3047. return this;
  3048. }
  3049. round() {
  3050. this.x = Math.round(this.x);
  3051. this.y = Math.round(this.y);
  3052. this.z = Math.round(this.z);
  3053. return this;
  3054. }
  3055. roundToZero() {
  3056. this.x = this.x < 0 ? Math.ceil(this.x) : Math.floor(this.x);
  3057. this.y = this.y < 0 ? Math.ceil(this.y) : Math.floor(this.y);
  3058. this.z = this.z < 0 ? Math.ceil(this.z) : Math.floor(this.z);
  3059. return this;
  3060. }
  3061. negate() {
  3062. this.x = -this.x;
  3063. this.y = -this.y;
  3064. this.z = -this.z;
  3065. return this;
  3066. }
  3067. dot(v) {
  3068. return this.x * v.x + this.y * v.y + this.z * v.z;
  3069. } // TODO lengthSquared?
  3070. lengthSq() {
  3071. return this.x * this.x + this.y * this.y + this.z * this.z;
  3072. }
  3073. length() {
  3074. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  3075. }
  3076. manhattanLength() {
  3077. return Math.abs(this.x) + Math.abs(this.y) + Math.abs(this.z);
  3078. }
  3079. normalize() {
  3080. return this.divideScalar(this.length() || 1);
  3081. }
  3082. setLength(length) {
  3083. return this.normalize().multiplyScalar(length);
  3084. }
  3085. lerp(v, alpha) {
  3086. this.x += (v.x - this.x) * alpha;
  3087. this.y += (v.y - this.y) * alpha;
  3088. this.z += (v.z - this.z) * alpha;
  3089. return this;
  3090. }
  3091. lerpVectors(v1, v2, alpha) {
  3092. this.x = v1.x + (v2.x - v1.x) * alpha;
  3093. this.y = v1.y + (v2.y - v1.y) * alpha;
  3094. this.z = v1.z + (v2.z - v1.z) * alpha;
  3095. return this;
  3096. }
  3097. cross(v) {
  3098. return this.crossVectors(this, v);
  3099. }
  3100. crossVectors(a, b) {
  3101. const ax = a.x,
  3102. ay = a.y,
  3103. az = a.z;
  3104. const bx = b.x,
  3105. by = b.y,
  3106. bz = b.z;
  3107. this.x = ay * bz - az * by;
  3108. this.y = az * bx - ax * bz;
  3109. this.z = ax * by - ay * bx;
  3110. return this;
  3111. }
  3112. projectOnVector(v) {
  3113. const denominator = v.lengthSq();
  3114. if (denominator === 0) return this.set(0, 0, 0);
  3115. const scalar = v.dot(this) / denominator;
  3116. return this.copy(v).multiplyScalar(scalar);
  3117. }
  3118. projectOnPlane(planeNormal) {
  3119. _vector$c.copy(this).projectOnVector(planeNormal);
  3120. return this.sub(_vector$c);
  3121. }
  3122. reflect(normal) {
  3123. // reflect incident vector off plane orthogonal to normal
  3124. // normal is assumed to have unit length
  3125. return this.sub(_vector$c.copy(normal).multiplyScalar(2 * this.dot(normal)));
  3126. }
  3127. angleTo(v) {
  3128. const denominator = Math.sqrt(this.lengthSq() * v.lengthSq());
  3129. if (denominator === 0) return Math.PI / 2;
  3130. const theta = this.dot(v) / denominator; // clamp, to handle numerical problems
  3131. return Math.acos(clamp(theta, -1, 1));
  3132. }
  3133. distanceTo(v) {
  3134. return Math.sqrt(this.distanceToSquared(v));
  3135. }
  3136. distanceToSquared(v) {
  3137. const dx = this.x - v.x,
  3138. dy = this.y - v.y,
  3139. dz = this.z - v.z;
  3140. return dx * dx + dy * dy + dz * dz;
  3141. }
  3142. manhattanDistanceTo(v) {
  3143. return Math.abs(this.x - v.x) + Math.abs(this.y - v.y) + Math.abs(this.z - v.z);
  3144. }
  3145. setFromSpherical(s) {
  3146. return this.setFromSphericalCoords(s.radius, s.phi, s.theta);
  3147. }
  3148. setFromSphericalCoords(radius, phi, theta) {
  3149. const sinPhiRadius = Math.sin(phi) * radius;
  3150. this.x = sinPhiRadius * Math.sin(theta);
  3151. this.y = Math.cos(phi) * radius;
  3152. this.z = sinPhiRadius * Math.cos(theta);
  3153. return this;
  3154. }
  3155. setFromCylindrical(c) {
  3156. return this.setFromCylindricalCoords(c.radius, c.theta, c.y);
  3157. }
  3158. setFromCylindricalCoords(radius, theta, y) {
  3159. this.x = radius * Math.sin(theta);
  3160. this.y = y;
  3161. this.z = radius * Math.cos(theta);
  3162. return this;
  3163. }
  3164. setFromMatrixPosition(m) {
  3165. const e = m.elements;
  3166. this.x = e[12];
  3167. this.y = e[13];
  3168. this.z = e[14];
  3169. return this;
  3170. }
  3171. setFromMatrixScale(m) {
  3172. const sx = this.setFromMatrixColumn(m, 0).length();
  3173. const sy = this.setFromMatrixColumn(m, 1).length();
  3174. const sz = this.setFromMatrixColumn(m, 2).length();
  3175. this.x = sx;
  3176. this.y = sy;
  3177. this.z = sz;
  3178. return this;
  3179. }
  3180. setFromMatrixColumn(m, index) {
  3181. return this.fromArray(m.elements, index * 4);
  3182. }
  3183. setFromMatrix3Column(m, index) {
  3184. return this.fromArray(m.elements, index * 3);
  3185. }
  3186. setFromEuler(e) {
  3187. this.x = e._x;
  3188. this.y = e._y;
  3189. this.z = e._z;
  3190. return this;
  3191. }
  3192. equals(v) {
  3193. return v.x === this.x && v.y === this.y && v.z === this.z;
  3194. }
  3195. fromArray(array, offset = 0) {
  3196. this.x = array[offset];
  3197. this.y = array[offset + 1];
  3198. this.z = array[offset + 2];
  3199. return this;
  3200. }
  3201. toArray(array = [], offset = 0) {
  3202. array[offset] = this.x;
  3203. array[offset + 1] = this.y;
  3204. array[offset + 2] = this.z;
  3205. return array;
  3206. }
  3207. fromBufferAttribute(attribute, index) {
  3208. this.x = attribute.getX(index);
  3209. this.y = attribute.getY(index);
  3210. this.z = attribute.getZ(index);
  3211. return this;
  3212. }
  3213. random() {
  3214. this.x = Math.random();
  3215. this.y = Math.random();
  3216. this.z = Math.random();
  3217. return this;
  3218. }
  3219. randomDirection() {
  3220. // Derived from https://mathworld.wolfram.com/SpherePointPicking.html
  3221. const u = (Math.random() - 0.5) * 2;
  3222. const t = Math.random() * Math.PI * 2;
  3223. const f = Math.sqrt(1 - u ** 2);
  3224. this.x = f * Math.cos(t);
  3225. this.y = f * Math.sin(t);
  3226. this.z = u;
  3227. return this;
  3228. }
  3229. *[Symbol.iterator]() {
  3230. yield this.x;
  3231. yield this.y;
  3232. yield this.z;
  3233. }
  3234. }
  3235. const _vector$c = /*@__PURE__*/new Vector3();
  3236. const _quaternion$4 = /*@__PURE__*/new Quaternion();
  3237. class Box3 {
  3238. constructor(min = new Vector3(+Infinity, +Infinity, +Infinity), max = new Vector3(-Infinity, -Infinity, -Infinity)) {
  3239. this.isBox3 = true;
  3240. this.min = min;
  3241. this.max = max;
  3242. }
  3243. set(min, max) {
  3244. this.min.copy(min);
  3245. this.max.copy(max);
  3246. return this;
  3247. }
  3248. setFromArray(array) {
  3249. let minX = +Infinity;
  3250. let minY = +Infinity;
  3251. let minZ = +Infinity;
  3252. let maxX = -Infinity;
  3253. let maxY = -Infinity;
  3254. let maxZ = -Infinity;
  3255. for (let i = 0, l = array.length; i < l; i += 3) {
  3256. const x = array[i];
  3257. const y = array[i + 1];
  3258. const z = array[i + 2];
  3259. if (x < minX) minX = x;
  3260. if (y < minY) minY = y;
  3261. if (z < minZ) minZ = z;
  3262. if (x > maxX) maxX = x;
  3263. if (y > maxY) maxY = y;
  3264. if (z > maxZ) maxZ = z;
  3265. }
  3266. this.min.set(minX, minY, minZ);
  3267. this.max.set(maxX, maxY, maxZ);
  3268. return this;
  3269. }
  3270. setFromBufferAttribute(attribute) {
  3271. let minX = +Infinity;
  3272. let minY = +Infinity;
  3273. let minZ = +Infinity;
  3274. let maxX = -Infinity;
  3275. let maxY = -Infinity;
  3276. let maxZ = -Infinity;
  3277. for (let i = 0, l = attribute.count; i < l; i++) {
  3278. const x = attribute.getX(i);
  3279. const y = attribute.getY(i);
  3280. const z = attribute.getZ(i);
  3281. if (x < minX) minX = x;
  3282. if (y < minY) minY = y;
  3283. if (z < minZ) minZ = z;
  3284. if (x > maxX) maxX = x;
  3285. if (y > maxY) maxY = y;
  3286. if (z > maxZ) maxZ = z;
  3287. }
  3288. this.min.set(minX, minY, minZ);
  3289. this.max.set(maxX, maxY, maxZ);
  3290. return this;
  3291. }
  3292. setFromPoints(points) {
  3293. this.makeEmpty();
  3294. for (let i = 0, il = points.length; i < il; i++) {
  3295. this.expandByPoint(points[i]);
  3296. }
  3297. return this;
  3298. }
  3299. setFromCenterAndSize(center, size) {
  3300. const halfSize = _vector$b.copy(size).multiplyScalar(0.5);
  3301. this.min.copy(center).sub(halfSize);
  3302. this.max.copy(center).add(halfSize);
  3303. return this;
  3304. }
  3305. setFromObject(object, precise = false) {
  3306. this.makeEmpty();
  3307. return this.expandByObject(object, precise);
  3308. }
  3309. clone() {
  3310. return new this.constructor().copy(this);
  3311. }
  3312. copy(box) {
  3313. this.min.copy(box.min);
  3314. this.max.copy(box.max);
  3315. return this;
  3316. }
  3317. makeEmpty() {
  3318. this.min.x = this.min.y = this.min.z = +Infinity;
  3319. this.max.x = this.max.y = this.max.z = -Infinity;
  3320. return this;
  3321. }
  3322. isEmpty() {
  3323. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  3324. return this.max.x < this.min.x || this.max.y < this.min.y || this.max.z < this.min.z;
  3325. }
  3326. getCenter(target) {
  3327. return this.isEmpty() ? target.set(0, 0, 0) : target.addVectors(this.min, this.max).multiplyScalar(0.5);
  3328. }
  3329. getSize(target) {
  3330. return this.isEmpty() ? target.set(0, 0, 0) : target.subVectors(this.max, this.min);
  3331. }
  3332. expandByPoint(point) {
  3333. this.min.min(point);
  3334. this.max.max(point);
  3335. return this;
  3336. }
  3337. expandByVector(vector) {
  3338. this.min.sub(vector);
  3339. this.max.add(vector);
  3340. return this;
  3341. }
  3342. expandByScalar(scalar) {
  3343. this.min.addScalar(-scalar);
  3344. this.max.addScalar(scalar);
  3345. return this;
  3346. }
  3347. expandByObject(object, precise = false) {
  3348. // Computes the world-axis-aligned bounding box of an object (including its children),
  3349. // accounting for both the object's, and children's, world transforms
  3350. object.updateWorldMatrix(false, false);
  3351. const geometry = object.geometry;
  3352. if (geometry !== undefined) {
  3353. if (precise && geometry.attributes != undefined && geometry.attributes.position !== undefined) {
  3354. const position = geometry.attributes.position;
  3355. for (let i = 0, l = position.count; i < l; i++) {
  3356. _vector$b.fromBufferAttribute(position, i).applyMatrix4(object.matrixWorld);
  3357. this.expandByPoint(_vector$b);
  3358. }
  3359. } else {
  3360. if (geometry.boundingBox === null) {
  3361. geometry.computeBoundingBox();
  3362. }
  3363. _box$3.copy(geometry.boundingBox);
  3364. _box$3.applyMatrix4(object.matrixWorld);
  3365. this.union(_box$3);
  3366. }
  3367. }
  3368. const children = object.children;
  3369. for (let i = 0, l = children.length; i < l; i++) {
  3370. this.expandByObject(children[i], precise);
  3371. }
  3372. return this;
  3373. }
  3374. containsPoint(point) {
  3375. 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;
  3376. }
  3377. containsBox(box) {
  3378. 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;
  3379. }
  3380. getParameter(point, target) {
  3381. // This can potentially have a divide by zero if the box
  3382. // has a size dimension of 0.
  3383. 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));
  3384. }
  3385. intersectsBox(box) {
  3386. // using 6 splitting planes to rule out intersections.
  3387. 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;
  3388. }
  3389. intersectsSphere(sphere) {
  3390. // Find the point on the AABB closest to the sphere center.
  3391. this.clampPoint(sphere.center, _vector$b); // If that point is inside the sphere, the AABB and sphere intersect.
  3392. return _vector$b.distanceToSquared(sphere.center) <= sphere.radius * sphere.radius;
  3393. }
  3394. intersectsPlane(plane) {
  3395. // We compute the minimum and maximum dot product values. If those values
  3396. // are on the same side (back or front) of the plane, then there is no intersection.
  3397. let min, max;
  3398. if (plane.normal.x > 0) {
  3399. min = plane.normal.x * this.min.x;
  3400. max = plane.normal.x * this.max.x;
  3401. } else {
  3402. min = plane.normal.x * this.max.x;
  3403. max = plane.normal.x * this.min.x;
  3404. }
  3405. if (plane.normal.y > 0) {
  3406. min += plane.normal.y * this.min.y;
  3407. max += plane.normal.y * this.max.y;
  3408. } else {
  3409. min += plane.normal.y * this.max.y;
  3410. max += plane.normal.y * this.min.y;
  3411. }
  3412. if (plane.normal.z > 0) {
  3413. min += plane.normal.z * this.min.z;
  3414. max += plane.normal.z * this.max.z;
  3415. } else {
  3416. min += plane.normal.z * this.max.z;
  3417. max += plane.normal.z * this.min.z;
  3418. }
  3419. return min <= -plane.constant && max >= -plane.constant;
  3420. }
  3421. intersectsTriangle(triangle) {
  3422. if (this.isEmpty()) {
  3423. return false;
  3424. } // compute box center and extents
  3425. this.getCenter(_center);
  3426. _extents.subVectors(this.max, _center); // translate triangle to aabb origin
  3427. _v0$2.subVectors(triangle.a, _center);
  3428. _v1$7.subVectors(triangle.b, _center);
  3429. _v2$4.subVectors(triangle.c, _center); // compute edge vectors for triangle
  3430. _f0.subVectors(_v1$7, _v0$2);
  3431. _f1.subVectors(_v2$4, _v1$7);
  3432. _f2.subVectors(_v0$2, _v2$4); // test against axes that are given by cross product combinations of the edges of the triangle and the edges of the aabb
  3433. // 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
  3434. // axis_ij = u_i x f_j (u0, u1, u2 = face normals of aabb = x,y,z axes vectors since aabb is axis aligned)
  3435. let axes = [0, -_f0.z, _f0.y, 0, -_f1.z, _f1.y, 0, -_f2.z, _f2.y, _f0.z, 0, -_f0.x, _f1.z, 0, -_f1.x, _f2.z, 0, -_f2.x, -_f0.y, _f0.x, 0, -_f1.y, _f1.x, 0, -_f2.y, _f2.x, 0];
  3436. if (!satForAxes(axes, _v0$2, _v1$7, _v2$4, _extents)) {
  3437. return false;
  3438. } // test 3 face normals from the aabb
  3439. axes = [1, 0, 0, 0, 1, 0, 0, 0, 1];
  3440. if (!satForAxes(axes, _v0$2, _v1$7, _v2$4, _extents)) {
  3441. return false;
  3442. } // finally testing the face normal of the triangle
  3443. // use already existing triangle edge vectors here
  3444. _triangleNormal.crossVectors(_f0, _f1);
  3445. axes = [_triangleNormal.x, _triangleNormal.y, _triangleNormal.z];
  3446. return satForAxes(axes, _v0$2, _v1$7, _v2$4, _extents);
  3447. }
  3448. clampPoint(point, target) {
  3449. return target.copy(point).clamp(this.min, this.max);
  3450. }
  3451. distanceToPoint(point) {
  3452. const clampedPoint = _vector$b.copy(point).clamp(this.min, this.max);
  3453. return clampedPoint.sub(point).length();
  3454. }
  3455. getBoundingSphere(target) {
  3456. this.getCenter(target.center);
  3457. target.radius = this.getSize(_vector$b).length() * 0.5;
  3458. return target;
  3459. }
  3460. intersect(box) {
  3461. this.min.max(box.min);
  3462. 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.
  3463. if (this.isEmpty()) this.makeEmpty();
  3464. return this;
  3465. }
  3466. union(box) {
  3467. this.min.min(box.min);
  3468. this.max.max(box.max);
  3469. return this;
  3470. }
  3471. applyMatrix4(matrix) {
  3472. // transform of empty box is an empty box.
  3473. if (this.isEmpty()) return this; // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  3474. _points[0].set(this.min.x, this.min.y, this.min.z).applyMatrix4(matrix); // 000
  3475. _points[1].set(this.min.x, this.min.y, this.max.z).applyMatrix4(matrix); // 001
  3476. _points[2].set(this.min.x, this.max.y, this.min.z).applyMatrix4(matrix); // 010
  3477. _points[3].set(this.min.x, this.max.y, this.max.z).applyMatrix4(matrix); // 011
  3478. _points[4].set(this.max.x, this.min.y, this.min.z).applyMatrix4(matrix); // 100
  3479. _points[5].set(this.max.x, this.min.y, this.max.z).applyMatrix4(matrix); // 101
  3480. _points[6].set(this.max.x, this.max.y, this.min.z).applyMatrix4(matrix); // 110
  3481. _points[7].set(this.max.x, this.max.y, this.max.z).applyMatrix4(matrix); // 111
  3482. this.setFromPoints(_points);
  3483. return this;
  3484. }
  3485. translate(offset) {
  3486. this.min.add(offset);
  3487. this.max.add(offset);
  3488. return this;
  3489. }
  3490. equals(box) {
  3491. return box.min.equals(this.min) && box.max.equals(this.max);
  3492. }
  3493. }
  3494. const _points = [/*@__PURE__*/new Vector3(), /*@__PURE__*/new Vector3(), /*@__PURE__*/new Vector3(), /*@__PURE__*/new Vector3(), /*@__PURE__*/new Vector3(), /*@__PURE__*/new Vector3(), /*@__PURE__*/new Vector3(), /*@__PURE__*/new Vector3()];
  3495. const _vector$b = /*@__PURE__*/new Vector3();
  3496. const _box$3 = /*@__PURE__*/new Box3(); // triangle centered vertices
  3497. const _v0$2 = /*@__PURE__*/new Vector3();
  3498. const _v1$7 = /*@__PURE__*/new Vector3();
  3499. const _v2$4 = /*@__PURE__*/new Vector3(); // triangle edge vectors
  3500. const _f0 = /*@__PURE__*/new Vector3();
  3501. const _f1 = /*@__PURE__*/new Vector3();
  3502. const _f2 = /*@__PURE__*/new Vector3();
  3503. const _center = /*@__PURE__*/new Vector3();
  3504. const _extents = /*@__PURE__*/new Vector3();
  3505. const _triangleNormal = /*@__PURE__*/new Vector3();
  3506. const _testAxis = /*@__PURE__*/new Vector3();
  3507. function satForAxes(axes, v0, v1, v2, extents) {
  3508. for (let i = 0, j = axes.length - 3; i <= j; i += 3) {
  3509. _testAxis.fromArray(axes, i); // project the aabb onto the separating axis
  3510. const r = extents.x * Math.abs(_testAxis.x) + extents.y * Math.abs(_testAxis.y) + extents.z * Math.abs(_testAxis.z); // project all 3 vertices of the triangle onto the separating axis
  3511. const p0 = v0.dot(_testAxis);
  3512. const p1 = v1.dot(_testAxis);
  3513. const p2 = v2.dot(_testAxis); // actual test, basically see if either of the most extreme of the triangle points intersects r
  3514. if (Math.max(-Math.max(p0, p1, p2), Math.min(p0, p1, p2)) > r) {
  3515. // points of the projected triangle are outside the projected half-length of the aabb
  3516. // the axis is separating and we can exit
  3517. return false;
  3518. }
  3519. }
  3520. return true;
  3521. }
  3522. const _box$2 = /*@__PURE__*/new Box3();
  3523. const _v1$6 = /*@__PURE__*/new Vector3();
  3524. const _v2$3 = /*@__PURE__*/new Vector3();
  3525. class Sphere {
  3526. constructor(center = new Vector3(), radius = -1) {
  3527. this.center = center;
  3528. this.radius = radius;
  3529. }
  3530. set(center, radius) {
  3531. this.center.copy(center);
  3532. this.radius = radius;
  3533. return this;
  3534. }
  3535. setFromPoints(points, optionalCenter) {
  3536. const center = this.center;
  3537. if (optionalCenter !== undefined) {
  3538. center.copy(optionalCenter);
  3539. } else {
  3540. _box$2.setFromPoints(points).getCenter(center);
  3541. }
  3542. let maxRadiusSq = 0;
  3543. for (let i = 0, il = points.length; i < il; i++) {
  3544. maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(points[i]));
  3545. }
  3546. this.radius = Math.sqrt(maxRadiusSq);
  3547. return this;
  3548. }
  3549. copy(sphere) {
  3550. this.center.copy(sphere.center);
  3551. this.radius = sphere.radius;
  3552. return this;
  3553. }
  3554. isEmpty() {
  3555. return this.radius < 0;
  3556. }
  3557. makeEmpty() {
  3558. this.center.set(0, 0, 0);
  3559. this.radius = -1;
  3560. return this;
  3561. }
  3562. containsPoint(point) {
  3563. return point.distanceToSquared(this.center) <= this.radius * this.radius;
  3564. }
  3565. distanceToPoint(point) {
  3566. return point.distanceTo(this.center) - this.radius;
  3567. }
  3568. intersectsSphere(sphere) {
  3569. const radiusSum = this.radius + sphere.radius;
  3570. return sphere.center.distanceToSquared(this.center) <= radiusSum * radiusSum;
  3571. }
  3572. intersectsBox(box) {
  3573. return box.intersectsSphere(this);
  3574. }
  3575. intersectsPlane(plane) {
  3576. return Math.abs(plane.distanceToPoint(this.center)) <= this.radius;
  3577. }
  3578. clampPoint(point, target) {
  3579. const deltaLengthSq = this.center.distanceToSquared(point);
  3580. target.copy(point);
  3581. if (deltaLengthSq > this.radius * this.radius) {
  3582. target.sub(this.center).normalize();
  3583. target.multiplyScalar(this.radius).add(this.center);
  3584. }
  3585. return target;
  3586. }
  3587. getBoundingBox(target) {
  3588. if (this.isEmpty()) {
  3589. // Empty sphere produces empty bounding box
  3590. target.makeEmpty();
  3591. return target;
  3592. }
  3593. target.set(this.center, this.center);
  3594. target.expandByScalar(this.radius);
  3595. return target;
  3596. }
  3597. applyMatrix4(matrix) {
  3598. this.center.applyMatrix4(matrix);
  3599. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  3600. return this;
  3601. }
  3602. translate(offset) {
  3603. this.center.add(offset);
  3604. return this;
  3605. }
  3606. expandByPoint(point) {
  3607. if (this.isEmpty()) {
  3608. this.center.copy(point);
  3609. this.radius = 0;
  3610. return this;
  3611. }
  3612. _v1$6.subVectors(point, this.center);
  3613. const lengthSq = _v1$6.lengthSq();
  3614. if (lengthSq > this.radius * this.radius) {
  3615. // calculate the minimal sphere
  3616. const length = Math.sqrt(lengthSq);
  3617. const delta = (length - this.radius) * 0.5;
  3618. this.center.addScaledVector(_v1$6, delta / length);
  3619. this.radius += delta;
  3620. }
  3621. return this;
  3622. }
  3623. union(sphere) {
  3624. if (sphere.isEmpty()) {
  3625. return this;
  3626. }
  3627. if (this.isEmpty()) {
  3628. this.copy(sphere);
  3629. return this;
  3630. }
  3631. if (this.center.equals(sphere.center) === true) {
  3632. this.radius = Math.max(this.radius, sphere.radius);
  3633. } else {
  3634. _v2$3.subVectors(sphere.center, this.center).setLength(sphere.radius);
  3635. this.expandByPoint(_v1$6.copy(sphere.center).add(_v2$3));
  3636. this.expandByPoint(_v1$6.copy(sphere.center).sub(_v2$3));
  3637. }
  3638. return this;
  3639. }
  3640. equals(sphere) {
  3641. return sphere.center.equals(this.center) && sphere.radius === this.radius;
  3642. }
  3643. clone() {
  3644. return new this.constructor().copy(this);
  3645. }
  3646. }
  3647. const _vector$a = /*@__PURE__*/new Vector3();
  3648. const _segCenter = /*@__PURE__*/new Vector3();
  3649. const _segDir = /*@__PURE__*/new Vector3();
  3650. const _diff = /*@__PURE__*/new Vector3();
  3651. const _edge1 = /*@__PURE__*/new Vector3();
  3652. const _edge2 = /*@__PURE__*/new Vector3();
  3653. const _normal$1 = /*@__PURE__*/new Vector3();
  3654. class Ray {
  3655. constructor(origin = new Vector3(), direction = new Vector3(0, 0, -1)) {
  3656. this.origin = origin;
  3657. this.direction = direction;
  3658. }
  3659. set(origin, direction) {
  3660. this.origin.copy(origin);
  3661. this.direction.copy(direction);
  3662. return this;
  3663. }
  3664. copy(ray) {
  3665. this.origin.copy(ray.origin);
  3666. this.direction.copy(ray.direction);
  3667. return this;
  3668. }
  3669. at(t, target) {
  3670. return target.copy(this.direction).multiplyScalar(t).add(this.origin);
  3671. }
  3672. lookAt(v) {
  3673. this.direction.copy(v).sub(this.origin).normalize();
  3674. return this;
  3675. }
  3676. recast(t) {
  3677. this.origin.copy(this.at(t, _vector$a));
  3678. return this;
  3679. }
  3680. closestPointToPoint(point, target) {
  3681. target.subVectors(point, this.origin);
  3682. const directionDistance = target.dot(this.direction);
  3683. if (directionDistance < 0) {
  3684. return target.copy(this.origin);
  3685. }
  3686. return target.copy(this.direction).multiplyScalar(directionDistance).add(this.origin);
  3687. }
  3688. distanceToPoint(point) {
  3689. return Math.sqrt(this.distanceSqToPoint(point));
  3690. }
  3691. distanceSqToPoint(point) {
  3692. const directionDistance = _vector$a.subVectors(point, this.origin).dot(this.direction); // point behind the ray
  3693. if (directionDistance < 0) {
  3694. return this.origin.distanceToSquared(point);
  3695. }
  3696. _vector$a.copy(this.direction).multiplyScalar(directionDistance).add(this.origin);
  3697. return _vector$a.distanceToSquared(point);
  3698. }
  3699. distanceSqToSegment(v0, v1, optionalPointOnRay, optionalPointOnSegment) {
  3700. // from https://github.com/pmjoniak/GeometricTools/blob/master/GTEngine/Include/Mathematics/GteDistRaySegment.h
  3701. // It returns the min distance between the ray and the segment
  3702. // defined by v0 and v1
  3703. // It can also set two optional targets :
  3704. // - The closest point on the ray
  3705. // - The closest point on the segment
  3706. _segCenter.copy(v0).add(v1).multiplyScalar(0.5);
  3707. _segDir.copy(v1).sub(v0).normalize();
  3708. _diff.copy(this.origin).sub(_segCenter);
  3709. const segExtent = v0.distanceTo(v1) * 0.5;
  3710. const a01 = -this.direction.dot(_segDir);
  3711. const b0 = _diff.dot(this.direction);
  3712. const b1 = -_diff.dot(_segDir);
  3713. const c = _diff.lengthSq();
  3714. const det = Math.abs(1 - a01 * a01);
  3715. let s0, s1, sqrDist, extDet;
  3716. if (det > 0) {
  3717. // The ray and segment are not parallel.
  3718. s0 = a01 * b1 - b0;
  3719. s1 = a01 * b0 - b1;
  3720. extDet = segExtent * det;
  3721. if (s0 >= 0) {
  3722. if (s1 >= -extDet) {
  3723. if (s1 <= extDet) {
  3724. // region 0
  3725. // Minimum at interior points of ray and segment.
  3726. const invDet = 1 / det;
  3727. s0 *= invDet;
  3728. s1 *= invDet;
  3729. sqrDist = s0 * (s0 + a01 * s1 + 2 * b0) + s1 * (a01 * s0 + s1 + 2 * b1) + c;
  3730. } else {
  3731. // region 1
  3732. s1 = segExtent;
  3733. s0 = Math.max(0, -(a01 * s1 + b0));
  3734. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  3735. }
  3736. } else {
  3737. // region 5
  3738. s1 = -segExtent;
  3739. s0 = Math.max(0, -(a01 * s1 + b0));
  3740. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  3741. }
  3742. } else {
  3743. if (s1 <= -extDet) {
  3744. // region 4
  3745. s0 = Math.max(0, -(-a01 * segExtent + b0));
  3746. s1 = s0 > 0 ? -segExtent : Math.min(Math.max(-segExtent, -b1), segExtent);
  3747. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  3748. } else if (s1 <= extDet) {
  3749. // region 3
  3750. s0 = 0;
  3751. s1 = Math.min(Math.max(-segExtent, -b1), segExtent);
  3752. sqrDist = s1 * (s1 + 2 * b1) + c;
  3753. } else {
  3754. // region 2
  3755. s0 = Math.max(0, -(a01 * segExtent + b0));
  3756. s1 = s0 > 0 ? segExtent : Math.min(Math.max(-segExtent, -b1), segExtent);
  3757. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  3758. }
  3759. }
  3760. } else {
  3761. // Ray and segment are parallel.
  3762. s1 = a01 > 0 ? -segExtent : segExtent;
  3763. s0 = Math.max(0, -(a01 * s1 + b0));
  3764. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  3765. }
  3766. if (optionalPointOnRay) {
  3767. optionalPointOnRay.copy(this.direction).multiplyScalar(s0).add(this.origin);
  3768. }
  3769. if (optionalPointOnSegment) {
  3770. optionalPointOnSegment.copy(_segDir).multiplyScalar(s1).add(_segCenter);
  3771. }
  3772. return sqrDist;
  3773. }
  3774. intersectSphere(sphere, target) {
  3775. _vector$a.subVectors(sphere.center, this.origin);
  3776. const tca = _vector$a.dot(this.direction);
  3777. const d2 = _vector$a.dot(_vector$a) - tca * tca;
  3778. const radius2 = sphere.radius * sphere.radius;
  3779. if (d2 > radius2) return null;
  3780. const thc = Math.sqrt(radius2 - d2); // t0 = first intersect point - entrance on front of sphere
  3781. const t0 = tca - thc; // t1 = second intersect point - exit point on back of sphere
  3782. const t1 = tca + thc; // test to see if both t0 and t1 are behind the ray - if so, return null
  3783. if (t0 < 0 && t1 < 0) return null; // test to see if t0 is behind the ray:
  3784. // if it is, the ray is inside the sphere, so return the second exit point scaled by t1,
  3785. // in order to always return an intersect point that is in front of the ray.
  3786. 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
  3787. return this.at(t0, target);
  3788. }
  3789. intersectsSphere(sphere) {
  3790. return this.distanceSqToPoint(sphere.center) <= sphere.radius * sphere.radius;
  3791. }
  3792. distanceToPlane(plane) {
  3793. const denominator = plane.normal.dot(this.direction);
  3794. if (denominator === 0) {
  3795. // line is coplanar, return origin
  3796. if (plane.distanceToPoint(this.origin) === 0) {
  3797. return 0;
  3798. } // Null is preferable to undefined since undefined means.... it is undefined
  3799. return null;
  3800. }
  3801. const t = -(this.origin.dot(plane.normal) + plane.constant) / denominator; // Return if the ray never intersects the plane
  3802. return t >= 0 ? t : null;
  3803. }
  3804. intersectPlane(plane, target) {
  3805. const t = this.distanceToPlane(plane);
  3806. if (t === null) {
  3807. return null;
  3808. }
  3809. return this.at(t, target);
  3810. }
  3811. intersectsPlane(plane) {
  3812. // check if the ray lies on the plane first
  3813. const distToPoint = plane.distanceToPoint(this.origin);
  3814. if (distToPoint === 0) {
  3815. return true;
  3816. }
  3817. const denominator = plane.normal.dot(this.direction);
  3818. if (denominator * distToPoint < 0) {
  3819. return true;
  3820. } // ray origin is behind the plane (and is pointing behind it)
  3821. return false;
  3822. }
  3823. intersectBox(box, target) {
  3824. let tmin, tmax, tymin, tymax, tzmin, tzmax;
  3825. const invdirx = 1 / this.direction.x,
  3826. invdiry = 1 / this.direction.y,
  3827. invdirz = 1 / this.direction.z;
  3828. const origin = this.origin;
  3829. if (invdirx >= 0) {
  3830. tmin = (box.min.x - origin.x) * invdirx;
  3831. tmax = (box.max.x - origin.x) * invdirx;
  3832. } else {
  3833. tmin = (box.max.x - origin.x) * invdirx;
  3834. tmax = (box.min.x - origin.x) * invdirx;
  3835. }
  3836. if (invdiry >= 0) {
  3837. tymin = (box.min.y - origin.y) * invdiry;
  3838. tymax = (box.max.y - origin.y) * invdiry;
  3839. } else {
  3840. tymin = (box.max.y - origin.y) * invdiry;
  3841. tymax = (box.min.y - origin.y) * invdiry;
  3842. }
  3843. if (tmin > tymax || tymin > tmax) return null; // These lines also handle the case where tmin or tmax is NaN
  3844. // (result of 0 * Infinity). x !== x returns true if x is NaN
  3845. if (tymin > tmin || tmin !== tmin) tmin = tymin;
  3846. if (tymax < tmax || tmax !== tmax) tmax = tymax;
  3847. if (invdirz >= 0) {
  3848. tzmin = (box.min.z - origin.z) * invdirz;
  3849. tzmax = (box.max.z - origin.z) * invdirz;
  3850. } else {
  3851. tzmin = (box.max.z - origin.z) * invdirz;
  3852. tzmax = (box.min.z - origin.z) * invdirz;
  3853. }
  3854. if (tmin > tzmax || tzmin > tmax) return null;
  3855. if (tzmin > tmin || tmin !== tmin) tmin = tzmin;
  3856. if (tzmax < tmax || tmax !== tmax) tmax = tzmax; //return point closest to the ray (positive side)
  3857. if (tmax < 0) return null;
  3858. return this.at(tmin >= 0 ? tmin : tmax, target);
  3859. }
  3860. intersectsBox(box) {
  3861. return this.intersectBox(box, _vector$a) !== null;
  3862. }
  3863. intersectTriangle(a, b, c, backfaceCulling, target) {
  3864. // Compute the offset origin, edges, and normal.
  3865. // from https://github.com/pmjoniak/GeometricTools/blob/master/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h
  3866. _edge1.subVectors(b, a);
  3867. _edge2.subVectors(c, a);
  3868. _normal$1.crossVectors(_edge1, _edge2); // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  3869. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  3870. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  3871. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  3872. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  3873. let DdN = this.direction.dot(_normal$1);
  3874. let sign;
  3875. if (DdN > 0) {
  3876. if (backfaceCulling) return null;
  3877. sign = 1;
  3878. } else if (DdN < 0) {
  3879. sign = -1;
  3880. DdN = -DdN;
  3881. } else {
  3882. return null;
  3883. }
  3884. _diff.subVectors(this.origin, a);
  3885. const DdQxE2 = sign * this.direction.dot(_edge2.crossVectors(_diff, _edge2)); // b1 < 0, no intersection
  3886. if (DdQxE2 < 0) {
  3887. return null;
  3888. }
  3889. const DdE1xQ = sign * this.direction.dot(_edge1.cross(_diff)); // b2 < 0, no intersection
  3890. if (DdE1xQ < 0) {
  3891. return null;
  3892. } // b1+b2 > 1, no intersection
  3893. if (DdQxE2 + DdE1xQ > DdN) {
  3894. return null;
  3895. } // Line intersects triangle, check if ray does.
  3896. const QdN = -sign * _diff.dot(_normal$1); // t < 0, no intersection
  3897. if (QdN < 0) {
  3898. return null;
  3899. } // Ray intersects triangle.
  3900. return this.at(QdN / DdN, target);
  3901. }
  3902. applyMatrix4(matrix4) {
  3903. this.origin.applyMatrix4(matrix4);
  3904. this.direction.transformDirection(matrix4);
  3905. return this;
  3906. }
  3907. equals(ray) {
  3908. return ray.origin.equals(this.origin) && ray.direction.equals(this.direction);
  3909. }
  3910. clone() {
  3911. return new this.constructor().copy(this);
  3912. }
  3913. }
  3914. class Matrix4 {
  3915. constructor() {
  3916. Matrix4.prototype.isMatrix4 = true;
  3917. this.elements = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];
  3918. }
  3919. set(n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44) {
  3920. const te = this.elements;
  3921. te[0] = n11;
  3922. te[4] = n12;
  3923. te[8] = n13;
  3924. te[12] = n14;
  3925. te[1] = n21;
  3926. te[5] = n22;
  3927. te[9] = n23;
  3928. te[13] = n24;
  3929. te[2] = n31;
  3930. te[6] = n32;
  3931. te[10] = n33;
  3932. te[14] = n34;
  3933. te[3] = n41;
  3934. te[7] = n42;
  3935. te[11] = n43;
  3936. te[15] = n44;
  3937. return this;
  3938. }
  3939. identity() {
  3940. this.set(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1);
  3941. return this;
  3942. }
  3943. clone() {
  3944. return new Matrix4().fromArray(this.elements);
  3945. }
  3946. copy(m) {
  3947. const te = this.elements;
  3948. const me = m.elements;
  3949. te[0] = me[0];
  3950. te[1] = me[1];
  3951. te[2] = me[2];
  3952. te[3] = me[3];
  3953. te[4] = me[4];
  3954. te[5] = me[5];
  3955. te[6] = me[6];
  3956. te[7] = me[7];
  3957. te[8] = me[8];
  3958. te[9] = me[9];
  3959. te[10] = me[10];
  3960. te[11] = me[11];
  3961. te[12] = me[12];
  3962. te[13] = me[13];
  3963. te[14] = me[14];
  3964. te[15] = me[15];
  3965. return this;
  3966. }
  3967. copyPosition(m) {
  3968. const te = this.elements,
  3969. me = m.elements;
  3970. te[12] = me[12];
  3971. te[13] = me[13];
  3972. te[14] = me[14];
  3973. return this;
  3974. }
  3975. setFromMatrix3(m) {
  3976. const me = m.elements;
  3977. this.set(me[0], me[3], me[6], 0, me[1], me[4], me[7], 0, me[2], me[5], me[8], 0, 0, 0, 0, 1);
  3978. return this;
  3979. }
  3980. extractBasis(xAxis, yAxis, zAxis) {
  3981. xAxis.setFromMatrixColumn(this, 0);
  3982. yAxis.setFromMatrixColumn(this, 1);
  3983. zAxis.setFromMatrixColumn(this, 2);
  3984. return this;
  3985. }
  3986. makeBasis(xAxis, yAxis, zAxis) {
  3987. 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);
  3988. return this;
  3989. }
  3990. extractRotation(m) {
  3991. // this method does not support reflection matrices
  3992. const te = this.elements;
  3993. const me = m.elements;
  3994. const scaleX = 1 / _v1$5.setFromMatrixColumn(m, 0).length();
  3995. const scaleY = 1 / _v1$5.setFromMatrixColumn(m, 1).length();
  3996. const scaleZ = 1 / _v1$5.setFromMatrixColumn(m, 2).length();
  3997. te[0] = me[0] * scaleX;
  3998. te[1] = me[1] * scaleX;
  3999. te[2] = me[2] * scaleX;
  4000. te[3] = 0;
  4001. te[4] = me[4] * scaleY;
  4002. te[5] = me[5] * scaleY;
  4003. te[6] = me[6] * scaleY;
  4004. te[7] = 0;
  4005. te[8] = me[8] * scaleZ;
  4006. te[9] = me[9] * scaleZ;
  4007. te[10] = me[10] * scaleZ;
  4008. te[11] = 0;
  4009. te[12] = 0;
  4010. te[13] = 0;
  4011. te[14] = 0;
  4012. te[15] = 1;
  4013. return this;
  4014. }
  4015. makeRotationFromEuler(euler) {
  4016. const te = this.elements;
  4017. const x = euler.x,
  4018. y = euler.y,
  4019. z = euler.z;
  4020. const a = Math.cos(x),
  4021. b = Math.sin(x);
  4022. const c = Math.cos(y),
  4023. d = Math.sin(y);
  4024. const e = Math.cos(z),
  4025. f = Math.sin(z);
  4026. if (euler.order === 'XYZ') {
  4027. const ae = a * e,
  4028. af = a * f,
  4029. be = b * e,
  4030. bf = b * f;
  4031. te[0] = c * e;
  4032. te[4] = -c * f;
  4033. te[8] = d;
  4034. te[1] = af + be * d;
  4035. te[5] = ae - bf * d;
  4036. te[9] = -b * c;
  4037. te[2] = bf - ae * d;
  4038. te[6] = be + af * d;
  4039. te[10] = a * c;
  4040. } else if (euler.order === 'YXZ') {
  4041. const ce = c * e,
  4042. cf = c * f,
  4043. de = d * e,
  4044. df = d * f;
  4045. te[0] = ce + df * b;
  4046. te[4] = de * b - cf;
  4047. te[8] = a * d;
  4048. te[1] = a * f;
  4049. te[5] = a * e;
  4050. te[9] = -b;
  4051. te[2] = cf * b - de;
  4052. te[6] = df + ce * b;
  4053. te[10] = a * c;
  4054. } else if (euler.order === 'ZXY') {
  4055. const ce = c * e,
  4056. cf = c * f,
  4057. de = d * e,
  4058. df = d * f;
  4059. te[0] = ce - df * b;
  4060. te[4] = -a * f;
  4061. te[8] = de + cf * b;
  4062. te[1] = cf + de * b;
  4063. te[5] = a * e;
  4064. te[9] = df - ce * b;
  4065. te[2] = -a * d;
  4066. te[6] = b;
  4067. te[10] = a * c;
  4068. } else if (euler.order === 'ZYX') {
  4069. const ae = a * e,
  4070. af = a * f,
  4071. be = b * e,
  4072. bf = b * f;
  4073. te[0] = c * e;
  4074. te[4] = be * d - af;
  4075. te[8] = ae * d + bf;
  4076. te[1] = c * f;
  4077. te[5] = bf * d + ae;
  4078. te[9] = af * d - be;
  4079. te[2] = -d;
  4080. te[6] = b * c;
  4081. te[10] = a * c;
  4082. } else if (euler.order === 'YZX') {
  4083. const ac = a * c,
  4084. ad = a * d,
  4085. bc = b * c,
  4086. bd = b * d;
  4087. te[0] = c * e;
  4088. te[4] = bd - ac * f;
  4089. te[8] = bc * f + ad;
  4090. te[1] = f;
  4091. te[5] = a * e;
  4092. te[9] = -b * e;
  4093. te[2] = -d * e;
  4094. te[6] = ad * f + bc;
  4095. te[10] = ac - bd * f;
  4096. } else if (euler.order === 'XZY') {
  4097. const ac = a * c,
  4098. ad = a * d,
  4099. bc = b * c,
  4100. bd = b * d;
  4101. te[0] = c * e;
  4102. te[4] = -f;
  4103. te[8] = d * e;
  4104. te[1] = ac * f + bd;
  4105. te[5] = a * e;
  4106. te[9] = ad * f - bc;
  4107. te[2] = bc * f - ad;
  4108. te[6] = b * e;
  4109. te[10] = bd * f + ac;
  4110. } // bottom row
  4111. te[3] = 0;
  4112. te[7] = 0;
  4113. te[11] = 0; // last column
  4114. te[12] = 0;
  4115. te[13] = 0;
  4116. te[14] = 0;
  4117. te[15] = 1;
  4118. return this;
  4119. }
  4120. makeRotationFromQuaternion(q) {
  4121. return this.compose(_zero, q, _one);
  4122. }
  4123. lookAt(eye, target, up) {
  4124. const te = this.elements;
  4125. _z.subVectors(eye, target);
  4126. if (_z.lengthSq() === 0) {
  4127. // eye and target are in the same position
  4128. _z.z = 1;
  4129. }
  4130. _z.normalize();
  4131. _x.crossVectors(up, _z);
  4132. if (_x.lengthSq() === 0) {
  4133. // up and z are parallel
  4134. if (Math.abs(up.z) === 1) {
  4135. _z.x += 0.0001;
  4136. } else {
  4137. _z.z += 0.0001;
  4138. }
  4139. _z.normalize();
  4140. _x.crossVectors(up, _z);
  4141. }
  4142. _x.normalize();
  4143. _y.crossVectors(_z, _x);
  4144. te[0] = _x.x;
  4145. te[4] = _y.x;
  4146. te[8] = _z.x;
  4147. te[1] = _x.y;
  4148. te[5] = _y.y;
  4149. te[9] = _z.y;
  4150. te[2] = _x.z;
  4151. te[6] = _y.z;
  4152. te[10] = _z.z;
  4153. return this;
  4154. }
  4155. multiply(m) {
  4156. return this.multiplyMatrices(this, m);
  4157. }
  4158. premultiply(m) {
  4159. return this.multiplyMatrices(m, this);
  4160. }
  4161. multiplyMatrices(a, b) {
  4162. const ae = a.elements;
  4163. const be = b.elements;
  4164. const te = this.elements;
  4165. const a11 = ae[0],
  4166. a12 = ae[4],
  4167. a13 = ae[8],
  4168. a14 = ae[12];
  4169. const a21 = ae[1],
  4170. a22 = ae[5],
  4171. a23 = ae[9],
  4172. a24 = ae[13];
  4173. const a31 = ae[2],
  4174. a32 = ae[6],
  4175. a33 = ae[10],
  4176. a34 = ae[14];
  4177. const a41 = ae[3],
  4178. a42 = ae[7],
  4179. a43 = ae[11],
  4180. a44 = ae[15];
  4181. const b11 = be[0],
  4182. b12 = be[4],
  4183. b13 = be[8],
  4184. b14 = be[12];
  4185. const b21 = be[1],
  4186. b22 = be[5],
  4187. b23 = be[9],
  4188. b24 = be[13];
  4189. const b31 = be[2],
  4190. b32 = be[6],
  4191. b33 = be[10],
  4192. b34 = be[14];
  4193. const b41 = be[3],
  4194. b42 = be[7],
  4195. b43 = be[11],
  4196. b44 = be[15];
  4197. te[0] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  4198. te[4] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  4199. te[8] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  4200. te[12] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  4201. te[1] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  4202. te[5] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  4203. te[9] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  4204. te[13] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  4205. te[2] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  4206. te[6] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  4207. te[10] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  4208. te[14] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  4209. te[3] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  4210. te[7] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  4211. te[11] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  4212. te[15] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  4213. return this;
  4214. }
  4215. multiplyScalar(s) {
  4216. const te = this.elements;
  4217. te[0] *= s;
  4218. te[4] *= s;
  4219. te[8] *= s;
  4220. te[12] *= s;
  4221. te[1] *= s;
  4222. te[5] *= s;
  4223. te[9] *= s;
  4224. te[13] *= s;
  4225. te[2] *= s;
  4226. te[6] *= s;
  4227. te[10] *= s;
  4228. te[14] *= s;
  4229. te[3] *= s;
  4230. te[7] *= s;
  4231. te[11] *= s;
  4232. te[15] *= s;
  4233. return this;
  4234. }
  4235. determinant() {
  4236. const te = this.elements;
  4237. const n11 = te[0],
  4238. n12 = te[4],
  4239. n13 = te[8],
  4240. n14 = te[12];
  4241. const n21 = te[1],
  4242. n22 = te[5],
  4243. n23 = te[9],
  4244. n24 = te[13];
  4245. const n31 = te[2],
  4246. n32 = te[6],
  4247. n33 = te[10],
  4248. n34 = te[14];
  4249. const n41 = te[3],
  4250. n42 = te[7],
  4251. n43 = te[11],
  4252. n44 = te[15]; //TODO: make this more efficient
  4253. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  4254. 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);
  4255. }
  4256. transpose() {
  4257. const te = this.elements;
  4258. let tmp;
  4259. tmp = te[1];
  4260. te[1] = te[4];
  4261. te[4] = tmp;
  4262. tmp = te[2];
  4263. te[2] = te[8];
  4264. te[8] = tmp;
  4265. tmp = te[6];
  4266. te[6] = te[9];
  4267. te[9] = tmp;
  4268. tmp = te[3];
  4269. te[3] = te[12];
  4270. te[12] = tmp;
  4271. tmp = te[7];
  4272. te[7] = te[13];
  4273. te[13] = tmp;
  4274. tmp = te[11];
  4275. te[11] = te[14];
  4276. te[14] = tmp;
  4277. return this;
  4278. }
  4279. setPosition(x, y, z) {
  4280. const te = this.elements;
  4281. if (x.isVector3) {
  4282. te[12] = x.x;
  4283. te[13] = x.y;
  4284. te[14] = x.z;
  4285. } else {
  4286. te[12] = x;
  4287. te[13] = y;
  4288. te[14] = z;
  4289. }
  4290. return this;
  4291. }
  4292. invert() {
  4293. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  4294. const te = this.elements,
  4295. n11 = te[0],
  4296. n21 = te[1],
  4297. n31 = te[2],
  4298. n41 = te[3],
  4299. n12 = te[4],
  4300. n22 = te[5],
  4301. n32 = te[6],
  4302. n42 = te[7],
  4303. n13 = te[8],
  4304. n23 = te[9],
  4305. n33 = te[10],
  4306. n43 = te[11],
  4307. n14 = te[12],
  4308. n24 = te[13],
  4309. n34 = te[14],
  4310. n44 = te[15],
  4311. t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44,
  4312. t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44,
  4313. t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44,
  4314. t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34;
  4315. const det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14;
  4316. if (det === 0) return this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  4317. const detInv = 1 / det;
  4318. te[0] = t11 * detInv;
  4319. te[1] = (n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44) * detInv;
  4320. te[2] = (n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44) * detInv;
  4321. te[3] = (n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43) * detInv;
  4322. te[4] = t12 * detInv;
  4323. te[5] = (n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44) * detInv;
  4324. te[6] = (n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44) * detInv;
  4325. te[7] = (n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43) * detInv;
  4326. te[8] = t13 * detInv;
  4327. te[9] = (n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44) * detInv;
  4328. te[10] = (n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44) * detInv;
  4329. te[11] = (n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43) * detInv;
  4330. te[12] = t14 * detInv;
  4331. te[13] = (n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34) * detInv;
  4332. te[14] = (n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34) * detInv;
  4333. te[15] = (n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33) * detInv;
  4334. return this;
  4335. }
  4336. scale(v) {
  4337. const te = this.elements;
  4338. const x = v.x,
  4339. y = v.y,
  4340. z = v.z;
  4341. te[0] *= x;
  4342. te[4] *= y;
  4343. te[8] *= z;
  4344. te[1] *= x;
  4345. te[5] *= y;
  4346. te[9] *= z;
  4347. te[2] *= x;
  4348. te[6] *= y;
  4349. te[10] *= z;
  4350. te[3] *= x;
  4351. te[7] *= y;
  4352. te[11] *= z;
  4353. return this;
  4354. }
  4355. getMaxScaleOnAxis() {
  4356. const te = this.elements;
  4357. const scaleXSq = te[0] * te[0] + te[1] * te[1] + te[2] * te[2];
  4358. const scaleYSq = te[4] * te[4] + te[5] * te[5] + te[6] * te[6];
  4359. const scaleZSq = te[8] * te[8] + te[9] * te[9] + te[10] * te[10];
  4360. return Math.sqrt(Math.max(scaleXSq, scaleYSq, scaleZSq));
  4361. }
  4362. makeTranslation(x, y, z) {
  4363. this.set(1, 0, 0, x, 0, 1, 0, y, 0, 0, 1, z, 0, 0, 0, 1);
  4364. return this;
  4365. }
  4366. makeRotationX(theta) {
  4367. const c = Math.cos(theta),
  4368. s = Math.sin(theta);
  4369. this.set(1, 0, 0, 0, 0, c, -s, 0, 0, s, c, 0, 0, 0, 0, 1);
  4370. return this;
  4371. }
  4372. makeRotationY(theta) {
  4373. const c = Math.cos(theta),
  4374. s = Math.sin(theta);
  4375. this.set(c, 0, s, 0, 0, 1, 0, 0, -s, 0, c, 0, 0, 0, 0, 1);
  4376. return this;
  4377. }
  4378. makeRotationZ(theta) {
  4379. const c = Math.cos(theta),
  4380. s = Math.sin(theta);
  4381. this.set(c, -s, 0, 0, s, c, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1);
  4382. return this;
  4383. }
  4384. makeRotationAxis(axis, angle) {
  4385. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  4386. const c = Math.cos(angle);
  4387. const s = Math.sin(angle);
  4388. const t = 1 - c;
  4389. const x = axis.x,
  4390. y = axis.y,
  4391. z = axis.z;
  4392. const tx = t * x,
  4393. ty = t * y;
  4394. 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);
  4395. return this;
  4396. }
  4397. makeScale(x, y, z) {
  4398. this.set(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1);
  4399. return this;
  4400. }
  4401. makeShear(xy, xz, yx, yz, zx, zy) {
  4402. this.set(1, yx, zx, 0, xy, 1, zy, 0, xz, yz, 1, 0, 0, 0, 0, 1);
  4403. return this;
  4404. }
  4405. compose(position, quaternion, scale) {
  4406. const te = this.elements;
  4407. const x = quaternion._x,
  4408. y = quaternion._y,
  4409. z = quaternion._z,
  4410. w = quaternion._w;
  4411. const x2 = x + x,
  4412. y2 = y + y,
  4413. z2 = z + z;
  4414. const xx = x * x2,
  4415. xy = x * y2,
  4416. xz = x * z2;
  4417. const yy = y * y2,
  4418. yz = y * z2,
  4419. zz = z * z2;
  4420. const wx = w * x2,
  4421. wy = w * y2,
  4422. wz = w * z2;
  4423. const sx = scale.x,
  4424. sy = scale.y,
  4425. sz = scale.z;
  4426. te[0] = (1 - (yy + zz)) * sx;
  4427. te[1] = (xy + wz) * sx;
  4428. te[2] = (xz - wy) * sx;
  4429. te[3] = 0;
  4430. te[4] = (xy - wz) * sy;
  4431. te[5] = (1 - (xx + zz)) * sy;
  4432. te[6] = (yz + wx) * sy;
  4433. te[7] = 0;
  4434. te[8] = (xz + wy) * sz;
  4435. te[9] = (yz - wx) * sz;
  4436. te[10] = (1 - (xx + yy)) * sz;
  4437. te[11] = 0;
  4438. te[12] = position.x;
  4439. te[13] = position.y;
  4440. te[14] = position.z;
  4441. te[15] = 1;
  4442. return this;
  4443. }
  4444. decompose(position, quaternion, scale) {
  4445. const te = this.elements;
  4446. let sx = _v1$5.set(te[0], te[1], te[2]).length();
  4447. const sy = _v1$5.set(te[4], te[5], te[6]).length();
  4448. const sz = _v1$5.set(te[8], te[9], te[10]).length(); // if determine is negative, we need to invert one scale
  4449. const det = this.determinant();
  4450. if (det < 0) sx = -sx;
  4451. position.x = te[12];
  4452. position.y = te[13];
  4453. position.z = te[14]; // scale the rotation part
  4454. _m1$2.copy(this);
  4455. const invSX = 1 / sx;
  4456. const invSY = 1 / sy;
  4457. const invSZ = 1 / sz;
  4458. _m1$2.elements[0] *= invSX;
  4459. _m1$2.elements[1] *= invSX;
  4460. _m1$2.elements[2] *= invSX;
  4461. _m1$2.elements[4] *= invSY;
  4462. _m1$2.elements[5] *= invSY;
  4463. _m1$2.elements[6] *= invSY;
  4464. _m1$2.elements[8] *= invSZ;
  4465. _m1$2.elements[9] *= invSZ;
  4466. _m1$2.elements[10] *= invSZ;
  4467. quaternion.setFromRotationMatrix(_m1$2);
  4468. scale.x = sx;
  4469. scale.y = sy;
  4470. scale.z = sz;
  4471. return this;
  4472. }
  4473. makePerspective(left, right, top, bottom, near, far) {
  4474. const te = this.elements;
  4475. const x = 2 * near / (right - left);
  4476. const y = 2 * near / (top - bottom);
  4477. const a = (right + left) / (right - left);
  4478. const b = (top + bottom) / (top - bottom);
  4479. const c = -(far + near) / (far - near);
  4480. const d = -2 * far * near / (far - near);
  4481. te[0] = x;
  4482. te[4] = 0;
  4483. te[8] = a;
  4484. te[12] = 0;
  4485. te[1] = 0;
  4486. te[5] = y;
  4487. te[9] = b;
  4488. te[13] = 0;
  4489. te[2] = 0;
  4490. te[6] = 0;
  4491. te[10] = c;
  4492. te[14] = d;
  4493. te[3] = 0;
  4494. te[7] = 0;
  4495. te[11] = -1;
  4496. te[15] = 0;
  4497. return this;
  4498. }
  4499. makeOrthographic(left, right, top, bottom, near, far) {
  4500. const te = this.elements;
  4501. const w = 1.0 / (right - left);
  4502. const h = 1.0 / (top - bottom);
  4503. const p = 1.0 / (far - near);
  4504. const x = (right + left) * w;
  4505. const y = (top + bottom) * h;
  4506. const z = (far + near) * p;
  4507. te[0] = 2 * w;
  4508. te[4] = 0;
  4509. te[8] = 0;
  4510. te[12] = -x;
  4511. te[1] = 0;
  4512. te[5] = 2 * h;
  4513. te[9] = 0;
  4514. te[13] = -y;
  4515. te[2] = 0;
  4516. te[6] = 0;
  4517. te[10] = -2 * p;
  4518. te[14] = -z;
  4519. te[3] = 0;
  4520. te[7] = 0;
  4521. te[11] = 0;
  4522. te[15] = 1;
  4523. return this;
  4524. }
  4525. equals(matrix) {
  4526. const te = this.elements;
  4527. const me = matrix.elements;
  4528. for (let i = 0; i < 16; i++) {
  4529. if (te[i] !== me[i]) return false;
  4530. }
  4531. return true;
  4532. }
  4533. fromArray(array, offset = 0) {
  4534. for (let i = 0; i < 16; i++) {
  4535. this.elements[i] = array[i + offset];
  4536. }
  4537. return this;
  4538. }
  4539. toArray(array = [], offset = 0) {
  4540. const te = this.elements;
  4541. array[offset] = te[0];
  4542. array[offset + 1] = te[1];
  4543. array[offset + 2] = te[2];
  4544. array[offset + 3] = te[3];
  4545. array[offset + 4] = te[4];
  4546. array[offset + 5] = te[5];
  4547. array[offset + 6] = te[6];
  4548. array[offset + 7] = te[7];
  4549. array[offset + 8] = te[8];
  4550. array[offset + 9] = te[9];
  4551. array[offset + 10] = te[10];
  4552. array[offset + 11] = te[11];
  4553. array[offset + 12] = te[12];
  4554. array[offset + 13] = te[13];
  4555. array[offset + 14] = te[14];
  4556. array[offset + 15] = te[15];
  4557. return array;
  4558. }
  4559. }
  4560. const _v1$5 = /*@__PURE__*/new Vector3();
  4561. const _m1$2 = /*@__PURE__*/new Matrix4();
  4562. const _zero = /*@__PURE__*/new Vector3(0, 0, 0);
  4563. const _one = /*@__PURE__*/new Vector3(1, 1, 1);
  4564. const _x = /*@__PURE__*/new Vector3();
  4565. const _y = /*@__PURE__*/new Vector3();
  4566. const _z = /*@__PURE__*/new Vector3();
  4567. const _matrix$1 = /*@__PURE__*/new Matrix4();
  4568. const _quaternion$3 = /*@__PURE__*/new Quaternion();
  4569. class Euler {
  4570. constructor(x = 0, y = 0, z = 0, order = Euler.DefaultOrder) {
  4571. this.isEuler = true;
  4572. this._x = x;
  4573. this._y = y;
  4574. this._z = z;
  4575. this._order = order;
  4576. }
  4577. get x() {
  4578. return this._x;
  4579. }
  4580. set x(value) {
  4581. this._x = value;
  4582. this._onChangeCallback();
  4583. }
  4584. get y() {
  4585. return this._y;
  4586. }
  4587. set y(value) {
  4588. this._y = value;
  4589. this._onChangeCallback();
  4590. }
  4591. get z() {
  4592. return this._z;
  4593. }
  4594. set z(value) {
  4595. this._z = value;
  4596. this._onChangeCallback();
  4597. }
  4598. get order() {
  4599. return this._order;
  4600. }
  4601. set order(value) {
  4602. this._order = value;
  4603. this._onChangeCallback();
  4604. }
  4605. set(x, y, z, order = this._order) {
  4606. this._x = x;
  4607. this._y = y;
  4608. this._z = z;
  4609. this._order = order;
  4610. this._onChangeCallback();
  4611. return this;
  4612. }
  4613. clone() {
  4614. return new this.constructor(this._x, this._y, this._z, this._order);
  4615. }
  4616. copy(euler) {
  4617. this._x = euler._x;
  4618. this._y = euler._y;
  4619. this._z = euler._z;
  4620. this._order = euler._order;
  4621. this._onChangeCallback();
  4622. return this;
  4623. }
  4624. setFromRotationMatrix(m, order = this._order, update = true) {
  4625. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  4626. const te = m.elements;
  4627. const m11 = te[0],
  4628. m12 = te[4],
  4629. m13 = te[8];
  4630. const m21 = te[1],
  4631. m22 = te[5],
  4632. m23 = te[9];
  4633. const m31 = te[2],
  4634. m32 = te[6],
  4635. m33 = te[10];
  4636. switch (order) {
  4637. case 'XYZ':
  4638. this._y = Math.asin(clamp(m13, -1, 1));
  4639. if (Math.abs(m13) < 0.9999999) {
  4640. this._x = Math.atan2(-m23, m33);
  4641. this._z = Math.atan2(-m12, m11);
  4642. } else {
  4643. this._x = Math.atan2(m32, m22);
  4644. this._z = 0;
  4645. }
  4646. break;
  4647. case 'YXZ':
  4648. this._x = Math.asin(-clamp(m23, -1, 1));
  4649. if (Math.abs(m23) < 0.9999999) {
  4650. this._y = Math.atan2(m13, m33);
  4651. this._z = Math.atan2(m21, m22);
  4652. } else {
  4653. this._y = Math.atan2(-m31, m11);
  4654. this._z = 0;
  4655. }
  4656. break;
  4657. case 'ZXY':
  4658. this._x = Math.asin(clamp(m32, -1, 1));
  4659. if (Math.abs(m32) < 0.9999999) {
  4660. this._y = Math.atan2(-m31, m33);
  4661. this._z = Math.atan2(-m12, m22);
  4662. } else {
  4663. this._y = 0;
  4664. this._z = Math.atan2(m21, m11);
  4665. }
  4666. break;
  4667. case 'ZYX':
  4668. this._y = Math.asin(-clamp(m31, -1, 1));
  4669. if (Math.abs(m31) < 0.9999999) {
  4670. this._x = Math.atan2(m32, m33);
  4671. this._z = Math.atan2(m21, m11);
  4672. } else {
  4673. this._x = 0;
  4674. this._z = Math.atan2(-m12, m22);
  4675. }
  4676. break;
  4677. case 'YZX':
  4678. this._z = Math.asin(clamp(m21, -1, 1));
  4679. if (Math.abs(m21) < 0.9999999) {
  4680. this._x = Math.atan2(-m23, m22);
  4681. this._y = Math.atan2(-m31, m11);
  4682. } else {
  4683. this._x = 0;
  4684. this._y = Math.atan2(m13, m33);
  4685. }
  4686. break;
  4687. case 'XZY':
  4688. this._z = Math.asin(-clamp(m12, -1, 1));
  4689. if (Math.abs(m12) < 0.9999999) {
  4690. this._x = Math.atan2(m32, m22);
  4691. this._y = Math.atan2(m13, m11);
  4692. } else {
  4693. this._x = Math.atan2(-m23, m33);
  4694. this._y = 0;
  4695. }
  4696. break;
  4697. default:
  4698. console.warn('THREE.Euler: .setFromRotationMatrix() encountered an unknown order: ' + order);
  4699. }
  4700. this._order = order;
  4701. if (update === true) this._onChangeCallback();
  4702. return this;
  4703. }
  4704. setFromQuaternion(q, order, update) {
  4705. _matrix$1.makeRotationFromQuaternion(q);
  4706. return this.setFromRotationMatrix(_matrix$1, order, update);
  4707. }
  4708. setFromVector3(v, order = this._order) {
  4709. return this.set(v.x, v.y, v.z, order);
  4710. }
  4711. reorder(newOrder) {
  4712. // WARNING: this discards revolution information -bhouston
  4713. _quaternion$3.setFromEuler(this);
  4714. return this.setFromQuaternion(_quaternion$3, newOrder);
  4715. }
  4716. equals(euler) {
  4717. return euler._x === this._x && euler._y === this._y && euler._z === this._z && euler._order === this._order;
  4718. }
  4719. fromArray(array) {
  4720. this._x = array[0];
  4721. this._y = array[1];
  4722. this._z = array[2];
  4723. if (array[3] !== undefined) this._order = array[3];
  4724. this._onChangeCallback();
  4725. return this;
  4726. }
  4727. toArray(array = [], offset = 0) {
  4728. array[offset] = this._x;
  4729. array[offset + 1] = this._y;
  4730. array[offset + 2] = this._z;
  4731. array[offset + 3] = this._order;
  4732. return array;
  4733. }
  4734. _onChange(callback) {
  4735. this._onChangeCallback = callback;
  4736. return this;
  4737. }
  4738. _onChangeCallback() {}
  4739. *[Symbol.iterator]() {
  4740. yield this._x;
  4741. yield this._y;
  4742. yield this._z;
  4743. yield this._order;
  4744. } // @deprecated since r138, 02cf0df1cb4575d5842fef9c85bb5a89fe020d53
  4745. toVector3() {
  4746. console.error('THREE.Euler: .toVector3() has been removed. Use Vector3.setFromEuler() instead');
  4747. }
  4748. }
  4749. Euler.DefaultOrder = 'XYZ';
  4750. Euler.RotationOrders = ['XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX'];
  4751. class Layers {
  4752. constructor() {
  4753. this.mask = 1 | 0;
  4754. }
  4755. set(channel) {
  4756. this.mask = (1 << channel | 0) >>> 0;
  4757. }
  4758. enable(channel) {
  4759. this.mask |= 1 << channel | 0;
  4760. }
  4761. enableAll() {
  4762. this.mask = 0xffffffff | 0;
  4763. }
  4764. toggle(channel) {
  4765. this.mask ^= 1 << channel | 0;
  4766. }
  4767. disable(channel) {
  4768. this.mask &= ~(1 << channel | 0);
  4769. }
  4770. disableAll() {
  4771. this.mask = 0;
  4772. }
  4773. test(layers) {
  4774. return (this.mask & layers.mask) !== 0;
  4775. }
  4776. isEnabled(channel) {
  4777. return (this.mask & (1 << channel | 0)) !== 0;
  4778. }
  4779. }
  4780. let _object3DId = 0;
  4781. const _v1$4 = /*@__PURE__*/new Vector3();
  4782. const _q1 = /*@__PURE__*/new Quaternion();
  4783. const _m1$1 = /*@__PURE__*/new Matrix4();
  4784. const _target = /*@__PURE__*/new Vector3();
  4785. const _position$3 = /*@__PURE__*/new Vector3();
  4786. const _scale$2 = /*@__PURE__*/new Vector3();
  4787. const _quaternion$2 = /*@__PURE__*/new Quaternion();
  4788. const _xAxis = /*@__PURE__*/new Vector3(1, 0, 0);
  4789. const _yAxis = /*@__PURE__*/new Vector3(0, 1, 0);
  4790. const _zAxis = /*@__PURE__*/new Vector3(0, 0, 1);
  4791. const _addedEvent = {
  4792. type: 'added'
  4793. };
  4794. const _removedEvent = {
  4795. type: 'removed'
  4796. };
  4797. class Object3D extends EventDispatcher {
  4798. constructor() {
  4799. super();
  4800. this.isObject3D = true;
  4801. Object.defineProperty(this, 'id', {
  4802. value: _object3DId++
  4803. });
  4804. this.uuid = generateUUID();
  4805. this.name = '';
  4806. this.type = 'Object3D';
  4807. this.parent = null;
  4808. this.children = [];
  4809. this.up = Object3D.DefaultUp.clone();
  4810. const position = new Vector3();
  4811. const rotation = new Euler();
  4812. const quaternion = new Quaternion();
  4813. const scale = new Vector3(1, 1, 1);
  4814. function onRotationChange() {
  4815. quaternion.setFromEuler(rotation, false);
  4816. }
  4817. function onQuaternionChange() {
  4818. rotation.setFromQuaternion(quaternion, undefined, false);
  4819. }
  4820. rotation._onChange(onRotationChange);
  4821. quaternion._onChange(onQuaternionChange);
  4822. Object.defineProperties(this, {
  4823. position: {
  4824. configurable: true,
  4825. enumerable: true,
  4826. value: position
  4827. },
  4828. rotation: {
  4829. configurable: true,
  4830. enumerable: true,
  4831. value: rotation
  4832. },
  4833. quaternion: {
  4834. configurable: true,
  4835. enumerable: true,
  4836. value: quaternion
  4837. },
  4838. scale: {
  4839. configurable: true,
  4840. enumerable: true,
  4841. value: scale
  4842. },
  4843. modelViewMatrix: {
  4844. value: new Matrix4()
  4845. },
  4846. normalMatrix: {
  4847. value: new Matrix3()
  4848. }
  4849. });
  4850. this.matrix = new Matrix4();
  4851. this.matrixWorld = new Matrix4();
  4852. this.matrixAutoUpdate = Object3D.DefaultMatrixAutoUpdate;
  4853. this.matrixWorldNeedsUpdate = false;
  4854. this.matrixWorldAutoUpdate = Object3D.DefaultMatrixWorldAutoUpdate; // checked by the renderer
  4855. this.layers = new Layers();
  4856. this.visible = true;
  4857. this.castShadow = false;
  4858. this.receiveShadow = false;
  4859. this.frustumCulled = true;
  4860. this.renderOrder = 0;
  4861. this.animations = [];
  4862. this.userData = {};
  4863. }
  4864. onBeforeRender() {}
  4865. onAfterRender() {}
  4866. applyMatrix4(matrix) {
  4867. if (this.matrixAutoUpdate) this.updateMatrix();
  4868. this.matrix.premultiply(matrix);
  4869. this.matrix.decompose(this.position, this.quaternion, this.scale);
  4870. }
  4871. applyQuaternion(q) {
  4872. this.quaternion.premultiply(q);
  4873. return this;
  4874. }
  4875. setRotationFromAxisAngle(axis, angle) {
  4876. // assumes axis is normalized
  4877. this.quaternion.setFromAxisAngle(axis, angle);
  4878. }
  4879. setRotationFromEuler(euler) {
  4880. this.quaternion.setFromEuler(euler, true);
  4881. }
  4882. setRotationFromMatrix(m) {
  4883. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  4884. this.quaternion.setFromRotationMatrix(m);
  4885. }
  4886. setRotationFromQuaternion(q) {
  4887. // assumes q is normalized
  4888. this.quaternion.copy(q);
  4889. }
  4890. rotateOnAxis(axis, angle) {
  4891. // rotate object on axis in object space
  4892. // axis is assumed to be normalized
  4893. _q1.setFromAxisAngle(axis, angle);
  4894. this.quaternion.multiply(_q1);
  4895. return this;
  4896. }
  4897. rotateOnWorldAxis(axis, angle) {
  4898. // rotate object on axis in world space
  4899. // axis is assumed to be normalized
  4900. // method assumes no rotated parent
  4901. _q1.setFromAxisAngle(axis, angle);
  4902. this.quaternion.premultiply(_q1);
  4903. return this;
  4904. }
  4905. rotateX(angle) {
  4906. return this.rotateOnAxis(_xAxis, angle);
  4907. }
  4908. rotateY(angle) {
  4909. return this.rotateOnAxis(_yAxis, angle);
  4910. }
  4911. rotateZ(angle) {
  4912. return this.rotateOnAxis(_zAxis, angle);
  4913. }
  4914. translateOnAxis(axis, distance) {
  4915. // translate object by distance along axis in object space
  4916. // axis is assumed to be normalized
  4917. _v1$4.copy(axis).applyQuaternion(this.quaternion);
  4918. this.position.add(_v1$4.multiplyScalar(distance));
  4919. return this;
  4920. }
  4921. translateX(distance) {
  4922. return this.translateOnAxis(_xAxis, distance);
  4923. }
  4924. translateY(distance) {
  4925. return this.translateOnAxis(_yAxis, distance);
  4926. }
  4927. translateZ(distance) {
  4928. return this.translateOnAxis(_zAxis, distance);
  4929. }
  4930. localToWorld(vector) {
  4931. return vector.applyMatrix4(this.matrixWorld);
  4932. }
  4933. worldToLocal(vector) {
  4934. return vector.applyMatrix4(_m1$1.copy(this.matrixWorld).invert());
  4935. }
  4936. lookAt(x, y, z) {
  4937. // This method does not support objects having non-uniformly-scaled parent(s)
  4938. if (x.isVector3) {
  4939. _target.copy(x);
  4940. } else {
  4941. _target.set(x, y, z);
  4942. }
  4943. const parent = this.parent;
  4944. this.updateWorldMatrix(true, false);
  4945. _position$3.setFromMatrixPosition(this.matrixWorld);
  4946. if (this.isCamera || this.isLight) {
  4947. _m1$1.lookAt(_position$3, _target, this.up);
  4948. } else {
  4949. _m1$1.lookAt(_target, _position$3, this.up);
  4950. }
  4951. this.quaternion.setFromRotationMatrix(_m1$1);
  4952. if (parent) {
  4953. _m1$1.extractRotation(parent.matrixWorld);
  4954. _q1.setFromRotationMatrix(_m1$1);
  4955. this.quaternion.premultiply(_q1.invert());
  4956. }
  4957. }
  4958. add(object) {
  4959. if (arguments.length > 1) {
  4960. for (let i = 0; i < arguments.length; i++) {
  4961. this.add(arguments[i]);
  4962. }
  4963. return this;
  4964. }
  4965. if (object === this) {
  4966. console.error('THREE.Object3D.add: object can\'t be added as a child of itself.', object);
  4967. return this;
  4968. }
  4969. if (object && object.isObject3D) {
  4970. if (object.parent !== null) {
  4971. object.parent.remove(object);
  4972. }
  4973. object.parent = this;
  4974. this.children.push(object);
  4975. object.dispatchEvent(_addedEvent);
  4976. } else {
  4977. console.error('THREE.Object3D.add: object not an instance of THREE.Object3D.', object);
  4978. }
  4979. return this;
  4980. }
  4981. remove(object) {
  4982. if (arguments.length > 1) {
  4983. for (let i = 0; i < arguments.length; i++) {
  4984. this.remove(arguments[i]);
  4985. }
  4986. return this;
  4987. }
  4988. const index = this.children.indexOf(object);
  4989. if (index !== -1) {
  4990. object.parent = null;
  4991. this.children.splice(index, 1);
  4992. object.dispatchEvent(_removedEvent);
  4993. }
  4994. return this;
  4995. }
  4996. removeFromParent() {
  4997. const parent = this.parent;
  4998. if (parent !== null) {
  4999. parent.remove(this);
  5000. }
  5001. return this;
  5002. }
  5003. clear() {
  5004. for (let i = 0; i < this.children.length; i++) {
  5005. const object = this.children[i];
  5006. object.parent = null;
  5007. object.dispatchEvent(_removedEvent);
  5008. }
  5009. this.children.length = 0;
  5010. return this;
  5011. }
  5012. attach(object) {
  5013. // adds object as a child of this, while maintaining the object's world transform
  5014. // Note: This method does not support scene graphs having non-uniformly-scaled nodes(s)
  5015. this.updateWorldMatrix(true, false);
  5016. _m1$1.copy(this.matrixWorld).invert();
  5017. if (object.parent !== null) {
  5018. object.parent.updateWorldMatrix(true, false);
  5019. _m1$1.multiply(object.parent.matrixWorld);
  5020. }
  5021. object.applyMatrix4(_m1$1);
  5022. this.add(object);
  5023. object.updateWorldMatrix(false, true);
  5024. return this;
  5025. }
  5026. getObjectById(id) {
  5027. return this.getObjectByProperty('id', id);
  5028. }
  5029. getObjectByName(name) {
  5030. return this.getObjectByProperty('name', name);
  5031. }
  5032. getObjectByProperty(name, value) {
  5033. if (this[name] === value) return this;
  5034. for (let i = 0, l = this.children.length; i < l; i++) {
  5035. const child = this.children[i];
  5036. const object = child.getObjectByProperty(name, value);
  5037. if (object !== undefined) {
  5038. return object;
  5039. }
  5040. }
  5041. return undefined;
  5042. }
  5043. getWorldPosition(target) {
  5044. this.updateWorldMatrix(true, false);
  5045. return target.setFromMatrixPosition(this.matrixWorld);
  5046. }
  5047. getWorldQuaternion(target) {
  5048. this.updateWorldMatrix(true, false);
  5049. this.matrixWorld.decompose(_position$3, target, _scale$2);
  5050. return target;
  5051. }
  5052. getWorldScale(target) {
  5053. this.updateWorldMatrix(true, false);
  5054. this.matrixWorld.decompose(_position$3, _quaternion$2, target);
  5055. return target;
  5056. }
  5057. getWorldDirection(target) {
  5058. this.updateWorldMatrix(true, false);
  5059. const e = this.matrixWorld.elements;
  5060. return target.set(e[8], e[9], e[10]).normalize();
  5061. }
  5062. raycast() {}
  5063. traverse(callback) {
  5064. callback(this);
  5065. const children = this.children;
  5066. for (let i = 0, l = children.length; i < l; i++) {
  5067. children[i].traverse(callback);
  5068. }
  5069. }
  5070. traverseVisible(callback) {
  5071. if (this.visible === false) return;
  5072. callback(this);
  5073. const children = this.children;
  5074. for (let i = 0, l = children.length; i < l; i++) {
  5075. children[i].traverseVisible(callback);
  5076. }
  5077. }
  5078. traverseAncestors(callback) {
  5079. const parent = this.parent;
  5080. if (parent !== null) {
  5081. callback(parent);
  5082. parent.traverseAncestors(callback);
  5083. }
  5084. }
  5085. updateMatrix() {
  5086. this.matrix.compose(this.position, this.quaternion, this.scale);
  5087. this.matrixWorldNeedsUpdate = true;
  5088. }
  5089. updateMatrixWorld(force) {
  5090. if (this.matrixAutoUpdate) this.updateMatrix();
  5091. if (this.matrixWorldNeedsUpdate || force) {
  5092. if (this.parent === null) {
  5093. this.matrixWorld.copy(this.matrix);
  5094. } else {
  5095. this.matrixWorld.multiplyMatrices(this.parent.matrixWorld, this.matrix);
  5096. }
  5097. this.matrixWorldNeedsUpdate = false;
  5098. force = true;
  5099. } // update children
  5100. const children = this.children;
  5101. for (let i = 0, l = children.length; i < l; i++) {
  5102. const child = children[i];
  5103. if (child.matrixWorldAutoUpdate === true || force === true) {
  5104. child.updateMatrixWorld(force);
  5105. }
  5106. }
  5107. }
  5108. updateWorldMatrix(updateParents, updateChildren) {
  5109. const parent = this.parent;
  5110. if (updateParents === true && parent !== null && parent.matrixWorldAutoUpdate === true) {
  5111. parent.updateWorldMatrix(true, false);
  5112. }
  5113. if (this.matrixAutoUpdate) this.updateMatrix();
  5114. if (this.parent === null) {
  5115. this.matrixWorld.copy(this.matrix);
  5116. } else {
  5117. this.matrixWorld.multiplyMatrices(this.parent.matrixWorld, this.matrix);
  5118. } // update children
  5119. if (updateChildren === true) {
  5120. const children = this.children;
  5121. for (let i = 0, l = children.length; i < l; i++) {
  5122. const child = children[i];
  5123. if (child.matrixWorldAutoUpdate === true) {
  5124. child.updateWorldMatrix(false, true);
  5125. }
  5126. }
  5127. }
  5128. }
  5129. toJSON(meta) {
  5130. // meta is a string when called from JSON.stringify
  5131. const isRootObject = meta === undefined || typeof meta === 'string';
  5132. const output = {}; // meta is a hash used to collect geometries, materials.
  5133. // not providing it implies that this is the root object
  5134. // being serialized.
  5135. if (isRootObject) {
  5136. // initialize meta obj
  5137. meta = {
  5138. geometries: {},
  5139. materials: {},
  5140. textures: {},
  5141. images: {},
  5142. shapes: {},
  5143. skeletons: {},
  5144. animations: {},
  5145. nodes: {}
  5146. };
  5147. output.metadata = {
  5148. version: 4.5,
  5149. type: 'Object',
  5150. generator: 'Object3D.toJSON'
  5151. };
  5152. } // standard Object3D serialization
  5153. const object = {};
  5154. object.uuid = this.uuid;
  5155. object.type = this.type;
  5156. if (this.name !== '') object.name = this.name;
  5157. if (this.castShadow === true) object.castShadow = true;
  5158. if (this.receiveShadow === true) object.receiveShadow = true;
  5159. if (this.visible === false) object.visible = false;
  5160. if (this.frustumCulled === false) object.frustumCulled = false;
  5161. if (this.renderOrder !== 0) object.renderOrder = this.renderOrder;
  5162. if (JSON.stringify(this.userData) !== '{}') object.userData = this.userData;
  5163. object.layers = this.layers.mask;
  5164. object.matrix = this.matrix.toArray();
  5165. if (this.matrixAutoUpdate === false) object.matrixAutoUpdate = false; // object specific properties
  5166. if (this.isInstancedMesh) {
  5167. object.type = 'InstancedMesh';
  5168. object.count = this.count;
  5169. object.instanceMatrix = this.instanceMatrix.toJSON();
  5170. if (this.instanceColor !== null) object.instanceColor = this.instanceColor.toJSON();
  5171. } //
  5172. function serialize(library, element) {
  5173. if (library[element.uuid] === undefined) {
  5174. library[element.uuid] = element.toJSON(meta);
  5175. }
  5176. return element.uuid;
  5177. }
  5178. if (this.isScene) {
  5179. if (this.background) {
  5180. if (this.background.isColor) {
  5181. object.background = this.background.toJSON();
  5182. } else if (this.background.isTexture) {
  5183. object.background = this.background.toJSON(meta).uuid;
  5184. }
  5185. }
  5186. if (this.environment && this.environment.isTexture && this.environment.isRenderTargetTexture !== true) {
  5187. object.environment = this.environment.toJSON(meta).uuid;
  5188. }
  5189. } else if (this.isMesh || this.isLine || this.isPoints) {
  5190. object.geometry = serialize(meta.geometries, this.geometry);
  5191. const parameters = this.geometry.parameters;
  5192. if (parameters !== undefined && parameters.shapes !== undefined) {
  5193. const shapes = parameters.shapes;
  5194. if (Array.isArray(shapes)) {
  5195. for (let i = 0, l = shapes.length; i < l; i++) {
  5196. const shape = shapes[i];
  5197. serialize(meta.shapes, shape);
  5198. }
  5199. } else {
  5200. serialize(meta.shapes, shapes);
  5201. }
  5202. }
  5203. }
  5204. if (this.isSkinnedMesh) {
  5205. object.bindMode = this.bindMode;
  5206. object.bindMatrix = this.bindMatrix.toArray();
  5207. if (this.skeleton !== undefined) {
  5208. serialize(meta.skeletons, this.skeleton);
  5209. object.skeleton = this.skeleton.uuid;
  5210. }
  5211. }
  5212. if (this.material !== undefined) {
  5213. if (Array.isArray(this.material)) {
  5214. const uuids = [];
  5215. for (let i = 0, l = this.material.length; i < l; i++) {
  5216. uuids.push(serialize(meta.materials, this.material[i]));
  5217. }
  5218. object.material = uuids;
  5219. } else {
  5220. object.material = serialize(meta.materials, this.material);
  5221. }
  5222. } //
  5223. if (this.children.length > 0) {
  5224. object.children = [];
  5225. for (let i = 0; i < this.children.length; i++) {
  5226. object.children.push(this.children[i].toJSON(meta).object);
  5227. }
  5228. } //
  5229. if (this.animations.length > 0) {
  5230. object.animations = [];
  5231. for (let i = 0; i < this.animations.length; i++) {
  5232. const animation = this.animations[i];
  5233. object.animations.push(serialize(meta.animations, animation));
  5234. }
  5235. }
  5236. if (isRootObject) {
  5237. const geometries = extractFromCache(meta.geometries);
  5238. const materials = extractFromCache(meta.materials);
  5239. const textures = extractFromCache(meta.textures);
  5240. const images = extractFromCache(meta.images);
  5241. const shapes = extractFromCache(meta.shapes);
  5242. const skeletons = extractFromCache(meta.skeletons);
  5243. const animations = extractFromCache(meta.animations);
  5244. const nodes = extractFromCache(meta.nodes);
  5245. if (geometries.length > 0) output.geometries = geometries;
  5246. if (materials.length > 0) output.materials = materials;
  5247. if (textures.length > 0) output.textures = textures;
  5248. if (images.length > 0) output.images = images;
  5249. if (shapes.length > 0) output.shapes = shapes;
  5250. if (skeletons.length > 0) output.skeletons = skeletons;
  5251. if (animations.length > 0) output.animations = animations;
  5252. if (nodes.length > 0) output.nodes = nodes;
  5253. }
  5254. output.object = object;
  5255. return output; // extract data from the cache hash
  5256. // remove metadata on each item
  5257. // and return as array
  5258. function extractFromCache(cache) {
  5259. const values = [];
  5260. for (const key in cache) {
  5261. const data = cache[key];
  5262. delete data.metadata;
  5263. values.push(data);
  5264. }
  5265. return values;
  5266. }
  5267. }
  5268. clone(recursive) {
  5269. return new this.constructor().copy(this, recursive);
  5270. }
  5271. copy(source, recursive = true) {
  5272. this.name = source.name;
  5273. this.up.copy(source.up);
  5274. this.position.copy(source.position);
  5275. this.rotation.order = source.rotation.order;
  5276. this.quaternion.copy(source.quaternion);
  5277. this.scale.copy(source.scale);
  5278. this.matrix.copy(source.matrix);
  5279. this.matrixWorld.copy(source.matrixWorld);
  5280. this.matrixAutoUpdate = source.matrixAutoUpdate;
  5281. this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;
  5282. this.matrixWorldAutoUpdate = source.matrixWorldAutoUpdate;
  5283. this.layers.mask = source.layers.mask;
  5284. this.visible = source.visible;
  5285. this.castShadow = source.castShadow;
  5286. this.receiveShadow = source.receiveShadow;
  5287. this.frustumCulled = source.frustumCulled;
  5288. this.renderOrder = source.renderOrder;
  5289. this.userData = JSON.parse(JSON.stringify(source.userData));
  5290. if (recursive === true) {
  5291. for (let i = 0; i < source.children.length; i++) {
  5292. const child = source.children[i];
  5293. this.add(child.clone());
  5294. }
  5295. }
  5296. return this;
  5297. }
  5298. }
  5299. Object3D.DefaultUp = /*@__PURE__*/new Vector3(0, 1, 0);
  5300. Object3D.DefaultMatrixAutoUpdate = true;
  5301. Object3D.DefaultMatrixWorldAutoUpdate = true;
  5302. const _v0$1 = /*@__PURE__*/new Vector3();
  5303. const _v1$3 = /*@__PURE__*/new Vector3();
  5304. const _v2$2 = /*@__PURE__*/new Vector3();
  5305. const _v3$1 = /*@__PURE__*/new Vector3();
  5306. const _vab = /*@__PURE__*/new Vector3();
  5307. const _vac = /*@__PURE__*/new Vector3();
  5308. const _vbc = /*@__PURE__*/new Vector3();
  5309. const _vap = /*@__PURE__*/new Vector3();
  5310. const _vbp = /*@__PURE__*/new Vector3();
  5311. const _vcp = /*@__PURE__*/new Vector3();
  5312. class Triangle {
  5313. constructor(a = new Vector3(), b = new Vector3(), c = new Vector3()) {
  5314. this.a = a;
  5315. this.b = b;
  5316. this.c = c;
  5317. }
  5318. static getNormal(a, b, c, target) {
  5319. target.subVectors(c, b);
  5320. _v0$1.subVectors(a, b);
  5321. target.cross(_v0$1);
  5322. const targetLengthSq = target.lengthSq();
  5323. if (targetLengthSq > 0) {
  5324. return target.multiplyScalar(1 / Math.sqrt(targetLengthSq));
  5325. }
  5326. return target.set(0, 0, 0);
  5327. } // static/instance method to calculate barycentric coordinates
  5328. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  5329. static getBarycoord(point, a, b, c, target) {
  5330. _v0$1.subVectors(c, a);
  5331. _v1$3.subVectors(b, a);
  5332. _v2$2.subVectors(point, a);
  5333. const dot00 = _v0$1.dot(_v0$1);
  5334. const dot01 = _v0$1.dot(_v1$3);
  5335. const dot02 = _v0$1.dot(_v2$2);
  5336. const dot11 = _v1$3.dot(_v1$3);
  5337. const dot12 = _v1$3.dot(_v2$2);
  5338. const denom = dot00 * dot11 - dot01 * dot01; // collinear or singular triangle
  5339. if (denom === 0) {
  5340. // arbitrary location outside of triangle?
  5341. // not sure if this is the best idea, maybe should be returning undefined
  5342. return target.set(-2, -1, -1);
  5343. }
  5344. const invDenom = 1 / denom;
  5345. const u = (dot11 * dot02 - dot01 * dot12) * invDenom;
  5346. const v = (dot00 * dot12 - dot01 * dot02) * invDenom; // barycentric coordinates must always sum to 1
  5347. return target.set(1 - u - v, v, u);
  5348. }
  5349. static containsPoint(point, a, b, c) {
  5350. this.getBarycoord(point, a, b, c, _v3$1);
  5351. return _v3$1.x >= 0 && _v3$1.y >= 0 && _v3$1.x + _v3$1.y <= 1;
  5352. }
  5353. static getUV(point, p1, p2, p3, uv1, uv2, uv3, target) {
  5354. this.getBarycoord(point, p1, p2, p3, _v3$1);
  5355. target.set(0, 0);
  5356. target.addScaledVector(uv1, _v3$1.x);
  5357. target.addScaledVector(uv2, _v3$1.y);
  5358. target.addScaledVector(uv3, _v3$1.z);
  5359. return target;
  5360. }
  5361. static isFrontFacing(a, b, c, direction) {
  5362. _v0$1.subVectors(c, b);
  5363. _v1$3.subVectors(a, b); // strictly front facing
  5364. return _v0$1.cross(_v1$3).dot(direction) < 0 ? true : false;
  5365. }
  5366. set(a, b, c) {
  5367. this.a.copy(a);
  5368. this.b.copy(b);
  5369. this.c.copy(c);
  5370. return this;
  5371. }
  5372. setFromPointsAndIndices(points, i0, i1, i2) {
  5373. this.a.copy(points[i0]);
  5374. this.b.copy(points[i1]);
  5375. this.c.copy(points[i2]);
  5376. return this;
  5377. }
  5378. setFromAttributeAndIndices(attribute, i0, i1, i2) {
  5379. this.a.fromBufferAttribute(attribute, i0);
  5380. this.b.fromBufferAttribute(attribute, i1);
  5381. this.c.fromBufferAttribute(attribute, i2);
  5382. return this;
  5383. }
  5384. clone() {
  5385. return new this.constructor().copy(this);
  5386. }
  5387. copy(triangle) {
  5388. this.a.copy(triangle.a);
  5389. this.b.copy(triangle.b);
  5390. this.c.copy(triangle.c);
  5391. return this;
  5392. }
  5393. getArea() {
  5394. _v0$1.subVectors(this.c, this.b);
  5395. _v1$3.subVectors(this.a, this.b);
  5396. return _v0$1.cross(_v1$3).length() * 0.5;
  5397. }
  5398. getMidpoint(target) {
  5399. return target.addVectors(this.a, this.b).add(this.c).multiplyScalar(1 / 3);
  5400. }
  5401. getNormal(target) {
  5402. return Triangle.getNormal(this.a, this.b, this.c, target);
  5403. }
  5404. getPlane(target) {
  5405. return target.setFromCoplanarPoints(this.a, this.b, this.c);
  5406. }
  5407. getBarycoord(point, target) {
  5408. return Triangle.getBarycoord(point, this.a, this.b, this.c, target);
  5409. }
  5410. getUV(point, uv1, uv2, uv3, target) {
  5411. return Triangle.getUV(point, this.a, this.b, this.c, uv1, uv2, uv3, target);
  5412. }
  5413. containsPoint(point) {
  5414. return Triangle.containsPoint(point, this.a, this.b, this.c);
  5415. }
  5416. isFrontFacing(direction) {
  5417. return Triangle.isFrontFacing(this.a, this.b, this.c, direction);
  5418. }
  5419. intersectsBox(box) {
  5420. return box.intersectsTriangle(this);
  5421. }
  5422. closestPointToPoint(p, target) {
  5423. const a = this.a,
  5424. b = this.b,
  5425. c = this.c;
  5426. let v, w; // algorithm thanks to Real-Time Collision Detection by Christer Ericson,
  5427. // published by Morgan Kaufmann Publishers, (c) 2005 Elsevier Inc.,
  5428. // under the accompanying license; see chapter 5.1.5 for detailed explanation.
  5429. // basically, we're distinguishing which of the voronoi regions of the triangle
  5430. // the point lies in with the minimum amount of redundant computation.
  5431. _vab.subVectors(b, a);
  5432. _vac.subVectors(c, a);
  5433. _vap.subVectors(p, a);
  5434. const d1 = _vab.dot(_vap);
  5435. const d2 = _vac.dot(_vap);
  5436. if (d1 <= 0 && d2 <= 0) {
  5437. // vertex region of A; barycentric coords (1, 0, 0)
  5438. return target.copy(a);
  5439. }
  5440. _vbp.subVectors(p, b);
  5441. const d3 = _vab.dot(_vbp);
  5442. const d4 = _vac.dot(_vbp);
  5443. if (d3 >= 0 && d4 <= d3) {
  5444. // vertex region of B; barycentric coords (0, 1, 0)
  5445. return target.copy(b);
  5446. }
  5447. const vc = d1 * d4 - d3 * d2;
  5448. if (vc <= 0 && d1 >= 0 && d3 <= 0) {
  5449. v = d1 / (d1 - d3); // edge region of AB; barycentric coords (1-v, v, 0)
  5450. return target.copy(a).addScaledVector(_vab, v);
  5451. }
  5452. _vcp.subVectors(p, c);
  5453. const d5 = _vab.dot(_vcp);
  5454. const d6 = _vac.dot(_vcp);
  5455. if (d6 >= 0 && d5 <= d6) {
  5456. // vertex region of C; barycentric coords (0, 0, 1)
  5457. return target.copy(c);
  5458. }
  5459. const vb = d5 * d2 - d1 * d6;
  5460. if (vb <= 0 && d2 >= 0 && d6 <= 0) {
  5461. w = d2 / (d2 - d6); // edge region of AC; barycentric coords (1-w, 0, w)
  5462. return target.copy(a).addScaledVector(_vac, w);
  5463. }
  5464. const va = d3 * d6 - d5 * d4;
  5465. if (va <= 0 && d4 - d3 >= 0 && d5 - d6 >= 0) {
  5466. _vbc.subVectors(c, b);
  5467. w = (d4 - d3) / (d4 - d3 + (d5 - d6)); // edge region of BC; barycentric coords (0, 1-w, w)
  5468. return target.copy(b).addScaledVector(_vbc, w); // edge region of BC
  5469. } // face region
  5470. const denom = 1 / (va + vb + vc); // u = va * denom
  5471. v = vb * denom;
  5472. w = vc * denom;
  5473. return target.copy(a).addScaledVector(_vab, v).addScaledVector(_vac, w);
  5474. }
  5475. equals(triangle) {
  5476. return triangle.a.equals(this.a) && triangle.b.equals(this.b) && triangle.c.equals(this.c);
  5477. }
  5478. }
  5479. let materialId = 0;
  5480. class Material extends EventDispatcher {
  5481. constructor() {
  5482. super();
  5483. this.isMaterial = true;
  5484. Object.defineProperty(this, 'id', {
  5485. value: materialId++
  5486. });
  5487. this.uuid = generateUUID();
  5488. this.name = '';
  5489. this.type = 'Material';
  5490. this.blending = NormalBlending;
  5491. this.side = FrontSide;
  5492. this.vertexColors = false;
  5493. this.opacity = 1;
  5494. this.transparent = false;
  5495. this.blendSrc = SrcAlphaFactor;
  5496. this.blendDst = OneMinusSrcAlphaFactor;
  5497. this.blendEquation = AddEquation;
  5498. this.blendSrcAlpha = null;
  5499. this.blendDstAlpha = null;
  5500. this.blendEquationAlpha = null;
  5501. this.depthFunc = LessEqualDepth;
  5502. this.depthTest = true;
  5503. this.depthWrite = true;
  5504. this.stencilWriteMask = 0xff;
  5505. this.stencilFunc = AlwaysStencilFunc;
  5506. this.stencilRef = 0;
  5507. this.stencilFuncMask = 0xff;
  5508. this.stencilFail = KeepStencilOp;
  5509. this.stencilZFail = KeepStencilOp;
  5510. this.stencilZPass = KeepStencilOp;
  5511. this.stencilWrite = false;
  5512. this.clippingPlanes = null;
  5513. this.clipIntersection = false;
  5514. this.clipShadows = false;
  5515. this.shadowSide = null;
  5516. this.colorWrite = true;
  5517. this.precision = null; // override the renderer's default precision for this material
  5518. this.polygonOffset = false;
  5519. this.polygonOffsetFactor = 0;
  5520. this.polygonOffsetUnits = 0;
  5521. this.dithering = false;
  5522. this.alphaToCoverage = false;
  5523. this.premultipliedAlpha = false;
  5524. this.visible = true;
  5525. this.toneMapped = true;
  5526. this.userData = {};
  5527. this.version = 0;
  5528. this._alphaTest = 0;
  5529. }
  5530. get alphaTest() {
  5531. return this._alphaTest;
  5532. }
  5533. set alphaTest(value) {
  5534. if (this._alphaTest > 0 !== value > 0) {
  5535. this.version++;
  5536. }
  5537. this._alphaTest = value;
  5538. }
  5539. onBuild() {}
  5540. onBeforeRender() {}
  5541. onBeforeCompile() {}
  5542. customProgramCacheKey() {
  5543. return this.onBeforeCompile.toString();
  5544. }
  5545. setValues(values) {
  5546. if (values === undefined) return;
  5547. for (const key in values) {
  5548. const newValue = values[key];
  5549. if (newValue === undefined) {
  5550. console.warn('THREE.Material: \'' + key + '\' parameter is undefined.');
  5551. continue;
  5552. }
  5553. const currentValue = this[key];
  5554. if (currentValue === undefined) {
  5555. console.warn('THREE.' + this.type + ': \'' + key + '\' is not a property of this material.');
  5556. continue;
  5557. }
  5558. if (currentValue && currentValue.isColor) {
  5559. currentValue.set(newValue);
  5560. } else if (currentValue && currentValue.isVector3 && newValue && newValue.isVector3) {
  5561. currentValue.copy(newValue);
  5562. } else {
  5563. this[key] = newValue;
  5564. }
  5565. }
  5566. }
  5567. toJSON(meta) {
  5568. const isRootObject = meta === undefined || typeof meta === 'string';
  5569. if (isRootObject) {
  5570. meta = {
  5571. textures: {},
  5572. images: {}
  5573. };
  5574. }
  5575. const data = {
  5576. metadata: {
  5577. version: 4.5,
  5578. type: 'Material',
  5579. generator: 'Material.toJSON'
  5580. }
  5581. }; // standard Material serialization
  5582. data.uuid = this.uuid;
  5583. data.type = this.type;
  5584. if (this.name !== '') data.name = this.name;
  5585. if (this.color && this.color.isColor) data.color = this.color.getHex();
  5586. if (this.roughness !== undefined) data.roughness = this.roughness;
  5587. if (this.metalness !== undefined) data.metalness = this.metalness;
  5588. if (this.sheen !== undefined) data.sheen = this.sheen;
  5589. if (this.sheenColor && this.sheenColor.isColor) data.sheenColor = this.sheenColor.getHex();
  5590. if (this.sheenRoughness !== undefined) data.sheenRoughness = this.sheenRoughness;
  5591. if (this.emissive && this.emissive.isColor) data.emissive = this.emissive.getHex();
  5592. if (this.emissiveIntensity && this.emissiveIntensity !== 1) data.emissiveIntensity = this.emissiveIntensity;
  5593. if (this.specular && this.specular.isColor) data.specular = this.specular.getHex();
  5594. if (this.specularIntensity !== undefined) data.specularIntensity = this.specularIntensity;
  5595. if (this.specularColor && this.specularColor.isColor) data.specularColor = this.specularColor.getHex();
  5596. if (this.shininess !== undefined) data.shininess = this.shininess;
  5597. if (this.clearcoat !== undefined) data.clearcoat = this.clearcoat;
  5598. if (this.clearcoatRoughness !== undefined) data.clearcoatRoughness = this.clearcoatRoughness;
  5599. if (this.clearcoatMap && this.clearcoatMap.isTexture) {
  5600. data.clearcoatMap = this.clearcoatMap.toJSON(meta).uuid;
  5601. }
  5602. if (this.clearcoatRoughnessMap && this.clearcoatRoughnessMap.isTexture) {
  5603. data.clearcoatRoughnessMap = this.clearcoatRoughnessMap.toJSON(meta).uuid;
  5604. }
  5605. if (this.clearcoatNormalMap && this.clearcoatNormalMap.isTexture) {
  5606. data.clearcoatNormalMap = this.clearcoatNormalMap.toJSON(meta).uuid;
  5607. data.clearcoatNormalScale = this.clearcoatNormalScale.toArray();
  5608. }
  5609. if (this.iridescence !== undefined) data.iridescence = this.iridescence;
  5610. if (this.iridescenceIOR !== undefined) data.iridescenceIOR = this.iridescenceIOR;
  5611. if (this.iridescenceThicknessRange !== undefined) data.iridescenceThicknessRange = this.iridescenceThicknessRange;
  5612. if (this.iridescenceMap && this.iridescenceMap.isTexture) {
  5613. data.iridescenceMap = this.iridescenceMap.toJSON(meta).uuid;
  5614. }
  5615. if (this.iridescenceThicknessMap && this.iridescenceThicknessMap.isTexture) {
  5616. data.iridescenceThicknessMap = this.iridescenceThicknessMap.toJSON(meta).uuid;
  5617. }
  5618. if (this.map && this.map.isTexture) data.map = this.map.toJSON(meta).uuid;
  5619. if (this.matcap && this.matcap.isTexture) data.matcap = this.matcap.toJSON(meta).uuid;
  5620. if (this.alphaMap && this.alphaMap.isTexture) data.alphaMap = this.alphaMap.toJSON(meta).uuid;
  5621. if (this.lightMap && this.lightMap.isTexture) {
  5622. data.lightMap = this.lightMap.toJSON(meta).uuid;
  5623. data.lightMapIntensity = this.lightMapIntensity;
  5624. }
  5625. if (this.aoMap && this.aoMap.isTexture) {
  5626. data.aoMap = this.aoMap.toJSON(meta).uuid;
  5627. data.aoMapIntensity = this.aoMapIntensity;
  5628. }
  5629. if (this.bumpMap && this.bumpMap.isTexture) {
  5630. data.bumpMap = this.bumpMap.toJSON(meta).uuid;
  5631. data.bumpScale = this.bumpScale;
  5632. }
  5633. if (this.normalMap && this.normalMap.isTexture) {
  5634. data.normalMap = this.normalMap.toJSON(meta).uuid;
  5635. data.normalMapType = this.normalMapType;
  5636. data.normalScale = this.normalScale.toArray();
  5637. }
  5638. if (this.displacementMap && this.displacementMap.isTexture) {
  5639. data.displacementMap = this.displacementMap.toJSON(meta).uuid;
  5640. data.displacementScale = this.displacementScale;
  5641. data.displacementBias = this.displacementBias;
  5642. }
  5643. if (this.roughnessMap && this.roughnessMap.isTexture) data.roughnessMap = this.roughnessMap.toJSON(meta).uuid;
  5644. if (this.metalnessMap && this.metalnessMap.isTexture) data.metalnessMap = this.metalnessMap.toJSON(meta).uuid;
  5645. if (this.emissiveMap && this.emissiveMap.isTexture) data.emissiveMap = this.emissiveMap.toJSON(meta).uuid;
  5646. if (this.specularMap && this.specularMap.isTexture) data.specularMap = this.specularMap.toJSON(meta).uuid;
  5647. if (this.specularIntensityMap && this.specularIntensityMap.isTexture) data.specularIntensityMap = this.specularIntensityMap.toJSON(meta).uuid;
  5648. if (this.specularColorMap && this.specularColorMap.isTexture) data.specularColorMap = this.specularColorMap.toJSON(meta).uuid;
  5649. if (this.envMap && this.envMap.isTexture) {
  5650. data.envMap = this.envMap.toJSON(meta).uuid;
  5651. if (this.combine !== undefined) data.combine = this.combine;
  5652. }
  5653. if (this.envMapIntensity !== undefined) data.envMapIntensity = this.envMapIntensity;
  5654. if (this.reflectivity !== undefined) data.reflectivity = this.reflectivity;
  5655. if (this.refractionRatio !== undefined) data.refractionRatio = this.refractionRatio;
  5656. if (this.gradientMap && this.gradientMap.isTexture) {
  5657. data.gradientMap = this.gradientMap.toJSON(meta).uuid;
  5658. }
  5659. if (this.transmission !== undefined) data.transmission = this.transmission;
  5660. if (this.transmissionMap && this.transmissionMap.isTexture) data.transmissionMap = this.transmissionMap.toJSON(meta).uuid;
  5661. if (this.thickness !== undefined) data.thickness = this.thickness;
  5662. if (this.thicknessMap && this.thicknessMap.isTexture) data.thicknessMap = this.thicknessMap.toJSON(meta).uuid;
  5663. if (this.attenuationDistance !== undefined) data.attenuationDistance = this.attenuationDistance;
  5664. if (this.attenuationColor !== undefined) data.attenuationColor = this.attenuationColor.getHex();
  5665. if (this.size !== undefined) data.size = this.size;
  5666. if (this.shadowSide !== null) data.shadowSide = this.shadowSide;
  5667. if (this.sizeAttenuation !== undefined) data.sizeAttenuation = this.sizeAttenuation;
  5668. if (this.blending !== NormalBlending) data.blending = this.blending;
  5669. if (this.side !== FrontSide) data.side = this.side;
  5670. if (this.vertexColors) data.vertexColors = true;
  5671. if (this.opacity < 1) data.opacity = this.opacity;
  5672. if (this.transparent === true) data.transparent = this.transparent;
  5673. data.depthFunc = this.depthFunc;
  5674. data.depthTest = this.depthTest;
  5675. data.depthWrite = this.depthWrite;
  5676. data.colorWrite = this.colorWrite;
  5677. data.stencilWrite = this.stencilWrite;
  5678. data.stencilWriteMask = this.stencilWriteMask;
  5679. data.stencilFunc = this.stencilFunc;
  5680. data.stencilRef = this.stencilRef;
  5681. data.stencilFuncMask = this.stencilFuncMask;
  5682. data.stencilFail = this.stencilFail;
  5683. data.stencilZFail = this.stencilZFail;
  5684. data.stencilZPass = this.stencilZPass; // rotation (SpriteMaterial)
  5685. if (this.rotation !== undefined && this.rotation !== 0) data.rotation = this.rotation;
  5686. if (this.polygonOffset === true) data.polygonOffset = true;
  5687. if (this.polygonOffsetFactor !== 0) data.polygonOffsetFactor = this.polygonOffsetFactor;
  5688. if (this.polygonOffsetUnits !== 0) data.polygonOffsetUnits = this.polygonOffsetUnits;
  5689. if (this.linewidth !== undefined && this.linewidth !== 1) data.linewidth = this.linewidth;
  5690. if (this.dashSize !== undefined) data.dashSize = this.dashSize;
  5691. if (this.gapSize !== undefined) data.gapSize = this.gapSize;
  5692. if (this.scale !== undefined) data.scale = this.scale;
  5693. if (this.dithering === true) data.dithering = true;
  5694. if (this.alphaTest > 0) data.alphaTest = this.alphaTest;
  5695. if (this.alphaToCoverage === true) data.alphaToCoverage = this.alphaToCoverage;
  5696. if (this.premultipliedAlpha === true) data.premultipliedAlpha = this.premultipliedAlpha;
  5697. if (this.wireframe === true) data.wireframe = this.wireframe;
  5698. if (this.wireframeLinewidth > 1) data.wireframeLinewidth = this.wireframeLinewidth;
  5699. if (this.wireframeLinecap !== 'round') data.wireframeLinecap = this.wireframeLinecap;
  5700. if (this.wireframeLinejoin !== 'round') data.wireframeLinejoin = this.wireframeLinejoin;
  5701. if (this.flatShading === true) data.flatShading = this.flatShading;
  5702. if (this.visible === false) data.visible = false;
  5703. if (this.toneMapped === false) data.toneMapped = false;
  5704. if (this.fog === false) data.fog = false;
  5705. if (JSON.stringify(this.userData) !== '{}') data.userData = this.userData; // TODO: Copied from Object3D.toJSON
  5706. function extractFromCache(cache) {
  5707. const values = [];
  5708. for (const key in cache) {
  5709. const data = cache[key];
  5710. delete data.metadata;
  5711. values.push(data);
  5712. }
  5713. return values;
  5714. }
  5715. if (isRootObject) {
  5716. const textures = extractFromCache(meta.textures);
  5717. const images = extractFromCache(meta.images);
  5718. if (textures.length > 0) data.textures = textures;
  5719. if (images.length > 0) data.images = images;
  5720. }
  5721. return data;
  5722. }
  5723. clone() {
  5724. return new this.constructor().copy(this);
  5725. }
  5726. copy(source) {
  5727. this.name = source.name;
  5728. this.blending = source.blending;
  5729. this.side = source.side;
  5730. this.vertexColors = source.vertexColors;
  5731. this.opacity = source.opacity;
  5732. this.transparent = source.transparent;
  5733. this.blendSrc = source.blendSrc;
  5734. this.blendDst = source.blendDst;
  5735. this.blendEquation = source.blendEquation;
  5736. this.blendSrcAlpha = source.blendSrcAlpha;
  5737. this.blendDstAlpha = source.blendDstAlpha;
  5738. this.blendEquationAlpha = source.blendEquationAlpha;
  5739. this.depthFunc = source.depthFunc;
  5740. this.depthTest = source.depthTest;
  5741. this.depthWrite = source.depthWrite;
  5742. this.stencilWriteMask = source.stencilWriteMask;
  5743. this.stencilFunc = source.stencilFunc;
  5744. this.stencilRef = source.stencilRef;
  5745. this.stencilFuncMask = source.stencilFuncMask;
  5746. this.stencilFail = source.stencilFail;
  5747. this.stencilZFail = source.stencilZFail;
  5748. this.stencilZPass = source.stencilZPass;
  5749. this.stencilWrite = source.stencilWrite;
  5750. const srcPlanes = source.clippingPlanes;
  5751. let dstPlanes = null;
  5752. if (srcPlanes !== null) {
  5753. const n = srcPlanes.length;
  5754. dstPlanes = new Array(n);
  5755. for (let i = 0; i !== n; ++i) {
  5756. dstPlanes[i] = srcPlanes[i].clone();
  5757. }
  5758. }
  5759. this.clippingPlanes = dstPlanes;
  5760. this.clipIntersection = source.clipIntersection;
  5761. this.clipShadows = source.clipShadows;
  5762. this.shadowSide = source.shadowSide;
  5763. this.colorWrite = source.colorWrite;
  5764. this.precision = source.precision;
  5765. this.polygonOffset = source.polygonOffset;
  5766. this.polygonOffsetFactor = source.polygonOffsetFactor;
  5767. this.polygonOffsetUnits = source.polygonOffsetUnits;
  5768. this.dithering = source.dithering;
  5769. this.alphaTest = source.alphaTest;
  5770. this.alphaToCoverage = source.alphaToCoverage;
  5771. this.premultipliedAlpha = source.premultipliedAlpha;
  5772. this.visible = source.visible;
  5773. this.toneMapped = source.toneMapped;
  5774. this.userData = JSON.parse(JSON.stringify(source.userData));
  5775. return this;
  5776. }
  5777. dispose() {
  5778. this.dispatchEvent({
  5779. type: 'dispose'
  5780. });
  5781. }
  5782. set needsUpdate(value) {
  5783. if (value === true) this.version++;
  5784. }
  5785. }
  5786. class MeshBasicMaterial extends Material {
  5787. constructor(parameters) {
  5788. super();
  5789. this.isMeshBasicMaterial = true;
  5790. this.type = 'MeshBasicMaterial';
  5791. this.color = new Color(0xffffff); // emissive
  5792. this.map = null;
  5793. this.lightMap = null;
  5794. this.lightMapIntensity = 1.0;
  5795. this.aoMap = null;
  5796. this.aoMapIntensity = 1.0;
  5797. this.specularMap = null;
  5798. this.alphaMap = null;
  5799. this.envMap = null;
  5800. this.combine = MultiplyOperation;
  5801. this.reflectivity = 1;
  5802. this.refractionRatio = 0.98;
  5803. this.wireframe = false;
  5804. this.wireframeLinewidth = 1;
  5805. this.wireframeLinecap = 'round';
  5806. this.wireframeLinejoin = 'round';
  5807. this.fog = true;
  5808. this.setValues(parameters);
  5809. }
  5810. copy(source) {
  5811. super.copy(source);
  5812. this.color.copy(source.color);
  5813. this.map = source.map;
  5814. this.lightMap = source.lightMap;
  5815. this.lightMapIntensity = source.lightMapIntensity;
  5816. this.aoMap = source.aoMap;
  5817. this.aoMapIntensity = source.aoMapIntensity;
  5818. this.specularMap = source.specularMap;
  5819. this.alphaMap = source.alphaMap;
  5820. this.envMap = source.envMap;
  5821. this.combine = source.combine;
  5822. this.reflectivity = source.reflectivity;
  5823. this.refractionRatio = source.refractionRatio;
  5824. this.wireframe = source.wireframe;
  5825. this.wireframeLinewidth = source.wireframeLinewidth;
  5826. this.wireframeLinecap = source.wireframeLinecap;
  5827. this.wireframeLinejoin = source.wireframeLinejoin;
  5828. this.fog = source.fog;
  5829. return this;
  5830. }
  5831. }
  5832. const _vector$9 = /*@__PURE__*/new Vector3();
  5833. const _vector2$1 = /*@__PURE__*/new Vector2();
  5834. class BufferAttribute {
  5835. constructor(array, itemSize, normalized) {
  5836. if (Array.isArray(array)) {
  5837. throw new TypeError('THREE.BufferAttribute: array should be a Typed Array.');
  5838. }
  5839. this.isBufferAttribute = true;
  5840. this.name = '';
  5841. this.array = array;
  5842. this.itemSize = itemSize;
  5843. this.count = array !== undefined ? array.length / itemSize : 0;
  5844. this.normalized = normalized === true;
  5845. this.usage = StaticDrawUsage;
  5846. this.updateRange = {
  5847. offset: 0,
  5848. count: -1
  5849. };
  5850. this.version = 0;
  5851. }
  5852. onUploadCallback() {}
  5853. set needsUpdate(value) {
  5854. if (value === true) this.version++;
  5855. }
  5856. setUsage(value) {
  5857. this.usage = value;
  5858. return this;
  5859. }
  5860. copy(source) {
  5861. this.name = source.name;
  5862. this.array = new source.array.constructor(source.array);
  5863. this.itemSize = source.itemSize;
  5864. this.count = source.count;
  5865. this.normalized = source.normalized;
  5866. this.usage = source.usage;
  5867. return this;
  5868. }
  5869. copyAt(index1, attribute, index2) {
  5870. index1 *= this.itemSize;
  5871. index2 *= attribute.itemSize;
  5872. for (let i = 0, l = this.itemSize; i < l; i++) {
  5873. this.array[index1 + i] = attribute.array[index2 + i];
  5874. }
  5875. return this;
  5876. }
  5877. copyArray(array) {
  5878. this.array.set(array);
  5879. return this;
  5880. }
  5881. applyMatrix3(m) {
  5882. if (this.itemSize === 2) {
  5883. for (let i = 0, l = this.count; i < l; i++) {
  5884. _vector2$1.fromBufferAttribute(this, i);
  5885. _vector2$1.applyMatrix3(m);
  5886. this.setXY(i, _vector2$1.x, _vector2$1.y);
  5887. }
  5888. } else if (this.itemSize === 3) {
  5889. for (let i = 0, l = this.count; i < l; i++) {
  5890. _vector$9.fromBufferAttribute(this, i);
  5891. _vector$9.applyMatrix3(m);
  5892. this.setXYZ(i, _vector$9.x, _vector$9.y, _vector$9.z);
  5893. }
  5894. }
  5895. return this;
  5896. }
  5897. applyMatrix4(m) {
  5898. for (let i = 0, l = this.count; i < l; i++) {
  5899. _vector$9.fromBufferAttribute(this, i);
  5900. _vector$9.applyMatrix4(m);
  5901. this.setXYZ(i, _vector$9.x, _vector$9.y, _vector$9.z);
  5902. }
  5903. return this;
  5904. }
  5905. applyNormalMatrix(m) {
  5906. for (let i = 0, l = this.count; i < l; i++) {
  5907. _vector$9.fromBufferAttribute(this, i);
  5908. _vector$9.applyNormalMatrix(m);
  5909. this.setXYZ(i, _vector$9.x, _vector$9.y, _vector$9.z);
  5910. }
  5911. return this;
  5912. }
  5913. transformDirection(m) {
  5914. for (let i = 0, l = this.count; i < l; i++) {
  5915. _vector$9.fromBufferAttribute(this, i);
  5916. _vector$9.transformDirection(m);
  5917. this.setXYZ(i, _vector$9.x, _vector$9.y, _vector$9.z);
  5918. }
  5919. return this;
  5920. }
  5921. set(value, offset = 0) {
  5922. // Matching BufferAttribute constructor, do not normalize the array.
  5923. this.array.set(value, offset);
  5924. return this;
  5925. }
  5926. getX(index) {
  5927. let x = this.array[index * this.itemSize];
  5928. if (this.normalized) x = denormalize(x, this.array);
  5929. return x;
  5930. }
  5931. setX(index, x) {
  5932. if (this.normalized) x = normalize(x, this.array);
  5933. this.array[index * this.itemSize] = x;
  5934. return this;
  5935. }
  5936. getY(index) {
  5937. let y = this.array[index * this.itemSize + 1];
  5938. if (this.normalized) y = denormalize(y, this.array);
  5939. return y;
  5940. }
  5941. setY(index, y) {
  5942. if (this.normalized) y = normalize(y, this.array);
  5943. this.array[index * this.itemSize + 1] = y;
  5944. return this;
  5945. }
  5946. getZ(index) {
  5947. let z = this.array[index * this.itemSize + 2];
  5948. if (this.normalized) z = denormalize(z, this.array);
  5949. return z;
  5950. }
  5951. setZ(index, z) {
  5952. if (this.normalized) z = normalize(z, this.array);
  5953. this.array[index * this.itemSize + 2] = z;
  5954. return this;
  5955. }
  5956. getW(index) {
  5957. let w = this.array[index * this.itemSize + 3];
  5958. if (this.normalized) w = denormalize(w, this.array);
  5959. return w;
  5960. }
  5961. setW(index, w) {
  5962. if (this.normalized) w = normalize(w, this.array);
  5963. this.array[index * this.itemSize + 3] = w;
  5964. return this;
  5965. }
  5966. setXY(index, x, y) {
  5967. index *= this.itemSize;
  5968. if (this.normalized) {
  5969. x = normalize(x, this.array);
  5970. y = normalize(y, this.array);
  5971. }
  5972. this.array[index + 0] = x;
  5973. this.array[index + 1] = y;
  5974. return this;
  5975. }
  5976. setXYZ(index, x, y, z) {
  5977. index *= this.itemSize;
  5978. if (this.normalized) {
  5979. x = normalize(x, this.array);
  5980. y = normalize(y, this.array);
  5981. z = normalize(z, this.array);
  5982. }
  5983. this.array[index + 0] = x;
  5984. this.array[index + 1] = y;
  5985. this.array[index + 2] = z;
  5986. return this;
  5987. }
  5988. setXYZW(index, x, y, z, w) {
  5989. index *= this.itemSize;
  5990. if (this.normalized) {
  5991. x = normalize(x, this.array);
  5992. y = normalize(y, this.array);
  5993. z = normalize(z, this.array);
  5994. w = normalize(w, this.array);
  5995. }
  5996. this.array[index + 0] = x;
  5997. this.array[index + 1] = y;
  5998. this.array[index + 2] = z;
  5999. this.array[index + 3] = w;
  6000. return this;
  6001. }
  6002. onUpload(callback) {
  6003. this.onUploadCallback = callback;
  6004. return this;
  6005. }
  6006. clone() {
  6007. return new this.constructor(this.array, this.itemSize).copy(this);
  6008. }
  6009. toJSON() {
  6010. const data = {
  6011. itemSize: this.itemSize,
  6012. type: this.array.constructor.name,
  6013. array: Array.from(this.array),
  6014. normalized: this.normalized
  6015. };
  6016. if (this.name !== '') data.name = this.name;
  6017. if (this.usage !== StaticDrawUsage) data.usage = this.usage;
  6018. if (this.updateRange.offset !== 0 || this.updateRange.count !== -1) data.updateRange = this.updateRange;
  6019. return data;
  6020. } // @deprecated
  6021. copyColorsArray() {
  6022. console.error('THREE.BufferAttribute: copyColorsArray() was removed in r144.');
  6023. }
  6024. copyVector2sArray() {
  6025. console.error('THREE.BufferAttribute: copyVector2sArray() was removed in r144.');
  6026. }
  6027. copyVector3sArray() {
  6028. console.error('THREE.BufferAttribute: copyVector3sArray() was removed in r144.');
  6029. }
  6030. copyVector4sArray() {
  6031. console.error('THREE.BufferAttribute: copyVector4sArray() was removed in r144.');
  6032. }
  6033. } //
  6034. class Int8BufferAttribute extends BufferAttribute {
  6035. constructor(array, itemSize, normalized) {
  6036. super(new Int8Array(array), itemSize, normalized);
  6037. }
  6038. }
  6039. class Uint8BufferAttribute extends BufferAttribute {
  6040. constructor(array, itemSize, normalized) {
  6041. super(new Uint8Array(array), itemSize, normalized);
  6042. }
  6043. }
  6044. class Uint8ClampedBufferAttribute extends BufferAttribute {
  6045. constructor(array, itemSize, normalized) {
  6046. super(new Uint8ClampedArray(array), itemSize, normalized);
  6047. }
  6048. }
  6049. class Int16BufferAttribute extends BufferAttribute {
  6050. constructor(array, itemSize, normalized) {
  6051. super(new Int16Array(array), itemSize, normalized);
  6052. }
  6053. }
  6054. class Uint16BufferAttribute extends BufferAttribute {
  6055. constructor(array, itemSize, normalized) {
  6056. super(new Uint16Array(array), itemSize, normalized);
  6057. }
  6058. }
  6059. class Int32BufferAttribute extends BufferAttribute {
  6060. constructor(array, itemSize, normalized) {
  6061. super(new Int32Array(array), itemSize, normalized);
  6062. }
  6063. }
  6064. class Uint32BufferAttribute extends BufferAttribute {
  6065. constructor(array, itemSize, normalized) {
  6066. super(new Uint32Array(array), itemSize, normalized);
  6067. }
  6068. }
  6069. class Float16BufferAttribute extends BufferAttribute {
  6070. constructor(array, itemSize, normalized) {
  6071. super(new Uint16Array(array), itemSize, normalized);
  6072. this.isFloat16BufferAttribute = true;
  6073. }
  6074. }
  6075. class Float32BufferAttribute extends BufferAttribute {
  6076. constructor(array, itemSize, normalized) {
  6077. super(new Float32Array(array), itemSize, normalized);
  6078. }
  6079. }
  6080. class Float64BufferAttribute extends BufferAttribute {
  6081. constructor(array, itemSize, normalized) {
  6082. super(new Float64Array(array), itemSize, normalized);
  6083. }
  6084. } //
  6085. let _id$1 = 0;
  6086. const _m1 = /*@__PURE__*/new Matrix4();
  6087. const _obj = /*@__PURE__*/new Object3D();
  6088. const _offset = /*@__PURE__*/new Vector3();
  6089. const _box$1 = /*@__PURE__*/new Box3();
  6090. const _boxMorphTargets = /*@__PURE__*/new Box3();
  6091. const _vector$8 = /*@__PURE__*/new Vector3();
  6092. class BufferGeometry extends EventDispatcher {
  6093. constructor() {
  6094. super();
  6095. this.isBufferGeometry = true;
  6096. Object.defineProperty(this, 'id', {
  6097. value: _id$1++
  6098. });
  6099. this.uuid = generateUUID();
  6100. this.name = '';
  6101. this.type = 'BufferGeometry';
  6102. this.index = null;
  6103. this.attributes = {};
  6104. this.morphAttributes = {};
  6105. this.morphTargetsRelative = false;
  6106. this.groups = [];
  6107. this.boundingBox = null;
  6108. this.boundingSphere = null;
  6109. this.drawRange = {
  6110. start: 0,
  6111. count: Infinity
  6112. };
  6113. this.userData = {};
  6114. }
  6115. getIndex() {
  6116. return this.index;
  6117. }
  6118. setIndex(index) {
  6119. if (Array.isArray(index)) {
  6120. this.index = new (arrayNeedsUint32(index) ? Uint32BufferAttribute : Uint16BufferAttribute)(index, 1);
  6121. } else {
  6122. this.index = index;
  6123. }
  6124. return this;
  6125. }
  6126. getAttribute(name) {
  6127. return this.attributes[name];
  6128. }
  6129. setAttribute(name, attribute) {
  6130. this.attributes[name] = attribute;
  6131. return this;
  6132. }
  6133. deleteAttribute(name) {
  6134. delete this.attributes[name];
  6135. return this;
  6136. }
  6137. hasAttribute(name) {
  6138. return this.attributes[name] !== undefined;
  6139. }
  6140. addGroup(start, count, materialIndex = 0) {
  6141. this.groups.push({
  6142. start: start,
  6143. count: count,
  6144. materialIndex: materialIndex
  6145. });
  6146. }
  6147. clearGroups() {
  6148. this.groups = [];
  6149. }
  6150. setDrawRange(start, count) {
  6151. this.drawRange.start = start;
  6152. this.drawRange.count = count;
  6153. }
  6154. applyMatrix4(matrix) {
  6155. const position = this.attributes.position;
  6156. if (position !== undefined) {
  6157. position.applyMatrix4(matrix);
  6158. position.needsUpdate = true;
  6159. }
  6160. const normal = this.attributes.normal;
  6161. if (normal !== undefined) {
  6162. const normalMatrix = new Matrix3().getNormalMatrix(matrix);
  6163. normal.applyNormalMatrix(normalMatrix);
  6164. normal.needsUpdate = true;
  6165. }
  6166. const tangent = this.attributes.tangent;
  6167. if (tangent !== undefined) {
  6168. tangent.transformDirection(matrix);
  6169. tangent.needsUpdate = true;
  6170. }
  6171. if (this.boundingBox !== null) {
  6172. this.computeBoundingBox();
  6173. }
  6174. if (this.boundingSphere !== null) {
  6175. this.computeBoundingSphere();
  6176. }
  6177. return this;
  6178. }
  6179. applyQuaternion(q) {
  6180. _m1.makeRotationFromQuaternion(q);
  6181. this.applyMatrix4(_m1);
  6182. return this;
  6183. }
  6184. rotateX(angle) {
  6185. // rotate geometry around world x-axis
  6186. _m1.makeRotationX(angle);
  6187. this.applyMatrix4(_m1);
  6188. return this;
  6189. }
  6190. rotateY(angle) {
  6191. // rotate geometry around world y-axis
  6192. _m1.makeRotationY(angle);
  6193. this.applyMatrix4(_m1);
  6194. return this;
  6195. }
  6196. rotateZ(angle) {
  6197. // rotate geometry around world z-axis
  6198. _m1.makeRotationZ(angle);
  6199. this.applyMatrix4(_m1);
  6200. return this;
  6201. }
  6202. translate(x, y, z) {
  6203. // translate geometry
  6204. _m1.makeTranslation(x, y, z);
  6205. this.applyMatrix4(_m1);
  6206. return this;
  6207. }
  6208. scale(x, y, z) {
  6209. // scale geometry
  6210. _m1.makeScale(x, y, z);
  6211. this.applyMatrix4(_m1);
  6212. return this;
  6213. }
  6214. lookAt(vector) {
  6215. _obj.lookAt(vector);
  6216. _obj.updateMatrix();
  6217. this.applyMatrix4(_obj.matrix);
  6218. return this;
  6219. }
  6220. center() {
  6221. this.computeBoundingBox();
  6222. this.boundingBox.getCenter(_offset).negate();
  6223. this.translate(_offset.x, _offset.y, _offset.z);
  6224. return this;
  6225. }
  6226. setFromPoints(points) {
  6227. const position = [];
  6228. for (let i = 0, l = points.length; i < l; i++) {
  6229. const point = points[i];
  6230. position.push(point.x, point.y, point.z || 0);
  6231. }
  6232. this.setAttribute('position', new Float32BufferAttribute(position, 3));
  6233. return this;
  6234. }
  6235. computeBoundingBox() {
  6236. if (this.boundingBox === null) {
  6237. this.boundingBox = new Box3();
  6238. }
  6239. const position = this.attributes.position;
  6240. const morphAttributesPosition = this.morphAttributes.position;
  6241. if (position && position.isGLBufferAttribute) {
  6242. console.error('THREE.BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box. Alternatively set "mesh.frustumCulled" to "false".', this);
  6243. this.boundingBox.set(new Vector3(-Infinity, -Infinity, -Infinity), new Vector3(+Infinity, +Infinity, +Infinity));
  6244. return;
  6245. }
  6246. if (position !== undefined) {
  6247. this.boundingBox.setFromBufferAttribute(position); // process morph attributes if present
  6248. if (morphAttributesPosition) {
  6249. for (let i = 0, il = morphAttributesPosition.length; i < il; i++) {
  6250. const morphAttribute = morphAttributesPosition[i];
  6251. _box$1.setFromBufferAttribute(morphAttribute);
  6252. if (this.morphTargetsRelative) {
  6253. _vector$8.addVectors(this.boundingBox.min, _box$1.min);
  6254. this.boundingBox.expandByPoint(_vector$8);
  6255. _vector$8.addVectors(this.boundingBox.max, _box$1.max);
  6256. this.boundingBox.expandByPoint(_vector$8);
  6257. } else {
  6258. this.boundingBox.expandByPoint(_box$1.min);
  6259. this.boundingBox.expandByPoint(_box$1.max);
  6260. }
  6261. }
  6262. }
  6263. } else {
  6264. this.boundingBox.makeEmpty();
  6265. }
  6266. if (isNaN(this.boundingBox.min.x) || isNaN(this.boundingBox.min.y) || isNaN(this.boundingBox.min.z)) {
  6267. console.error('THREE.BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this);
  6268. }
  6269. }
  6270. computeBoundingSphere() {
  6271. if (this.boundingSphere === null) {
  6272. this.boundingSphere = new Sphere();
  6273. }
  6274. const position = this.attributes.position;
  6275. const morphAttributesPosition = this.morphAttributes.position;
  6276. if (position && position.isGLBufferAttribute) {
  6277. console.error('THREE.BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere. Alternatively set "mesh.frustumCulled" to "false".', this);
  6278. this.boundingSphere.set(new Vector3(), Infinity);
  6279. return;
  6280. }
  6281. if (position) {
  6282. // first, find the center of the bounding sphere
  6283. const center = this.boundingSphere.center;
  6284. _box$1.setFromBufferAttribute(position); // process morph attributes if present
  6285. if (morphAttributesPosition) {
  6286. for (let i = 0, il = morphAttributesPosition.length; i < il; i++) {
  6287. const morphAttribute = morphAttributesPosition[i];
  6288. _boxMorphTargets.setFromBufferAttribute(morphAttribute);
  6289. if (this.morphTargetsRelative) {
  6290. _vector$8.addVectors(_box$1.min, _boxMorphTargets.min);
  6291. _box$1.expandByPoint(_vector$8);
  6292. _vector$8.addVectors(_box$1.max, _boxMorphTargets.max);
  6293. _box$1.expandByPoint(_vector$8);
  6294. } else {
  6295. _box$1.expandByPoint(_boxMorphTargets.min);
  6296. _box$1.expandByPoint(_boxMorphTargets.max);
  6297. }
  6298. }
  6299. }
  6300. _box$1.getCenter(center); // second, try to find a boundingSphere with a radius smaller than the
  6301. // boundingSphere of the boundingBox: sqrt(3) smaller in the best case
  6302. let maxRadiusSq = 0;
  6303. for (let i = 0, il = position.count; i < il; i++) {
  6304. _vector$8.fromBufferAttribute(position, i);
  6305. maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(_vector$8));
  6306. } // process morph attributes if present
  6307. if (morphAttributesPosition) {
  6308. for (let i = 0, il = morphAttributesPosition.length; i < il; i++) {
  6309. const morphAttribute = morphAttributesPosition[i];
  6310. const morphTargetsRelative = this.morphTargetsRelative;
  6311. for (let j = 0, jl = morphAttribute.count; j < jl; j++) {
  6312. _vector$8.fromBufferAttribute(morphAttribute, j);
  6313. if (morphTargetsRelative) {
  6314. _offset.fromBufferAttribute(position, j);
  6315. _vector$8.add(_offset);
  6316. }
  6317. maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(_vector$8));
  6318. }
  6319. }
  6320. }
  6321. this.boundingSphere.radius = Math.sqrt(maxRadiusSq);
  6322. if (isNaN(this.boundingSphere.radius)) {
  6323. console.error('THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this);
  6324. }
  6325. }
  6326. }
  6327. computeTangents() {
  6328. const index = this.index;
  6329. const attributes = this.attributes; // based on http://www.terathon.com/code/tangent.html
  6330. // (per vertex tangents)
  6331. if (index === null || attributes.position === undefined || attributes.normal === undefined || attributes.uv === undefined) {
  6332. console.error('THREE.BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)');
  6333. return;
  6334. }
  6335. const indices = index.array;
  6336. const positions = attributes.position.array;
  6337. const normals = attributes.normal.array;
  6338. const uvs = attributes.uv.array;
  6339. const nVertices = positions.length / 3;
  6340. if (this.hasAttribute('tangent') === false) {
  6341. this.setAttribute('tangent', new BufferAttribute(new Float32Array(4 * nVertices), 4));
  6342. }
  6343. const tangents = this.getAttribute('tangent').array;
  6344. const tan1 = [],
  6345. tan2 = [];
  6346. for (let i = 0; i < nVertices; i++) {
  6347. tan1[i] = new Vector3();
  6348. tan2[i] = new Vector3();
  6349. }
  6350. const vA = new Vector3(),
  6351. vB = new Vector3(),
  6352. vC = new Vector3(),
  6353. uvA = new Vector2(),
  6354. uvB = new Vector2(),
  6355. uvC = new Vector2(),
  6356. sdir = new Vector3(),
  6357. tdir = new Vector3();
  6358. function handleTriangle(a, b, c) {
  6359. vA.fromArray(positions, a * 3);
  6360. vB.fromArray(positions, b * 3);
  6361. vC.fromArray(positions, c * 3);
  6362. uvA.fromArray(uvs, a * 2);
  6363. uvB.fromArray(uvs, b * 2);
  6364. uvC.fromArray(uvs, c * 2);
  6365. vB.sub(vA);
  6366. vC.sub(vA);
  6367. uvB.sub(uvA);
  6368. uvC.sub(uvA);
  6369. const r = 1.0 / (uvB.x * uvC.y - uvC.x * uvB.y); // silently ignore degenerate uv triangles having coincident or colinear vertices
  6370. if (!isFinite(r)) return;
  6371. sdir.copy(vB).multiplyScalar(uvC.y).addScaledVector(vC, -uvB.y).multiplyScalar(r);
  6372. tdir.copy(vC).multiplyScalar(uvB.x).addScaledVector(vB, -uvC.x).multiplyScalar(r);
  6373. tan1[a].add(sdir);
  6374. tan1[b].add(sdir);
  6375. tan1[c].add(sdir);
  6376. tan2[a].add(tdir);
  6377. tan2[b].add(tdir);
  6378. tan2[c].add(tdir);
  6379. }
  6380. let groups = this.groups;
  6381. if (groups.length === 0) {
  6382. groups = [{
  6383. start: 0,
  6384. count: indices.length
  6385. }];
  6386. }
  6387. for (let i = 0, il = groups.length; i < il; ++i) {
  6388. const group = groups[i];
  6389. const start = group.start;
  6390. const count = group.count;
  6391. for (let j = start, jl = start + count; j < jl; j += 3) {
  6392. handleTriangle(indices[j + 0], indices[j + 1], indices[j + 2]);
  6393. }
  6394. }
  6395. const tmp = new Vector3(),
  6396. tmp2 = new Vector3();
  6397. const n = new Vector3(),
  6398. n2 = new Vector3();
  6399. function handleVertex(v) {
  6400. n.fromArray(normals, v * 3);
  6401. n2.copy(n);
  6402. const t = tan1[v]; // Gram-Schmidt orthogonalize
  6403. tmp.copy(t);
  6404. tmp.sub(n.multiplyScalar(n.dot(t))).normalize(); // Calculate handedness
  6405. tmp2.crossVectors(n2, t);
  6406. const test = tmp2.dot(tan2[v]);
  6407. const w = test < 0.0 ? -1.0 : 1.0;
  6408. tangents[v * 4] = tmp.x;
  6409. tangents[v * 4 + 1] = tmp.y;
  6410. tangents[v * 4 + 2] = tmp.z;
  6411. tangents[v * 4 + 3] = w;
  6412. }
  6413. for (let i = 0, il = groups.length; i < il; ++i) {
  6414. const group = groups[i];
  6415. const start = group.start;
  6416. const count = group.count;
  6417. for (let j = start, jl = start + count; j < jl; j += 3) {
  6418. handleVertex(indices[j + 0]);
  6419. handleVertex(indices[j + 1]);
  6420. handleVertex(indices[j + 2]);
  6421. }
  6422. }
  6423. }
  6424. computeVertexNormals() {
  6425. const index = this.index;
  6426. const positionAttribute = this.getAttribute('position');
  6427. if (positionAttribute !== undefined) {
  6428. let normalAttribute = this.getAttribute('normal');
  6429. if (normalAttribute === undefined) {
  6430. normalAttribute = new BufferAttribute(new Float32Array(positionAttribute.count * 3), 3);
  6431. this.setAttribute('normal', normalAttribute);
  6432. } else {
  6433. // reset existing normals to zero
  6434. for (let i = 0, il = normalAttribute.count; i < il; i++) {
  6435. normalAttribute.setXYZ(i, 0, 0, 0);
  6436. }
  6437. }
  6438. const pA = new Vector3(),
  6439. pB = new Vector3(),
  6440. pC = new Vector3();
  6441. const nA = new Vector3(),
  6442. nB = new Vector3(),
  6443. nC = new Vector3();
  6444. const cb = new Vector3(),
  6445. ab = new Vector3(); // indexed elements
  6446. if (index) {
  6447. for (let i = 0, il = index.count; i < il; i += 3) {
  6448. const vA = index.getX(i + 0);
  6449. const vB = index.getX(i + 1);
  6450. const vC = index.getX(i + 2);
  6451. pA.fromBufferAttribute(positionAttribute, vA);
  6452. pB.fromBufferAttribute(positionAttribute, vB);
  6453. pC.fromBufferAttribute(positionAttribute, vC);
  6454. cb.subVectors(pC, pB);
  6455. ab.subVectors(pA, pB);
  6456. cb.cross(ab);
  6457. nA.fromBufferAttribute(normalAttribute, vA);
  6458. nB.fromBufferAttribute(normalAttribute, vB);
  6459. nC.fromBufferAttribute(normalAttribute, vC);
  6460. nA.add(cb);
  6461. nB.add(cb);
  6462. nC.add(cb);
  6463. normalAttribute.setXYZ(vA, nA.x, nA.y, nA.z);
  6464. normalAttribute.setXYZ(vB, nB.x, nB.y, nB.z);
  6465. normalAttribute.setXYZ(vC, nC.x, nC.y, nC.z);
  6466. }
  6467. } else {
  6468. // non-indexed elements (unconnected triangle soup)
  6469. for (let i = 0, il = positionAttribute.count; i < il; i += 3) {
  6470. pA.fromBufferAttribute(positionAttribute, i + 0);
  6471. pB.fromBufferAttribute(positionAttribute, i + 1);
  6472. pC.fromBufferAttribute(positionAttribute, i + 2);
  6473. cb.subVectors(pC, pB);
  6474. ab.subVectors(pA, pB);
  6475. cb.cross(ab);
  6476. normalAttribute.setXYZ(i + 0, cb.x, cb.y, cb.z);
  6477. normalAttribute.setXYZ(i + 1, cb.x, cb.y, cb.z);
  6478. normalAttribute.setXYZ(i + 2, cb.x, cb.y, cb.z);
  6479. }
  6480. }
  6481. this.normalizeNormals();
  6482. normalAttribute.needsUpdate = true;
  6483. }
  6484. } // @deprecated since r144
  6485. merge() {
  6486. console.error('THREE.BufferGeometry.merge() has been removed. Use THREE.BufferGeometryUtils.mergeBufferGeometries() instead.');
  6487. return this;
  6488. }
  6489. normalizeNormals() {
  6490. const normals = this.attributes.normal;
  6491. for (let i = 0, il = normals.count; i < il; i++) {
  6492. _vector$8.fromBufferAttribute(normals, i);
  6493. _vector$8.normalize();
  6494. normals.setXYZ(i, _vector$8.x, _vector$8.y, _vector$8.z);
  6495. }
  6496. }
  6497. toNonIndexed() {
  6498. function convertBufferAttribute(attribute, indices) {
  6499. const array = attribute.array;
  6500. const itemSize = attribute.itemSize;
  6501. const normalized = attribute.normalized;
  6502. const array2 = new array.constructor(indices.length * itemSize);
  6503. let index = 0,
  6504. index2 = 0;
  6505. for (let i = 0, l = indices.length; i < l; i++) {
  6506. if (attribute.isInterleavedBufferAttribute) {
  6507. index = indices[i] * attribute.data.stride + attribute.offset;
  6508. } else {
  6509. index = indices[i] * itemSize;
  6510. }
  6511. for (let j = 0; j < itemSize; j++) {
  6512. array2[index2++] = array[index++];
  6513. }
  6514. }
  6515. return new BufferAttribute(array2, itemSize, normalized);
  6516. } //
  6517. if (this.index === null) {
  6518. console.warn('THREE.BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed.');
  6519. return this;
  6520. }
  6521. const geometry2 = new BufferGeometry();
  6522. const indices = this.index.array;
  6523. const attributes = this.attributes; // attributes
  6524. for (const name in attributes) {
  6525. const attribute = attributes[name];
  6526. const newAttribute = convertBufferAttribute(attribute, indices);
  6527. geometry2.setAttribute(name, newAttribute);
  6528. } // morph attributes
  6529. const morphAttributes = this.morphAttributes;
  6530. for (const name in morphAttributes) {
  6531. const morphArray = [];
  6532. const morphAttribute = morphAttributes[name]; // morphAttribute: array of Float32BufferAttributes
  6533. for (let i = 0, il = morphAttribute.length; i < il; i++) {
  6534. const attribute = morphAttribute[i];
  6535. const newAttribute = convertBufferAttribute(attribute, indices);
  6536. morphArray.push(newAttribute);
  6537. }
  6538. geometry2.morphAttributes[name] = morphArray;
  6539. }
  6540. geometry2.morphTargetsRelative = this.morphTargetsRelative; // groups
  6541. const groups = this.groups;
  6542. for (let i = 0, l = groups.length; i < l; i++) {
  6543. const group = groups[i];
  6544. geometry2.addGroup(group.start, group.count, group.materialIndex);
  6545. }
  6546. return geometry2;
  6547. }
  6548. toJSON() {
  6549. const data = {
  6550. metadata: {
  6551. version: 4.5,
  6552. type: 'BufferGeometry',
  6553. generator: 'BufferGeometry.toJSON'
  6554. }
  6555. }; // standard BufferGeometry serialization
  6556. data.uuid = this.uuid;
  6557. data.type = this.type;
  6558. if (this.name !== '') data.name = this.name;
  6559. if (Object.keys(this.userData).length > 0) data.userData = this.userData;
  6560. if (this.parameters !== undefined) {
  6561. const parameters = this.parameters;
  6562. for (const key in parameters) {
  6563. if (parameters[key] !== undefined) data[key] = parameters[key];
  6564. }
  6565. return data;
  6566. } // for simplicity the code assumes attributes are not shared across geometries, see #15811
  6567. data.data = {
  6568. attributes: {}
  6569. };
  6570. const index = this.index;
  6571. if (index !== null) {
  6572. data.data.index = {
  6573. type: index.array.constructor.name,
  6574. array: Array.prototype.slice.call(index.array)
  6575. };
  6576. }
  6577. const attributes = this.attributes;
  6578. for (const key in attributes) {
  6579. const attribute = attributes[key];
  6580. data.data.attributes[key] = attribute.toJSON(data.data);
  6581. }
  6582. const morphAttributes = {};
  6583. let hasMorphAttributes = false;
  6584. for (const key in this.morphAttributes) {
  6585. const attributeArray = this.morphAttributes[key];
  6586. const array = [];
  6587. for (let i = 0, il = attributeArray.length; i < il; i++) {
  6588. const attribute = attributeArray[i];
  6589. array.push(attribute.toJSON(data.data));
  6590. }
  6591. if (array.length > 0) {
  6592. morphAttributes[key] = array;
  6593. hasMorphAttributes = true;
  6594. }
  6595. }
  6596. if (hasMorphAttributes) {
  6597. data.data.morphAttributes = morphAttributes;
  6598. data.data.morphTargetsRelative = this.morphTargetsRelative;
  6599. }
  6600. const groups = this.groups;
  6601. if (groups.length > 0) {
  6602. data.data.groups = JSON.parse(JSON.stringify(groups));
  6603. }
  6604. const boundingSphere = this.boundingSphere;
  6605. if (boundingSphere !== null) {
  6606. data.data.boundingSphere = {
  6607. center: boundingSphere.center.toArray(),
  6608. radius: boundingSphere.radius
  6609. };
  6610. }
  6611. return data;
  6612. }
  6613. clone() {
  6614. return new this.constructor().copy(this);
  6615. }
  6616. copy(source) {
  6617. // reset
  6618. this.index = null;
  6619. this.attributes = {};
  6620. this.morphAttributes = {};
  6621. this.groups = [];
  6622. this.boundingBox = null;
  6623. this.boundingSphere = null; // used for storing cloned, shared data
  6624. const data = {}; // name
  6625. this.name = source.name; // index
  6626. const index = source.index;
  6627. if (index !== null) {
  6628. this.setIndex(index.clone(data));
  6629. } // attributes
  6630. const attributes = source.attributes;
  6631. for (const name in attributes) {
  6632. const attribute = attributes[name];
  6633. this.setAttribute(name, attribute.clone(data));
  6634. } // morph attributes
  6635. const morphAttributes = source.morphAttributes;
  6636. for (const name in morphAttributes) {
  6637. const array = [];
  6638. const morphAttribute = morphAttributes[name]; // morphAttribute: array of Float32BufferAttributes
  6639. for (let i = 0, l = morphAttribute.length; i < l; i++) {
  6640. array.push(morphAttribute[i].clone(data));
  6641. }
  6642. this.morphAttributes[name] = array;
  6643. }
  6644. this.morphTargetsRelative = source.morphTargetsRelative; // groups
  6645. const groups = source.groups;
  6646. for (let i = 0, l = groups.length; i < l; i++) {
  6647. const group = groups[i];
  6648. this.addGroup(group.start, group.count, group.materialIndex);
  6649. } // bounding box
  6650. const boundingBox = source.boundingBox;
  6651. if (boundingBox !== null) {
  6652. this.boundingBox = boundingBox.clone();
  6653. } // bounding sphere
  6654. const boundingSphere = source.boundingSphere;
  6655. if (boundingSphere !== null) {
  6656. this.boundingSphere = boundingSphere.clone();
  6657. } // draw range
  6658. this.drawRange.start = source.drawRange.start;
  6659. this.drawRange.count = source.drawRange.count; // user data
  6660. this.userData = source.userData; // geometry generator parameters
  6661. if (source.parameters !== undefined) this.parameters = Object.assign({}, source.parameters);
  6662. return this;
  6663. }
  6664. dispose() {
  6665. this.dispatchEvent({
  6666. type: 'dispose'
  6667. });
  6668. }
  6669. }
  6670. const _inverseMatrix$2 = /*@__PURE__*/new Matrix4();
  6671. const _ray$2 = /*@__PURE__*/new Ray();
  6672. const _sphere$3 = /*@__PURE__*/new Sphere();
  6673. const _vA$1 = /*@__PURE__*/new Vector3();
  6674. const _vB$1 = /*@__PURE__*/new Vector3();
  6675. const _vC$1 = /*@__PURE__*/new Vector3();
  6676. const _tempA = /*@__PURE__*/new Vector3();
  6677. const _tempB = /*@__PURE__*/new Vector3();
  6678. const _tempC = /*@__PURE__*/new Vector3();
  6679. const _morphA = /*@__PURE__*/new Vector3();
  6680. const _morphB = /*@__PURE__*/new Vector3();
  6681. const _morphC = /*@__PURE__*/new Vector3();
  6682. const _uvA$1 = /*@__PURE__*/new Vector2();
  6683. const _uvB$1 = /*@__PURE__*/new Vector2();
  6684. const _uvC$1 = /*@__PURE__*/new Vector2();
  6685. const _intersectionPoint = /*@__PURE__*/new Vector3();
  6686. const _intersectionPointWorld = /*@__PURE__*/new Vector3();
  6687. class Mesh extends Object3D {
  6688. constructor(geometry = new BufferGeometry(), material = new MeshBasicMaterial()) {
  6689. super();
  6690. this.isMesh = true;
  6691. this.type = 'Mesh';
  6692. this.geometry = geometry;
  6693. this.material = material;
  6694. this.updateMorphTargets();
  6695. }
  6696. copy(source, recursive) {
  6697. super.copy(source, recursive);
  6698. if (source.morphTargetInfluences !== undefined) {
  6699. this.morphTargetInfluences = source.morphTargetInfluences.slice();
  6700. }
  6701. if (source.morphTargetDictionary !== undefined) {
  6702. this.morphTargetDictionary = Object.assign({}, source.morphTargetDictionary);
  6703. }
  6704. this.material = source.material;
  6705. this.geometry = source.geometry;
  6706. return this;
  6707. }
  6708. updateMorphTargets() {
  6709. const geometry = this.geometry;
  6710. const morphAttributes = geometry.morphAttributes;
  6711. const keys = Object.keys(morphAttributes);
  6712. if (keys.length > 0) {
  6713. const morphAttribute = morphAttributes[keys[0]];
  6714. if (morphAttribute !== undefined) {
  6715. this.morphTargetInfluences = [];
  6716. this.morphTargetDictionary = {};
  6717. for (let m = 0, ml = morphAttribute.length; m < ml; m++) {
  6718. const name = morphAttribute[m].name || String(m);
  6719. this.morphTargetInfluences.push(0);
  6720. this.morphTargetDictionary[name] = m;
  6721. }
  6722. }
  6723. }
  6724. }
  6725. raycast(raycaster, intersects) {
  6726. const geometry = this.geometry;
  6727. const material = this.material;
  6728. const matrixWorld = this.matrixWorld;
  6729. if (material === undefined) return; // Checking boundingSphere distance to ray
  6730. if (geometry.boundingSphere === null) geometry.computeBoundingSphere();
  6731. _sphere$3.copy(geometry.boundingSphere);
  6732. _sphere$3.applyMatrix4(matrixWorld);
  6733. if (raycaster.ray.intersectsSphere(_sphere$3) === false) return; //
  6734. _inverseMatrix$2.copy(matrixWorld).invert();
  6735. _ray$2.copy(raycaster.ray).applyMatrix4(_inverseMatrix$2); // Check boundingBox before continuing
  6736. if (geometry.boundingBox !== null) {
  6737. if (_ray$2.intersectsBox(geometry.boundingBox) === false) return;
  6738. }
  6739. let intersection;
  6740. const index = geometry.index;
  6741. const position = geometry.attributes.position;
  6742. const morphPosition = geometry.morphAttributes.position;
  6743. const morphTargetsRelative = geometry.morphTargetsRelative;
  6744. const uv = geometry.attributes.uv;
  6745. const uv2 = geometry.attributes.uv2;
  6746. const groups = geometry.groups;
  6747. const drawRange = geometry.drawRange;
  6748. if (index !== null) {
  6749. // indexed buffer geometry
  6750. if (Array.isArray(material)) {
  6751. for (let i = 0, il = groups.length; i < il; i++) {
  6752. const group = groups[i];
  6753. const groupMaterial = material[group.materialIndex];
  6754. const start = Math.max(group.start, drawRange.start);
  6755. const end = Math.min(index.count, Math.min(group.start + group.count, drawRange.start + drawRange.count));
  6756. for (let j = start, jl = end; j < jl; j += 3) {
  6757. const a = index.getX(j);
  6758. const b = index.getX(j + 1);
  6759. const c = index.getX(j + 2);
  6760. intersection = checkBufferGeometryIntersection(this, groupMaterial, raycaster, _ray$2, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c);
  6761. if (intersection) {
  6762. intersection.faceIndex = Math.floor(j / 3); // triangle number in indexed buffer semantics
  6763. intersection.face.materialIndex = group.materialIndex;
  6764. intersects.push(intersection);
  6765. }
  6766. }
  6767. }
  6768. } else {
  6769. const start = Math.max(0, drawRange.start);
  6770. const end = Math.min(index.count, drawRange.start + drawRange.count);
  6771. for (let i = start, il = end; i < il; i += 3) {
  6772. const a = index.getX(i);
  6773. const b = index.getX(i + 1);
  6774. const c = index.getX(i + 2);
  6775. intersection = checkBufferGeometryIntersection(this, material, raycaster, _ray$2, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c);
  6776. if (intersection) {
  6777. intersection.faceIndex = Math.floor(i / 3); // triangle number in indexed buffer semantics
  6778. intersects.push(intersection);
  6779. }
  6780. }
  6781. }
  6782. } else if (position !== undefined) {
  6783. // non-indexed buffer geometry
  6784. if (Array.isArray(material)) {
  6785. for (let i = 0, il = groups.length; i < il; i++) {
  6786. const group = groups[i];
  6787. const groupMaterial = material[group.materialIndex];
  6788. const start = Math.max(group.start, drawRange.start);
  6789. const end = Math.min(position.count, Math.min(group.start + group.count, drawRange.start + drawRange.count));
  6790. for (let j = start, jl = end; j < jl; j += 3) {
  6791. const a = j;
  6792. const b = j + 1;
  6793. const c = j + 2;
  6794. intersection = checkBufferGeometryIntersection(this, groupMaterial, raycaster, _ray$2, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c);
  6795. if (intersection) {
  6796. intersection.faceIndex = Math.floor(j / 3); // triangle number in non-indexed buffer semantics
  6797. intersection.face.materialIndex = group.materialIndex;
  6798. intersects.push(intersection);
  6799. }
  6800. }
  6801. }
  6802. } else {
  6803. const start = Math.max(0, drawRange.start);
  6804. const end = Math.min(position.count, drawRange.start + drawRange.count);
  6805. for (let i = start, il = end; i < il; i += 3) {
  6806. const a = i;
  6807. const b = i + 1;
  6808. const c = i + 2;
  6809. intersection = checkBufferGeometryIntersection(this, material, raycaster, _ray$2, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c);
  6810. if (intersection) {
  6811. intersection.faceIndex = Math.floor(i / 3); // triangle number in non-indexed buffer semantics
  6812. intersects.push(intersection);
  6813. }
  6814. }
  6815. }
  6816. }
  6817. }
  6818. }
  6819. function checkIntersection(object, material, raycaster, ray, pA, pB, pC, point) {
  6820. let intersect;
  6821. if (material.side === BackSide) {
  6822. intersect = ray.intersectTriangle(pC, pB, pA, true, point);
  6823. } else {
  6824. intersect = ray.intersectTriangle(pA, pB, pC, material.side !== DoubleSide, point);
  6825. }
  6826. if (intersect === null) return null;
  6827. _intersectionPointWorld.copy(point);
  6828. _intersectionPointWorld.applyMatrix4(object.matrixWorld);
  6829. const distance = raycaster.ray.origin.distanceTo(_intersectionPointWorld);
  6830. if (distance < raycaster.near || distance > raycaster.far) return null;
  6831. return {
  6832. distance: distance,
  6833. point: _intersectionPointWorld.clone(),
  6834. object: object
  6835. };
  6836. }
  6837. function checkBufferGeometryIntersection(object, material, raycaster, ray, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c) {
  6838. _vA$1.fromBufferAttribute(position, a);
  6839. _vB$1.fromBufferAttribute(position, b);
  6840. _vC$1.fromBufferAttribute(position, c);
  6841. const morphInfluences = object.morphTargetInfluences;
  6842. if (morphPosition && morphInfluences) {
  6843. _morphA.set(0, 0, 0);
  6844. _morphB.set(0, 0, 0);
  6845. _morphC.set(0, 0, 0);
  6846. for (let i = 0, il = morphPosition.length; i < il; i++) {
  6847. const influence = morphInfluences[i];
  6848. const morphAttribute = morphPosition[i];
  6849. if (influence === 0) continue;
  6850. _tempA.fromBufferAttribute(morphAttribute, a);
  6851. _tempB.fromBufferAttribute(morphAttribute, b);
  6852. _tempC.fromBufferAttribute(morphAttribute, c);
  6853. if (morphTargetsRelative) {
  6854. _morphA.addScaledVector(_tempA, influence);
  6855. _morphB.addScaledVector(_tempB, influence);
  6856. _morphC.addScaledVector(_tempC, influence);
  6857. } else {
  6858. _morphA.addScaledVector(_tempA.sub(_vA$1), influence);
  6859. _morphB.addScaledVector(_tempB.sub(_vB$1), influence);
  6860. _morphC.addScaledVector(_tempC.sub(_vC$1), influence);
  6861. }
  6862. }
  6863. _vA$1.add(_morphA);
  6864. _vB$1.add(_morphB);
  6865. _vC$1.add(_morphC);
  6866. }
  6867. if (object.isSkinnedMesh) {
  6868. object.boneTransform(a, _vA$1);
  6869. object.boneTransform(b, _vB$1);
  6870. object.boneTransform(c, _vC$1);
  6871. }
  6872. const intersection = checkIntersection(object, material, raycaster, ray, _vA$1, _vB$1, _vC$1, _intersectionPoint);
  6873. if (intersection) {
  6874. if (uv) {
  6875. _uvA$1.fromBufferAttribute(uv, a);
  6876. _uvB$1.fromBufferAttribute(uv, b);
  6877. _uvC$1.fromBufferAttribute(uv, c);
  6878. intersection.uv = Triangle.getUV(_intersectionPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2());
  6879. }
  6880. if (uv2) {
  6881. _uvA$1.fromBufferAttribute(uv2, a);
  6882. _uvB$1.fromBufferAttribute(uv2, b);
  6883. _uvC$1.fromBufferAttribute(uv2, c);
  6884. intersection.uv2 = Triangle.getUV(_intersectionPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2());
  6885. }
  6886. const face = {
  6887. a: a,
  6888. b: b,
  6889. c: c,
  6890. normal: new Vector3(),
  6891. materialIndex: 0
  6892. };
  6893. Triangle.getNormal(_vA$1, _vB$1, _vC$1, face.normal);
  6894. intersection.face = face;
  6895. }
  6896. return intersection;
  6897. }
  6898. class BoxGeometry extends BufferGeometry {
  6899. constructor(width = 1, height = 1, depth = 1, widthSegments = 1, heightSegments = 1, depthSegments = 1) {
  6900. super();
  6901. this.type = 'BoxGeometry';
  6902. this.parameters = {
  6903. width: width,
  6904. height: height,
  6905. depth: depth,
  6906. widthSegments: widthSegments,
  6907. heightSegments: heightSegments,
  6908. depthSegments: depthSegments
  6909. };
  6910. const scope = this; // segments
  6911. widthSegments = Math.floor(widthSegments);
  6912. heightSegments = Math.floor(heightSegments);
  6913. depthSegments = Math.floor(depthSegments); // buffers
  6914. const indices = [];
  6915. const vertices = [];
  6916. const normals = [];
  6917. const uvs = []; // helper variables
  6918. let numberOfVertices = 0;
  6919. let groupStart = 0; // build each side of the box geometry
  6920. buildPlane('z', 'y', 'x', -1, -1, depth, height, width, depthSegments, heightSegments, 0); // px
  6921. buildPlane('z', 'y', 'x', 1, -1, depth, height, -width, depthSegments, heightSegments, 1); // nx
  6922. buildPlane('x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2); // py
  6923. buildPlane('x', 'z', 'y', 1, -1, width, depth, -height, widthSegments, depthSegments, 3); // ny
  6924. buildPlane('x', 'y', 'z', 1, -1, width, height, depth, widthSegments, heightSegments, 4); // pz
  6925. buildPlane('x', 'y', 'z', -1, -1, width, height, -depth, widthSegments, heightSegments, 5); // nz
  6926. // build geometry
  6927. this.setIndex(indices);
  6928. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  6929. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  6930. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  6931. function buildPlane(u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex) {
  6932. const segmentWidth = width / gridX;
  6933. const segmentHeight = height / gridY;
  6934. const widthHalf = width / 2;
  6935. const heightHalf = height / 2;
  6936. const depthHalf = depth / 2;
  6937. const gridX1 = gridX + 1;
  6938. const gridY1 = gridY + 1;
  6939. let vertexCounter = 0;
  6940. let groupCount = 0;
  6941. const vector = new Vector3(); // generate vertices, normals and uvs
  6942. for (let iy = 0; iy < gridY1; iy++) {
  6943. const y = iy * segmentHeight - heightHalf;
  6944. for (let ix = 0; ix < gridX1; ix++) {
  6945. const x = ix * segmentWidth - widthHalf; // set values to correct vector component
  6946. vector[u] = x * udir;
  6947. vector[v] = y * vdir;
  6948. vector[w] = depthHalf; // now apply vector to vertex buffer
  6949. vertices.push(vector.x, vector.y, vector.z); // set values to correct vector component
  6950. vector[u] = 0;
  6951. vector[v] = 0;
  6952. vector[w] = depth > 0 ? 1 : -1; // now apply vector to normal buffer
  6953. normals.push(vector.x, vector.y, vector.z); // uvs
  6954. uvs.push(ix / gridX);
  6955. uvs.push(1 - iy / gridY); // counters
  6956. vertexCounter += 1;
  6957. }
  6958. } // indices
  6959. // 1. you need three indices to draw a single face
  6960. // 2. a single segment consists of two faces
  6961. // 3. so we need to generate six (2*3) indices per segment
  6962. for (let iy = 0; iy < gridY; iy++) {
  6963. for (let ix = 0; ix < gridX; ix++) {
  6964. const a = numberOfVertices + ix + gridX1 * iy;
  6965. const b = numberOfVertices + ix + gridX1 * (iy + 1);
  6966. const c = numberOfVertices + (ix + 1) + gridX1 * (iy + 1);
  6967. const d = numberOfVertices + (ix + 1) + gridX1 * iy; // faces
  6968. indices.push(a, b, d);
  6969. indices.push(b, c, d); // increase counter
  6970. groupCount += 6;
  6971. }
  6972. } // add a group to the geometry. this will ensure multi material support
  6973. scope.addGroup(groupStart, groupCount, materialIndex); // calculate new start value for groups
  6974. groupStart += groupCount; // update total number of vertices
  6975. numberOfVertices += vertexCounter;
  6976. }
  6977. }
  6978. static fromJSON(data) {
  6979. return new BoxGeometry(data.width, data.height, data.depth, data.widthSegments, data.heightSegments, data.depthSegments);
  6980. }
  6981. }
  6982. /**
  6983. * Uniform Utilities
  6984. */
  6985. function cloneUniforms(src) {
  6986. const dst = {};
  6987. for (const u in src) {
  6988. dst[u] = {};
  6989. for (const p in src[u]) {
  6990. const property = src[u][p];
  6991. if (property && (property.isColor || property.isMatrix3 || property.isMatrix4 || property.isVector2 || property.isVector3 || property.isVector4 || property.isTexture || property.isQuaternion)) {
  6992. dst[u][p] = property.clone();
  6993. } else if (Array.isArray(property)) {
  6994. dst[u][p] = property.slice();
  6995. } else {
  6996. dst[u][p] = property;
  6997. }
  6998. }
  6999. }
  7000. return dst;
  7001. }
  7002. function mergeUniforms(uniforms) {
  7003. const merged = {};
  7004. for (let u = 0; u < uniforms.length; u++) {
  7005. const tmp = cloneUniforms(uniforms[u]);
  7006. for (const p in tmp) {
  7007. merged[p] = tmp[p];
  7008. }
  7009. }
  7010. return merged;
  7011. }
  7012. function cloneUniformsGroups(src) {
  7013. const dst = [];
  7014. for (let u = 0; u < src.length; u++) {
  7015. dst.push(src[u].clone());
  7016. }
  7017. return dst;
  7018. } // Legacy
  7019. const UniformsUtils = {
  7020. clone: cloneUniforms,
  7021. merge: mergeUniforms
  7022. };
  7023. var default_vertex = "void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}";
  7024. var default_fragment = "void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}";
  7025. class ShaderMaterial extends Material {
  7026. constructor(parameters) {
  7027. super();
  7028. this.isShaderMaterial = true;
  7029. this.type = 'ShaderMaterial';
  7030. this.defines = {};
  7031. this.uniforms = {};
  7032. this.uniformsGroups = [];
  7033. this.vertexShader = default_vertex;
  7034. this.fragmentShader = default_fragment;
  7035. this.linewidth = 1;
  7036. this.wireframe = false;
  7037. this.wireframeLinewidth = 1;
  7038. this.fog = false; // set to use scene fog
  7039. this.lights = false; // set to use scene lights
  7040. this.clipping = false; // set to use user-defined clipping planes
  7041. this.extensions = {
  7042. derivatives: false,
  7043. // set to use derivatives
  7044. fragDepth: false,
  7045. // set to use fragment depth values
  7046. drawBuffers: false,
  7047. // set to use draw buffers
  7048. shaderTextureLOD: false // set to use shader texture LOD
  7049. }; // When rendered geometry doesn't include these attributes but the material does,
  7050. // use these default values in WebGL. This avoids errors when buffer data is missing.
  7051. this.defaultAttributeValues = {
  7052. 'color': [1, 1, 1],
  7053. 'uv': [0, 0],
  7054. 'uv2': [0, 0]
  7055. };
  7056. this.index0AttributeName = undefined;
  7057. this.uniformsNeedUpdate = false;
  7058. this.glslVersion = null;
  7059. if (parameters !== undefined) {
  7060. this.setValues(parameters);
  7061. }
  7062. }
  7063. copy(source) {
  7064. super.copy(source);
  7065. this.fragmentShader = source.fragmentShader;
  7066. this.vertexShader = source.vertexShader;
  7067. this.uniforms = cloneUniforms(source.uniforms);
  7068. this.uniformsGroups = cloneUniformsGroups(source.uniformsGroups);
  7069. this.defines = Object.assign({}, source.defines);
  7070. this.wireframe = source.wireframe;
  7071. this.wireframeLinewidth = source.wireframeLinewidth;
  7072. this.fog = source.fog;
  7073. this.lights = source.lights;
  7074. this.clipping = source.clipping;
  7075. this.extensions = Object.assign({}, source.extensions);
  7076. this.glslVersion = source.glslVersion;
  7077. return this;
  7078. }
  7079. toJSON(meta) {
  7080. const data = super.toJSON(meta);
  7081. data.glslVersion = this.glslVersion;
  7082. data.uniforms = {};
  7083. for (const name in this.uniforms) {
  7084. const uniform = this.uniforms[name];
  7085. const value = uniform.value;
  7086. if (value && value.isTexture) {
  7087. data.uniforms[name] = {
  7088. type: 't',
  7089. value: value.toJSON(meta).uuid
  7090. };
  7091. } else if (value && value.isColor) {
  7092. data.uniforms[name] = {
  7093. type: 'c',
  7094. value: value.getHex()
  7095. };
  7096. } else if (value && value.isVector2) {
  7097. data.uniforms[name] = {
  7098. type: 'v2',
  7099. value: value.toArray()
  7100. };
  7101. } else if (value && value.isVector3) {
  7102. data.uniforms[name] = {
  7103. type: 'v3',
  7104. value: value.toArray()
  7105. };
  7106. } else if (value && value.isVector4) {
  7107. data.uniforms[name] = {
  7108. type: 'v4',
  7109. value: value.toArray()
  7110. };
  7111. } else if (value && value.isMatrix3) {
  7112. data.uniforms[name] = {
  7113. type: 'm3',
  7114. value: value.toArray()
  7115. };
  7116. } else if (value && value.isMatrix4) {
  7117. data.uniforms[name] = {
  7118. type: 'm4',
  7119. value: value.toArray()
  7120. };
  7121. } else {
  7122. data.uniforms[name] = {
  7123. value: value
  7124. }; // note: the array variants v2v, v3v, v4v, m4v and tv are not supported so far
  7125. }
  7126. }
  7127. if (Object.keys(this.defines).length > 0) data.defines = this.defines;
  7128. data.vertexShader = this.vertexShader;
  7129. data.fragmentShader = this.fragmentShader;
  7130. const extensions = {};
  7131. for (const key in this.extensions) {
  7132. if (this.extensions[key] === true) extensions[key] = true;
  7133. }
  7134. if (Object.keys(extensions).length > 0) data.extensions = extensions;
  7135. return data;
  7136. }
  7137. }
  7138. class Camera extends Object3D {
  7139. constructor() {
  7140. super();
  7141. this.isCamera = true;
  7142. this.type = 'Camera';
  7143. this.matrixWorldInverse = new Matrix4();
  7144. this.projectionMatrix = new Matrix4();
  7145. this.projectionMatrixInverse = new Matrix4();
  7146. }
  7147. copy(source, recursive) {
  7148. super.copy(source, recursive);
  7149. this.matrixWorldInverse.copy(source.matrixWorldInverse);
  7150. this.projectionMatrix.copy(source.projectionMatrix);
  7151. this.projectionMatrixInverse.copy(source.projectionMatrixInverse);
  7152. return this;
  7153. }
  7154. getWorldDirection(target) {
  7155. this.updateWorldMatrix(true, false);
  7156. const e = this.matrixWorld.elements;
  7157. return target.set(-e[8], -e[9], -e[10]).normalize();
  7158. }
  7159. updateMatrixWorld(force) {
  7160. super.updateMatrixWorld(force);
  7161. this.matrixWorldInverse.copy(this.matrixWorld).invert();
  7162. }
  7163. updateWorldMatrix(updateParents, updateChildren) {
  7164. super.updateWorldMatrix(updateParents, updateChildren);
  7165. this.matrixWorldInverse.copy(this.matrixWorld).invert();
  7166. }
  7167. clone() {
  7168. return new this.constructor().copy(this);
  7169. }
  7170. }
  7171. class PerspectiveCamera extends Camera {
  7172. constructor(fov = 50, aspect = 1, near = 0.1, far = 2000) {
  7173. super();
  7174. this.isPerspectiveCamera = true;
  7175. this.type = 'PerspectiveCamera';
  7176. this.fov = fov;
  7177. this.zoom = 1;
  7178. this.near = near;
  7179. this.far = far;
  7180. this.focus = 10;
  7181. this.aspect = aspect;
  7182. this.view = null;
  7183. this.filmGauge = 35; // width of the film (default in millimeters)
  7184. this.filmOffset = 0; // horizontal film offset (same unit as gauge)
  7185. this.updateProjectionMatrix();
  7186. }
  7187. copy(source, recursive) {
  7188. super.copy(source, recursive);
  7189. this.fov = source.fov;
  7190. this.zoom = source.zoom;
  7191. this.near = source.near;
  7192. this.far = source.far;
  7193. this.focus = source.focus;
  7194. this.aspect = source.aspect;
  7195. this.view = source.view === null ? null : Object.assign({}, source.view);
  7196. this.filmGauge = source.filmGauge;
  7197. this.filmOffset = source.filmOffset;
  7198. return this;
  7199. }
  7200. /**
  7201. * Sets the FOV by focal length in respect to the current .filmGauge.
  7202. *
  7203. * The default film gauge is 35, so that the focal length can be specified for
  7204. * a 35mm (full frame) camera.
  7205. *
  7206. * Values for focal length and film gauge must have the same unit.
  7207. */
  7208. setFocalLength(focalLength) {
  7209. /** see {@link http://www.bobatkins.com/photography/technical/field_of_view.html} */
  7210. const vExtentSlope = 0.5 * this.getFilmHeight() / focalLength;
  7211. this.fov = RAD2DEG * 2 * Math.atan(vExtentSlope);
  7212. this.updateProjectionMatrix();
  7213. }
  7214. /**
  7215. * Calculates the focal length from the current .fov and .filmGauge.
  7216. */
  7217. getFocalLength() {
  7218. const vExtentSlope = Math.tan(DEG2RAD * 0.5 * this.fov);
  7219. return 0.5 * this.getFilmHeight() / vExtentSlope;
  7220. }
  7221. getEffectiveFOV() {
  7222. return RAD2DEG * 2 * Math.atan(Math.tan(DEG2RAD * 0.5 * this.fov) / this.zoom);
  7223. }
  7224. getFilmWidth() {
  7225. // film not completely covered in portrait format (aspect < 1)
  7226. return this.filmGauge * Math.min(this.aspect, 1);
  7227. }
  7228. getFilmHeight() {
  7229. // film not completely covered in landscape format (aspect > 1)
  7230. return this.filmGauge / Math.max(this.aspect, 1);
  7231. }
  7232. /**
  7233. * Sets an offset in a larger frustum. This is useful for multi-window or
  7234. * multi-monitor/multi-machine setups.
  7235. *
  7236. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  7237. * the monitors are in grid like this
  7238. *
  7239. * +---+---+---+
  7240. * | A | B | C |
  7241. * +---+---+---+
  7242. * | D | E | F |
  7243. * +---+---+---+
  7244. *
  7245. * then for each monitor you would call it like this
  7246. *
  7247. * const w = 1920;
  7248. * const h = 1080;
  7249. * const fullWidth = w * 3;
  7250. * const fullHeight = h * 2;
  7251. *
  7252. * --A--
  7253. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  7254. * --B--
  7255. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  7256. * --C--
  7257. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  7258. * --D--
  7259. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  7260. * --E--
  7261. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  7262. * --F--
  7263. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  7264. *
  7265. * Note there is no reason monitors have to be the same size or in a grid.
  7266. */
  7267. setViewOffset(fullWidth, fullHeight, x, y, width, height) {
  7268. this.aspect = fullWidth / fullHeight;
  7269. if (this.view === null) {
  7270. this.view = {
  7271. enabled: true,
  7272. fullWidth: 1,
  7273. fullHeight: 1,
  7274. offsetX: 0,
  7275. offsetY: 0,
  7276. width: 1,
  7277. height: 1
  7278. };
  7279. }
  7280. this.view.enabled = true;
  7281. this.view.fullWidth = fullWidth;
  7282. this.view.fullHeight = fullHeight;
  7283. this.view.offsetX = x;
  7284. this.view.offsetY = y;
  7285. this.view.width = width;
  7286. this.view.height = height;
  7287. this.updateProjectionMatrix();
  7288. }
  7289. clearViewOffset() {
  7290. if (this.view !== null) {
  7291. this.view.enabled = false;
  7292. }
  7293. this.updateProjectionMatrix();
  7294. }
  7295. updateProjectionMatrix() {
  7296. const near = this.near;
  7297. let top = near * Math.tan(DEG2RAD * 0.5 * this.fov) / this.zoom;
  7298. let height = 2 * top;
  7299. let width = this.aspect * height;
  7300. let left = -0.5 * width;
  7301. const view = this.view;
  7302. if (this.view !== null && this.view.enabled) {
  7303. const fullWidth = view.fullWidth,
  7304. fullHeight = view.fullHeight;
  7305. left += view.offsetX * width / fullWidth;
  7306. top -= view.offsetY * height / fullHeight;
  7307. width *= view.width / fullWidth;
  7308. height *= view.height / fullHeight;
  7309. }
  7310. const skew = this.filmOffset;
  7311. if (skew !== 0) left += near * skew / this.getFilmWidth();
  7312. this.projectionMatrix.makePerspective(left, left + width, top, top - height, near, this.far);
  7313. this.projectionMatrixInverse.copy(this.projectionMatrix).invert();
  7314. }
  7315. toJSON(meta) {
  7316. const data = super.toJSON(meta);
  7317. data.object.fov = this.fov;
  7318. data.object.zoom = this.zoom;
  7319. data.object.near = this.near;
  7320. data.object.far = this.far;
  7321. data.object.focus = this.focus;
  7322. data.object.aspect = this.aspect;
  7323. if (this.view !== null) data.object.view = Object.assign({}, this.view);
  7324. data.object.filmGauge = this.filmGauge;
  7325. data.object.filmOffset = this.filmOffset;
  7326. return data;
  7327. }
  7328. }
  7329. const fov = 90,
  7330. aspect = 1;
  7331. class CubeCamera extends Object3D {
  7332. constructor(near, far, renderTarget) {
  7333. super();
  7334. this.type = 'CubeCamera';
  7335. this.renderTarget = renderTarget;
  7336. const cameraPX = new PerspectiveCamera(fov, aspect, near, far);
  7337. cameraPX.layers = this.layers;
  7338. cameraPX.up.set(0, -1, 0);
  7339. cameraPX.lookAt(new Vector3(1, 0, 0));
  7340. this.add(cameraPX);
  7341. const cameraNX = new PerspectiveCamera(fov, aspect, near, far);
  7342. cameraNX.layers = this.layers;
  7343. cameraNX.up.set(0, -1, 0);
  7344. cameraNX.lookAt(new Vector3(-1, 0, 0));
  7345. this.add(cameraNX);
  7346. const cameraPY = new PerspectiveCamera(fov, aspect, near, far);
  7347. cameraPY.layers = this.layers;
  7348. cameraPY.up.set(0, 0, 1);
  7349. cameraPY.lookAt(new Vector3(0, 1, 0));
  7350. this.add(cameraPY);
  7351. const cameraNY = new PerspectiveCamera(fov, aspect, near, far);
  7352. cameraNY.layers = this.layers;
  7353. cameraNY.up.set(0, 0, -1);
  7354. cameraNY.lookAt(new Vector3(0, -1, 0));
  7355. this.add(cameraNY);
  7356. const cameraPZ = new PerspectiveCamera(fov, aspect, near, far);
  7357. cameraPZ.layers = this.layers;
  7358. cameraPZ.up.set(0, -1, 0);
  7359. cameraPZ.lookAt(new Vector3(0, 0, 1));
  7360. this.add(cameraPZ);
  7361. const cameraNZ = new PerspectiveCamera(fov, aspect, near, far);
  7362. cameraNZ.layers = this.layers;
  7363. cameraNZ.up.set(0, -1, 0);
  7364. cameraNZ.lookAt(new Vector3(0, 0, -1));
  7365. this.add(cameraNZ);
  7366. }
  7367. update(renderer, scene) {
  7368. if (this.parent === null) this.updateMatrixWorld();
  7369. const renderTarget = this.renderTarget;
  7370. const [cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ] = this.children;
  7371. const currentRenderTarget = renderer.getRenderTarget();
  7372. const currentToneMapping = renderer.toneMapping;
  7373. const currentXrEnabled = renderer.xr.enabled;
  7374. renderer.toneMapping = NoToneMapping;
  7375. renderer.xr.enabled = false;
  7376. const generateMipmaps = renderTarget.texture.generateMipmaps;
  7377. renderTarget.texture.generateMipmaps = false;
  7378. renderer.setRenderTarget(renderTarget, 0);
  7379. renderer.render(scene, cameraPX);
  7380. renderer.setRenderTarget(renderTarget, 1);
  7381. renderer.render(scene, cameraNX);
  7382. renderer.setRenderTarget(renderTarget, 2);
  7383. renderer.render(scene, cameraPY);
  7384. renderer.setRenderTarget(renderTarget, 3);
  7385. renderer.render(scene, cameraNY);
  7386. renderer.setRenderTarget(renderTarget, 4);
  7387. renderer.render(scene, cameraPZ);
  7388. renderTarget.texture.generateMipmaps = generateMipmaps;
  7389. renderer.setRenderTarget(renderTarget, 5);
  7390. renderer.render(scene, cameraNZ);
  7391. renderer.setRenderTarget(currentRenderTarget);
  7392. renderer.toneMapping = currentToneMapping;
  7393. renderer.xr.enabled = currentXrEnabled;
  7394. renderTarget.texture.needsPMREMUpdate = true;
  7395. }
  7396. }
  7397. class CubeTexture extends Texture {
  7398. constructor(images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding) {
  7399. images = images !== undefined ? images : [];
  7400. mapping = mapping !== undefined ? mapping : CubeReflectionMapping;
  7401. super(images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding);
  7402. this.isCubeTexture = true;
  7403. this.flipY = false;
  7404. }
  7405. get images() {
  7406. return this.image;
  7407. }
  7408. set images(value) {
  7409. this.image = value;
  7410. }
  7411. }
  7412. class WebGLCubeRenderTarget extends WebGLRenderTarget {
  7413. constructor(size, options = {}) {
  7414. super(size, size, options);
  7415. this.isWebGLCubeRenderTarget = true;
  7416. const image = {
  7417. width: size,
  7418. height: size,
  7419. depth: 1
  7420. };
  7421. const images = [image, image, image, image, image, image];
  7422. this.texture = new CubeTexture(images, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding); // By convention -- likely based on the RenderMan spec from the 1990's -- cube maps are specified by WebGL (and three.js)
  7423. // in a coordinate system in which positive-x is to the right when looking up the positive-z axis -- in other words,
  7424. // in a left-handed coordinate system. By continuing this convention, preexisting cube maps continued to render correctly.
  7425. // three.js uses a right-handed coordinate system. So environment maps used in three.js appear to have px and nx swapped
  7426. // and the flag isRenderTargetTexture controls this conversion. The flip is not required when using WebGLCubeRenderTarget.texture
  7427. // as a cube texture (this is detected when isRenderTargetTexture is set to true for cube textures).
  7428. this.texture.isRenderTargetTexture = true;
  7429. this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false;
  7430. this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter;
  7431. }
  7432. fromEquirectangularTexture(renderer, texture) {
  7433. this.texture.type = texture.type;
  7434. this.texture.encoding = texture.encoding;
  7435. this.texture.generateMipmaps = texture.generateMipmaps;
  7436. this.texture.minFilter = texture.minFilter;
  7437. this.texture.magFilter = texture.magFilter;
  7438. const shader = {
  7439. uniforms: {
  7440. tEquirect: {
  7441. value: null
  7442. }
  7443. },
  7444. vertexShader:
  7445. /* glsl */
  7446. `
  7447. varying vec3 vWorldDirection;
  7448. vec3 transformDirection( in vec3 dir, in mat4 matrix ) {
  7449. return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );
  7450. }
  7451. void main() {
  7452. vWorldDirection = transformDirection( position, modelMatrix );
  7453. #include <begin_vertex>
  7454. #include <project_vertex>
  7455. }
  7456. `,
  7457. fragmentShader:
  7458. /* glsl */
  7459. `
  7460. uniform sampler2D tEquirect;
  7461. varying vec3 vWorldDirection;
  7462. #include <common>
  7463. void main() {
  7464. vec3 direction = normalize( vWorldDirection );
  7465. vec2 sampleUV = equirectUv( direction );
  7466. gl_FragColor = texture2D( tEquirect, sampleUV );
  7467. }
  7468. `
  7469. };
  7470. const geometry = new BoxGeometry(5, 5, 5);
  7471. const material = new ShaderMaterial({
  7472. name: 'CubemapFromEquirect',
  7473. uniforms: cloneUniforms(shader.uniforms),
  7474. vertexShader: shader.vertexShader,
  7475. fragmentShader: shader.fragmentShader,
  7476. side: BackSide,
  7477. blending: NoBlending
  7478. });
  7479. material.uniforms.tEquirect.value = texture;
  7480. const mesh = new Mesh(geometry, material);
  7481. const currentMinFilter = texture.minFilter; // Avoid blurred poles
  7482. if (texture.minFilter === LinearMipmapLinearFilter) texture.minFilter = LinearFilter;
  7483. const camera = new CubeCamera(1, 10, this);
  7484. camera.update(renderer, mesh);
  7485. texture.minFilter = currentMinFilter;
  7486. mesh.geometry.dispose();
  7487. mesh.material.dispose();
  7488. return this;
  7489. }
  7490. clear(renderer, color, depth, stencil) {
  7491. const currentRenderTarget = renderer.getRenderTarget();
  7492. for (let i = 0; i < 6; i++) {
  7493. renderer.setRenderTarget(this, i);
  7494. renderer.clear(color, depth, stencil);
  7495. }
  7496. renderer.setRenderTarget(currentRenderTarget);
  7497. }
  7498. }
  7499. const _vector1 = /*@__PURE__*/new Vector3();
  7500. const _vector2 = /*@__PURE__*/new Vector3();
  7501. const _normalMatrix = /*@__PURE__*/new Matrix3();
  7502. class Plane {
  7503. constructor(normal = new Vector3(1, 0, 0), constant = 0) {
  7504. this.isPlane = true; // normal is assumed to be normalized
  7505. this.normal = normal;
  7506. this.constant = constant;
  7507. }
  7508. set(normal, constant) {
  7509. this.normal.copy(normal);
  7510. this.constant = constant;
  7511. return this;
  7512. }
  7513. setComponents(x, y, z, w) {
  7514. this.normal.set(x, y, z);
  7515. this.constant = w;
  7516. return this;
  7517. }
  7518. setFromNormalAndCoplanarPoint(normal, point) {
  7519. this.normal.copy(normal);
  7520. this.constant = -point.dot(this.normal);
  7521. return this;
  7522. }
  7523. setFromCoplanarPoints(a, b, c) {
  7524. const normal = _vector1.subVectors(c, b).cross(_vector2.subVectors(a, b)).normalize(); // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  7525. this.setFromNormalAndCoplanarPoint(normal, a);
  7526. return this;
  7527. }
  7528. copy(plane) {
  7529. this.normal.copy(plane.normal);
  7530. this.constant = plane.constant;
  7531. return this;
  7532. }
  7533. normalize() {
  7534. // Note: will lead to a divide by zero if the plane is invalid.
  7535. const inverseNormalLength = 1.0 / this.normal.length();
  7536. this.normal.multiplyScalar(inverseNormalLength);
  7537. this.constant *= inverseNormalLength;
  7538. return this;
  7539. }
  7540. negate() {
  7541. this.constant *= -1;
  7542. this.normal.negate();
  7543. return this;
  7544. }
  7545. distanceToPoint(point) {
  7546. return this.normal.dot(point) + this.constant;
  7547. }
  7548. distanceToSphere(sphere) {
  7549. return this.distanceToPoint(sphere.center) - sphere.radius;
  7550. }
  7551. projectPoint(point, target) {
  7552. return target.copy(this.normal).multiplyScalar(-this.distanceToPoint(point)).add(point);
  7553. }
  7554. intersectLine(line, target) {
  7555. const direction = line.delta(_vector1);
  7556. const denominator = this.normal.dot(direction);
  7557. if (denominator === 0) {
  7558. // line is coplanar, return origin
  7559. if (this.distanceToPoint(line.start) === 0) {
  7560. return target.copy(line.start);
  7561. } // Unsure if this is the correct method to handle this case.
  7562. return null;
  7563. }
  7564. const t = -(line.start.dot(this.normal) + this.constant) / denominator;
  7565. if (t < 0 || t > 1) {
  7566. return null;
  7567. }
  7568. return target.copy(direction).multiplyScalar(t).add(line.start);
  7569. }
  7570. intersectsLine(line) {
  7571. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  7572. const startSign = this.distanceToPoint(line.start);
  7573. const endSign = this.distanceToPoint(line.end);
  7574. return startSign < 0 && endSign > 0 || endSign < 0 && startSign > 0;
  7575. }
  7576. intersectsBox(box) {
  7577. return box.intersectsPlane(this);
  7578. }
  7579. intersectsSphere(sphere) {
  7580. return sphere.intersectsPlane(this);
  7581. }
  7582. coplanarPoint(target) {
  7583. return target.copy(this.normal).multiplyScalar(-this.constant);
  7584. }
  7585. applyMatrix4(matrix, optionalNormalMatrix) {
  7586. const normalMatrix = optionalNormalMatrix || _normalMatrix.getNormalMatrix(matrix);
  7587. const referencePoint = this.coplanarPoint(_vector1).applyMatrix4(matrix);
  7588. const normal = this.normal.applyMatrix3(normalMatrix).normalize();
  7589. this.constant = -referencePoint.dot(normal);
  7590. return this;
  7591. }
  7592. translate(offset) {
  7593. this.constant -= offset.dot(this.normal);
  7594. return this;
  7595. }
  7596. equals(plane) {
  7597. return plane.normal.equals(this.normal) && plane.constant === this.constant;
  7598. }
  7599. clone() {
  7600. return new this.constructor().copy(this);
  7601. }
  7602. }
  7603. const _sphere$2 = /*@__PURE__*/new Sphere();
  7604. const _vector$7 = /*@__PURE__*/new Vector3();
  7605. class Frustum {
  7606. constructor(p0 = new Plane(), p1 = new Plane(), p2 = new Plane(), p3 = new Plane(), p4 = new Plane(), p5 = new Plane()) {
  7607. this.planes = [p0, p1, p2, p3, p4, p5];
  7608. }
  7609. set(p0, p1, p2, p3, p4, p5) {
  7610. const planes = this.planes;
  7611. planes[0].copy(p0);
  7612. planes[1].copy(p1);
  7613. planes[2].copy(p2);
  7614. planes[3].copy(p3);
  7615. planes[4].copy(p4);
  7616. planes[5].copy(p5);
  7617. return this;
  7618. }
  7619. copy(frustum) {
  7620. const planes = this.planes;
  7621. for (let i = 0; i < 6; i++) {
  7622. planes[i].copy(frustum.planes[i]);
  7623. }
  7624. return this;
  7625. }
  7626. setFromProjectionMatrix(m) {
  7627. const planes = this.planes;
  7628. const me = m.elements;
  7629. const me0 = me[0],
  7630. me1 = me[1],
  7631. me2 = me[2],
  7632. me3 = me[3];
  7633. const me4 = me[4],
  7634. me5 = me[5],
  7635. me6 = me[6],
  7636. me7 = me[7];
  7637. const me8 = me[8],
  7638. me9 = me[9],
  7639. me10 = me[10],
  7640. me11 = me[11];
  7641. const me12 = me[12],
  7642. me13 = me[13],
  7643. me14 = me[14],
  7644. me15 = me[15];
  7645. planes[0].setComponents(me3 - me0, me7 - me4, me11 - me8, me15 - me12).normalize();
  7646. planes[1].setComponents(me3 + me0, me7 + me4, me11 + me8, me15 + me12).normalize();
  7647. planes[2].setComponents(me3 + me1, me7 + me5, me11 + me9, me15 + me13).normalize();
  7648. planes[3].setComponents(me3 - me1, me7 - me5, me11 - me9, me15 - me13).normalize();
  7649. planes[4].setComponents(me3 - me2, me7 - me6, me11 - me10, me15 - me14).normalize();
  7650. planes[5].setComponents(me3 + me2, me7 + me6, me11 + me10, me15 + me14).normalize();
  7651. return this;
  7652. }
  7653. intersectsObject(object) {
  7654. const geometry = object.geometry;
  7655. if (geometry.boundingSphere === null) geometry.computeBoundingSphere();
  7656. _sphere$2.copy(geometry.boundingSphere).applyMatrix4(object.matrixWorld);
  7657. return this.intersectsSphere(_sphere$2);
  7658. }
  7659. intersectsSprite(sprite) {
  7660. _sphere$2.center.set(0, 0, 0);
  7661. _sphere$2.radius = 0.7071067811865476;
  7662. _sphere$2.applyMatrix4(sprite.matrixWorld);
  7663. return this.intersectsSphere(_sphere$2);
  7664. }
  7665. intersectsSphere(sphere) {
  7666. const planes = this.planes;
  7667. const center = sphere.center;
  7668. const negRadius = -sphere.radius;
  7669. for (let i = 0; i < 6; i++) {
  7670. const distance = planes[i].distanceToPoint(center);
  7671. if (distance < negRadius) {
  7672. return false;
  7673. }
  7674. }
  7675. return true;
  7676. }
  7677. intersectsBox(box) {
  7678. const planes = this.planes;
  7679. for (let i = 0; i < 6; i++) {
  7680. const plane = planes[i]; // corner at max distance
  7681. _vector$7.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  7682. _vector$7.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  7683. _vector$7.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  7684. if (plane.distanceToPoint(_vector$7) < 0) {
  7685. return false;
  7686. }
  7687. }
  7688. return true;
  7689. }
  7690. containsPoint(point) {
  7691. const planes = this.planes;
  7692. for (let i = 0; i < 6; i++) {
  7693. if (planes[i].distanceToPoint(point) < 0) {
  7694. return false;
  7695. }
  7696. }
  7697. return true;
  7698. }
  7699. clone() {
  7700. return new this.constructor().copy(this);
  7701. }
  7702. }
  7703. function WebGLAnimation() {
  7704. let context = null;
  7705. let isAnimating = false;
  7706. let animationLoop = null;
  7707. let requestId = null;
  7708. function onAnimationFrame(time, frame) {
  7709. animationLoop(time, frame);
  7710. requestId = context.requestAnimationFrame(onAnimationFrame);
  7711. }
  7712. return {
  7713. start: function () {
  7714. if (isAnimating === true) return;
  7715. if (animationLoop === null) return;
  7716. requestId = context.requestAnimationFrame(onAnimationFrame);
  7717. isAnimating = true;
  7718. },
  7719. stop: function () {
  7720. context.cancelAnimationFrame(requestId);
  7721. isAnimating = false;
  7722. },
  7723. setAnimationLoop: function (callback) {
  7724. animationLoop = callback;
  7725. },
  7726. setContext: function (value) {
  7727. context = value;
  7728. }
  7729. };
  7730. }
  7731. function WebGLAttributes(gl, capabilities) {
  7732. const isWebGL2 = capabilities.isWebGL2;
  7733. const buffers = new WeakMap();
  7734. function createBuffer(attribute, bufferType) {
  7735. const array = attribute.array;
  7736. const usage = attribute.usage;
  7737. const buffer = gl.createBuffer();
  7738. gl.bindBuffer(bufferType, buffer);
  7739. gl.bufferData(bufferType, array, usage);
  7740. attribute.onUploadCallback();
  7741. let type;
  7742. if (array instanceof Float32Array) {
  7743. type = gl.FLOAT;
  7744. } else if (array instanceof Uint16Array) {
  7745. if (attribute.isFloat16BufferAttribute) {
  7746. if (isWebGL2) {
  7747. type = gl.HALF_FLOAT;
  7748. } else {
  7749. throw new Error('THREE.WebGLAttributes: Usage of Float16BufferAttribute requires WebGL2.');
  7750. }
  7751. } else {
  7752. type = gl.UNSIGNED_SHORT;
  7753. }
  7754. } else if (array instanceof Int16Array) {
  7755. type = gl.SHORT;
  7756. } else if (array instanceof Uint32Array) {
  7757. type = gl.UNSIGNED_INT;
  7758. } else if (array instanceof Int32Array) {
  7759. type = gl.INT;
  7760. } else if (array instanceof Int8Array) {
  7761. type = gl.BYTE;
  7762. } else if (array instanceof Uint8Array) {
  7763. type = gl.UNSIGNED_BYTE;
  7764. } else if (array instanceof Uint8ClampedArray) {
  7765. type = gl.UNSIGNED_BYTE;
  7766. } else {
  7767. throw new Error('THREE.WebGLAttributes: Unsupported buffer data format: ' + array);
  7768. }
  7769. return {
  7770. buffer: buffer,
  7771. type: type,
  7772. bytesPerElement: array.BYTES_PER_ELEMENT,
  7773. version: attribute.version
  7774. };
  7775. }
  7776. function updateBuffer(buffer, attribute, bufferType) {
  7777. const array = attribute.array;
  7778. const updateRange = attribute.updateRange;
  7779. gl.bindBuffer(bufferType, buffer);
  7780. if (updateRange.count === -1) {
  7781. // Not using update ranges
  7782. gl.bufferSubData(bufferType, 0, array);
  7783. } else {
  7784. if (isWebGL2) {
  7785. gl.bufferSubData(bufferType, updateRange.offset * array.BYTES_PER_ELEMENT, array, updateRange.offset, updateRange.count);
  7786. } else {
  7787. gl.bufferSubData(bufferType, updateRange.offset * array.BYTES_PER_ELEMENT, array.subarray(updateRange.offset, updateRange.offset + updateRange.count));
  7788. }
  7789. updateRange.count = -1; // reset range
  7790. }
  7791. } //
  7792. function get(attribute) {
  7793. if (attribute.isInterleavedBufferAttribute) attribute = attribute.data;
  7794. return buffers.get(attribute);
  7795. }
  7796. function remove(attribute) {
  7797. if (attribute.isInterleavedBufferAttribute) attribute = attribute.data;
  7798. const data = buffers.get(attribute);
  7799. if (data) {
  7800. gl.deleteBuffer(data.buffer);
  7801. buffers.delete(attribute);
  7802. }
  7803. }
  7804. function update(attribute, bufferType) {
  7805. if (attribute.isGLBufferAttribute) {
  7806. const cached = buffers.get(attribute);
  7807. if (!cached || cached.version < attribute.version) {
  7808. buffers.set(attribute, {
  7809. buffer: attribute.buffer,
  7810. type: attribute.type,
  7811. bytesPerElement: attribute.elementSize,
  7812. version: attribute.version
  7813. });
  7814. }
  7815. return;
  7816. }
  7817. if (attribute.isInterleavedBufferAttribute) attribute = attribute.data;
  7818. const data = buffers.get(attribute);
  7819. if (data === undefined) {
  7820. buffers.set(attribute, createBuffer(attribute, bufferType));
  7821. } else if (data.version < attribute.version) {
  7822. updateBuffer(data.buffer, attribute, bufferType);
  7823. data.version = attribute.version;
  7824. }
  7825. }
  7826. return {
  7827. get: get,
  7828. remove: remove,
  7829. update: update
  7830. };
  7831. }
  7832. class PlaneGeometry extends BufferGeometry {
  7833. constructor(width = 1, height = 1, widthSegments = 1, heightSegments = 1) {
  7834. super();
  7835. this.type = 'PlaneGeometry';
  7836. this.parameters = {
  7837. width: width,
  7838. height: height,
  7839. widthSegments: widthSegments,
  7840. heightSegments: heightSegments
  7841. };
  7842. const width_half = width / 2;
  7843. const height_half = height / 2;
  7844. const gridX = Math.floor(widthSegments);
  7845. const gridY = Math.floor(heightSegments);
  7846. const gridX1 = gridX + 1;
  7847. const gridY1 = gridY + 1;
  7848. const segment_width = width / gridX;
  7849. const segment_height = height / gridY; //
  7850. const indices = [];
  7851. const vertices = [];
  7852. const normals = [];
  7853. const uvs = [];
  7854. for (let iy = 0; iy < gridY1; iy++) {
  7855. const y = iy * segment_height - height_half;
  7856. for (let ix = 0; ix < gridX1; ix++) {
  7857. const x = ix * segment_width - width_half;
  7858. vertices.push(x, -y, 0);
  7859. normals.push(0, 0, 1);
  7860. uvs.push(ix / gridX);
  7861. uvs.push(1 - iy / gridY);
  7862. }
  7863. }
  7864. for (let iy = 0; iy < gridY; iy++) {
  7865. for (let ix = 0; ix < gridX; ix++) {
  7866. const a = ix + gridX1 * iy;
  7867. const b = ix + gridX1 * (iy + 1);
  7868. const c = ix + 1 + gridX1 * (iy + 1);
  7869. const d = ix + 1 + gridX1 * iy;
  7870. indices.push(a, b, d);
  7871. indices.push(b, c, d);
  7872. }
  7873. }
  7874. this.setIndex(indices);
  7875. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  7876. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  7877. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  7878. }
  7879. static fromJSON(data) {
  7880. return new PlaneGeometry(data.width, data.height, data.widthSegments, data.heightSegments);
  7881. }
  7882. }
  7883. var alphamap_fragment = "#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, vUv ).g;\n#endif";
  7884. var alphamap_pars_fragment = "#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif";
  7885. var alphatest_fragment = "#ifdef USE_ALPHATEST\n\tif ( diffuseColor.a < alphaTest ) discard;\n#endif";
  7886. var alphatest_pars_fragment = "#ifdef USE_ALPHATEST\n\tuniform float alphaTest;\n#endif";
  7887. 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.roughness );\n\t#endif\n#endif";
  7888. var aomap_pars_fragment = "#ifdef USE_AOMAP\n\tuniform sampler2D aoMap;\n\tuniform float aoMapIntensity;\n#endif";
  7889. var begin_vertex = "vec3 transformed = vec3( position );";
  7890. var beginnormal_vertex = "vec3 objectNormal = vec3( normal );\n#ifdef USE_TANGENT\n\tvec3 objectTangent = vec3( tangent.xyz );\n#endif";
  7891. var bsdfs = "vec3 BRDF_Lambert( const in vec3 diffuseColor ) {\n\treturn RECIPROCAL_PI * diffuseColor;\n}\nvec3 F_Schlick( const in vec3 f0, const in float f90, const in float dotVH ) {\n\tfloat fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH );\n\treturn f0 * ( 1.0 - fresnel ) + ( f90 * fresnel );\n}\nfloat F_Schlick( const in float f0, const in float f90, const in float dotVH ) {\n\tfloat fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH );\n\treturn f0 * ( 1.0 - fresnel ) + ( f90 * fresnel );\n}\nvec3 Schlick_to_F0( const in vec3 f, const in float f90, const in float dotVH ) {\n float x = clamp( 1.0 - dotVH, 0.0, 1.0 );\n float x2 = x * x;\n float x5 = clamp( x * x2 * x2, 0.0, 0.9999 );\n return ( f - vec3( f90 ) * x5 ) / ( 1.0 - x5 );\n}\nfloat V_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_GGX( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in vec3 f0, const in float f90, const in float roughness ) {\n\tfloat alpha = pow2( roughness );\n\tvec3 halfDir = normalize( lightDir + viewDir );\n\tfloat dotNL = saturate( dot( normal, lightDir ) );\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat dotVH = saturate( dot( viewDir, halfDir ) );\n\tvec3 F = F_Schlick( f0, f90, dotVH );\n\tfloat V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n\tfloat D = D_GGX( alpha, dotNH );\n\treturn F * ( V * D );\n}\n#ifdef USE_IRIDESCENCE\n\tvec3 BRDF_GGX_Iridescence( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in vec3 f0, const in float f90, const in float iridescence, const in vec3 iridescenceFresnel, const in float roughness ) {\n\t\tfloat alpha = pow2( roughness );\n\t\tvec3 halfDir = normalize( lightDir + viewDir );\n\t\tfloat dotNL = saturate( dot( normal, lightDir ) );\n\t\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\t\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\t\tfloat dotVH = saturate( dot( viewDir, halfDir ) );\n\t\tvec3 F = mix( F_Schlick( f0, f90, dotVH ), iridescenceFresnel, iridescence );\n\t\tfloat V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n\t\tfloat D = D_GGX( alpha, dotNH );\n\t\treturn F * ( V * D );\n\t}\n#endif\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}\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_BlinnPhong( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in vec3 specularColor, const in float shininess ) {\n\tvec3 halfDir = normalize( lightDir + viewDir );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat dotVH = saturate( dot( viewDir, halfDir ) );\n\tvec3 F = F_Schlick( specularColor, 1.0, dotVH );\n\tfloat G = G_BlinnPhong_Implicit( );\n\tfloat D = D_BlinnPhong( shininess, dotNH );\n\treturn F * ( G * D );\n}\n#if defined( USE_SHEEN )\nfloat D_Charlie( float roughness, float dotNH ) {\n\tfloat alpha = pow2( roughness );\n\tfloat invAlpha = 1.0 / alpha;\n\tfloat cos2h = dotNH * dotNH;\n\tfloat sin2h = max( 1.0 - cos2h, 0.0078125 );\n\treturn ( 2.0 + invAlpha ) * pow( sin2h, invAlpha * 0.5 ) / ( 2.0 * PI );\n}\nfloat V_Neubelt( float dotNV, float dotNL ) {\n\treturn saturate( 1.0 / ( 4.0 * ( dotNL + dotNV - dotNL * dotNV ) ) );\n}\nvec3 BRDF_Sheen( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, vec3 sheenColor, const in float sheenRoughness ) {\n\tvec3 halfDir = normalize( lightDir + viewDir );\n\tfloat dotNL = saturate( dot( normal, lightDir ) );\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat D = D_Charlie( sheenRoughness, dotNH );\n\tfloat V = V_Neubelt( dotNV, dotNL );\n\treturn sheenColor * ( D * V );\n}\n#endif";
  7892. var iridescence_fragment = "#ifdef USE_IRIDESCENCE\n\tconst mat3 XYZ_TO_REC709 = mat3(\n\t\t 3.2404542, -0.9692660, 0.0556434,\n\t\t-1.5371385, 1.8760108, -0.2040259,\n\t\t-0.4985314, 0.0415560, 1.0572252\n\t);\n\tvec3 Fresnel0ToIor( vec3 fresnel0 ) {\n\t\tvec3 sqrtF0 = sqrt( fresnel0 );\n\t\treturn ( vec3( 1.0 ) + sqrtF0 ) / ( vec3( 1.0 ) - sqrtF0 );\n\t}\n\tvec3 IorToFresnel0( vec3 transmittedIor, float incidentIor ) {\n\t\treturn pow2( ( transmittedIor - vec3( incidentIor ) ) / ( transmittedIor + vec3( incidentIor ) ) );\n\t}\n\tfloat IorToFresnel0( float transmittedIor, float incidentIor ) {\n\t\treturn pow2( ( transmittedIor - incidentIor ) / ( transmittedIor + incidentIor ));\n\t}\n\tvec3 evalSensitivity( float OPD, vec3 shift ) {\n\t\tfloat phase = 2.0 * PI * OPD * 1.0e-9;\n\t\tvec3 val = vec3( 5.4856e-13, 4.4201e-13, 5.2481e-13 );\n\t\tvec3 pos = vec3( 1.6810e+06, 1.7953e+06, 2.2084e+06 );\n\t\tvec3 var = vec3( 4.3278e+09, 9.3046e+09, 6.6121e+09 );\n\t\tvec3 xyz = val * sqrt( 2.0 * PI * var ) * cos( pos * phase + shift ) * exp( - pow2( phase ) * var );\n\t\txyz.x += 9.7470e-14 * sqrt( 2.0 * PI * 4.5282e+09 ) * cos( 2.2399e+06 * phase + shift[ 0 ] ) * exp( - 4.5282e+09 * pow2( phase ) );\n\t\txyz /= 1.0685e-7;\n\t\tvec3 rgb = XYZ_TO_REC709 * xyz;\n\t\treturn rgb;\n\t}\n\tvec3 evalIridescence( float outsideIOR, float eta2, float cosTheta1, float thinFilmThickness, vec3 baseF0 ) {\n\t\tvec3 I;\n\t\tfloat iridescenceIOR = mix( outsideIOR, eta2, smoothstep( 0.0, 0.03, thinFilmThickness ) );\n\t\tfloat sinTheta2Sq = pow2( outsideIOR / iridescenceIOR ) * ( 1.0 - pow2( cosTheta1 ) );\n\t\tfloat cosTheta2Sq = 1.0 - sinTheta2Sq;\n\t\tif ( cosTheta2Sq < 0.0 ) {\n\t\t\t return vec3( 1.0 );\n\t\t}\n\t\tfloat cosTheta2 = sqrt( cosTheta2Sq );\n\t\tfloat R0 = IorToFresnel0( iridescenceIOR, outsideIOR );\n\t\tfloat R12 = F_Schlick( R0, 1.0, cosTheta1 );\n\t\tfloat R21 = R12;\n\t\tfloat T121 = 1.0 - R12;\n\t\tfloat phi12 = 0.0;\n\t\tif ( iridescenceIOR < outsideIOR ) phi12 = PI;\n\t\tfloat phi21 = PI - phi12;\n\t\tvec3 baseIOR = Fresnel0ToIor( clamp( baseF0, 0.0, 0.9999 ) );\t\tvec3 R1 = IorToFresnel0( baseIOR, iridescenceIOR );\n\t\tvec3 R23 = F_Schlick( R1, 1.0, cosTheta2 );\n\t\tvec3 phi23 = vec3( 0.0 );\n\t\tif ( baseIOR[ 0 ] < iridescenceIOR ) phi23[ 0 ] = PI;\n\t\tif ( baseIOR[ 1 ] < iridescenceIOR ) phi23[ 1 ] = PI;\n\t\tif ( baseIOR[ 2 ] < iridescenceIOR ) phi23[ 2 ] = PI;\n\t\tfloat OPD = 2.0 * iridescenceIOR * thinFilmThickness * cosTheta2;\n\t\tvec3 phi = vec3( phi21 ) + phi23;\n\t\tvec3 R123 = clamp( R12 * R23, 1e-5, 0.9999 );\n\t\tvec3 r123 = sqrt( R123 );\n\t\tvec3 Rs = pow2( T121 ) * R23 / ( vec3( 1.0 ) - R123 );\n\t\tvec3 C0 = R12 + Rs;\n\t\tI = C0;\n\t\tvec3 Cm = Rs - T121;\n\t\tfor ( int m = 1; m <= 2; ++ m ) {\n\t\t\tCm *= r123;\n\t\t\tvec3 Sm = 2.0 * evalSensitivity( float( m ) * OPD, float( m ) * phi );\n\t\t\tI += Cm * Sm;\n\t\t}\n\t\treturn max( I, vec3( 0.0 ) );\n\t}\n#endif";
  7893. 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, float faceDirection ) {\n\t\tvec3 vSigmaX = dFdx( surf_pos.xyz );\n\t\tvec3 vSigmaY = dFdy( surf_pos.xyz );\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 ) * faceDirection;\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";
  7894. var clipping_planes_fragment = "#if NUM_CLIPPING_PLANES > 0\n\tvec4 plane;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) {\n\t\tplane = clippingPlanes[ i ];\n\t\tif ( dot( vClipPosition, plane.xyz ) > plane.w ) discard;\n\t}\n\t#pragma unroll_loop_end\n\t#if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES\n\t\tbool clipped = true;\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) {\n\t\t\tplane = clippingPlanes[ i ];\n\t\t\tclipped = ( dot( vClipPosition, plane.xyz ) > plane.w ) && clipped;\n\t\t}\n\t\t#pragma unroll_loop_end\n\t\tif ( clipped ) discard;\n\t#endif\n#endif";
  7895. var clipping_planes_pars_fragment = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n\tuniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];\n#endif";
  7896. var clipping_planes_pars_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n#endif";
  7897. var clipping_planes_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvClipPosition = - mvPosition.xyz;\n#endif";
  7898. var color_fragment = "#if defined( USE_COLOR_ALPHA )\n\tdiffuseColor *= vColor;\n#elif defined( USE_COLOR )\n\tdiffuseColor.rgb *= vColor;\n#endif";
  7899. var color_pars_fragment = "#if defined( USE_COLOR_ALPHA )\n\tvarying vec4 vColor;\n#elif defined( USE_COLOR )\n\tvarying vec3 vColor;\n#endif";
  7900. var color_pars_vertex = "#if defined( USE_COLOR_ALPHA )\n\tvarying vec4 vColor;\n#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR )\n\tvarying vec3 vColor;\n#endif";
  7901. var color_vertex = "#if defined( USE_COLOR_ALPHA )\n\tvColor = vec4( 1.0 );\n#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR )\n\tvColor = vec3( 1.0 );\n#endif\n#ifdef USE_COLOR\n\tvColor *= color;\n#endif\n#ifdef USE_INSTANCING_COLOR\n\tvColor.xyz *= instanceColor.xyz;\n#endif";
  7902. var common = "#define PI 3.141592653589793\n#define PI2 6.283185307179586\n#define PI_HALF 1.5707963267948966\n#define RECIPROCAL_PI 0.3183098861837907\n#define RECIPROCAL_PI2 0.15915494309189535\n#define EPSILON 1e-6\n#ifndef saturate\n#define saturate( a ) clamp( a, 0.0, 1.0 )\n#endif\n#define whiteComplement( a ) ( 1.0 - saturate( a ) )\nfloat pow2( const in float x ) { return x*x; }\nvec3 pow2( const in vec3 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 max3( const in vec3 v ) { return max( max( v.x, v.y ), v.z ); }\nfloat average( const in vec3 v ) { return dot( v, vec3( 0.3333333 ) ); }\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 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 USE_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}\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 luminance( const in vec3 rgb ) {\n\tconst vec3 weights = vec3( 0.2126729, 0.7151522, 0.0721750 );\n\treturn dot( weights, rgb );\n}\nbool isPerspectiveMatrix( mat4 m ) {\n\treturn m[ 2 ][ 3 ] == - 1.0;\n}\nvec2 equirectUv( in vec3 dir ) {\n\tfloat u = atan( dir.z, dir.x ) * RECIPROCAL_PI2 + 0.5;\n\tfloat v = asin( clamp( dir.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;\n\treturn vec2( u, v );\n}";
  7903. var cube_uv_reflection_fragment = "#ifdef ENVMAP_TYPE_CUBE_UV\n\t#define cubeUV_minMipLevel 4.0\n\t#define cubeUV_minTileSize 16.0\n\tfloat getFace( vec3 direction ) {\n\t\tvec3 absDirection = abs( direction );\n\t\tfloat face = - 1.0;\n\t\tif ( absDirection.x > absDirection.z ) {\n\t\t\tif ( absDirection.x > absDirection.y )\n\t\t\t\tface = direction.x > 0.0 ? 0.0 : 3.0;\n\t\t\telse\n\t\t\t\tface = direction.y > 0.0 ? 1.0 : 4.0;\n\t\t} else {\n\t\t\tif ( absDirection.z > absDirection.y )\n\t\t\t\tface = direction.z > 0.0 ? 2.0 : 5.0;\n\t\t\telse\n\t\t\t\tface = direction.y > 0.0 ? 1.0 : 4.0;\n\t\t}\n\t\treturn face;\n\t}\n\tvec2 getUV( vec3 direction, float face ) {\n\t\tvec2 uv;\n\t\tif ( face == 0.0 ) {\n\t\t\tuv = vec2( direction.z, direction.y ) / abs( direction.x );\n\t\t} else if ( face == 1.0 ) {\n\t\t\tuv = vec2( - direction.x, - direction.z ) / abs( direction.y );\n\t\t} else if ( face == 2.0 ) {\n\t\t\tuv = vec2( - direction.x, direction.y ) / abs( direction.z );\n\t\t} else if ( face == 3.0 ) {\n\t\t\tuv = vec2( - direction.z, direction.y ) / abs( direction.x );\n\t\t} else if ( face == 4.0 ) {\n\t\t\tuv = vec2( - direction.x, direction.z ) / abs( direction.y );\n\t\t} else {\n\t\t\tuv = vec2( direction.x, direction.y ) / abs( direction.z );\n\t\t}\n\t\treturn 0.5 * ( uv + 1.0 );\n\t}\n\tvec3 bilinearCubeUV( sampler2D envMap, vec3 direction, float mipInt ) {\n\t\tfloat face = getFace( direction );\n\t\tfloat filterInt = max( cubeUV_minMipLevel - mipInt, 0.0 );\n\t\tmipInt = max( mipInt, cubeUV_minMipLevel );\n\t\tfloat faceSize = exp2( mipInt );\n\t\tvec2 uv = getUV( direction, face ) * ( faceSize - 2.0 ) + 1.0;\n\t\tif ( face > 2.0 ) {\n\t\t\tuv.y += faceSize;\n\t\t\tface -= 3.0;\n\t\t}\n\t\tuv.x += face * faceSize;\n\t\tuv.x += filterInt * 3.0 * cubeUV_minTileSize;\n\t\tuv.y += 4.0 * ( exp2( CUBEUV_MAX_MIP ) - faceSize );\n\t\tuv.x *= CUBEUV_TEXEL_WIDTH;\n\t\tuv.y *= CUBEUV_TEXEL_HEIGHT;\n\t\t#ifdef texture2DGradEXT\n\t\t\treturn texture2DGradEXT( envMap, uv, vec2( 0.0 ), vec2( 0.0 ) ).rgb;\n\t\t#else\n\t\t\treturn texture2D( envMap, uv ).rgb;\n\t\t#endif\n\t}\n\t#define cubeUV_r0 1.0\n\t#define cubeUV_v0 0.339\n\t#define cubeUV_m0 - 2.0\n\t#define cubeUV_r1 0.8\n\t#define cubeUV_v1 0.276\n\t#define cubeUV_m1 - 1.0\n\t#define cubeUV_r4 0.4\n\t#define cubeUV_v4 0.046\n\t#define cubeUV_m4 2.0\n\t#define cubeUV_r5 0.305\n\t#define cubeUV_v5 0.016\n\t#define cubeUV_m5 3.0\n\t#define cubeUV_r6 0.21\n\t#define cubeUV_v6 0.0038\n\t#define cubeUV_m6 4.0\n\tfloat roughnessToMip( float roughness ) {\n\t\tfloat mip = 0.0;\n\t\tif ( roughness >= cubeUV_r1 ) {\n\t\t\tmip = ( cubeUV_r0 - roughness ) * ( cubeUV_m1 - cubeUV_m0 ) / ( cubeUV_r0 - cubeUV_r1 ) + cubeUV_m0;\n\t\t} else if ( roughness >= cubeUV_r4 ) {\n\t\t\tmip = ( cubeUV_r1 - roughness ) * ( cubeUV_m4 - cubeUV_m1 ) / ( cubeUV_r1 - cubeUV_r4 ) + cubeUV_m1;\n\t\t} else if ( roughness >= cubeUV_r5 ) {\n\t\t\tmip = ( cubeUV_r4 - roughness ) * ( cubeUV_m5 - cubeUV_m4 ) / ( cubeUV_r4 - cubeUV_r5 ) + cubeUV_m4;\n\t\t} else if ( roughness >= cubeUV_r6 ) {\n\t\t\tmip = ( cubeUV_r5 - roughness ) * ( cubeUV_m6 - cubeUV_m5 ) / ( cubeUV_r5 - cubeUV_r6 ) + cubeUV_m5;\n\t\t} else {\n\t\t\tmip = - 2.0 * log2( 1.16 * roughness );\t\t}\n\t\treturn mip;\n\t}\n\tvec4 textureCubeUV( sampler2D envMap, vec3 sampleDir, float roughness ) {\n\t\tfloat mip = clamp( roughnessToMip( roughness ), cubeUV_m0, CUBEUV_MAX_MIP );\n\t\tfloat mipF = fract( mip );\n\t\tfloat mipInt = floor( mip );\n\t\tvec3 color0 = bilinearCubeUV( envMap, sampleDir, mipInt );\n\t\tif ( mipF == 0.0 ) {\n\t\t\treturn vec4( color0, 1.0 );\n\t\t} else {\n\t\t\tvec3 color1 = bilinearCubeUV( envMap, sampleDir, mipInt + 1.0 );\n\t\t\treturn vec4( mix( color0, color1, mipF ), 1.0 );\n\t\t}\n\t}\n#endif";
  7904. var defaultnormal_vertex = "vec3 transformedNormal = objectNormal;\n#ifdef USE_INSTANCING\n\tmat3 m = mat3( instanceMatrix );\n\ttransformedNormal /= vec3( dot( m[ 0 ], m[ 0 ] ), dot( m[ 1 ], m[ 1 ] ), dot( m[ 2 ], m[ 2 ] ) );\n\ttransformedNormal = m * transformedNormal;\n#endif\ntransformedNormal = normalMatrix * transformedNormal;\n#ifdef FLIP_SIDED\n\ttransformedNormal = - transformedNormal;\n#endif\n#ifdef USE_TANGENT\n\tvec3 transformedTangent = ( modelViewMatrix * vec4( objectTangent, 0.0 ) ).xyz;\n\t#ifdef FLIP_SIDED\n\t\ttransformedTangent = - transformedTangent;\n\t#endif\n#endif";
  7905. var displacementmap_pars_vertex = "#ifdef USE_DISPLACEMENTMAP\n\tuniform sampler2D displacementMap;\n\tuniform float displacementScale;\n\tuniform float displacementBias;\n#endif";
  7906. var displacementmap_vertex = "#ifdef USE_DISPLACEMENTMAP\n\ttransformed += normalize( objectNormal ) * ( texture2D( displacementMap, vUv ).x * displacementScale + displacementBias );\n#endif";
  7907. var emissivemap_fragment = "#ifdef USE_EMISSIVEMAP\n\tvec4 emissiveColor = texture2D( emissiveMap, vUv );\n\ttotalEmissiveRadiance *= emissiveColor.rgb;\n#endif";
  7908. var emissivemap_pars_fragment = "#ifdef USE_EMISSIVEMAP\n\tuniform sampler2D emissiveMap;\n#endif";
  7909. var encodings_fragment = "gl_FragColor = linearToOutputTexel( gl_FragColor );";
  7910. var encodings_pars_fragment = "vec4 LinearToLinear( in vec4 value ) {\n\treturn value;\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}";
  7911. var envmap_fragment = "#ifdef USE_ENVMAP\n\t#ifdef ENV_WORLDPOS\n\t\tvec3 cameraToFrag;\n\t\tif ( isOrthographic ) {\n\t\t\tcameraToFrag = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );\n\t\t} else {\n\t\t\tcameraToFrag = normalize( vWorldPosition - cameraPosition );\n\t\t}\n\t\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvec3 reflectVec = reflect( cameraToFrag, worldNormal );\n\t\t#else\n\t\t\tvec3 reflectVec = refract( cameraToFrag, worldNormal, refractionRatio );\n\t\t#endif\n\t#else\n\t\tvec3 reflectVec = vReflect;\n\t#endif\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tvec4 envColor = textureCube( envMap, vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );\n\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\tvec4 envColor = textureCubeUV( envMap, reflectVec, 0.0 );\n\t#else\n\t\tvec4 envColor = vec4( 0.0 );\n\t#endif\n\t#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";
  7912. var envmap_common_pars_fragment = "#ifdef USE_ENVMAP\n\tuniform float envMapIntensity;\n\tuniform float flipEnvMap;\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";
  7913. var envmap_pars_fragment = "#ifdef USE_ENVMAP\n\tuniform float reflectivity;\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT )\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";
  7914. var envmap_pars_vertex = "#ifdef USE_ENVMAP\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT )\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";
  7915. var envmap_vertex = "#ifdef USE_ENVMAP\n\t#ifdef ENV_WORLDPOS\n\t\tvWorldPosition = worldPosition.xyz;\n\t#else\n\t\tvec3 cameraToVertex;\n\t\tif ( isOrthographic ) {\n\t\t\tcameraToVertex = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );\n\t\t} else {\n\t\t\tcameraToVertex = normalize( worldPosition.xyz - cameraPosition );\n\t\t}\n\t\tvec3 worldNormal = inverseTransformDirection( transformedNormal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvReflect = reflect( cameraToVertex, worldNormal );\n\t\t#else\n\t\t\tvReflect = refract( cameraToVertex, worldNormal, refractionRatio );\n\t\t#endif\n\t#endif\n#endif";
  7916. var fog_vertex = "#ifdef USE_FOG\n\tvFogDepth = - mvPosition.z;\n#endif";
  7917. var fog_pars_vertex = "#ifdef USE_FOG\n\tvarying float vFogDepth;\n#endif";
  7918. var fog_fragment = "#ifdef USE_FOG\n\t#ifdef FOG_EXP2\n\t\tfloat fogFactor = 1.0 - exp( - fogDensity * fogDensity * vFogDepth * vFogDepth );\n\t#else\n\t\tfloat fogFactor = smoothstep( fogNear, fogFar, vFogDepth );\n\t#endif\n\tgl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor );\n#endif";
  7919. var fog_pars_fragment = "#ifdef USE_FOG\n\tuniform vec3 fogColor;\n\tvarying float vFogDepth;\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";
  7920. var gradientmap_pars_fragment = "#ifdef USE_GRADIENTMAP\n\tuniform sampler2D gradientMap;\n#endif\nvec3 getGradientIrradiance( vec3 normal, vec3 lightDirection ) {\n\tfloat dotNL = dot( normal, lightDirection );\n\tvec2 coord = vec2( dotNL * 0.5 + 0.5, 0.0 );\n\t#ifdef USE_GRADIENTMAP\n\t\treturn vec3( texture2D( gradientMap, coord ).r );\n\t#else\n\t\tvec2 fw = fwidth( coord ) * 0.5;\n\t\treturn mix( vec3( 0.7 ), vec3( 1.0 ), smoothstep( 0.7 - fw.x, 0.7 + fw.x, coord.x ) );\n\t#endif\n}";
  7921. var lightmap_fragment = "#ifdef USE_LIGHTMAP\n\tvec4 lightMapTexel = texture2D( lightMap, vUv2 );\n\tvec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity;\n\treflectedLight.indirectDiffuse += lightMapIrradiance;\n#endif";
  7922. var lightmap_pars_fragment = "#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif";
  7923. var lights_lambert_fragment = "LambertMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularStrength = specularStrength;";
  7924. var lights_lambert_pars_fragment = "varying vec3 vViewPosition;\nstruct LambertMaterial {\n\tvec3 diffuseColor;\n\tfloat specularStrength;\n};\nvoid RE_Direct_Lambert( const in IncidentLight directLight, const in GeometricContext geometry, const in LambertMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Lambert( const in vec3 irradiance, const in GeometricContext geometry, const in LambertMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_Lambert\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Lambert\n#define Material_LightProbeLOD( material )\t(0)";
  7925. 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 vec3 normal ) {\n\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\tvec3 irradiance = shGetIrradianceAt( worldNormal, lightProbe );\n\treturn irradiance;\n}\nvec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) {\n\tvec3 irradiance = ambientLightColor;\n\treturn irradiance;\n}\nfloat getDistanceAttenuation( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) {\n\t#if defined ( PHYSICALLY_CORRECT_LIGHTS )\n\t\tfloat distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 );\n\t\tif ( cutoffDistance > 0.0 ) {\n\t\t\tdistanceFalloff *= pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) );\n\t\t}\n\t\treturn distanceFalloff;\n\t#else\n\t\tif ( cutoffDistance > 0.0 && decayExponent > 0.0 ) {\n\t\t\treturn pow( saturate( - lightDistance / cutoffDistance + 1.0 ), decayExponent );\n\t\t}\n\t\treturn 1.0;\n\t#endif\n}\nfloat getSpotAttenuation( const in float coneCosine, const in float penumbraCosine, const in float angleCosine ) {\n\treturn smoothstep( coneCosine, penumbraCosine, angleCosine );\n}\n#if NUM_DIR_LIGHTS > 0\n\tstruct DirectionalLight {\n\t\tvec3 direction;\n\t\tvec3 color;\n\t};\n\tuniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ];\n\tvoid getDirectionalLightInfo( const in DirectionalLight directionalLight, const in GeometricContext geometry, out IncidentLight light ) {\n\t\tlight.color = directionalLight.color;\n\t\tlight.direction = directionalLight.direction;\n\t\tlight.visible = true;\n\t}\n#endif\n#if NUM_POINT_LIGHTS > 0\n\tstruct PointLight {\n\t\tvec3 position;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t};\n\tuniform PointLight pointLights[ NUM_POINT_LIGHTS ];\n\tvoid getPointLightInfo( const in PointLight pointLight, const in GeometricContext geometry, out IncidentLight light ) {\n\t\tvec3 lVector = pointLight.position - geometry.position;\n\t\tlight.direction = normalize( lVector );\n\t\tfloat lightDistance = length( lVector );\n\t\tlight.color = pointLight.color;\n\t\tlight.color *= getDistanceAttenuation( lightDistance, pointLight.distance, pointLight.decay );\n\t\tlight.visible = ( light.color != vec3( 0.0 ) );\n\t}\n#endif\n#if NUM_SPOT_LIGHTS > 0\n\tstruct SpotLight {\n\t\tvec3 position;\n\t\tvec3 direction;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t\tfloat coneCos;\n\t\tfloat penumbraCos;\n\t};\n\tuniform SpotLight spotLights[ NUM_SPOT_LIGHTS ];\n\tvoid getSpotLightInfo( const in SpotLight spotLight, const in GeometricContext geometry, out IncidentLight light ) {\n\t\tvec3 lVector = spotLight.position - geometry.position;\n\t\tlight.direction = normalize( lVector );\n\t\tfloat angleCos = dot( light.direction, spotLight.direction );\n\t\tfloat spotAttenuation = getSpotAttenuation( spotLight.coneCos, spotLight.penumbraCos, angleCos );\n\t\tif ( spotAttenuation > 0.0 ) {\n\t\t\tfloat lightDistance = length( lVector );\n\t\t\tlight.color = spotLight.color * spotAttenuation;\n\t\t\tlight.color *= getDistanceAttenuation( lightDistance, spotLight.distance, spotLight.decay );\n\t\t\tlight.visible = ( light.color != vec3( 0.0 ) );\n\t\t} else {\n\t\t\tlight.color = vec3( 0.0 );\n\t\t\tlight.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 vec3 normal ) {\n\t\tfloat dotNL = dot( normal, hemiLight.direction );\n\t\tfloat hemiDiffuseWeight = 0.5 * dotNL + 0.5;\n\t\tvec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight );\n\t\treturn irradiance;\n\t}\n#endif";
  7926. var envmap_physical_pars_fragment = "#if defined( USE_ENVMAP )\n\tvec3 getIBLIrradiance( const in vec3 normal ) {\n\t\t#if defined( ENVMAP_TYPE_CUBE_UV )\n\t\t\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, worldNormal, 1.0 );\n\t\t\treturn PI * envMapColor.rgb * envMapIntensity;\n\t\t#else\n\t\t\treturn vec3( 0.0 );\n\t\t#endif\n\t}\n\tvec3 getIBLRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness ) {\n\t\t#if defined( ENVMAP_TYPE_CUBE_UV )\n\t\t\tvec3 reflectVec = reflect( - viewDir, normal );\n\t\t\treflectVec = normalize( mix( reflectVec, normal, roughness * roughness) );\n\t\t\treflectVec = inverseTransformDirection( reflectVec, viewMatrix );\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, reflectVec, roughness );\n\t\t\treturn envMapColor.rgb * envMapIntensity;\n\t\t#else\n\t\t\treturn vec3( 0.0 );\n\t\t#endif\n\t}\n#endif";
  7927. var lights_toon_fragment = "ToonMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;";
  7928. var lights_toon_pars_fragment = "varying vec3 vViewPosition;\nstruct ToonMaterial {\n\tvec3 diffuseColor;\n};\nvoid RE_Direct_Toon( const in IncidentLight directLight, const in GeometricContext geometry, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {\n\tvec3 irradiance = getGradientIrradiance( geometry.normal, directLight.direction ) * directLight.color;\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Toon( const in vec3 irradiance, const in GeometricContext geometry, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_Toon\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Toon\n#define Material_LightProbeLOD( material )\t(0)";
  7929. var lights_phong_fragment = "BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;";
  7930. var lights_phong_pars_fragment = "varying vec3 vViewPosition;\nstruct BlinnPhongMaterial {\n\tvec3 diffuseColor;\n\tvec3 specularColor;\n\tfloat specularShininess;\n\tfloat specularStrength;\n};\nvoid RE_Direct_BlinnPhong( const in IncidentLight directLight, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n\treflectedLight.directSpecular += irradiance * BRDF_BlinnPhong( directLight.direction, geometry.viewDir, geometry.normal, 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_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)";
  7931. var lights_physical_fragment = "PhysicalMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb * ( 1.0 - metalnessFactor );\nvec3 dxy = max( abs( dFdx( geometryNormal ) ), abs( dFdy( geometryNormal ) ) );\nfloat geometryRoughness = max( max( dxy.x, dxy.y ), dxy.z );\nmaterial.roughness = max( roughnessFactor, 0.0525 );material.roughness += geometryRoughness;\nmaterial.roughness = min( material.roughness, 1.0 );\n#ifdef IOR\n\tmaterial.ior = ior;\n\t#ifdef SPECULAR\n\t\tfloat specularIntensityFactor = specularIntensity;\n\t\tvec3 specularColorFactor = specularColor;\n\t\t#ifdef USE_SPECULARINTENSITYMAP\n\t\t\tspecularIntensityFactor *= texture2D( specularIntensityMap, vUv ).a;\n\t\t#endif\n\t\t#ifdef USE_SPECULARCOLORMAP\n\t\t\tspecularColorFactor *= texture2D( specularColorMap, vUv ).rgb;\n\t\t#endif\n\t\tmaterial.specularF90 = mix( specularIntensityFactor, 1.0, metalnessFactor );\n\t#else\n\t\tfloat specularIntensityFactor = 1.0;\n\t\tvec3 specularColorFactor = vec3( 1.0 );\n\t\tmaterial.specularF90 = 1.0;\n\t#endif\n\tmaterial.specularColor = mix( min( pow2( ( material.ior - 1.0 ) / ( material.ior + 1.0 ) ) * specularColorFactor, vec3( 1.0 ) ) * specularIntensityFactor, diffuseColor.rgb, metalnessFactor );\n#else\n\tmaterial.specularColor = mix( vec3( 0.04 ), diffuseColor.rgb, metalnessFactor );\n\tmaterial.specularF90 = 1.0;\n#endif\n#ifdef USE_CLEARCOAT\n\tmaterial.clearcoat = clearcoat;\n\tmaterial.clearcoatRoughness = clearcoatRoughness;\n\tmaterial.clearcoatF0 = vec3( 0.04 );\n\tmaterial.clearcoatF90 = 1.0;\n\t#ifdef USE_CLEARCOATMAP\n\t\tmaterial.clearcoat *= texture2D( clearcoatMap, vUv ).x;\n\t#endif\n\t#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\t\tmaterial.clearcoatRoughness *= texture2D( clearcoatRoughnessMap, vUv ).y;\n\t#endif\n\tmaterial.clearcoat = saturate( material.clearcoat );\tmaterial.clearcoatRoughness = max( material.clearcoatRoughness, 0.0525 );\n\tmaterial.clearcoatRoughness += geometryRoughness;\n\tmaterial.clearcoatRoughness = min( material.clearcoatRoughness, 1.0 );\n#endif\n#ifdef USE_IRIDESCENCE\n\tmaterial.iridescence = iridescence;\n\tmaterial.iridescenceIOR = iridescenceIOR;\n\t#ifdef USE_IRIDESCENCEMAP\n\t\tmaterial.iridescence *= texture2D( iridescenceMap, vUv ).r;\n\t#endif\n\t#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\t\tmaterial.iridescenceThickness = (iridescenceThicknessMaximum - iridescenceThicknessMinimum) * texture2D( iridescenceThicknessMap, vUv ).g + iridescenceThicknessMinimum;\n\t#else\n\t\tmaterial.iridescenceThickness = iridescenceThicknessMaximum;\n\t#endif\n#endif\n#ifdef USE_SHEEN\n\tmaterial.sheenColor = sheenColor;\n\t#ifdef USE_SHEENCOLORMAP\n\t\tmaterial.sheenColor *= texture2D( sheenColorMap, vUv ).rgb;\n\t#endif\n\tmaterial.sheenRoughness = clamp( sheenRoughness, 0.07, 1.0 );\n\t#ifdef USE_SHEENROUGHNESSMAP\n\t\tmaterial.sheenRoughness *= texture2D( sheenRoughnessMap, vUv ).a;\n\t#endif\n#endif";
  7932. var lights_physical_pars_fragment = "struct PhysicalMaterial {\n\tvec3 diffuseColor;\n\tfloat roughness;\n\tvec3 specularColor;\n\tfloat specularF90;\n\t#ifdef USE_CLEARCOAT\n\t\tfloat clearcoat;\n\t\tfloat clearcoatRoughness;\n\t\tvec3 clearcoatF0;\n\t\tfloat clearcoatF90;\n\t#endif\n\t#ifdef USE_IRIDESCENCE\n\t\tfloat iridescence;\n\t\tfloat iridescenceIOR;\n\t\tfloat iridescenceThickness;\n\t\tvec3 iridescenceFresnel;\n\t\tvec3 iridescenceF0;\n\t#endif\n\t#ifdef USE_SHEEN\n\t\tvec3 sheenColor;\n\t\tfloat sheenRoughness;\n\t#endif\n\t#ifdef IOR\n\t\tfloat ior;\n\t#endif\n\t#ifdef USE_TRANSMISSION\n\t\tfloat transmission;\n\t\tfloat transmissionAlpha;\n\t\tfloat thickness;\n\t\tfloat attenuationDistance;\n\t\tvec3 attenuationColor;\n\t#endif\n};\nvec3 clearcoatSpecular = vec3( 0.0 );\nvec3 sheenSpecular = vec3( 0.0 );\nfloat IBLSheenBRDF( const in vec3 normal, const in vec3 viewDir, const in float roughness ) {\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat r2 = roughness * roughness;\n\tfloat a = roughness < 0.25 ? -339.2 * r2 + 161.4 * roughness - 25.9 : -8.48 * r2 + 14.3 * roughness - 9.95;\n\tfloat b = roughness < 0.25 ? 44.0 * r2 - 23.7 * roughness + 3.26 : 1.97 * r2 - 3.27 * roughness + 0.72;\n\tfloat DG = exp( a * dotNV + b ) + ( roughness < 0.25 ? 0.0 : 0.1 * ( roughness - 0.25 ) );\n\treturn saturate( DG * RECIPROCAL_PI );\n}\nvec2 DFGApprox( const in vec3 normal, const in vec3 viewDir, const in float roughness ) {\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\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\tvec2 fab = vec2( - 1.04, 1.04 ) * a004 + r.zw;\n\treturn fab;\n}\nvec3 EnvironmentBRDF( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness ) {\n\tvec2 fab = DFGApprox( normal, viewDir, roughness );\n\treturn specularColor * fab.x + specularF90 * fab.y;\n}\n#ifdef USE_IRIDESCENCE\nvoid computeMultiscatteringIridescence( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float iridescence, const in vec3 iridescenceF0, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) {\n#else\nvoid computeMultiscattering( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) {\n#endif\n\tvec2 fab = DFGApprox( normal, viewDir, roughness );\n\t#ifdef USE_IRIDESCENCE\n\t\tvec3 Fr = mix( specularColor, iridescenceF0, iridescence );\n\t#else\n\t\tvec3 Fr = specularColor;\n\t#endif\n\tvec3 FssEss = Fr * fab.x + specularF90 * fab.y;\n\tfloat Ess = fab.x + fab.y;\n\tfloat Ems = 1.0 - Ess;\n\tvec3 Favg = Fr + ( 1.0 - Fr ) * 0.047619;\tvec3 Fms = FssEss * Favg / ( 1.0 - Ems * Favg );\n\tsingleScatter += FssEss;\n\tmultiScatter += Fms * Ems;\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.roughness;\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#ifdef USE_CLEARCOAT\n\t\tfloat dotNLcc = saturate( dot( geometry.clearcoatNormal, directLight.direction ) );\n\t\tvec3 ccIrradiance = dotNLcc * directLight.color;\n\t\tclearcoatSpecular += ccIrradiance * BRDF_GGX( directLight.direction, geometry.viewDir, geometry.clearcoatNormal, material.clearcoatF0, material.clearcoatF90, material.clearcoatRoughness );\n\t#endif\n\t#ifdef USE_SHEEN\n\t\tsheenSpecular += irradiance * BRDF_Sheen( directLight.direction, geometry.viewDir, geometry.normal, material.sheenColor, material.sheenRoughness );\n\t#endif\n\t#ifdef USE_IRIDESCENCE\n\t\treflectedLight.directSpecular += irradiance * BRDF_GGX_Iridescence( directLight.direction, geometry.viewDir, geometry.normal, material.specularColor, material.specularF90, material.iridescence, material.iridescenceFresnel, material.roughness );\n\t#else\n\t\treflectedLight.directSpecular += irradiance * BRDF_GGX( directLight.direction, geometry.viewDir, geometry.normal, material.specularColor, material.specularF90, material.roughness );\n\t#endif\n\treflectedLight.directDiffuse += irradiance * BRDF_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_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 USE_CLEARCOAT\n\t\tclearcoatSpecular += clearcoatRadiance * EnvironmentBRDF( geometry.clearcoatNormal, geometry.viewDir, material.clearcoatF0, material.clearcoatF90, material.clearcoatRoughness );\n\t#endif\n\t#ifdef USE_SHEEN\n\t\tsheenSpecular += irradiance * material.sheenColor * IBLSheenBRDF( geometry.normal, geometry.viewDir, material.sheenRoughness );\n\t#endif\n\tvec3 singleScattering = vec3( 0.0 );\n\tvec3 multiScattering = vec3( 0.0 );\n\tvec3 cosineWeightedIrradiance = irradiance * RECIPROCAL_PI;\n\t#ifdef USE_IRIDESCENCE\n\t\tcomputeMultiscatteringIridescence( geometry.normal, geometry.viewDir, material.specularColor, material.specularF90, material.iridescence, material.iridescenceFresnel, material.roughness, singleScattering, multiScattering );\n\t#else\n\t\tcomputeMultiscattering( geometry.normal, geometry.viewDir, material.specularColor, material.specularF90, material.roughness, singleScattering, multiScattering );\n\t#endif\n\tvec3 totalScattering = singleScattering + multiScattering;\n\tvec3 diffuse = material.diffuseColor * ( 1.0 - max( max( totalScattering.r, totalScattering.g ), totalScattering.b ) );\n\treflectedLight.indirectSpecular += 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}";
  7933. var lights_fragment_begin = "\nGeometricContext geometry;\ngeometry.position = - vViewPosition;\ngeometry.normal = normal;\ngeometry.viewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition );\n#ifdef USE_CLEARCOAT\n\tgeometry.clearcoatNormal = clearcoatNormal;\n#endif\n#ifdef USE_IRIDESCENCE\n\tfloat dotNVi = saturate( dot( normal, geometry.viewDir ) );\n\tif ( material.iridescenceThickness == 0.0 ) {\n\t\tmaterial.iridescence = 0.0;\n\t} else {\n\t\tmaterial.iridescence = saturate( material.iridescence );\n\t}\n\tif ( material.iridescence > 0.0 ) {\n\t\tmaterial.iridescenceFresnel = evalIridescence( 1.0, material.iridescenceIOR, dotNVi, material.iridescenceThickness, material.specularColor );\n\t\tmaterial.iridescenceF0 = Schlick_to_F0( material.iridescenceFresnel, 1.0, dotNVi );\n\t}\n#endif\nIncidentLight directLight;\n#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct )\n\tPointLight pointLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_POINT_LIGHT_SHADOWS > 0\n\tPointLightShadow pointLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tpointLight = pointLights[ i ];\n\t\tgetPointLightInfo( pointLight, geometry, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS )\n\t\tpointLightShadow = pointLightShadows[ i ];\n\t\tdirectLight.color *= all( bvec2( directLight.visible, receiveShadow ) ) ? getPointShadow( pointShadowMap[ i ], pointLightShadow.shadowMapSize, pointLightShadow.shadowBias, pointLightShadow.shadowRadius, vPointShadowCoord[ i ], pointLightShadow.shadowCameraNear, pointLightShadow.shadowCameraFar ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct )\n\tSpotLight spotLight;\n\tvec4 spotColor;\n\tvec3 spotLightCoord;\n\tbool inSpotLightMap;\n\t#if defined( USE_SHADOWMAP ) && NUM_SPOT_LIGHT_SHADOWS > 0\n\tSpotLightShadow spotLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tspotLight = spotLights[ i ];\n\t\tgetSpotLightInfo( spotLight, geometry, directLight );\n\t\t#if ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS )\n\t\t#define SPOT_LIGHT_MAP_INDEX UNROLLED_LOOP_INDEX\n\t\t#elif ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n\t\t#define SPOT_LIGHT_MAP_INDEX NUM_SPOT_LIGHT_MAPS\n\t\t#else\n\t\t#define SPOT_LIGHT_MAP_INDEX ( UNROLLED_LOOP_INDEX - NUM_SPOT_LIGHT_SHADOWS + NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS )\n\t\t#endif\n\t\t#if ( SPOT_LIGHT_MAP_INDEX < NUM_SPOT_LIGHT_MAPS )\n\t\t\tspotLightCoord = vSpotLightCoord[ i ].xyz / vSpotLightCoord[ i ].w;\n\t\t\tinSpotLightMap = all( lessThan( abs( spotLightCoord * 2. - 1. ), vec3( 1.0 ) ) );\n\t\t\tspotColor = texture2D( spotLightMap[ SPOT_LIGHT_MAP_INDEX ], spotLightCoord.xy );\n\t\t\tdirectLight.color = inSpotLightMap ? directLight.color * spotColor.rgb : directLight.color;\n\t\t#endif\n\t\t#undef SPOT_LIGHT_MAP_INDEX\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n\t\tspotLightShadow = spotLightShadows[ i ];\n\t\tdirectLight.color *= all( bvec2( directLight.visible, receiveShadow ) ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotLightCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct )\n\tDirectionalLight directionalLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0\n\tDirectionalLightShadow directionalLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tdirectionalLight = directionalLights[ i ];\n\t\tgetDirectionalLightInfo( directionalLight, geometry, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS )\n\t\tdirectionalLightShadow = directionalLightShadows[ i ];\n\t\tdirectLight.color *= all( bvec2( directLight.visible, receiveShadow ) ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea )\n\tRectAreaLight rectAreaLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) {\n\t\trectAreaLight = rectAreaLights[ i ];\n\t\tRE_Direct_RectArea( rectAreaLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if defined( RE_IndirectDiffuse )\n\tvec3 iblIrradiance = vec3( 0.0 );\n\tvec3 irradiance = getAmbientLightIrradiance( ambientLightColor );\n\tirradiance += getLightProbeIrradiance( lightProbe, geometry.normal );\n\t#if ( NUM_HEMI_LIGHTS > 0 )\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\t\t\tirradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry.normal );\n\t\t}\n\t\t#pragma unroll_loop_end\n\t#endif\n#endif\n#if defined( RE_IndirectSpecular )\n\tvec3 radiance = vec3( 0.0 );\n\tvec3 clearcoatRadiance = vec3( 0.0 );\n#endif";
  7934. var lights_fragment_maps = "#if defined( RE_IndirectDiffuse )\n\t#ifdef USE_LIGHTMAP\n\t\tvec4 lightMapTexel = texture2D( lightMap, vUv2 );\n\t\tvec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity;\n\t\tirradiance += lightMapIrradiance;\n\t#endif\n\t#if defined( USE_ENVMAP ) && defined( STANDARD ) && defined( ENVMAP_TYPE_CUBE_UV )\n\t\tiblIrradiance += getIBLIrradiance( geometry.normal );\n\t#endif\n#endif\n#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular )\n\tradiance += getIBLRadiance( geometry.viewDir, geometry.normal, material.roughness );\n\t#ifdef USE_CLEARCOAT\n\t\tclearcoatRadiance += getIBLRadiance( geometry.viewDir, geometry.clearcoatNormal, material.clearcoatRoughness );\n\t#endif\n#endif";
  7935. 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";
  7936. var logdepthbuf_fragment = "#if defined( USE_LOGDEPTHBUF ) && defined( USE_LOGDEPTHBUF_EXT )\n\tgl_FragDepthEXT = vIsPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;\n#endif";
  7937. 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";
  7938. 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";
  7939. 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";
  7940. var map_fragment = "#ifdef USE_MAP\n\tvec4 sampledDiffuseColor = texture2D( map, vUv );\n\t#ifdef DECODE_VIDEO_TEXTURE\n\t\tsampledDiffuseColor = vec4( mix( pow( sampledDiffuseColor.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), sampledDiffuseColor.rgb * 0.0773993808, vec3( lessThanEqual( sampledDiffuseColor.rgb, vec3( 0.04045 ) ) ) ), sampledDiffuseColor.w );\n\t#endif\n\tdiffuseColor *= sampledDiffuseColor;\n#endif";
  7941. var map_pars_fragment = "#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif";
  7942. var map_particle_fragment = "#if defined( USE_MAP ) || defined( USE_ALPHAMAP )\n\tvec2 uv = ( uvTransform * vec3( gl_PointCoord.x, 1.0 - gl_PointCoord.y, 1 ) ).xy;\n#endif\n#ifdef USE_MAP\n\tdiffuseColor *= texture2D( map, uv );\n#endif\n#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, uv ).g;\n#endif";
  7943. var map_particle_pars_fragment = "#if defined( USE_MAP ) || defined( USE_ALPHAMAP )\n\tuniform mat3 uvTransform;\n#endif\n#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif\n#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif";
  7944. var metalnessmap_fragment = "float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n\tvec4 texelMetalness = texture2D( metalnessMap, vUv );\n\tmetalnessFactor *= texelMetalness.b;\n#endif";
  7945. var metalnessmap_pars_fragment = "#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif";
  7946. var morphcolor_vertex = "#if defined( USE_MORPHCOLORS ) && defined( MORPHTARGETS_TEXTURE )\n\tvColor *= morphTargetBaseInfluence;\n\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\t#if defined( USE_COLOR_ALPHA )\n\t\t\tif ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ) * morphTargetInfluences[ i ];\n\t\t#elif defined( USE_COLOR )\n\t\t\tif ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ).rgb * morphTargetInfluences[ i ];\n\t\t#endif\n\t}\n#endif";
  7947. var morphnormal_vertex = "#ifdef USE_MORPHNORMALS\n\tobjectNormal *= morphTargetBaseInfluence;\n\t#ifdef MORPHTARGETS_TEXTURE\n\t\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\t\tif ( morphTargetInfluences[ i ] != 0.0 ) objectNormal += getMorph( gl_VertexID, i, 1 ).xyz * morphTargetInfluences[ i ];\n\t\t}\n\t#else\n\t\tobjectNormal += morphNormal0 * morphTargetInfluences[ 0 ];\n\t\tobjectNormal += morphNormal1 * morphTargetInfluences[ 1 ];\n\t\tobjectNormal += morphNormal2 * morphTargetInfluences[ 2 ];\n\t\tobjectNormal += morphNormal3 * morphTargetInfluences[ 3 ];\n\t#endif\n#endif";
  7948. var morphtarget_pars_vertex = "#ifdef USE_MORPHTARGETS\n\tuniform float morphTargetBaseInfluence;\n\t#ifdef MORPHTARGETS_TEXTURE\n\t\tuniform float morphTargetInfluences[ MORPHTARGETS_COUNT ];\n\t\tuniform sampler2DArray morphTargetsTexture;\n\t\tuniform ivec2 morphTargetsTextureSize;\n\t\tvec4 getMorph( const in int vertexIndex, const in int morphTargetIndex, const in int offset ) {\n\t\t\tint texelIndex = vertexIndex * MORPHTARGETS_TEXTURE_STRIDE + offset;\n\t\t\tint y = texelIndex / morphTargetsTextureSize.x;\n\t\t\tint x = texelIndex - y * morphTargetsTextureSize.x;\n\t\t\tivec3 morphUV = ivec3( x, y, morphTargetIndex );\n\t\t\treturn texelFetch( morphTargetsTexture, morphUV, 0 );\n\t\t}\n\t#else\n\t\t#ifndef USE_MORPHNORMALS\n\t\t\tuniform float morphTargetInfluences[ 8 ];\n\t\t#else\n\t\t\tuniform float morphTargetInfluences[ 4 ];\n\t\t#endif\n\t#endif\n#endif";
  7949. var morphtarget_vertex = "#ifdef USE_MORPHTARGETS\n\ttransformed *= morphTargetBaseInfluence;\n\t#ifdef MORPHTARGETS_TEXTURE\n\t\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\t\tif ( morphTargetInfluences[ i ] != 0.0 ) transformed += getMorph( gl_VertexID, i, 0 ).xyz * morphTargetInfluences[ i ];\n\t\t}\n\t#else\n\t\ttransformed += morphTarget0 * morphTargetInfluences[ 0 ];\n\t\ttransformed += morphTarget1 * morphTargetInfluences[ 1 ];\n\t\ttransformed += morphTarget2 * morphTargetInfluences[ 2 ];\n\t\ttransformed += morphTarget3 * morphTargetInfluences[ 3 ];\n\t\t#ifndef USE_MORPHNORMALS\n\t\t\ttransformed += morphTarget4 * morphTargetInfluences[ 4 ];\n\t\t\ttransformed += morphTarget5 * morphTargetInfluences[ 5 ];\n\t\t\ttransformed += morphTarget6 * morphTargetInfluences[ 6 ];\n\t\t\ttransformed += morphTarget7 * morphTargetInfluences[ 7 ];\n\t\t#endif\n\t#endif\n#endif";
  7950. var normal_fragment_begin = "float faceDirection = gl_FrontFacing ? 1.0 : - 1.0;\n#ifdef FLAT_SHADED\n\tvec3 fdx = dFdx( vViewPosition );\n\tvec3 fdy = dFdy( vViewPosition );\n\tvec3 normal = normalize( cross( fdx, fdy ) );\n#else\n\tvec3 normal = normalize( vNormal );\n\t#ifdef DOUBLE_SIDED\n\t\tnormal = normal * faceDirection;\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 * faceDirection;\n\t\t\tbitangent = bitangent * faceDirection;\n\t\t#endif\n\t\t#if defined( TANGENTSPACE_NORMALMAP ) || defined( USE_CLEARCOAT_NORMALMAP )\n\t\t\tmat3 vTBN = mat3( tangent, bitangent, normal );\n\t\t#endif\n\t#endif\n#endif\nvec3 geometryNormal = normal;";
  7951. 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 * faceDirection;\n\t#endif\n\tnormal = normalize( normalMatrix * normal );\n#elif defined( TANGENTSPACE_NORMALMAP )\n\tvec3 mapN = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;\n\tmapN.xy *= normalScale;\n\t#ifdef USE_TANGENT\n\t\tnormal = normalize( vTBN * mapN );\n\t#else\n\t\tnormal = perturbNormal2Arb( - vViewPosition, normal, mapN, faceDirection );\n\t#endif\n#elif defined( USE_BUMPMAP )\n\tnormal = perturbNormalArb( - vViewPosition, normal, dHdxy_fwd(), faceDirection );\n#endif";
  7952. var normal_pars_fragment = "#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";
  7953. var normal_pars_vertex = "#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";
  7954. var normal_vertex = "#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";
  7955. var normalmap_pars_fragment = "#ifdef USE_NORMALMAP\n\tuniform sampler2D normalMap;\n\tuniform vec2 normalScale;\n#endif\n#ifdef OBJECTSPACE_NORMALMAP\n\tuniform mat3 normalMatrix;\n#endif\n#if ! defined ( USE_TANGENT ) && ( defined ( TANGENTSPACE_NORMALMAP ) || defined ( USE_CLEARCOAT_NORMALMAP ) )\n\tvec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm, vec3 mapN, float faceDirection ) {\n\t\tvec3 q0 = dFdx( eye_pos.xyz );\n\t\tvec3 q1 = dFdy( eye_pos.xyz );\n\t\tvec2 st0 = dFdx( vUv.st );\n\t\tvec2 st1 = dFdy( vUv.st );\n\t\tvec3 N = surf_norm;\n\t\tvec3 q1perp = cross( q1, N );\n\t\tvec3 q0perp = cross( N, q0 );\n\t\tvec3 T = q1perp * st0.x + q0perp * st1.x;\n\t\tvec3 B = q1perp * st0.y + q0perp * st1.y;\n\t\tfloat det = max( dot( T, T ), dot( B, B ) );\n\t\tfloat scale = ( det == 0.0 ) ? 0.0 : faceDirection * inversesqrt( det );\n\t\treturn normalize( T * ( mapN.x * scale ) + B * ( mapN.y * scale ) + N * mapN.z );\n\t}\n#endif";
  7956. var clearcoat_normal_fragment_begin = "#ifdef USE_CLEARCOAT\n\tvec3 clearcoatNormal = geometryNormal;\n#endif";
  7957. var clearcoat_normal_fragment_maps = "#ifdef USE_CLEARCOAT_NORMALMAP\n\tvec3 clearcoatMapN = texture2D( clearcoatNormalMap, vUv ).xyz * 2.0 - 1.0;\n\tclearcoatMapN.xy *= clearcoatNormalScale;\n\t#ifdef USE_TANGENT\n\t\tclearcoatNormal = normalize( vTBN * clearcoatMapN );\n\t#else\n\t\tclearcoatNormal = perturbNormal2Arb( - vViewPosition, clearcoatNormal, clearcoatMapN, faceDirection );\n\t#endif\n#endif";
  7958. var clearcoat_pars_fragment = "#ifdef USE_CLEARCOATMAP\n\tuniform sampler2D clearcoatMap;\n#endif\n#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\tuniform sampler2D clearcoatRoughnessMap;\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n\tuniform sampler2D clearcoatNormalMap;\n\tuniform vec2 clearcoatNormalScale;\n#endif";
  7959. var iridescence_pars_fragment = "#ifdef USE_IRIDESCENCEMAP\n\tuniform sampler2D iridescenceMap;\n#endif\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\tuniform sampler2D iridescenceThicknessMap;\n#endif";
  7960. var output_fragment = "#ifdef OPAQUE\ndiffuseColor.a = 1.0;\n#endif\n#ifdef USE_TRANSMISSION\ndiffuseColor.a *= material.transmissionAlpha + 0.1;\n#endif\ngl_FragColor = vec4( outgoingLight, diffuseColor.a );";
  7961. var packing = "vec3 packNormalToRGB( const in vec3 normal ) {\n\treturn normalize( normal ) * 0.5 + 0.5;\n}\nvec3 unpackRGBToNormal( const in vec3 rgb ) {\n\treturn 2.0 * rgb.xyz - 1.0;\n}\nconst float PackUpscale = 256. / 255.;const float UnpackDownscale = 255. / 256.;\nconst vec3 PackFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );\nconst vec4 UnpackFactors = UnpackDownscale / vec4( PackFactors, 1. );\nconst float ShiftRight8 = 1. / 256.;\nvec4 packDepthToRGBA( const in float v ) {\n\tvec4 r = vec4( fract( v * PackFactors ), v );\n\tr.yzw -= r.xyz * ShiftRight8;\treturn r * PackUpscale;\n}\nfloat unpackRGBAToDepth( const in vec4 v ) {\n\treturn dot( v, UnpackFactors );\n}\nvec4 pack2HalfToRGBA( vec2 v ) {\n\tvec4 r = vec4( v.x, fract( v.x * 255.0 ), v.y, fract( v.y * 255.0 ) );\n\treturn vec4( r.x - r.y / 255.0, r.y, r.z - r.w / 255.0, r.w );\n}\nvec2 unpackRGBATo2Half( vec4 v ) {\n\treturn vec2( v.x + ( v.y / 255.0 ), v.z + ( v.w / 255.0 ) );\n}\nfloat viewZToOrthographicDepth( const in float viewZ, const in float near, const in float far ) {\n\treturn ( viewZ + near ) / ( near - far );\n}\nfloat orthographicDepthToViewZ( const in float linearClipZ, const in float near, const in float far ) {\n\treturn linearClipZ * ( near - far ) - near;\n}\nfloat viewZToPerspectiveDepth( const in float viewZ, const in float near, const in float far ) {\n\treturn ( ( near + viewZ ) * far ) / ( ( far - near ) * viewZ );\n}\nfloat perspectiveDepthToViewZ( const in float invClipZ, const in float near, const in float far ) {\n\treturn ( near * far ) / ( ( far - near ) * invClipZ - far );\n}";
  7962. var premultiplied_alpha_fragment = "#ifdef PREMULTIPLIED_ALPHA\n\tgl_FragColor.rgb *= gl_FragColor.a;\n#endif";
  7963. 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;";
  7964. var dithering_fragment = "#ifdef DITHERING\n\tgl_FragColor.rgb = dithering( gl_FragColor.rgb );\n#endif";
  7965. 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";
  7966. var roughnessmap_fragment = "float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n\tvec4 texelRoughness = texture2D( roughnessMap, vUv );\n\troughnessFactor *= texelRoughness.g;\n#endif";
  7967. var roughnessmap_pars_fragment = "#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif";
  7968. var shadowmap_pars_fragment = "#if NUM_SPOT_LIGHT_COORDS > 0\n varying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ];\n#endif\n#if NUM_SPOT_LIGHT_MAPS > 0\n uniform sampler2D spotLightMap[ NUM_SPOT_LIGHT_MAPS ];\n#endif\n#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tstruct DirectionalLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ];\n\t\tstruct SpotLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D pointShadowMap[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tstruct PointLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t\tfloat shadowCameraNear;\n\t\t\tfloat shadowCameraFar;\n\t\t};\n\t\tuniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];\n\t#endif\n\tfloat texture2DCompare( sampler2D depths, vec2 uv, float compare ) {\n\t\treturn step( compare, unpackRGBAToDepth( texture2D( depths, uv ) ) );\n\t}\n\tvec2 texture2DDistribution( sampler2D shadow, vec2 uv ) {\n\t\treturn unpackRGBATo2Half( texture2D( shadow, uv ) );\n\t}\n\tfloat VSMShadow (sampler2D shadow, vec2 uv, float compare ){\n\t\tfloat occlusion = 1.0;\n\t\tvec2 distribution = texture2DDistribution( shadow, uv );\n\t\tfloat hard_shadow = step( compare , distribution.x );\n\t\tif (hard_shadow != 1.0 ) {\n\t\t\tfloat distance = compare - distribution.x ;\n\t\t\tfloat variance = max( 0.00000, distribution.y * distribution.y );\n\t\t\tfloat softness_probability = variance / (variance + distance * distance );\t\t\tsoftness_probability = clamp( ( softness_probability - 0.3 ) / ( 0.95 - 0.3 ), 0.0, 1.0 );\t\t\tocclusion = clamp( max( hard_shadow, softness_probability ), 0.0, 1.0 );\n\t\t}\n\t\treturn occlusion;\n\t}\n\tfloat getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\n\t\tfloat shadow = 1.0;\n\t\tshadowCoord.xyz /= shadowCoord.w;\n\t\tshadowCoord.z += shadowBias;\n\t\tbvec4 inFrustumVec = bvec4 ( shadowCoord.x >= 0.0, shadowCoord.x <= 1.0, shadowCoord.y >= 0.0, shadowCoord.y <= 1.0 );\n\t\tbool inFrustum = all( inFrustumVec );\n\t\tbvec2 frustumTestVec = bvec2( inFrustum, shadowCoord.z <= 1.0 );\n\t\tbool frustumTest = all( frustumTestVec );\n\t\tif ( frustumTest ) {\n\t\t#if defined( SHADOWMAP_TYPE_PCF )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\tfloat dx0 = - texelSize.x * shadowRadius;\n\t\t\tfloat dy0 = - texelSize.y * shadowRadius;\n\t\t\tfloat dx1 = + texelSize.x * shadowRadius;\n\t\t\tfloat dy1 = + texelSize.y * shadowRadius;\n\t\t\tfloat dx2 = dx0 / 2.0;\n\t\t\tfloat dy2 = dy0 / 2.0;\n\t\t\tfloat dx3 = dx1 / 2.0;\n\t\t\tfloat dy3 = dy1 / 2.0;\n\t\t\tshadow = (\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z )\n\t\t\t) * ( 1.0 / 17.0 );\n\t\t#elif defined( SHADOWMAP_TYPE_PCF_SOFT )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\tfloat dx = texelSize.x;\n\t\t\tfloat dy = texelSize.y;\n\t\t\tvec2 uv = shadowCoord.xy;\n\t\t\tvec2 f = fract( uv * shadowMapSize + 0.5 );\n\t\t\tuv -= f * texelSize;\n\t\t\tshadow = (\n\t\t\t\ttexture2DCompare( shadowMap, uv, shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + vec2( dx, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + vec2( 0.0, dy ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + texelSize, shadowCoord.z ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( -dx, 0.0 ), shadowCoord.z ),\n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 0.0 ), shadowCoord.z ),\n\t\t\t\t\t f.x ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( -dx, dy ), shadowCoord.z ),\n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, dy ), shadowCoord.z ),\n\t\t\t\t\t f.x ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( 0.0, -dy ), shadowCoord.z ),\n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 0.0, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t f.y ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( dx, -dy ), shadowCoord.z ),\n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( dx, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t f.y ) +\n\t\t\t\tmix( mix( texture2DCompare( shadowMap, uv + vec2( -dx, -dy ), shadowCoord.z ),\n\t\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, -dy ), shadowCoord.z ),\n\t\t\t\t\t\t f.x ),\n\t\t\t\t\t mix( texture2DCompare( shadowMap, uv + vec2( -dx, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t\t f.x ),\n\t\t\t\t\t f.y )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#elif defined( SHADOWMAP_TYPE_VSM )\n\t\t\tshadow = VSMShadow( shadowMap, shadowCoord.xy, shadowCoord.z );\n\t\t#else\n\t\t\tshadow = texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z );\n\t\t#endif\n\t\t}\n\t\treturn shadow;\n\t}\n\tvec2 cubeToUV( vec3 v, float texelSizeY ) {\n\t\tvec3 absV = abs( v );\n\t\tfloat scaleToCube = 1.0 / max( absV.x, max( absV.y, absV.z ) );\n\t\tabsV *= scaleToCube;\n\t\tv *= scaleToCube * ( 1.0 - 2.0 * texelSizeY );\n\t\tvec2 planar = v.xy;\n\t\tfloat almostATexel = 1.5 * texelSizeY;\n\t\tfloat almostOne = 1.0 - almostATexel;\n\t\tif ( absV.z >= almostOne ) {\n\t\t\tif ( v.z > 0.0 )\n\t\t\t\tplanar.x = 4.0 - v.x;\n\t\t} else if ( absV.x >= almostOne ) {\n\t\t\tfloat signX = sign( v.x );\n\t\t\tplanar.x = v.z * signX + 2.0 * signX;\n\t\t} else if ( absV.y >= almostOne ) {\n\t\t\tfloat signY = sign( v.y );\n\t\t\tplanar.x = v.x + 2.0 * signY + 2.0;\n\t\t\tplanar.y = v.z * signY - 2.0;\n\t\t}\n\t\treturn vec2( 0.125, 0.25 ) * planar + vec2( 0.375, 0.75 );\n\t}\n\tfloat getPointShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) {\n\t\tvec2 texelSize = vec2( 1.0 ) / ( shadowMapSize * vec2( 4.0, 2.0 ) );\n\t\tvec3 lightToPosition = shadowCoord.xyz;\n\t\tfloat dp = ( length( lightToPosition ) - shadowCameraNear ) / ( shadowCameraFar - shadowCameraNear );\t\tdp += shadowBias;\n\t\tvec3 bd3D = normalize( lightToPosition );\n\t\t#if defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_PCF_SOFT ) || defined( SHADOWMAP_TYPE_VSM )\n\t\t\tvec2 offset = vec2( - 1, 1 ) * shadowRadius * texelSize.y;\n\t\t\treturn (\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxx, texelSize.y ), dp )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#else\n\t\t\treturn texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp );\n\t\t#endif\n\t}\n#endif";
  7969. var shadowmap_pars_vertex = "#if NUM_SPOT_LIGHT_COORDS > 0\n uniform mat4 spotLightMatrix[ NUM_SPOT_LIGHT_COORDS ];\n varying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ];\n#endif\n#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t\tuniform mat4 directionalShadowMatrix[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tstruct DirectionalLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\t\tstruct SpotLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t\tuniform mat4 pointShadowMatrix[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tstruct PointLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t\tfloat shadowCameraNear;\n\t\t\tfloat shadowCameraFar;\n\t\t};\n\t\tuniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];\n\t#endif\n#endif";
  7970. var shadowmap_vertex = "#if defined( USE_SHADOWMAP ) || ( NUM_SPOT_LIGHT_COORDS > 0 )\n\t#if NUM_DIR_LIGHT_SHADOWS > 0 || NUM_SPOT_LIGHT_COORDS > 0 || NUM_POINT_LIGHT_SHADOWS > 0\n\t\tvec3 shadowWorldNormal = inverseTransformDirection( transformedNormal, viewMatrix );\n\t\tvec4 shadowWorldPosition;\n\t#endif\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {\n\t\tshadowWorldPosition = worldPosition + vec4( shadowWorldNormal * directionalLightShadows[ i ].shadowNormalBias, 0 );\n\t\tvDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * shadowWorldPosition;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_SPOT_LIGHT_COORDS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHT_COORDS; i ++ ) {\n\t\tshadowWorldPosition = worldPosition;\n\t\t#if ( defined( USE_SHADOWMAP ) && UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n\t\t\tshadowWorldPosition.xyz += shadowWorldNormal * spotLightShadows[ i ].shadowNormalBias;\n\t\t#endif\n\t\tvSpotLightCoord[ i ] = spotLightMatrix[ i ] * shadowWorldPosition;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {\n\t\tshadowWorldPosition = worldPosition + vec4( shadowWorldNormal * pointLightShadows[ i ].shadowNormalBias, 0 );\n\t\tvPointShadowCoord[ i ] = pointShadowMatrix[ i ] * shadowWorldPosition;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n#endif";
  7971. var shadowmask_pars_fragment = "float getShadowMask() {\n\tfloat shadow = 1.0;\n\t#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\tDirectionalLightShadow directionalLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {\n\t\tdirectionalLight = directionalLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\tSpotLightShadow spotLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHT_SHADOWS; i ++ ) {\n\t\tspotLight = spotLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowBias, spotLight.shadowRadius, vSpotLightCoord[ i ] ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\tPointLightShadow pointLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {\n\t\tpointLight = pointLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ], pointLight.shadowCameraNear, pointLight.shadowCameraFar ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#endif\n\treturn shadow;\n}";
  7972. 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";
  7973. var skinning_pars_vertex = "#ifdef USE_SKINNING\n\tuniform mat4 bindMatrix;\n\tuniform mat4 bindMatrixInverse;\n\tuniform highp sampler2D boneTexture;\n\tuniform int boneTextureSize;\n\tmat4 getBoneMatrix( const in float i ) {\n\t\tfloat j = i * 4.0;\n\t\tfloat x = mod( j, float( boneTextureSize ) );\n\t\tfloat y = floor( j / float( boneTextureSize ) );\n\t\tfloat dx = 1.0 / float( boneTextureSize );\n\t\tfloat dy = 1.0 / float( boneTextureSize );\n\t\ty = dy * ( y + 0.5 );\n\t\tvec4 v1 = texture2D( boneTexture, vec2( dx * ( x + 0.5 ), y ) );\n\t\tvec4 v2 = texture2D( boneTexture, vec2( dx * ( x + 1.5 ), y ) );\n\t\tvec4 v3 = texture2D( boneTexture, vec2( dx * ( x + 2.5 ), y ) );\n\t\tvec4 v4 = texture2D( boneTexture, vec2( dx * ( x + 3.5 ), y ) );\n\t\tmat4 bone = mat4( v1, v2, v3, v4 );\n\t\treturn bone;\n\t}\n#endif";
  7974. 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";
  7975. 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";
  7976. 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";
  7977. var specularmap_pars_fragment = "#ifdef USE_SPECULARMAP\n\tuniform sampler2D specularMap;\n#endif";
  7978. var tonemapping_fragment = "#if defined( TONE_MAPPING )\n\tgl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif";
  7979. var tonemapping_pars_fragment = "#ifndef saturate\n#define saturate( a ) clamp( a, 0.0, 1.0 )\n#endif\nuniform float toneMappingExposure;\nvec3 LinearToneMapping( vec3 color ) {\n\treturn toneMappingExposure * color;\n}\nvec3 ReinhardToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\treturn saturate( color / ( vec3( 1.0 ) + color ) );\n}\nvec3 OptimizedCineonToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\tcolor = max( vec3( 0.0 ), color - 0.004 );\n\treturn pow( ( color * ( 6.2 * color + 0.5 ) ) / ( color * ( 6.2 * color + 1.7 ) + 0.06 ), vec3( 2.2 ) );\n}\nvec3 RRTAndODTFit( vec3 v ) {\n\tvec3 a = v * ( v + 0.0245786 ) - 0.000090537;\n\tvec3 b = v * ( 0.983729 * v + 0.4329510 ) + 0.238081;\n\treturn a / b;\n}\nvec3 ACESFilmicToneMapping( vec3 color ) {\n\tconst mat3 ACESInputMat = mat3(\n\t\tvec3( 0.59719, 0.07600, 0.02840 ),\t\tvec3( 0.35458, 0.90834, 0.13383 ),\n\t\tvec3( 0.04823, 0.01566, 0.83777 )\n\t);\n\tconst mat3 ACESOutputMat = mat3(\n\t\tvec3( 1.60475, -0.10208, -0.00327 ),\t\tvec3( -0.53108, 1.10813, -0.07276 ),\n\t\tvec3( -0.07367, -0.00605, 1.07602 )\n\t);\n\tcolor *= toneMappingExposure / 0.6;\n\tcolor = ACESInputMat * color;\n\tcolor = RRTAndODTFit( color );\n\tcolor = ACESOutputMat * color;\n\treturn saturate( color );\n}\nvec3 CustomToneMapping( vec3 color ) { return color; }";
  7980. var transmission_fragment = "#ifdef USE_TRANSMISSION\n\tmaterial.transmission = transmission;\n\tmaterial.transmissionAlpha = 1.0;\n\tmaterial.thickness = thickness;\n\tmaterial.attenuationDistance = attenuationDistance;\n\tmaterial.attenuationColor = attenuationColor;\n\t#ifdef USE_TRANSMISSIONMAP\n\t\tmaterial.transmission *= texture2D( transmissionMap, vUv ).r;\n\t#endif\n\t#ifdef USE_THICKNESSMAP\n\t\tmaterial.thickness *= texture2D( thicknessMap, vUv ).g;\n\t#endif\n\tvec3 pos = vWorldPosition;\n\tvec3 v = normalize( cameraPosition - pos );\n\tvec3 n = inverseTransformDirection( normal, viewMatrix );\n\tvec4 transmission = getIBLVolumeRefraction(\n\t\tn, v, material.roughness, material.diffuseColor, material.specularColor, material.specularF90,\n\t\tpos, modelMatrix, viewMatrix, projectionMatrix, material.ior, material.thickness,\n\t\tmaterial.attenuationColor, material.attenuationDistance );\n\tmaterial.transmissionAlpha = mix( material.transmissionAlpha, transmission.a, material.transmission );\n\ttotalDiffuse = mix( totalDiffuse, transmission.rgb, material.transmission );\n#endif";
  7981. var transmission_pars_fragment = "#ifdef USE_TRANSMISSION\n\tuniform float transmission;\n\tuniform float thickness;\n\tuniform float attenuationDistance;\n\tuniform vec3 attenuationColor;\n\t#ifdef USE_TRANSMISSIONMAP\n\t\tuniform sampler2D transmissionMap;\n\t#endif\n\t#ifdef USE_THICKNESSMAP\n\t\tuniform sampler2D thicknessMap;\n\t#endif\n\tuniform vec2 transmissionSamplerSize;\n\tuniform sampler2D transmissionSamplerMap;\n\tuniform mat4 modelMatrix;\n\tuniform mat4 projectionMatrix;\n\tvarying vec3 vWorldPosition;\n\tvec3 getVolumeTransmissionRay( const in vec3 n, const in vec3 v, const in float thickness, const in float ior, const in mat4 modelMatrix ) {\n\t\tvec3 refractionVector = refract( - v, normalize( n ), 1.0 / ior );\n\t\tvec3 modelScale;\n\t\tmodelScale.x = length( vec3( modelMatrix[ 0 ].xyz ) );\n\t\tmodelScale.y = length( vec3( modelMatrix[ 1 ].xyz ) );\n\t\tmodelScale.z = length( vec3( modelMatrix[ 2 ].xyz ) );\n\t\treturn normalize( refractionVector ) * thickness * modelScale;\n\t}\n\tfloat applyIorToRoughness( const in float roughness, const in float ior ) {\n\t\treturn roughness * clamp( ior * 2.0 - 2.0, 0.0, 1.0 );\n\t}\n\tvec4 getTransmissionSample( const in vec2 fragCoord, const in float roughness, const in float ior ) {\n\t\tfloat framebufferLod = log2( transmissionSamplerSize.x ) * applyIorToRoughness( roughness, ior );\n\t\t#ifdef texture2DLodEXT\n\t\t\treturn texture2DLodEXT( transmissionSamplerMap, fragCoord.xy, framebufferLod );\n\t\t#else\n\t\t\treturn texture2D( transmissionSamplerMap, fragCoord.xy, framebufferLod );\n\t\t#endif\n\t}\n\tvec3 applyVolumeAttenuation( const in vec3 radiance, const in float transmissionDistance, const in vec3 attenuationColor, const in float attenuationDistance ) {\n\t\tif ( isinf( attenuationDistance ) ) {\n\t\t\treturn radiance;\n\t\t} else {\n\t\t\tvec3 attenuationCoefficient = -log( attenuationColor ) / attenuationDistance;\n\t\t\tvec3 transmittance = exp( - attenuationCoefficient * transmissionDistance );\t\t\treturn transmittance * radiance;\n\t\t}\n\t}\n\tvec4 getIBLVolumeRefraction( const in vec3 n, const in vec3 v, const in float roughness, const in vec3 diffuseColor,\n\t\tconst in vec3 specularColor, const in float specularF90, const in vec3 position, const in mat4 modelMatrix,\n\t\tconst in mat4 viewMatrix, const in mat4 projMatrix, const in float ior, const in float thickness,\n\t\tconst in vec3 attenuationColor, const in float attenuationDistance ) {\n\t\tvec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );\n\t\tvec3 refractedRayExit = position + transmissionRay;\n\t\tvec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 );\n\t\tvec2 refractionCoords = ndcPos.xy / ndcPos.w;\n\t\trefractionCoords += 1.0;\n\t\trefractionCoords /= 2.0;\n\t\tvec4 transmittedLight = getTransmissionSample( refractionCoords, roughness, ior );\n\t\tvec3 attenuatedColor = applyVolumeAttenuation( transmittedLight.rgb, length( transmissionRay ), attenuationColor, attenuationDistance );\n\t\tvec3 F = EnvironmentBRDF( n, v, specularColor, specularF90, roughness );\n\t\treturn vec4( ( 1.0 - F ) * attenuatedColor * diffuseColor, transmittedLight.a );\n\t}\n#endif";
  7982. var uv_pars_fragment = "#if ( defined( USE_UV ) && ! defined( UVS_VERTEX_ONLY ) )\n\tvarying vec2 vUv;\n#endif";
  7983. var uv_pars_vertex = "#ifdef USE_UV\n\t#ifdef UVS_VERTEX_ONLY\n\t\tvec2 vUv;\n\t#else\n\t\tvarying vec2 vUv;\n\t#endif\n\tuniform mat3 uvTransform;\n#endif";
  7984. var uv_vertex = "#ifdef USE_UV\n\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n#endif";
  7985. var uv2_pars_fragment = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvarying vec2 vUv2;\n#endif";
  7986. var uv2_pars_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tattribute vec2 uv2;\n\tvarying vec2 vUv2;\n\tuniform mat3 uv2Transform;\n#endif";
  7987. var uv2_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvUv2 = ( uv2Transform * vec3( uv2, 1 ) ).xy;\n#endif";
  7988. var worldpos_vertex = "#if defined( USE_ENVMAP ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP ) || defined ( USE_TRANSMISSION ) || NUM_SPOT_LIGHT_COORDS > 0\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";
  7989. const vertex$g = "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}";
  7990. const fragment$g = "uniform sampler2D t2D;\nvarying vec2 vUv;\nvoid main() {\n\tgl_FragColor = texture2D( t2D, vUv );\n\t#ifdef DECODE_VIDEO_TEXTURE\n\t\tgl_FragColor = vec4( mix( pow( gl_FragColor.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), gl_FragColor.rgb * 0.0773993808, vec3( lessThanEqual( gl_FragColor.rgb, vec3( 0.04045 ) ) ) ), gl_FragColor.w );\n\t#endif\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n}";
  7991. const vertex$f = "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}";
  7992. const fragment$f = "#include <envmap_common_pars_fragment>\nuniform float opacity;\nvarying vec3 vWorldDirection;\n#include <cube_uv_reflection_fragment>\nvoid main() {\n\tvec3 vReflect = vWorldDirection;\n\t#include <envmap_fragment>\n\tgl_FragColor = envColor;\n\tgl_FragColor.a *= opacity;\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n}";
  7993. const vertex$e = "#include <common>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvarying vec2 vHighPrecisionZW;\nvoid main() {\n\t#include <uv_vertex>\n\t#include <skinbase_vertex>\n\t#ifdef USE_DISPLACEMENTMAP\n\t\t#include <beginnormal_vertex>\n\t\t#include <morphnormal_vertex>\n\t\t#include <skinnormal_vertex>\n\t#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvHighPrecisionZW = gl_Position.zw;\n}";
  7994. const fragment$e = "#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 <alphatest_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvarying vec2 vHighPrecisionZW;\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( 1.0 );\n\t#if DEPTH_PACKING == 3200\n\t\tdiffuseColor.a = opacity;\n\t#endif\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <logdepthbuf_fragment>\n\tfloat fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5;\n\t#if DEPTH_PACKING == 3200\n\t\tgl_FragColor = vec4( vec3( 1.0 - fragCoordZ ), opacity );\n\t#elif DEPTH_PACKING == 3201\n\t\tgl_FragColor = packDepthToRGBA( fragCoordZ );\n\t#endif\n}";
  7995. const vertex$d = "#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}";
  7996. const fragment$d = "#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 <alphatest_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}";
  7997. const vertex$c = "varying vec3 vWorldDirection;\n#include <common>\nvoid main() {\n\tvWorldDirection = transformDirection( position, modelMatrix );\n\t#include <begin_vertex>\n\t#include <project_vertex>\n}";
  7998. const fragment$c = "uniform sampler2D tEquirect;\nvarying vec3 vWorldDirection;\n#include <common>\nvoid main() {\n\tvec3 direction = normalize( vWorldDirection );\n\tvec2 sampleUV = equirectUv( direction );\n\tgl_FragColor = texture2D( tEquirect, sampleUV );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n}";
  7999. const vertex$b = "uniform float scale;\nattribute float lineDistance;\nvarying float vLineDistance;\n#include <common>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\tvLineDistance = scale * lineDistance;\n\t#include <color_vertex>\n\t#include <morphcolor_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <fog_vertex>\n}";
  8000. const fragment$b = "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\t#include <output_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n}";
  8001. const vertex$a = "#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 <morphcolor_vertex>\n\t#if defined ( USE_ENVMAP ) || defined ( USE_SKINNING )\n\t\t#include <beginnormal_vertex>\n\t\t#include <morphnormal_vertex>\n\t\t#include <skinbase_vertex>\n\t\t#include <skinnormal_vertex>\n\t\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 <clipping_planes_vertex>\n\t#include <worldpos_vertex>\n\t#include <envmap_vertex>\n\t#include <fog_vertex>\n}";
  8002. const fragment$a = "uniform vec3 diffuse;\nuniform float opacity;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_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\tvec4 lightMapTexel = texture2D( lightMap, vUv2 );\n\t\treflectedLight.indirectDiffuse += lightMapTexel.rgb * lightMapIntensity * RECIPROCAL_PI;\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\t#include <output_fragment>\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}";
  8003. const vertex$9 = "#define LAMBERT\nvarying vec3 vViewPosition;\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 <normal_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 <morphcolor_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 <normal_vertex>\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}";
  8004. const fragment$9 = "#define LAMBERT\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_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 <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <normal_pars_fragment>\n#include <lights_lambert_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_lambert_fragment>\n\t#include <lights_fragment_begin>\n\t#include <lights_fragment_maps>\n\t#include <lights_fragment_end>\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\t#include <envmap_fragment>\n\t#include <output_fragment>\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}";
  8005. const vertex$8 = "#define MATCAP\nvarying vec3 vViewPosition;\n#include <common>\n#include <uv_pars_vertex>\n#include <color_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <fog_pars_vertex>\n#include <normal_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <color_vertex>\n\t#include <morphcolor_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 <normal_vertex>\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}";
  8006. const fragment$8 = "#define MATCAP\nuniform vec3 diffuse;\nuniform float opacity;\nuniform sampler2D matcap;\nvarying vec3 vViewPosition;\n#include <common>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <fog_pars_fragment>\n#include <normal_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\tvec3 viewDir = normalize( vViewPosition );\n\tvec3 x = normalize( vec3( viewDir.z, 0.0, - viewDir.x ) );\n\tvec3 y = cross( viewDir, x );\n\tvec2 uv = vec2( dot( x, normal ), dot( y, normal ) ) * 0.495 + 0.5;\n\t#ifdef USE_MATCAP\n\t\tvec4 matcapColor = texture2D( matcap, uv );\n\t#else\n\t\tvec4 matcapColor = vec4( vec3( mix( 0.2, 0.8, uv.y ) ), 1.0 );\n\t#endif\n\tvec3 outgoingLight = diffuseColor.rgb * matcapColor.rgb;\n\t#include <output_fragment>\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}";
  8007. const vertex$7 = "#define NORMAL\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP )\n\tvarying vec3 vViewPosition;\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <normal_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#include <normal_vertex>\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}";
  8008. const fragment$7 = "#define NORMAL\nuniform float opacity;\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP )\n\tvarying vec3 vViewPosition;\n#endif\n#include <packing>\n#include <uv_pars_fragment>\n#include <normal_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\t#ifdef OPAQUE\n\t\tgl_FragColor.a = 1.0;\n\t#endif\n}";
  8009. const vertex$6 = "#define PHONG\nvarying vec3 vViewPosition;\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 <normal_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 <morphcolor_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 <normal_vertex>\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}";
  8010. const fragment$6 = "#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 <alphatest_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 <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <normal_pars_fragment>\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\t#include <output_fragment>\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}";
  8011. const vertex$5 = "#define STANDARD\nvarying vec3 vViewPosition;\n#ifdef USE_TRANSMISSION\n\tvarying vec3 vWorldPosition;\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 <normal_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 <morphcolor_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 <normal_vertex>\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#ifdef USE_TRANSMISSION\n\tvWorldPosition = worldPosition.xyz;\n#endif\n}";
  8012. const fragment$5 = "#define STANDARD\n#ifdef PHYSICAL\n\t#define IOR\n\t#define SPECULAR\n#endif\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float roughness;\nuniform float metalness;\nuniform float opacity;\n#ifdef IOR\n\tuniform float ior;\n#endif\n#ifdef SPECULAR\n\tuniform float specularIntensity;\n\tuniform vec3 specularColor;\n\t#ifdef USE_SPECULARINTENSITYMAP\n\t\tuniform sampler2D specularIntensityMap;\n\t#endif\n\t#ifdef USE_SPECULARCOLORMAP\n\t\tuniform sampler2D specularColorMap;\n\t#endif\n#endif\n#ifdef USE_CLEARCOAT\n\tuniform float clearcoat;\n\tuniform float clearcoatRoughness;\n#endif\n#ifdef USE_IRIDESCENCE\n\tuniform float iridescence;\n\tuniform float iridescenceIOR;\n\tuniform float iridescenceThicknessMinimum;\n\tuniform float iridescenceThicknessMaximum;\n#endif\n#ifdef USE_SHEEN\n\tuniform vec3 sheenColor;\n\tuniform float sheenRoughness;\n\t#ifdef USE_SHEENCOLORMAP\n\t\tuniform sampler2D sheenColorMap;\n\t#endif\n\t#ifdef USE_SHEENROUGHNESSMAP\n\t\tuniform sampler2D sheenRoughnessMap;\n\t#endif\n#endif\nvarying vec3 vViewPosition;\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 <alphatest_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <bsdfs>\n#include <iridescence_fragment>\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 <normal_pars_fragment>\n#include <lights_physical_pars_fragment>\n#include <transmission_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <clearcoat_pars_fragment>\n#include <iridescence_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 totalDiffuse = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse;\n\tvec3 totalSpecular = reflectedLight.directSpecular + reflectedLight.indirectSpecular;\n\t#include <transmission_fragment>\n\tvec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance;\n\t#ifdef USE_SHEEN\n\t\tfloat sheenEnergyComp = 1.0 - 0.157 * max3( material.sheenColor );\n\t\toutgoingLight = outgoingLight * sheenEnergyComp + sheenSpecular;\n\t#endif\n\t#ifdef USE_CLEARCOAT\n\t\tfloat dotNVcc = saturate( dot( geometry.clearcoatNormal, geometry.viewDir ) );\n\t\tvec3 Fcc = F_Schlick( material.clearcoatF0, material.clearcoatF90, dotNVcc );\n\t\toutgoingLight = outgoingLight * ( 1.0 - material.clearcoat * Fcc ) + clearcoatSpecular * material.clearcoat;\n\t#endif\n\t#include <output_fragment>\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}";
  8013. const vertex$4 = "#define TOON\nvarying vec3 vViewPosition;\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 <normal_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 <morphcolor_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 <normal_vertex>\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}";
  8014. const fragment$4 = "#define TOON\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <gradientmap_pars_fragment>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <normal_pars_fragment>\n#include <lights_toon_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\t#include <emissivemap_fragment>\n\t#include <lights_toon_fragment>\n\t#include <lights_fragment_begin>\n\t#include <lights_fragment_maps>\n\t#include <lights_fragment_end>\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\t#include <output_fragment>\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}";
  8015. const vertex$3 = "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 <morphcolor_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}";
  8016. const fragment$3 = "uniform vec3 diffuse;\nuniform float opacity;\n#include <common>\n#include <color_pars_fragment>\n#include <map_particle_pars_fragment>\n#include <alphatest_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\t#include <output_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n}";
  8017. const vertex$2 = "#include <common>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\nvoid main() {\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 <worldpos_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}";
  8018. const fragment$2 = "uniform vec3 color;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <shadowmap_pars_fragment>\n#include <shadowmask_pars_fragment>\nvoid main() {\n\tgl_FragColor = vec4( color, opacity * ( 1.0 - getShadowMask() ) );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n}";
  8019. const vertex$1 = "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}";
  8020. const fragment$1 = "uniform vec3 diffuse;\nuniform float opacity;\n#include <common>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <fog_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\t#include <output_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n}";
  8021. const ShaderChunk = {
  8022. alphamap_fragment: alphamap_fragment,
  8023. alphamap_pars_fragment: alphamap_pars_fragment,
  8024. alphatest_fragment: alphatest_fragment,
  8025. alphatest_pars_fragment: alphatest_pars_fragment,
  8026. aomap_fragment: aomap_fragment,
  8027. aomap_pars_fragment: aomap_pars_fragment,
  8028. begin_vertex: begin_vertex,
  8029. beginnormal_vertex: beginnormal_vertex,
  8030. bsdfs: bsdfs,
  8031. iridescence_fragment: iridescence_fragment,
  8032. bumpmap_pars_fragment: bumpmap_pars_fragment,
  8033. clipping_planes_fragment: clipping_planes_fragment,
  8034. clipping_planes_pars_fragment: clipping_planes_pars_fragment,
  8035. clipping_planes_pars_vertex: clipping_planes_pars_vertex,
  8036. clipping_planes_vertex: clipping_planes_vertex,
  8037. color_fragment: color_fragment,
  8038. color_pars_fragment: color_pars_fragment,
  8039. color_pars_vertex: color_pars_vertex,
  8040. color_vertex: color_vertex,
  8041. common: common,
  8042. cube_uv_reflection_fragment: cube_uv_reflection_fragment,
  8043. defaultnormal_vertex: defaultnormal_vertex,
  8044. displacementmap_pars_vertex: displacementmap_pars_vertex,
  8045. displacementmap_vertex: displacementmap_vertex,
  8046. emissivemap_fragment: emissivemap_fragment,
  8047. emissivemap_pars_fragment: emissivemap_pars_fragment,
  8048. encodings_fragment: encodings_fragment,
  8049. encodings_pars_fragment: encodings_pars_fragment,
  8050. envmap_fragment: envmap_fragment,
  8051. envmap_common_pars_fragment: envmap_common_pars_fragment,
  8052. envmap_pars_fragment: envmap_pars_fragment,
  8053. envmap_pars_vertex: envmap_pars_vertex,
  8054. envmap_physical_pars_fragment: envmap_physical_pars_fragment,
  8055. envmap_vertex: envmap_vertex,
  8056. fog_vertex: fog_vertex,
  8057. fog_pars_vertex: fog_pars_vertex,
  8058. fog_fragment: fog_fragment,
  8059. fog_pars_fragment: fog_pars_fragment,
  8060. gradientmap_pars_fragment: gradientmap_pars_fragment,
  8061. lightmap_fragment: lightmap_fragment,
  8062. lightmap_pars_fragment: lightmap_pars_fragment,
  8063. lights_lambert_fragment: lights_lambert_fragment,
  8064. lights_lambert_pars_fragment: lights_lambert_pars_fragment,
  8065. lights_pars_begin: lights_pars_begin,
  8066. lights_toon_fragment: lights_toon_fragment,
  8067. lights_toon_pars_fragment: lights_toon_pars_fragment,
  8068. lights_phong_fragment: lights_phong_fragment,
  8069. lights_phong_pars_fragment: lights_phong_pars_fragment,
  8070. lights_physical_fragment: lights_physical_fragment,
  8071. lights_physical_pars_fragment: lights_physical_pars_fragment,
  8072. lights_fragment_begin: lights_fragment_begin,
  8073. lights_fragment_maps: lights_fragment_maps,
  8074. lights_fragment_end: lights_fragment_end,
  8075. logdepthbuf_fragment: logdepthbuf_fragment,
  8076. logdepthbuf_pars_fragment: logdepthbuf_pars_fragment,
  8077. logdepthbuf_pars_vertex: logdepthbuf_pars_vertex,
  8078. logdepthbuf_vertex: logdepthbuf_vertex,
  8079. map_fragment: map_fragment,
  8080. map_pars_fragment: map_pars_fragment,
  8081. map_particle_fragment: map_particle_fragment,
  8082. map_particle_pars_fragment: map_particle_pars_fragment,
  8083. metalnessmap_fragment: metalnessmap_fragment,
  8084. metalnessmap_pars_fragment: metalnessmap_pars_fragment,
  8085. morphcolor_vertex: morphcolor_vertex,
  8086. morphnormal_vertex: morphnormal_vertex,
  8087. morphtarget_pars_vertex: morphtarget_pars_vertex,
  8088. morphtarget_vertex: morphtarget_vertex,
  8089. normal_fragment_begin: normal_fragment_begin,
  8090. normal_fragment_maps: normal_fragment_maps,
  8091. normal_pars_fragment: normal_pars_fragment,
  8092. normal_pars_vertex: normal_pars_vertex,
  8093. normal_vertex: normal_vertex,
  8094. normalmap_pars_fragment: normalmap_pars_fragment,
  8095. clearcoat_normal_fragment_begin: clearcoat_normal_fragment_begin,
  8096. clearcoat_normal_fragment_maps: clearcoat_normal_fragment_maps,
  8097. clearcoat_pars_fragment: clearcoat_pars_fragment,
  8098. iridescence_pars_fragment: iridescence_pars_fragment,
  8099. output_fragment: output_fragment,
  8100. packing: packing,
  8101. premultiplied_alpha_fragment: premultiplied_alpha_fragment,
  8102. project_vertex: project_vertex,
  8103. dithering_fragment: dithering_fragment,
  8104. dithering_pars_fragment: dithering_pars_fragment,
  8105. roughnessmap_fragment: roughnessmap_fragment,
  8106. roughnessmap_pars_fragment: roughnessmap_pars_fragment,
  8107. shadowmap_pars_fragment: shadowmap_pars_fragment,
  8108. shadowmap_pars_vertex: shadowmap_pars_vertex,
  8109. shadowmap_vertex: shadowmap_vertex,
  8110. shadowmask_pars_fragment: shadowmask_pars_fragment,
  8111. skinbase_vertex: skinbase_vertex,
  8112. skinning_pars_vertex: skinning_pars_vertex,
  8113. skinning_vertex: skinning_vertex,
  8114. skinnormal_vertex: skinnormal_vertex,
  8115. specularmap_fragment: specularmap_fragment,
  8116. specularmap_pars_fragment: specularmap_pars_fragment,
  8117. tonemapping_fragment: tonemapping_fragment,
  8118. tonemapping_pars_fragment: tonemapping_pars_fragment,
  8119. transmission_fragment: transmission_fragment,
  8120. transmission_pars_fragment: transmission_pars_fragment,
  8121. uv_pars_fragment: uv_pars_fragment,
  8122. uv_pars_vertex: uv_pars_vertex,
  8123. uv_vertex: uv_vertex,
  8124. uv2_pars_fragment: uv2_pars_fragment,
  8125. uv2_pars_vertex: uv2_pars_vertex,
  8126. uv2_vertex: uv2_vertex,
  8127. worldpos_vertex: worldpos_vertex,
  8128. background_vert: vertex$g,
  8129. background_frag: fragment$g,
  8130. cube_vert: vertex$f,
  8131. cube_frag: fragment$f,
  8132. depth_vert: vertex$e,
  8133. depth_frag: fragment$e,
  8134. distanceRGBA_vert: vertex$d,
  8135. distanceRGBA_frag: fragment$d,
  8136. equirect_vert: vertex$c,
  8137. equirect_frag: fragment$c,
  8138. linedashed_vert: vertex$b,
  8139. linedashed_frag: fragment$b,
  8140. meshbasic_vert: vertex$a,
  8141. meshbasic_frag: fragment$a,
  8142. meshlambert_vert: vertex$9,
  8143. meshlambert_frag: fragment$9,
  8144. meshmatcap_vert: vertex$8,
  8145. meshmatcap_frag: fragment$8,
  8146. meshnormal_vert: vertex$7,
  8147. meshnormal_frag: fragment$7,
  8148. meshphong_vert: vertex$6,
  8149. meshphong_frag: fragment$6,
  8150. meshphysical_vert: vertex$5,
  8151. meshphysical_frag: fragment$5,
  8152. meshtoon_vert: vertex$4,
  8153. meshtoon_frag: fragment$4,
  8154. points_vert: vertex$3,
  8155. points_frag: fragment$3,
  8156. shadow_vert: vertex$2,
  8157. shadow_frag: fragment$2,
  8158. sprite_vert: vertex$1,
  8159. sprite_frag: fragment$1
  8160. };
  8161. /**
  8162. * Uniforms library for shared webgl shaders
  8163. */
  8164. const UniformsLib = {
  8165. common: {
  8166. diffuse: {
  8167. value: /*@__PURE__*/new Color(0xffffff)
  8168. },
  8169. opacity: {
  8170. value: 1.0
  8171. },
  8172. map: {
  8173. value: null
  8174. },
  8175. uvTransform: {
  8176. value: /*@__PURE__*/new Matrix3()
  8177. },
  8178. uv2Transform: {
  8179. value: /*@__PURE__*/new Matrix3()
  8180. },
  8181. alphaMap: {
  8182. value: null
  8183. },
  8184. alphaTest: {
  8185. value: 0
  8186. }
  8187. },
  8188. specularmap: {
  8189. specularMap: {
  8190. value: null
  8191. }
  8192. },
  8193. envmap: {
  8194. envMap: {
  8195. value: null
  8196. },
  8197. flipEnvMap: {
  8198. value: -1
  8199. },
  8200. reflectivity: {
  8201. value: 1.0
  8202. },
  8203. // basic, lambert, phong
  8204. ior: {
  8205. value: 1.5
  8206. },
  8207. // physical
  8208. refractionRatio: {
  8209. value: 0.98
  8210. } // basic, lambert, phong
  8211. },
  8212. aomap: {
  8213. aoMap: {
  8214. value: null
  8215. },
  8216. aoMapIntensity: {
  8217. value: 1
  8218. }
  8219. },
  8220. lightmap: {
  8221. lightMap: {
  8222. value: null
  8223. },
  8224. lightMapIntensity: {
  8225. value: 1
  8226. }
  8227. },
  8228. emissivemap: {
  8229. emissiveMap: {
  8230. value: null
  8231. }
  8232. },
  8233. bumpmap: {
  8234. bumpMap: {
  8235. value: null
  8236. },
  8237. bumpScale: {
  8238. value: 1
  8239. }
  8240. },
  8241. normalmap: {
  8242. normalMap: {
  8243. value: null
  8244. },
  8245. normalScale: {
  8246. value: /*@__PURE__*/new Vector2(1, 1)
  8247. }
  8248. },
  8249. displacementmap: {
  8250. displacementMap: {
  8251. value: null
  8252. },
  8253. displacementScale: {
  8254. value: 1
  8255. },
  8256. displacementBias: {
  8257. value: 0
  8258. }
  8259. },
  8260. roughnessmap: {
  8261. roughnessMap: {
  8262. value: null
  8263. }
  8264. },
  8265. metalnessmap: {
  8266. metalnessMap: {
  8267. value: null
  8268. }
  8269. },
  8270. gradientmap: {
  8271. gradientMap: {
  8272. value: null
  8273. }
  8274. },
  8275. fog: {
  8276. fogDensity: {
  8277. value: 0.00025
  8278. },
  8279. fogNear: {
  8280. value: 1
  8281. },
  8282. fogFar: {
  8283. value: 2000
  8284. },
  8285. fogColor: {
  8286. value: /*@__PURE__*/new Color(0xffffff)
  8287. }
  8288. },
  8289. lights: {
  8290. ambientLightColor: {
  8291. value: []
  8292. },
  8293. lightProbe: {
  8294. value: []
  8295. },
  8296. directionalLights: {
  8297. value: [],
  8298. properties: {
  8299. direction: {},
  8300. color: {}
  8301. }
  8302. },
  8303. directionalLightShadows: {
  8304. value: [],
  8305. properties: {
  8306. shadowBias: {},
  8307. shadowNormalBias: {},
  8308. shadowRadius: {},
  8309. shadowMapSize: {}
  8310. }
  8311. },
  8312. directionalShadowMap: {
  8313. value: []
  8314. },
  8315. directionalShadowMatrix: {
  8316. value: []
  8317. },
  8318. spotLights: {
  8319. value: [],
  8320. properties: {
  8321. color: {},
  8322. position: {},
  8323. direction: {},
  8324. distance: {},
  8325. coneCos: {},
  8326. penumbraCos: {},
  8327. decay: {}
  8328. }
  8329. },
  8330. spotLightShadows: {
  8331. value: [],
  8332. properties: {
  8333. shadowBias: {},
  8334. shadowNormalBias: {},
  8335. shadowRadius: {},
  8336. shadowMapSize: {}
  8337. }
  8338. },
  8339. spotLightMap: {
  8340. value: []
  8341. },
  8342. spotShadowMap: {
  8343. value: []
  8344. },
  8345. spotLightMatrix: {
  8346. value: []
  8347. },
  8348. pointLights: {
  8349. value: [],
  8350. properties: {
  8351. color: {},
  8352. position: {},
  8353. decay: {},
  8354. distance: {}
  8355. }
  8356. },
  8357. pointLightShadows: {
  8358. value: [],
  8359. properties: {
  8360. shadowBias: {},
  8361. shadowNormalBias: {},
  8362. shadowRadius: {},
  8363. shadowMapSize: {},
  8364. shadowCameraNear: {},
  8365. shadowCameraFar: {}
  8366. }
  8367. },
  8368. pointShadowMap: {
  8369. value: []
  8370. },
  8371. pointShadowMatrix: {
  8372. value: []
  8373. },
  8374. hemisphereLights: {
  8375. value: [],
  8376. properties: {
  8377. direction: {},
  8378. skyColor: {},
  8379. groundColor: {}
  8380. }
  8381. },
  8382. // TODO (abelnation): RectAreaLight BRDF data needs to be moved from example to main src
  8383. rectAreaLights: {
  8384. value: [],
  8385. properties: {
  8386. color: {},
  8387. position: {},
  8388. width: {},
  8389. height: {}
  8390. }
  8391. },
  8392. ltc_1: {
  8393. value: null
  8394. },
  8395. ltc_2: {
  8396. value: null
  8397. }
  8398. },
  8399. points: {
  8400. diffuse: {
  8401. value: /*@__PURE__*/new Color(0xffffff)
  8402. },
  8403. opacity: {
  8404. value: 1.0
  8405. },
  8406. size: {
  8407. value: 1.0
  8408. },
  8409. scale: {
  8410. value: 1.0
  8411. },
  8412. map: {
  8413. value: null
  8414. },
  8415. alphaMap: {
  8416. value: null
  8417. },
  8418. alphaTest: {
  8419. value: 0
  8420. },
  8421. uvTransform: {
  8422. value: /*@__PURE__*/new Matrix3()
  8423. }
  8424. },
  8425. sprite: {
  8426. diffuse: {
  8427. value: /*@__PURE__*/new Color(0xffffff)
  8428. },
  8429. opacity: {
  8430. value: 1.0
  8431. },
  8432. center: {
  8433. value: /*@__PURE__*/new Vector2(0.5, 0.5)
  8434. },
  8435. rotation: {
  8436. value: 0.0
  8437. },
  8438. map: {
  8439. value: null
  8440. },
  8441. alphaMap: {
  8442. value: null
  8443. },
  8444. alphaTest: {
  8445. value: 0
  8446. },
  8447. uvTransform: {
  8448. value: /*@__PURE__*/new Matrix3()
  8449. }
  8450. }
  8451. };
  8452. const ShaderLib = {
  8453. basic: {
  8454. uniforms: /*@__PURE__*/mergeUniforms([UniformsLib.common, UniformsLib.specularmap, UniformsLib.envmap, UniformsLib.aomap, UniformsLib.lightmap, UniformsLib.fog]),
  8455. vertexShader: ShaderChunk.meshbasic_vert,
  8456. fragmentShader: ShaderChunk.meshbasic_frag
  8457. },
  8458. lambert: {
  8459. uniforms: /*@__PURE__*/mergeUniforms([UniformsLib.common, UniformsLib.specularmap, UniformsLib.envmap, UniformsLib.aomap, UniformsLib.lightmap, UniformsLib.emissivemap, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, UniformsLib.fog, UniformsLib.lights, {
  8460. emissive: {
  8461. value: /*@__PURE__*/new Color(0x000000)
  8462. }
  8463. }]),
  8464. vertexShader: ShaderChunk.meshlambert_vert,
  8465. fragmentShader: ShaderChunk.meshlambert_frag
  8466. },
  8467. phong: {
  8468. uniforms: /*@__PURE__*/mergeUniforms([UniformsLib.common, UniformsLib.specularmap, UniformsLib.envmap, UniformsLib.aomap, UniformsLib.lightmap, UniformsLib.emissivemap, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, UniformsLib.fog, UniformsLib.lights, {
  8469. emissive: {
  8470. value: /*@__PURE__*/new Color(0x000000)
  8471. },
  8472. specular: {
  8473. value: /*@__PURE__*/new Color(0x111111)
  8474. },
  8475. shininess: {
  8476. value: 30
  8477. }
  8478. }]),
  8479. vertexShader: ShaderChunk.meshphong_vert,
  8480. fragmentShader: ShaderChunk.meshphong_frag
  8481. },
  8482. standard: {
  8483. uniforms: /*@__PURE__*/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, {
  8484. emissive: {
  8485. value: /*@__PURE__*/new Color(0x000000)
  8486. },
  8487. roughness: {
  8488. value: 1.0
  8489. },
  8490. metalness: {
  8491. value: 0.0
  8492. },
  8493. envMapIntensity: {
  8494. value: 1
  8495. } // temporary
  8496. }]),
  8497. vertexShader: ShaderChunk.meshphysical_vert,
  8498. fragmentShader: ShaderChunk.meshphysical_frag
  8499. },
  8500. toon: {
  8501. uniforms: /*@__PURE__*/mergeUniforms([UniformsLib.common, UniformsLib.aomap, UniformsLib.lightmap, UniformsLib.emissivemap, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, UniformsLib.gradientmap, UniformsLib.fog, UniformsLib.lights, {
  8502. emissive: {
  8503. value: /*@__PURE__*/new Color(0x000000)
  8504. }
  8505. }]),
  8506. vertexShader: ShaderChunk.meshtoon_vert,
  8507. fragmentShader: ShaderChunk.meshtoon_frag
  8508. },
  8509. matcap: {
  8510. uniforms: /*@__PURE__*/mergeUniforms([UniformsLib.common, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, UniformsLib.fog, {
  8511. matcap: {
  8512. value: null
  8513. }
  8514. }]),
  8515. vertexShader: ShaderChunk.meshmatcap_vert,
  8516. fragmentShader: ShaderChunk.meshmatcap_frag
  8517. },
  8518. points: {
  8519. uniforms: /*@__PURE__*/mergeUniforms([UniformsLib.points, UniformsLib.fog]),
  8520. vertexShader: ShaderChunk.points_vert,
  8521. fragmentShader: ShaderChunk.points_frag
  8522. },
  8523. dashed: {
  8524. uniforms: /*@__PURE__*/mergeUniforms([UniformsLib.common, UniformsLib.fog, {
  8525. scale: {
  8526. value: 1
  8527. },
  8528. dashSize: {
  8529. value: 1
  8530. },
  8531. totalSize: {
  8532. value: 2
  8533. }
  8534. }]),
  8535. vertexShader: ShaderChunk.linedashed_vert,
  8536. fragmentShader: ShaderChunk.linedashed_frag
  8537. },
  8538. depth: {
  8539. uniforms: /*@__PURE__*/mergeUniforms([UniformsLib.common, UniformsLib.displacementmap]),
  8540. vertexShader: ShaderChunk.depth_vert,
  8541. fragmentShader: ShaderChunk.depth_frag
  8542. },
  8543. normal: {
  8544. uniforms: /*@__PURE__*/mergeUniforms([UniformsLib.common, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, {
  8545. opacity: {
  8546. value: 1.0
  8547. }
  8548. }]),
  8549. vertexShader: ShaderChunk.meshnormal_vert,
  8550. fragmentShader: ShaderChunk.meshnormal_frag
  8551. },
  8552. sprite: {
  8553. uniforms: /*@__PURE__*/mergeUniforms([UniformsLib.sprite, UniformsLib.fog]),
  8554. vertexShader: ShaderChunk.sprite_vert,
  8555. fragmentShader: ShaderChunk.sprite_frag
  8556. },
  8557. background: {
  8558. uniforms: {
  8559. uvTransform: {
  8560. value: /*@__PURE__*/new Matrix3()
  8561. },
  8562. t2D: {
  8563. value: null
  8564. }
  8565. },
  8566. vertexShader: ShaderChunk.background_vert,
  8567. fragmentShader: ShaderChunk.background_frag
  8568. },
  8569. cube: {
  8570. uniforms: /*@__PURE__*/mergeUniforms([UniformsLib.envmap, {
  8571. opacity: {
  8572. value: 1.0
  8573. }
  8574. }]),
  8575. vertexShader: ShaderChunk.cube_vert,
  8576. fragmentShader: ShaderChunk.cube_frag
  8577. },
  8578. equirect: {
  8579. uniforms: {
  8580. tEquirect: {
  8581. value: null
  8582. }
  8583. },
  8584. vertexShader: ShaderChunk.equirect_vert,
  8585. fragmentShader: ShaderChunk.equirect_frag
  8586. },
  8587. distanceRGBA: {
  8588. uniforms: /*@__PURE__*/mergeUniforms([UniformsLib.common, UniformsLib.displacementmap, {
  8589. referencePosition: {
  8590. value: /*@__PURE__*/new Vector3()
  8591. },
  8592. nearDistance: {
  8593. value: 1
  8594. },
  8595. farDistance: {
  8596. value: 1000
  8597. }
  8598. }]),
  8599. vertexShader: ShaderChunk.distanceRGBA_vert,
  8600. fragmentShader: ShaderChunk.distanceRGBA_frag
  8601. },
  8602. shadow: {
  8603. uniforms: /*@__PURE__*/mergeUniforms([UniformsLib.lights, UniformsLib.fog, {
  8604. color: {
  8605. value: /*@__PURE__*/new Color(0x00000)
  8606. },
  8607. opacity: {
  8608. value: 1.0
  8609. }
  8610. }]),
  8611. vertexShader: ShaderChunk.shadow_vert,
  8612. fragmentShader: ShaderChunk.shadow_frag
  8613. }
  8614. };
  8615. ShaderLib.physical = {
  8616. uniforms: /*@__PURE__*/mergeUniforms([ShaderLib.standard.uniforms, {
  8617. clearcoat: {
  8618. value: 0
  8619. },
  8620. clearcoatMap: {
  8621. value: null
  8622. },
  8623. clearcoatRoughness: {
  8624. value: 0
  8625. },
  8626. clearcoatRoughnessMap: {
  8627. value: null
  8628. },
  8629. clearcoatNormalScale: {
  8630. value: /*@__PURE__*/new Vector2(1, 1)
  8631. },
  8632. clearcoatNormalMap: {
  8633. value: null
  8634. },
  8635. iridescence: {
  8636. value: 0
  8637. },
  8638. iridescenceMap: {
  8639. value: null
  8640. },
  8641. iridescenceIOR: {
  8642. value: 1.3
  8643. },
  8644. iridescenceThicknessMinimum: {
  8645. value: 100
  8646. },
  8647. iridescenceThicknessMaximum: {
  8648. value: 400
  8649. },
  8650. iridescenceThicknessMap: {
  8651. value: null
  8652. },
  8653. sheen: {
  8654. value: 0
  8655. },
  8656. sheenColor: {
  8657. value: /*@__PURE__*/new Color(0x000000)
  8658. },
  8659. sheenColorMap: {
  8660. value: null
  8661. },
  8662. sheenRoughness: {
  8663. value: 1
  8664. },
  8665. sheenRoughnessMap: {
  8666. value: null
  8667. },
  8668. transmission: {
  8669. value: 0
  8670. },
  8671. transmissionMap: {
  8672. value: null
  8673. },
  8674. transmissionSamplerSize: {
  8675. value: /*@__PURE__*/new Vector2()
  8676. },
  8677. transmissionSamplerMap: {
  8678. value: null
  8679. },
  8680. thickness: {
  8681. value: 0
  8682. },
  8683. thicknessMap: {
  8684. value: null
  8685. },
  8686. attenuationDistance: {
  8687. value: 0
  8688. },
  8689. attenuationColor: {
  8690. value: /*@__PURE__*/new Color(0x000000)
  8691. },
  8692. specularIntensity: {
  8693. value: 1
  8694. },
  8695. specularIntensityMap: {
  8696. value: null
  8697. },
  8698. specularColor: {
  8699. value: /*@__PURE__*/new Color(1, 1, 1)
  8700. },
  8701. specularColorMap: {
  8702. value: null
  8703. }
  8704. }]),
  8705. vertexShader: ShaderChunk.meshphysical_vert,
  8706. fragmentShader: ShaderChunk.meshphysical_frag
  8707. };
  8708. function WebGLBackground(renderer, cubemaps, state, objects, alpha, premultipliedAlpha) {
  8709. const clearColor = new Color(0x000000);
  8710. let clearAlpha = alpha === true ? 0 : 1;
  8711. let planeMesh;
  8712. let boxMesh;
  8713. let currentBackground = null;
  8714. let currentBackgroundVersion = 0;
  8715. let currentTonemapping = null;
  8716. function render(renderList, scene) {
  8717. let forceClear = false;
  8718. let background = scene.isScene === true ? scene.background : null;
  8719. if (background && background.isTexture) {
  8720. background = cubemaps.get(background);
  8721. } // Ignore background in AR
  8722. // TODO: Reconsider this.
  8723. const xr = renderer.xr;
  8724. const session = xr.getSession && xr.getSession();
  8725. if (session && session.environmentBlendMode === 'additive') {
  8726. background = null;
  8727. }
  8728. if (background === null) {
  8729. setClear(clearColor, clearAlpha);
  8730. } else if (background && background.isColor) {
  8731. setClear(background, 1);
  8732. forceClear = true;
  8733. }
  8734. if (renderer.autoClear || forceClear) {
  8735. renderer.clear(renderer.autoClearColor, renderer.autoClearDepth, renderer.autoClearStencil);
  8736. }
  8737. if (background && (background.isCubeTexture || background.mapping === CubeUVReflectionMapping)) {
  8738. if (boxMesh === undefined) {
  8739. boxMesh = new Mesh(new BoxGeometry(1, 1, 1), new ShaderMaterial({
  8740. name: 'BackgroundCubeMaterial',
  8741. uniforms: cloneUniforms(ShaderLib.cube.uniforms),
  8742. vertexShader: ShaderLib.cube.vertexShader,
  8743. fragmentShader: ShaderLib.cube.fragmentShader,
  8744. side: BackSide,
  8745. depthTest: false,
  8746. depthWrite: false,
  8747. fog: false
  8748. }));
  8749. boxMesh.geometry.deleteAttribute('normal');
  8750. boxMesh.geometry.deleteAttribute('uv');
  8751. boxMesh.onBeforeRender = function (renderer, scene, camera) {
  8752. this.matrixWorld.copyPosition(camera.matrixWorld);
  8753. }; // add "envMap" material property so the renderer can evaluate it like for built-in materials
  8754. Object.defineProperty(boxMesh.material, 'envMap', {
  8755. get: function () {
  8756. return this.uniforms.envMap.value;
  8757. }
  8758. });
  8759. objects.update(boxMesh);
  8760. }
  8761. boxMesh.material.uniforms.envMap.value = background;
  8762. boxMesh.material.uniforms.flipEnvMap.value = background.isCubeTexture && background.isRenderTargetTexture === false ? -1 : 1;
  8763. if (currentBackground !== background || currentBackgroundVersion !== background.version || currentTonemapping !== renderer.toneMapping) {
  8764. boxMesh.material.needsUpdate = true;
  8765. currentBackground = background;
  8766. currentBackgroundVersion = background.version;
  8767. currentTonemapping = renderer.toneMapping;
  8768. }
  8769. boxMesh.layers.enableAll(); // push to the pre-sorted opaque render list
  8770. renderList.unshift(boxMesh, boxMesh.geometry, boxMesh.material, 0, 0, null);
  8771. } else if (background && background.isTexture) {
  8772. if (planeMesh === undefined) {
  8773. planeMesh = new Mesh(new PlaneGeometry(2, 2), new ShaderMaterial({
  8774. name: 'BackgroundMaterial',
  8775. uniforms: cloneUniforms(ShaderLib.background.uniforms),
  8776. vertexShader: ShaderLib.background.vertexShader,
  8777. fragmentShader: ShaderLib.background.fragmentShader,
  8778. side: FrontSide,
  8779. depthTest: false,
  8780. depthWrite: false,
  8781. fog: false
  8782. }));
  8783. planeMesh.geometry.deleteAttribute('normal'); // add "map" material property so the renderer can evaluate it like for built-in materials
  8784. Object.defineProperty(planeMesh.material, 'map', {
  8785. get: function () {
  8786. return this.uniforms.t2D.value;
  8787. }
  8788. });
  8789. objects.update(planeMesh);
  8790. }
  8791. planeMesh.material.uniforms.t2D.value = background;
  8792. if (background.matrixAutoUpdate === true) {
  8793. background.updateMatrix();
  8794. }
  8795. planeMesh.material.uniforms.uvTransform.value.copy(background.matrix);
  8796. if (currentBackground !== background || currentBackgroundVersion !== background.version || currentTonemapping !== renderer.toneMapping) {
  8797. planeMesh.material.needsUpdate = true;
  8798. currentBackground = background;
  8799. currentBackgroundVersion = background.version;
  8800. currentTonemapping = renderer.toneMapping;
  8801. }
  8802. planeMesh.layers.enableAll(); // push to the pre-sorted opaque render list
  8803. renderList.unshift(planeMesh, planeMesh.geometry, planeMesh.material, 0, 0, null);
  8804. }
  8805. }
  8806. function setClear(color, alpha) {
  8807. state.buffers.color.setClear(color.r, color.g, color.b, alpha, premultipliedAlpha);
  8808. }
  8809. return {
  8810. getClearColor: function () {
  8811. return clearColor;
  8812. },
  8813. setClearColor: function (color, alpha = 1) {
  8814. clearColor.set(color);
  8815. clearAlpha = alpha;
  8816. setClear(clearColor, clearAlpha);
  8817. },
  8818. getClearAlpha: function () {
  8819. return clearAlpha;
  8820. },
  8821. setClearAlpha: function (alpha) {
  8822. clearAlpha = alpha;
  8823. setClear(clearColor, clearAlpha);
  8824. },
  8825. render: render
  8826. };
  8827. }
  8828. function WebGLBindingStates(gl, extensions, attributes, capabilities) {
  8829. const maxVertexAttributes = gl.getParameter(gl.MAX_VERTEX_ATTRIBS);
  8830. const extension = capabilities.isWebGL2 ? null : extensions.get('OES_vertex_array_object');
  8831. const vaoAvailable = capabilities.isWebGL2 || extension !== null;
  8832. const bindingStates = {};
  8833. const defaultState = createBindingState(null);
  8834. let currentState = defaultState;
  8835. let forceUpdate = false;
  8836. function setup(object, material, program, geometry, index) {
  8837. let updateBuffers = false;
  8838. if (vaoAvailable) {
  8839. const state = getBindingState(geometry, program, material);
  8840. if (currentState !== state) {
  8841. currentState = state;
  8842. bindVertexArrayObject(currentState.object);
  8843. }
  8844. updateBuffers = needsUpdate(object, geometry, program, index);
  8845. if (updateBuffers) saveCache(object, geometry, program, index);
  8846. } else {
  8847. const wireframe = material.wireframe === true;
  8848. if (currentState.geometry !== geometry.id || currentState.program !== program.id || currentState.wireframe !== wireframe) {
  8849. currentState.geometry = geometry.id;
  8850. currentState.program = program.id;
  8851. currentState.wireframe = wireframe;
  8852. updateBuffers = true;
  8853. }
  8854. }
  8855. if (index !== null) {
  8856. attributes.update(index, gl.ELEMENT_ARRAY_BUFFER);
  8857. }
  8858. if (updateBuffers || forceUpdate) {
  8859. forceUpdate = false;
  8860. setupVertexAttributes(object, material, program, geometry);
  8861. if (index !== null) {
  8862. gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, attributes.get(index).buffer);
  8863. }
  8864. }
  8865. }
  8866. function createVertexArrayObject() {
  8867. if (capabilities.isWebGL2) return gl.createVertexArray();
  8868. return extension.createVertexArrayOES();
  8869. }
  8870. function bindVertexArrayObject(vao) {
  8871. if (capabilities.isWebGL2) return gl.bindVertexArray(vao);
  8872. return extension.bindVertexArrayOES(vao);
  8873. }
  8874. function deleteVertexArrayObject(vao) {
  8875. if (capabilities.isWebGL2) return gl.deleteVertexArray(vao);
  8876. return extension.deleteVertexArrayOES(vao);
  8877. }
  8878. function getBindingState(geometry, program, material) {
  8879. const wireframe = material.wireframe === true;
  8880. let programMap = bindingStates[geometry.id];
  8881. if (programMap === undefined) {
  8882. programMap = {};
  8883. bindingStates[geometry.id] = programMap;
  8884. }
  8885. let stateMap = programMap[program.id];
  8886. if (stateMap === undefined) {
  8887. stateMap = {};
  8888. programMap[program.id] = stateMap;
  8889. }
  8890. let state = stateMap[wireframe];
  8891. if (state === undefined) {
  8892. state = createBindingState(createVertexArrayObject());
  8893. stateMap[wireframe] = state;
  8894. }
  8895. return state;
  8896. }
  8897. function createBindingState(vao) {
  8898. const newAttributes = [];
  8899. const enabledAttributes = [];
  8900. const attributeDivisors = [];
  8901. for (let i = 0; i < maxVertexAttributes; i++) {
  8902. newAttributes[i] = 0;
  8903. enabledAttributes[i] = 0;
  8904. attributeDivisors[i] = 0;
  8905. }
  8906. return {
  8907. // for backward compatibility on non-VAO support browser
  8908. geometry: null,
  8909. program: null,
  8910. wireframe: false,
  8911. newAttributes: newAttributes,
  8912. enabledAttributes: enabledAttributes,
  8913. attributeDivisors: attributeDivisors,
  8914. object: vao,
  8915. attributes: {},
  8916. index: null
  8917. };
  8918. }
  8919. function needsUpdate(object, geometry, program, index) {
  8920. const cachedAttributes = currentState.attributes;
  8921. const geometryAttributes = geometry.attributes;
  8922. let attributesNum = 0;
  8923. const programAttributes = program.getAttributes();
  8924. for (const name in programAttributes) {
  8925. const programAttribute = programAttributes[name];
  8926. if (programAttribute.location >= 0) {
  8927. const cachedAttribute = cachedAttributes[name];
  8928. let geometryAttribute = geometryAttributes[name];
  8929. if (geometryAttribute === undefined) {
  8930. if (name === 'instanceMatrix' && object.instanceMatrix) geometryAttribute = object.instanceMatrix;
  8931. if (name === 'instanceColor' && object.instanceColor) geometryAttribute = object.instanceColor;
  8932. }
  8933. if (cachedAttribute === undefined) return true;
  8934. if (cachedAttribute.attribute !== geometryAttribute) return true;
  8935. if (geometryAttribute && cachedAttribute.data !== geometryAttribute.data) return true;
  8936. attributesNum++;
  8937. }
  8938. }
  8939. if (currentState.attributesNum !== attributesNum) return true;
  8940. if (currentState.index !== index) return true;
  8941. return false;
  8942. }
  8943. function saveCache(object, geometry, program, index) {
  8944. const cache = {};
  8945. const attributes = geometry.attributes;
  8946. let attributesNum = 0;
  8947. const programAttributes = program.getAttributes();
  8948. for (const name in programAttributes) {
  8949. const programAttribute = programAttributes[name];
  8950. if (programAttribute.location >= 0) {
  8951. let attribute = attributes[name];
  8952. if (attribute === undefined) {
  8953. if (name === 'instanceMatrix' && object.instanceMatrix) attribute = object.instanceMatrix;
  8954. if (name === 'instanceColor' && object.instanceColor) attribute = object.instanceColor;
  8955. }
  8956. const data = {};
  8957. data.attribute = attribute;
  8958. if (attribute && attribute.data) {
  8959. data.data = attribute.data;
  8960. }
  8961. cache[name] = data;
  8962. attributesNum++;
  8963. }
  8964. }
  8965. currentState.attributes = cache;
  8966. currentState.attributesNum = attributesNum;
  8967. currentState.index = index;
  8968. }
  8969. function initAttributes() {
  8970. const newAttributes = currentState.newAttributes;
  8971. for (let i = 0, il = newAttributes.length; i < il; i++) {
  8972. newAttributes[i] = 0;
  8973. }
  8974. }
  8975. function enableAttribute(attribute) {
  8976. enableAttributeAndDivisor(attribute, 0);
  8977. }
  8978. function enableAttributeAndDivisor(attribute, meshPerAttribute) {
  8979. const newAttributes = currentState.newAttributes;
  8980. const enabledAttributes = currentState.enabledAttributes;
  8981. const attributeDivisors = currentState.attributeDivisors;
  8982. newAttributes[attribute] = 1;
  8983. if (enabledAttributes[attribute] === 0) {
  8984. gl.enableVertexAttribArray(attribute);
  8985. enabledAttributes[attribute] = 1;
  8986. }
  8987. if (attributeDivisors[attribute] !== meshPerAttribute) {
  8988. const extension = capabilities.isWebGL2 ? gl : extensions.get('ANGLE_instanced_arrays');
  8989. extension[capabilities.isWebGL2 ? 'vertexAttribDivisor' : 'vertexAttribDivisorANGLE'](attribute, meshPerAttribute);
  8990. attributeDivisors[attribute] = meshPerAttribute;
  8991. }
  8992. }
  8993. function disableUnusedAttributes() {
  8994. const newAttributes = currentState.newAttributes;
  8995. const enabledAttributes = currentState.enabledAttributes;
  8996. for (let i = 0, il = enabledAttributes.length; i < il; i++) {
  8997. if (enabledAttributes[i] !== newAttributes[i]) {
  8998. gl.disableVertexAttribArray(i);
  8999. enabledAttributes[i] = 0;
  9000. }
  9001. }
  9002. }
  9003. function vertexAttribPointer(index, size, type, normalized, stride, offset) {
  9004. if (capabilities.isWebGL2 === true && (type === gl.INT || type === gl.UNSIGNED_INT)) {
  9005. gl.vertexAttribIPointer(index, size, type, stride, offset);
  9006. } else {
  9007. gl.vertexAttribPointer(index, size, type, normalized, stride, offset);
  9008. }
  9009. }
  9010. function setupVertexAttributes(object, material, program, geometry) {
  9011. if (capabilities.isWebGL2 === false && (object.isInstancedMesh || geometry.isInstancedBufferGeometry)) {
  9012. if (extensions.get('ANGLE_instanced_arrays') === null) return;
  9013. }
  9014. initAttributes();
  9015. const geometryAttributes = geometry.attributes;
  9016. const programAttributes = program.getAttributes();
  9017. const materialDefaultAttributeValues = material.defaultAttributeValues;
  9018. for (const name in programAttributes) {
  9019. const programAttribute = programAttributes[name];
  9020. if (programAttribute.location >= 0) {
  9021. let geometryAttribute = geometryAttributes[name];
  9022. if (geometryAttribute === undefined) {
  9023. if (name === 'instanceMatrix' && object.instanceMatrix) geometryAttribute = object.instanceMatrix;
  9024. if (name === 'instanceColor' && object.instanceColor) geometryAttribute = object.instanceColor;
  9025. }
  9026. if (geometryAttribute !== undefined) {
  9027. const normalized = geometryAttribute.normalized;
  9028. const size = geometryAttribute.itemSize;
  9029. const attribute = attributes.get(geometryAttribute); // TODO Attribute may not be available on context restore
  9030. if (attribute === undefined) continue;
  9031. const buffer = attribute.buffer;
  9032. const type = attribute.type;
  9033. const bytesPerElement = attribute.bytesPerElement;
  9034. if (geometryAttribute.isInterleavedBufferAttribute) {
  9035. const data = geometryAttribute.data;
  9036. const stride = data.stride;
  9037. const offset = geometryAttribute.offset;
  9038. if (data.isInstancedInterleavedBuffer) {
  9039. for (let i = 0; i < programAttribute.locationSize; i++) {
  9040. enableAttributeAndDivisor(programAttribute.location + i, data.meshPerAttribute);
  9041. }
  9042. if (object.isInstancedMesh !== true && geometry._maxInstanceCount === undefined) {
  9043. geometry._maxInstanceCount = data.meshPerAttribute * data.count;
  9044. }
  9045. } else {
  9046. for (let i = 0; i < programAttribute.locationSize; i++) {
  9047. enableAttribute(programAttribute.location + i);
  9048. }
  9049. }
  9050. gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
  9051. for (let i = 0; i < programAttribute.locationSize; i++) {
  9052. vertexAttribPointer(programAttribute.location + i, size / programAttribute.locationSize, type, normalized, stride * bytesPerElement, (offset + size / programAttribute.locationSize * i) * bytesPerElement);
  9053. }
  9054. } else {
  9055. if (geometryAttribute.isInstancedBufferAttribute) {
  9056. for (let i = 0; i < programAttribute.locationSize; i++) {
  9057. enableAttributeAndDivisor(programAttribute.location + i, geometryAttribute.meshPerAttribute);
  9058. }
  9059. if (object.isInstancedMesh !== true && geometry._maxInstanceCount === undefined) {
  9060. geometry._maxInstanceCount = geometryAttribute.meshPerAttribute * geometryAttribute.count;
  9061. }
  9062. } else {
  9063. for (let i = 0; i < programAttribute.locationSize; i++) {
  9064. enableAttribute(programAttribute.location + i);
  9065. }
  9066. }
  9067. gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
  9068. for (let i = 0; i < programAttribute.locationSize; i++) {
  9069. vertexAttribPointer(programAttribute.location + i, size / programAttribute.locationSize, type, normalized, size * bytesPerElement, size / programAttribute.locationSize * i * bytesPerElement);
  9070. }
  9071. }
  9072. } else if (materialDefaultAttributeValues !== undefined) {
  9073. const value = materialDefaultAttributeValues[name];
  9074. if (value !== undefined) {
  9075. switch (value.length) {
  9076. case 2:
  9077. gl.vertexAttrib2fv(programAttribute.location, value);
  9078. break;
  9079. case 3:
  9080. gl.vertexAttrib3fv(programAttribute.location, value);
  9081. break;
  9082. case 4:
  9083. gl.vertexAttrib4fv(programAttribute.location, value);
  9084. break;
  9085. default:
  9086. gl.vertexAttrib1fv(programAttribute.location, value);
  9087. }
  9088. }
  9089. }
  9090. }
  9091. }
  9092. disableUnusedAttributes();
  9093. }
  9094. function dispose() {
  9095. reset();
  9096. for (const geometryId in bindingStates) {
  9097. const programMap = bindingStates[geometryId];
  9098. for (const programId in programMap) {
  9099. const stateMap = programMap[programId];
  9100. for (const wireframe in stateMap) {
  9101. deleteVertexArrayObject(stateMap[wireframe].object);
  9102. delete stateMap[wireframe];
  9103. }
  9104. delete programMap[programId];
  9105. }
  9106. delete bindingStates[geometryId];
  9107. }
  9108. }
  9109. function releaseStatesOfGeometry(geometry) {
  9110. if (bindingStates[geometry.id] === undefined) return;
  9111. const programMap = bindingStates[geometry.id];
  9112. for (const programId in programMap) {
  9113. const stateMap = programMap[programId];
  9114. for (const wireframe in stateMap) {
  9115. deleteVertexArrayObject(stateMap[wireframe].object);
  9116. delete stateMap[wireframe];
  9117. }
  9118. delete programMap[programId];
  9119. }
  9120. delete bindingStates[geometry.id];
  9121. }
  9122. function releaseStatesOfProgram(program) {
  9123. for (const geometryId in bindingStates) {
  9124. const programMap = bindingStates[geometryId];
  9125. if (programMap[program.id] === undefined) continue;
  9126. const stateMap = programMap[program.id];
  9127. for (const wireframe in stateMap) {
  9128. deleteVertexArrayObject(stateMap[wireframe].object);
  9129. delete stateMap[wireframe];
  9130. }
  9131. delete programMap[program.id];
  9132. }
  9133. }
  9134. function reset() {
  9135. resetDefaultState();
  9136. forceUpdate = true;
  9137. if (currentState === defaultState) return;
  9138. currentState = defaultState;
  9139. bindVertexArrayObject(currentState.object);
  9140. } // for backward-compatibility
  9141. function resetDefaultState() {
  9142. defaultState.geometry = null;
  9143. defaultState.program = null;
  9144. defaultState.wireframe = false;
  9145. }
  9146. return {
  9147. setup: setup,
  9148. reset: reset,
  9149. resetDefaultState: resetDefaultState,
  9150. dispose: dispose,
  9151. releaseStatesOfGeometry: releaseStatesOfGeometry,
  9152. releaseStatesOfProgram: releaseStatesOfProgram,
  9153. initAttributes: initAttributes,
  9154. enableAttribute: enableAttribute,
  9155. disableUnusedAttributes: disableUnusedAttributes
  9156. };
  9157. }
  9158. function WebGLBufferRenderer(gl, extensions, info, capabilities) {
  9159. const isWebGL2 = capabilities.isWebGL2;
  9160. let mode;
  9161. function setMode(value) {
  9162. mode = value;
  9163. }
  9164. function render(start, count) {
  9165. gl.drawArrays(mode, start, count);
  9166. info.update(count, mode, 1);
  9167. }
  9168. function renderInstances(start, count, primcount) {
  9169. if (primcount === 0) return;
  9170. let extension, methodName;
  9171. if (isWebGL2) {
  9172. extension = gl;
  9173. methodName = 'drawArraysInstanced';
  9174. } else {
  9175. extension = extensions.get('ANGLE_instanced_arrays');
  9176. methodName = 'drawArraysInstancedANGLE';
  9177. if (extension === null) {
  9178. console.error('THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.');
  9179. return;
  9180. }
  9181. }
  9182. extension[methodName](mode, start, count, primcount);
  9183. info.update(count, mode, primcount);
  9184. } //
  9185. this.setMode = setMode;
  9186. this.render = render;
  9187. this.renderInstances = renderInstances;
  9188. }
  9189. function WebGLCapabilities(gl, extensions, parameters) {
  9190. let maxAnisotropy;
  9191. function getMaxAnisotropy() {
  9192. if (maxAnisotropy !== undefined) return maxAnisotropy;
  9193. if (extensions.has('EXT_texture_filter_anisotropic') === true) {
  9194. const extension = extensions.get('EXT_texture_filter_anisotropic');
  9195. maxAnisotropy = gl.getParameter(extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT);
  9196. } else {
  9197. maxAnisotropy = 0;
  9198. }
  9199. return maxAnisotropy;
  9200. }
  9201. function getMaxPrecision(precision) {
  9202. if (precision === 'highp') {
  9203. if (gl.getShaderPrecisionFormat(gl.VERTEX_SHADER, gl.HIGH_FLOAT).precision > 0 && gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.HIGH_FLOAT).precision > 0) {
  9204. return 'highp';
  9205. }
  9206. precision = 'mediump';
  9207. }
  9208. if (precision === 'mediump') {
  9209. if (gl.getShaderPrecisionFormat(gl.VERTEX_SHADER, gl.MEDIUM_FLOAT).precision > 0 && gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.MEDIUM_FLOAT).precision > 0) {
  9210. return 'mediump';
  9211. }
  9212. }
  9213. return 'lowp';
  9214. }
  9215. const isWebGL2 = typeof WebGL2RenderingContext !== 'undefined' && gl instanceof WebGL2RenderingContext || typeof WebGL2ComputeRenderingContext !== 'undefined' && gl instanceof WebGL2ComputeRenderingContext;
  9216. let precision = parameters.precision !== undefined ? parameters.precision : 'highp';
  9217. const maxPrecision = getMaxPrecision(precision);
  9218. if (maxPrecision !== precision) {
  9219. console.warn('THREE.WebGLRenderer:', precision, 'not supported, using', maxPrecision, 'instead.');
  9220. precision = maxPrecision;
  9221. }
  9222. const drawBuffers = isWebGL2 || extensions.has('WEBGL_draw_buffers');
  9223. const logarithmicDepthBuffer = parameters.logarithmicDepthBuffer === true;
  9224. const maxTextures = gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS);
  9225. const maxVertexTextures = gl.getParameter(gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  9226. const maxTextureSize = gl.getParameter(gl.MAX_TEXTURE_SIZE);
  9227. const maxCubemapSize = gl.getParameter(gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  9228. const maxAttributes = gl.getParameter(gl.MAX_VERTEX_ATTRIBS);
  9229. const maxVertexUniforms = gl.getParameter(gl.MAX_VERTEX_UNIFORM_VECTORS);
  9230. const maxVaryings = gl.getParameter(gl.MAX_VARYING_VECTORS);
  9231. const maxFragmentUniforms = gl.getParameter(gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  9232. const vertexTextures = maxVertexTextures > 0;
  9233. const floatFragmentTextures = isWebGL2 || extensions.has('OES_texture_float');
  9234. const floatVertexTextures = vertexTextures && floatFragmentTextures;
  9235. const maxSamples = isWebGL2 ? gl.getParameter(gl.MAX_SAMPLES) : 0;
  9236. return {
  9237. isWebGL2: isWebGL2,
  9238. drawBuffers: drawBuffers,
  9239. getMaxAnisotropy: getMaxAnisotropy,
  9240. getMaxPrecision: getMaxPrecision,
  9241. precision: precision,
  9242. logarithmicDepthBuffer: logarithmicDepthBuffer,
  9243. maxTextures: maxTextures,
  9244. maxVertexTextures: maxVertexTextures,
  9245. maxTextureSize: maxTextureSize,
  9246. maxCubemapSize: maxCubemapSize,
  9247. maxAttributes: maxAttributes,
  9248. maxVertexUniforms: maxVertexUniforms,
  9249. maxVaryings: maxVaryings,
  9250. maxFragmentUniforms: maxFragmentUniforms,
  9251. vertexTextures: vertexTextures,
  9252. floatFragmentTextures: floatFragmentTextures,
  9253. floatVertexTextures: floatVertexTextures,
  9254. maxSamples: maxSamples
  9255. };
  9256. }
  9257. function WebGLClipping(properties) {
  9258. const scope = this;
  9259. let globalState = null,
  9260. numGlobalPlanes = 0,
  9261. localClippingEnabled = false,
  9262. renderingShadows = false;
  9263. const plane = new Plane(),
  9264. viewNormalMatrix = new Matrix3(),
  9265. uniform = {
  9266. value: null,
  9267. needsUpdate: false
  9268. };
  9269. this.uniform = uniform;
  9270. this.numPlanes = 0;
  9271. this.numIntersection = 0;
  9272. this.init = function (planes, enableLocalClipping, camera) {
  9273. const enabled = planes.length !== 0 || enableLocalClipping || // enable state of previous frame - the clipping code has to
  9274. // run another frame in order to reset the state:
  9275. numGlobalPlanes !== 0 || localClippingEnabled;
  9276. localClippingEnabled = enableLocalClipping;
  9277. globalState = projectPlanes(planes, camera, 0);
  9278. numGlobalPlanes = planes.length;
  9279. return enabled;
  9280. };
  9281. this.beginShadows = function () {
  9282. renderingShadows = true;
  9283. projectPlanes(null);
  9284. };
  9285. this.endShadows = function () {
  9286. renderingShadows = false;
  9287. resetGlobalState();
  9288. };
  9289. this.setState = function (material, camera, useCache) {
  9290. const planes = material.clippingPlanes,
  9291. clipIntersection = material.clipIntersection,
  9292. clipShadows = material.clipShadows;
  9293. const materialProperties = properties.get(material);
  9294. if (!localClippingEnabled || planes === null || planes.length === 0 || renderingShadows && !clipShadows) {
  9295. // there's no local clipping
  9296. if (renderingShadows) {
  9297. // there's no global clipping
  9298. projectPlanes(null);
  9299. } else {
  9300. resetGlobalState();
  9301. }
  9302. } else {
  9303. const nGlobal = renderingShadows ? 0 : numGlobalPlanes,
  9304. lGlobal = nGlobal * 4;
  9305. let dstArray = materialProperties.clippingState || null;
  9306. uniform.value = dstArray; // ensure unique state
  9307. dstArray = projectPlanes(planes, camera, lGlobal, useCache);
  9308. for (let i = 0; i !== lGlobal; ++i) {
  9309. dstArray[i] = globalState[i];
  9310. }
  9311. materialProperties.clippingState = dstArray;
  9312. this.numIntersection = clipIntersection ? this.numPlanes : 0;
  9313. this.numPlanes += nGlobal;
  9314. }
  9315. };
  9316. function resetGlobalState() {
  9317. if (uniform.value !== globalState) {
  9318. uniform.value = globalState;
  9319. uniform.needsUpdate = numGlobalPlanes > 0;
  9320. }
  9321. scope.numPlanes = numGlobalPlanes;
  9322. scope.numIntersection = 0;
  9323. }
  9324. function projectPlanes(planes, camera, dstOffset, skipTransform) {
  9325. const nPlanes = planes !== null ? planes.length : 0;
  9326. let dstArray = null;
  9327. if (nPlanes !== 0) {
  9328. dstArray = uniform.value;
  9329. if (skipTransform !== true || dstArray === null) {
  9330. const flatSize = dstOffset + nPlanes * 4,
  9331. viewMatrix = camera.matrixWorldInverse;
  9332. viewNormalMatrix.getNormalMatrix(viewMatrix);
  9333. if (dstArray === null || dstArray.length < flatSize) {
  9334. dstArray = new Float32Array(flatSize);
  9335. }
  9336. for (let i = 0, i4 = dstOffset; i !== nPlanes; ++i, i4 += 4) {
  9337. plane.copy(planes[i]).applyMatrix4(viewMatrix, viewNormalMatrix);
  9338. plane.normal.toArray(dstArray, i4);
  9339. dstArray[i4 + 3] = plane.constant;
  9340. }
  9341. }
  9342. uniform.value = dstArray;
  9343. uniform.needsUpdate = true;
  9344. }
  9345. scope.numPlanes = nPlanes;
  9346. scope.numIntersection = 0;
  9347. return dstArray;
  9348. }
  9349. }
  9350. function WebGLCubeMaps(renderer) {
  9351. let cubemaps = new WeakMap();
  9352. function mapTextureMapping(texture, mapping) {
  9353. if (mapping === EquirectangularReflectionMapping) {
  9354. texture.mapping = CubeReflectionMapping;
  9355. } else if (mapping === EquirectangularRefractionMapping) {
  9356. texture.mapping = CubeRefractionMapping;
  9357. }
  9358. return texture;
  9359. }
  9360. function get(texture) {
  9361. if (texture && texture.isTexture && texture.isRenderTargetTexture === false) {
  9362. const mapping = texture.mapping;
  9363. if (mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping) {
  9364. if (cubemaps.has(texture)) {
  9365. const cubemap = cubemaps.get(texture).texture;
  9366. return mapTextureMapping(cubemap, texture.mapping);
  9367. } else {
  9368. const image = texture.image;
  9369. if (image && image.height > 0) {
  9370. const renderTarget = new WebGLCubeRenderTarget(image.height / 2);
  9371. renderTarget.fromEquirectangularTexture(renderer, texture);
  9372. cubemaps.set(texture, renderTarget);
  9373. texture.addEventListener('dispose', onTextureDispose);
  9374. return mapTextureMapping(renderTarget.texture, texture.mapping);
  9375. } else {
  9376. // image not yet ready. try the conversion next frame
  9377. return null;
  9378. }
  9379. }
  9380. }
  9381. }
  9382. return texture;
  9383. }
  9384. function onTextureDispose(event) {
  9385. const texture = event.target;
  9386. texture.removeEventListener('dispose', onTextureDispose);
  9387. const cubemap = cubemaps.get(texture);
  9388. if (cubemap !== undefined) {
  9389. cubemaps.delete(texture);
  9390. cubemap.dispose();
  9391. }
  9392. }
  9393. function dispose() {
  9394. cubemaps = new WeakMap();
  9395. }
  9396. return {
  9397. get: get,
  9398. dispose: dispose
  9399. };
  9400. }
  9401. class OrthographicCamera extends Camera {
  9402. constructor(left = -1, right = 1, top = 1, bottom = -1, near = 0.1, far = 2000) {
  9403. super();
  9404. this.isOrthographicCamera = true;
  9405. this.type = 'OrthographicCamera';
  9406. this.zoom = 1;
  9407. this.view = null;
  9408. this.left = left;
  9409. this.right = right;
  9410. this.top = top;
  9411. this.bottom = bottom;
  9412. this.near = near;
  9413. this.far = far;
  9414. this.updateProjectionMatrix();
  9415. }
  9416. copy(source, recursive) {
  9417. super.copy(source, recursive);
  9418. this.left = source.left;
  9419. this.right = source.right;
  9420. this.top = source.top;
  9421. this.bottom = source.bottom;
  9422. this.near = source.near;
  9423. this.far = source.far;
  9424. this.zoom = source.zoom;
  9425. this.view = source.view === null ? null : Object.assign({}, source.view);
  9426. return this;
  9427. }
  9428. setViewOffset(fullWidth, fullHeight, x, y, width, height) {
  9429. if (this.view === null) {
  9430. this.view = {
  9431. enabled: true,
  9432. fullWidth: 1,
  9433. fullHeight: 1,
  9434. offsetX: 0,
  9435. offsetY: 0,
  9436. width: 1,
  9437. height: 1
  9438. };
  9439. }
  9440. this.view.enabled = true;
  9441. this.view.fullWidth = fullWidth;
  9442. this.view.fullHeight = fullHeight;
  9443. this.view.offsetX = x;
  9444. this.view.offsetY = y;
  9445. this.view.width = width;
  9446. this.view.height = height;
  9447. this.updateProjectionMatrix();
  9448. }
  9449. clearViewOffset() {
  9450. if (this.view !== null) {
  9451. this.view.enabled = false;
  9452. }
  9453. this.updateProjectionMatrix();
  9454. }
  9455. updateProjectionMatrix() {
  9456. const dx = (this.right - this.left) / (2 * this.zoom);
  9457. const dy = (this.top - this.bottom) / (2 * this.zoom);
  9458. const cx = (this.right + this.left) / 2;
  9459. const cy = (this.top + this.bottom) / 2;
  9460. let left = cx - dx;
  9461. let right = cx + dx;
  9462. let top = cy + dy;
  9463. let bottom = cy - dy;
  9464. if (this.view !== null && this.view.enabled) {
  9465. const scaleW = (this.right - this.left) / this.view.fullWidth / this.zoom;
  9466. const scaleH = (this.top - this.bottom) / this.view.fullHeight / this.zoom;
  9467. left += scaleW * this.view.offsetX;
  9468. right = left + scaleW * this.view.width;
  9469. top -= scaleH * this.view.offsetY;
  9470. bottom = top - scaleH * this.view.height;
  9471. }
  9472. this.projectionMatrix.makeOrthographic(left, right, top, bottom, this.near, this.far);
  9473. this.projectionMatrixInverse.copy(this.projectionMatrix).invert();
  9474. }
  9475. toJSON(meta) {
  9476. const data = super.toJSON(meta);
  9477. data.object.zoom = this.zoom;
  9478. data.object.left = this.left;
  9479. data.object.right = this.right;
  9480. data.object.top = this.top;
  9481. data.object.bottom = this.bottom;
  9482. data.object.near = this.near;
  9483. data.object.far = this.far;
  9484. if (this.view !== null) data.object.view = Object.assign({}, this.view);
  9485. return data;
  9486. }
  9487. }
  9488. const LOD_MIN = 4; // The standard deviations (radians) associated with the extra mips. These are
  9489. // chosen to approximate a Trowbridge-Reitz distribution function times the
  9490. // geometric shadowing function. These sigma values squared must match the
  9491. // variance #defines in cube_uv_reflection_fragment.glsl.js.
  9492. const EXTRA_LOD_SIGMA = [0.125, 0.215, 0.35, 0.446, 0.526, 0.582]; // The maximum length of the blur for loop. Smaller sigmas will use fewer
  9493. // samples and exit early, but not recompile the shader.
  9494. const MAX_SAMPLES = 20;
  9495. const _flatCamera = /*@__PURE__*/new OrthographicCamera();
  9496. const _clearColor = /*@__PURE__*/new Color();
  9497. let _oldTarget = null; // Golden Ratio
  9498. const PHI = (1 + Math.sqrt(5)) / 2;
  9499. const INV_PHI = 1 / PHI; // Vertices of a dodecahedron (except the opposites, which represent the
  9500. // same axis), used as axis directions evenly spread on a sphere.
  9501. const _axisDirections = [/*@__PURE__*/new Vector3(1, 1, 1), /*@__PURE__*/new Vector3(-1, 1, 1), /*@__PURE__*/new Vector3(1, 1, -1), /*@__PURE__*/new Vector3(-1, 1, -1), /*@__PURE__*/new Vector3(0, PHI, INV_PHI), /*@__PURE__*/new Vector3(0, PHI, -INV_PHI), /*@__PURE__*/new Vector3(INV_PHI, 0, PHI), /*@__PURE__*/new Vector3(-INV_PHI, 0, PHI), /*@__PURE__*/new Vector3(PHI, INV_PHI, 0), /*@__PURE__*/new Vector3(-PHI, INV_PHI, 0)];
  9502. /**
  9503. * This class generates a Prefiltered, Mipmapped Radiance Environment Map
  9504. * (PMREM) from a cubeMap environment texture. This allows different levels of
  9505. * blur to be quickly accessed based on material roughness. It is packed into a
  9506. * special CubeUV format that allows us to perform custom interpolation so that
  9507. * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap
  9508. * chain, it only goes down to the LOD_MIN level (above), and then creates extra
  9509. * even more filtered 'mips' at the same LOD_MIN resolution, associated with
  9510. * higher roughness levels. In this way we maintain resolution to smoothly
  9511. * interpolate diffuse lighting while limiting sampling computation.
  9512. *
  9513. * Paper: Fast, Accurate Image-Based Lighting
  9514. * https://drive.google.com/file/d/15y8r_UpKlU9SvV4ILb0C3qCPecS8pvLz/view
  9515. */
  9516. class PMREMGenerator {
  9517. constructor(renderer) {
  9518. this._renderer = renderer;
  9519. this._pingPongRenderTarget = null;
  9520. this._lodMax = 0;
  9521. this._cubeSize = 0;
  9522. this._lodPlanes = [];
  9523. this._sizeLods = [];
  9524. this._sigmas = [];
  9525. this._blurMaterial = null;
  9526. this._cubemapMaterial = null;
  9527. this._equirectMaterial = null;
  9528. this._compileMaterial(this._blurMaterial);
  9529. }
  9530. /**
  9531. * Generates a PMREM from a supplied Scene, which can be faster than using an
  9532. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  9533. * in radians to be applied to the scene before PMREM generation. Optional near
  9534. * and far planes ensure the scene is rendered in its entirety (the cubeCamera
  9535. * is placed at the origin).
  9536. */
  9537. fromScene(scene, sigma = 0, near = 0.1, far = 100) {
  9538. _oldTarget = this._renderer.getRenderTarget();
  9539. this._setSize(256);
  9540. const cubeUVRenderTarget = this._allocateTargets();
  9541. cubeUVRenderTarget.depthBuffer = true;
  9542. this._sceneToCubeUV(scene, near, far, cubeUVRenderTarget);
  9543. if (sigma > 0) {
  9544. this._blur(cubeUVRenderTarget, 0, 0, sigma);
  9545. }
  9546. this._applyPMREM(cubeUVRenderTarget);
  9547. this._cleanup(cubeUVRenderTarget);
  9548. return cubeUVRenderTarget;
  9549. }
  9550. /**
  9551. * Generates a PMREM from an equirectangular texture, which can be either LDR
  9552. * or HDR. The ideal input image size is 1k (1024 x 512),
  9553. * as this matches best with the 256 x 256 cubemap output.
  9554. */
  9555. fromEquirectangular(equirectangular, renderTarget = null) {
  9556. return this._fromTexture(equirectangular, renderTarget);
  9557. }
  9558. /**
  9559. * Generates a PMREM from an cubemap texture, which can be either LDR
  9560. * or HDR. The ideal input cube size is 256 x 256,
  9561. * as this matches best with the 256 x 256 cubemap output.
  9562. */
  9563. fromCubemap(cubemap, renderTarget = null) {
  9564. return this._fromTexture(cubemap, renderTarget);
  9565. }
  9566. /**
  9567. * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during
  9568. * your texture's network fetch for increased concurrency.
  9569. */
  9570. compileCubemapShader() {
  9571. if (this._cubemapMaterial === null) {
  9572. this._cubemapMaterial = _getCubemapMaterial();
  9573. this._compileMaterial(this._cubemapMaterial);
  9574. }
  9575. }
  9576. /**
  9577. * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during
  9578. * your texture's network fetch for increased concurrency.
  9579. */
  9580. compileEquirectangularShader() {
  9581. if (this._equirectMaterial === null) {
  9582. this._equirectMaterial = _getEquirectMaterial();
  9583. this._compileMaterial(this._equirectMaterial);
  9584. }
  9585. }
  9586. /**
  9587. * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class,
  9588. * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on
  9589. * one of them will cause any others to also become unusable.
  9590. */
  9591. dispose() {
  9592. this._dispose();
  9593. if (this._cubemapMaterial !== null) this._cubemapMaterial.dispose();
  9594. if (this._equirectMaterial !== null) this._equirectMaterial.dispose();
  9595. } // private interface
  9596. _setSize(cubeSize) {
  9597. this._lodMax = Math.floor(Math.log2(cubeSize));
  9598. this._cubeSize = Math.pow(2, this._lodMax);
  9599. }
  9600. _dispose() {
  9601. if (this._blurMaterial !== null) this._blurMaterial.dispose();
  9602. if (this._pingPongRenderTarget !== null) this._pingPongRenderTarget.dispose();
  9603. for (let i = 0; i < this._lodPlanes.length; i++) {
  9604. this._lodPlanes[i].dispose();
  9605. }
  9606. }
  9607. _cleanup(outputTarget) {
  9608. this._renderer.setRenderTarget(_oldTarget);
  9609. outputTarget.scissorTest = false;
  9610. _setViewport(outputTarget, 0, 0, outputTarget.width, outputTarget.height);
  9611. }
  9612. _fromTexture(texture, renderTarget) {
  9613. if (texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping) {
  9614. this._setSize(texture.image.length === 0 ? 16 : texture.image[0].width || texture.image[0].image.width);
  9615. } else {
  9616. // Equirectangular
  9617. this._setSize(texture.image.width / 4);
  9618. }
  9619. _oldTarget = this._renderer.getRenderTarget();
  9620. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  9621. this._textureToCubeUV(texture, cubeUVRenderTarget);
  9622. this._applyPMREM(cubeUVRenderTarget);
  9623. this._cleanup(cubeUVRenderTarget);
  9624. return cubeUVRenderTarget;
  9625. }
  9626. _allocateTargets() {
  9627. const width = 3 * Math.max(this._cubeSize, 16 * 7);
  9628. const height = 4 * this._cubeSize;
  9629. const params = {
  9630. magFilter: LinearFilter,
  9631. minFilter: LinearFilter,
  9632. generateMipmaps: false,
  9633. type: HalfFloatType,
  9634. format: RGBAFormat,
  9635. encoding: LinearEncoding,
  9636. depthBuffer: false
  9637. };
  9638. const cubeUVRenderTarget = _createRenderTarget(width, height, params);
  9639. if (this._pingPongRenderTarget === null || this._pingPongRenderTarget.width !== width) {
  9640. if (this._pingPongRenderTarget !== null) {
  9641. this._dispose();
  9642. }
  9643. this._pingPongRenderTarget = _createRenderTarget(width, height, params);
  9644. const {
  9645. _lodMax
  9646. } = this;
  9647. ({
  9648. sizeLods: this._sizeLods,
  9649. lodPlanes: this._lodPlanes,
  9650. sigmas: this._sigmas
  9651. } = _createPlanes(_lodMax));
  9652. this._blurMaterial = _getBlurShader(_lodMax, width, height);
  9653. }
  9654. return cubeUVRenderTarget;
  9655. }
  9656. _compileMaterial(material) {
  9657. const tmpMesh = new Mesh(this._lodPlanes[0], material);
  9658. this._renderer.compile(tmpMesh, _flatCamera);
  9659. }
  9660. _sceneToCubeUV(scene, near, far, cubeUVRenderTarget) {
  9661. const fov = 90;
  9662. const aspect = 1;
  9663. const cubeCamera = new PerspectiveCamera(fov, aspect, near, far);
  9664. const upSign = [1, -1, 1, 1, 1, 1];
  9665. const forwardSign = [1, 1, 1, -1, -1, -1];
  9666. const renderer = this._renderer;
  9667. const originalAutoClear = renderer.autoClear;
  9668. const toneMapping = renderer.toneMapping;
  9669. renderer.getClearColor(_clearColor);
  9670. renderer.toneMapping = NoToneMapping;
  9671. renderer.autoClear = false;
  9672. const backgroundMaterial = new MeshBasicMaterial({
  9673. name: 'PMREM.Background',
  9674. side: BackSide,
  9675. depthWrite: false,
  9676. depthTest: false
  9677. });
  9678. const backgroundBox = new Mesh(new BoxGeometry(), backgroundMaterial);
  9679. let useSolidColor = false;
  9680. const background = scene.background;
  9681. if (background) {
  9682. if (background.isColor) {
  9683. backgroundMaterial.color.copy(background);
  9684. scene.background = null;
  9685. useSolidColor = true;
  9686. }
  9687. } else {
  9688. backgroundMaterial.color.copy(_clearColor);
  9689. useSolidColor = true;
  9690. }
  9691. for (let i = 0; i < 6; i++) {
  9692. const col = i % 3;
  9693. if (col === 0) {
  9694. cubeCamera.up.set(0, upSign[i], 0);
  9695. cubeCamera.lookAt(forwardSign[i], 0, 0);
  9696. } else if (col === 1) {
  9697. cubeCamera.up.set(0, 0, upSign[i]);
  9698. cubeCamera.lookAt(0, forwardSign[i], 0);
  9699. } else {
  9700. cubeCamera.up.set(0, upSign[i], 0);
  9701. cubeCamera.lookAt(0, 0, forwardSign[i]);
  9702. }
  9703. const size = this._cubeSize;
  9704. _setViewport(cubeUVRenderTarget, col * size, i > 2 ? size : 0, size, size);
  9705. renderer.setRenderTarget(cubeUVRenderTarget);
  9706. if (useSolidColor) {
  9707. renderer.render(backgroundBox, cubeCamera);
  9708. }
  9709. renderer.render(scene, cubeCamera);
  9710. }
  9711. backgroundBox.geometry.dispose();
  9712. backgroundBox.material.dispose();
  9713. renderer.toneMapping = toneMapping;
  9714. renderer.autoClear = originalAutoClear;
  9715. scene.background = background;
  9716. }
  9717. _textureToCubeUV(texture, cubeUVRenderTarget) {
  9718. const renderer = this._renderer;
  9719. const isCubeTexture = texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping;
  9720. if (isCubeTexture) {
  9721. if (this._cubemapMaterial === null) {
  9722. this._cubemapMaterial = _getCubemapMaterial();
  9723. }
  9724. this._cubemapMaterial.uniforms.flipEnvMap.value = texture.isRenderTargetTexture === false ? -1 : 1;
  9725. } else {
  9726. if (this._equirectMaterial === null) {
  9727. this._equirectMaterial = _getEquirectMaterial();
  9728. }
  9729. }
  9730. const material = isCubeTexture ? this._cubemapMaterial : this._equirectMaterial;
  9731. const mesh = new Mesh(this._lodPlanes[0], material);
  9732. const uniforms = material.uniforms;
  9733. uniforms['envMap'].value = texture;
  9734. const size = this._cubeSize;
  9735. _setViewport(cubeUVRenderTarget, 0, 0, 3 * size, 2 * size);
  9736. renderer.setRenderTarget(cubeUVRenderTarget);
  9737. renderer.render(mesh, _flatCamera);
  9738. }
  9739. _applyPMREM(cubeUVRenderTarget) {
  9740. const renderer = this._renderer;
  9741. const autoClear = renderer.autoClear;
  9742. renderer.autoClear = false;
  9743. for (let i = 1; i < this._lodPlanes.length; i++) {
  9744. const sigma = Math.sqrt(this._sigmas[i] * this._sigmas[i] - this._sigmas[i - 1] * this._sigmas[i - 1]);
  9745. const poleAxis = _axisDirections[(i - 1) % _axisDirections.length];
  9746. this._blur(cubeUVRenderTarget, i - 1, i, sigma, poleAxis);
  9747. }
  9748. renderer.autoClear = autoClear;
  9749. }
  9750. /**
  9751. * This is a two-pass Gaussian blur for a cubemap. Normally this is done
  9752. * vertically and horizontally, but this breaks down on a cube. Here we apply
  9753. * the blur latitudinally (around the poles), and then longitudinally (towards
  9754. * the poles) to approximate the orthogonally-separable blur. It is least
  9755. * accurate at the poles, but still does a decent job.
  9756. */
  9757. _blur(cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis) {
  9758. const pingPongRenderTarget = this._pingPongRenderTarget;
  9759. this._halfBlur(cubeUVRenderTarget, pingPongRenderTarget, lodIn, lodOut, sigma, 'latitudinal', poleAxis);
  9760. this._halfBlur(pingPongRenderTarget, cubeUVRenderTarget, lodOut, lodOut, sigma, 'longitudinal', poleAxis);
  9761. }
  9762. _halfBlur(targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis) {
  9763. const renderer = this._renderer;
  9764. const blurMaterial = this._blurMaterial;
  9765. if (direction !== 'latitudinal' && direction !== 'longitudinal') {
  9766. console.error('blur direction must be either latitudinal or longitudinal!');
  9767. } // Number of standard deviations at which to cut off the discrete approximation.
  9768. const STANDARD_DEVIATIONS = 3;
  9769. const blurMesh = new Mesh(this._lodPlanes[lodOut], blurMaterial);
  9770. const blurUniforms = blurMaterial.uniforms;
  9771. const pixels = this._sizeLods[lodIn] - 1;
  9772. const radiansPerPixel = isFinite(sigmaRadians) ? Math.PI / (2 * pixels) : 2 * Math.PI / (2 * MAX_SAMPLES - 1);
  9773. const sigmaPixels = sigmaRadians / radiansPerPixel;
  9774. const samples = isFinite(sigmaRadians) ? 1 + Math.floor(STANDARD_DEVIATIONS * sigmaPixels) : MAX_SAMPLES;
  9775. if (samples > MAX_SAMPLES) {
  9776. console.warn(`sigmaRadians, ${sigmaRadians}, is too large and will clip, as it requested ${samples} samples when the maximum is set to ${MAX_SAMPLES}`);
  9777. }
  9778. const weights = [];
  9779. let sum = 0;
  9780. for (let i = 0; i < MAX_SAMPLES; ++i) {
  9781. const x = i / sigmaPixels;
  9782. const weight = Math.exp(-x * x / 2);
  9783. weights.push(weight);
  9784. if (i === 0) {
  9785. sum += weight;
  9786. } else if (i < samples) {
  9787. sum += 2 * weight;
  9788. }
  9789. }
  9790. for (let i = 0; i < weights.length; i++) {
  9791. weights[i] = weights[i] / sum;
  9792. }
  9793. blurUniforms['envMap'].value = targetIn.texture;
  9794. blurUniforms['samples'].value = samples;
  9795. blurUniforms['weights'].value = weights;
  9796. blurUniforms['latitudinal'].value = direction === 'latitudinal';
  9797. if (poleAxis) {
  9798. blurUniforms['poleAxis'].value = poleAxis;
  9799. }
  9800. const {
  9801. _lodMax
  9802. } = this;
  9803. blurUniforms['dTheta'].value = radiansPerPixel;
  9804. blurUniforms['mipInt'].value = _lodMax - lodIn;
  9805. const outputSize = this._sizeLods[lodOut];
  9806. const x = 3 * outputSize * (lodOut > _lodMax - LOD_MIN ? lodOut - _lodMax + LOD_MIN : 0);
  9807. const y = 4 * (this._cubeSize - outputSize);
  9808. _setViewport(targetOut, x, y, 3 * outputSize, 2 * outputSize);
  9809. renderer.setRenderTarget(targetOut);
  9810. renderer.render(blurMesh, _flatCamera);
  9811. }
  9812. }
  9813. function _createPlanes(lodMax) {
  9814. const lodPlanes = [];
  9815. const sizeLods = [];
  9816. const sigmas = [];
  9817. let lod = lodMax;
  9818. const totalLods = lodMax - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length;
  9819. for (let i = 0; i < totalLods; i++) {
  9820. const sizeLod = Math.pow(2, lod);
  9821. sizeLods.push(sizeLod);
  9822. let sigma = 1.0 / sizeLod;
  9823. if (i > lodMax - LOD_MIN) {
  9824. sigma = EXTRA_LOD_SIGMA[i - lodMax + LOD_MIN - 1];
  9825. } else if (i === 0) {
  9826. sigma = 0;
  9827. }
  9828. sigmas.push(sigma);
  9829. const texelSize = 1.0 / (sizeLod - 2);
  9830. const min = -texelSize;
  9831. const max = 1 + texelSize;
  9832. const uv1 = [min, min, max, min, max, max, min, min, max, max, min, max];
  9833. const cubeFaces = 6;
  9834. const vertices = 6;
  9835. const positionSize = 3;
  9836. const uvSize = 2;
  9837. const faceIndexSize = 1;
  9838. const position = new Float32Array(positionSize * vertices * cubeFaces);
  9839. const uv = new Float32Array(uvSize * vertices * cubeFaces);
  9840. const faceIndex = new Float32Array(faceIndexSize * vertices * cubeFaces);
  9841. for (let face = 0; face < cubeFaces; face++) {
  9842. const x = face % 3 * 2 / 3 - 1;
  9843. const y = face > 2 ? 0 : -1;
  9844. const coordinates = [x, y, 0, x + 2 / 3, y, 0, x + 2 / 3, y + 1, 0, x, y, 0, x + 2 / 3, y + 1, 0, x, y + 1, 0];
  9845. position.set(coordinates, positionSize * vertices * face);
  9846. uv.set(uv1, uvSize * vertices * face);
  9847. const fill = [face, face, face, face, face, face];
  9848. faceIndex.set(fill, faceIndexSize * vertices * face);
  9849. }
  9850. const planes = new BufferGeometry();
  9851. planes.setAttribute('position', new BufferAttribute(position, positionSize));
  9852. planes.setAttribute('uv', new BufferAttribute(uv, uvSize));
  9853. planes.setAttribute('faceIndex', new BufferAttribute(faceIndex, faceIndexSize));
  9854. lodPlanes.push(planes);
  9855. if (lod > LOD_MIN) {
  9856. lod--;
  9857. }
  9858. }
  9859. return {
  9860. lodPlanes,
  9861. sizeLods,
  9862. sigmas
  9863. };
  9864. }
  9865. function _createRenderTarget(width, height, params) {
  9866. const cubeUVRenderTarget = new WebGLRenderTarget(width, height, params);
  9867. cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping;
  9868. cubeUVRenderTarget.texture.name = 'PMREM.cubeUv';
  9869. cubeUVRenderTarget.scissorTest = true;
  9870. return cubeUVRenderTarget;
  9871. }
  9872. function _setViewport(target, x, y, width, height) {
  9873. target.viewport.set(x, y, width, height);
  9874. target.scissor.set(x, y, width, height);
  9875. }
  9876. function _getBlurShader(lodMax, width, height) {
  9877. const weights = new Float32Array(MAX_SAMPLES);
  9878. const poleAxis = new Vector3(0, 1, 0);
  9879. const shaderMaterial = new ShaderMaterial({
  9880. name: 'SphericalGaussianBlur',
  9881. defines: {
  9882. 'n': MAX_SAMPLES,
  9883. 'CUBEUV_TEXEL_WIDTH': 1.0 / width,
  9884. 'CUBEUV_TEXEL_HEIGHT': 1.0 / height,
  9885. 'CUBEUV_MAX_MIP': `${lodMax}.0`
  9886. },
  9887. uniforms: {
  9888. 'envMap': {
  9889. value: null
  9890. },
  9891. 'samples': {
  9892. value: 1
  9893. },
  9894. 'weights': {
  9895. value: weights
  9896. },
  9897. 'latitudinal': {
  9898. value: false
  9899. },
  9900. 'dTheta': {
  9901. value: 0
  9902. },
  9903. 'mipInt': {
  9904. value: 0
  9905. },
  9906. 'poleAxis': {
  9907. value: poleAxis
  9908. }
  9909. },
  9910. vertexShader: _getCommonVertexShader(),
  9911. fragmentShader:
  9912. /* glsl */
  9913. `
  9914. precision mediump float;
  9915. precision mediump int;
  9916. varying vec3 vOutputDirection;
  9917. uniform sampler2D envMap;
  9918. uniform int samples;
  9919. uniform float weights[ n ];
  9920. uniform bool latitudinal;
  9921. uniform float dTheta;
  9922. uniform float mipInt;
  9923. uniform vec3 poleAxis;
  9924. #define ENVMAP_TYPE_CUBE_UV
  9925. #include <cube_uv_reflection_fragment>
  9926. vec3 getSample( float theta, vec3 axis ) {
  9927. float cosTheta = cos( theta );
  9928. // Rodrigues' axis-angle rotation
  9929. vec3 sampleDirection = vOutputDirection * cosTheta
  9930. + cross( axis, vOutputDirection ) * sin( theta )
  9931. + axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta );
  9932. return bilinearCubeUV( envMap, sampleDirection, mipInt );
  9933. }
  9934. void main() {
  9935. vec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection );
  9936. if ( all( equal( axis, vec3( 0.0 ) ) ) ) {
  9937. axis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x );
  9938. }
  9939. axis = normalize( axis );
  9940. gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );
  9941. gl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis );
  9942. for ( int i = 1; i < n; i++ ) {
  9943. if ( i >= samples ) {
  9944. break;
  9945. }
  9946. float theta = dTheta * float( i );
  9947. gl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis );
  9948. gl_FragColor.rgb += weights[ i ] * getSample( theta, axis );
  9949. }
  9950. }
  9951. `,
  9952. blending: NoBlending,
  9953. depthTest: false,
  9954. depthWrite: false
  9955. });
  9956. return shaderMaterial;
  9957. }
  9958. function _getEquirectMaterial() {
  9959. return new ShaderMaterial({
  9960. name: 'EquirectangularToCubeUV',
  9961. uniforms: {
  9962. 'envMap': {
  9963. value: null
  9964. }
  9965. },
  9966. vertexShader: _getCommonVertexShader(),
  9967. fragmentShader:
  9968. /* glsl */
  9969. `
  9970. precision mediump float;
  9971. precision mediump int;
  9972. varying vec3 vOutputDirection;
  9973. uniform sampler2D envMap;
  9974. #include <common>
  9975. void main() {
  9976. vec3 outputDirection = normalize( vOutputDirection );
  9977. vec2 uv = equirectUv( outputDirection );
  9978. gl_FragColor = vec4( texture2D ( envMap, uv ).rgb, 1.0 );
  9979. }
  9980. `,
  9981. blending: NoBlending,
  9982. depthTest: false,
  9983. depthWrite: false
  9984. });
  9985. }
  9986. function _getCubemapMaterial() {
  9987. return new ShaderMaterial({
  9988. name: 'CubemapToCubeUV',
  9989. uniforms: {
  9990. 'envMap': {
  9991. value: null
  9992. },
  9993. 'flipEnvMap': {
  9994. value: -1
  9995. }
  9996. },
  9997. vertexShader: _getCommonVertexShader(),
  9998. fragmentShader:
  9999. /* glsl */
  10000. `
  10001. precision mediump float;
  10002. precision mediump int;
  10003. uniform float flipEnvMap;
  10004. varying vec3 vOutputDirection;
  10005. uniform samplerCube envMap;
  10006. void main() {
  10007. gl_FragColor = textureCube( envMap, vec3( flipEnvMap * vOutputDirection.x, vOutputDirection.yz ) );
  10008. }
  10009. `,
  10010. blending: NoBlending,
  10011. depthTest: false,
  10012. depthWrite: false
  10013. });
  10014. }
  10015. function _getCommonVertexShader() {
  10016. return (
  10017. /* glsl */
  10018. `
  10019. precision mediump float;
  10020. precision mediump int;
  10021. attribute float faceIndex;
  10022. varying vec3 vOutputDirection;
  10023. // RH coordinate system; PMREM face-indexing convention
  10024. vec3 getDirection( vec2 uv, float face ) {
  10025. uv = 2.0 * uv - 1.0;
  10026. vec3 direction = vec3( uv, 1.0 );
  10027. if ( face == 0.0 ) {
  10028. direction = direction.zyx; // ( 1, v, u ) pos x
  10029. } else if ( face == 1.0 ) {
  10030. direction = direction.xzy;
  10031. direction.xz *= -1.0; // ( -u, 1, -v ) pos y
  10032. } else if ( face == 2.0 ) {
  10033. direction.x *= -1.0; // ( -u, v, 1 ) pos z
  10034. } else if ( face == 3.0 ) {
  10035. direction = direction.zyx;
  10036. direction.xz *= -1.0; // ( -1, v, -u ) neg x
  10037. } else if ( face == 4.0 ) {
  10038. direction = direction.xzy;
  10039. direction.xy *= -1.0; // ( -u, -1, v ) neg y
  10040. } else if ( face == 5.0 ) {
  10041. direction.z *= -1.0; // ( u, v, -1 ) neg z
  10042. }
  10043. return direction;
  10044. }
  10045. void main() {
  10046. vOutputDirection = getDirection( uv, faceIndex );
  10047. gl_Position = vec4( position, 1.0 );
  10048. }
  10049. `
  10050. );
  10051. }
  10052. function WebGLCubeUVMaps(renderer) {
  10053. let cubeUVmaps = new WeakMap();
  10054. let pmremGenerator = null;
  10055. function get(texture) {
  10056. if (texture && texture.isTexture) {
  10057. const mapping = texture.mapping;
  10058. const isEquirectMap = mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping;
  10059. const isCubeMap = mapping === CubeReflectionMapping || mapping === CubeRefractionMapping; // equirect/cube map to cubeUV conversion
  10060. if (isEquirectMap || isCubeMap) {
  10061. if (texture.isRenderTargetTexture && texture.needsPMREMUpdate === true) {
  10062. texture.needsPMREMUpdate = false;
  10063. let renderTarget = cubeUVmaps.get(texture);
  10064. if (pmremGenerator === null) pmremGenerator = new PMREMGenerator(renderer);
  10065. renderTarget = isEquirectMap ? pmremGenerator.fromEquirectangular(texture, renderTarget) : pmremGenerator.fromCubemap(texture, renderTarget);
  10066. cubeUVmaps.set(texture, renderTarget);
  10067. return renderTarget.texture;
  10068. } else {
  10069. if (cubeUVmaps.has(texture)) {
  10070. return cubeUVmaps.get(texture).texture;
  10071. } else {
  10072. const image = texture.image;
  10073. if (isEquirectMap && image && image.height > 0 || isCubeMap && image && isCubeTextureComplete(image)) {
  10074. if (pmremGenerator === null) pmremGenerator = new PMREMGenerator(renderer);
  10075. const renderTarget = isEquirectMap ? pmremGenerator.fromEquirectangular(texture) : pmremGenerator.fromCubemap(texture);
  10076. cubeUVmaps.set(texture, renderTarget);
  10077. texture.addEventListener('dispose', onTextureDispose);
  10078. return renderTarget.texture;
  10079. } else {
  10080. // image not yet ready. try the conversion next frame
  10081. return null;
  10082. }
  10083. }
  10084. }
  10085. }
  10086. }
  10087. return texture;
  10088. }
  10089. function isCubeTextureComplete(image) {
  10090. let count = 0;
  10091. const length = 6;
  10092. for (let i = 0; i < length; i++) {
  10093. if (image[i] !== undefined) count++;
  10094. }
  10095. return count === length;
  10096. }
  10097. function onTextureDispose(event) {
  10098. const texture = event.target;
  10099. texture.removeEventListener('dispose', onTextureDispose);
  10100. const cubemapUV = cubeUVmaps.get(texture);
  10101. if (cubemapUV !== undefined) {
  10102. cubeUVmaps.delete(texture);
  10103. cubemapUV.dispose();
  10104. }
  10105. }
  10106. function dispose() {
  10107. cubeUVmaps = new WeakMap();
  10108. if (pmremGenerator !== null) {
  10109. pmremGenerator.dispose();
  10110. pmremGenerator = null;
  10111. }
  10112. }
  10113. return {
  10114. get: get,
  10115. dispose: dispose
  10116. };
  10117. }
  10118. function WebGLExtensions(gl) {
  10119. const extensions = {};
  10120. function getExtension(name) {
  10121. if (extensions[name] !== undefined) {
  10122. return extensions[name];
  10123. }
  10124. let extension;
  10125. switch (name) {
  10126. case 'WEBGL_depth_texture':
  10127. extension = gl.getExtension('WEBGL_depth_texture') || gl.getExtension('MOZ_WEBGL_depth_texture') || gl.getExtension('WEBKIT_WEBGL_depth_texture');
  10128. break;
  10129. case 'EXT_texture_filter_anisotropic':
  10130. extension = gl.getExtension('EXT_texture_filter_anisotropic') || gl.getExtension('MOZ_EXT_texture_filter_anisotropic') || gl.getExtension('WEBKIT_EXT_texture_filter_anisotropic');
  10131. break;
  10132. case 'WEBGL_compressed_texture_s3tc':
  10133. extension = gl.getExtension('WEBGL_compressed_texture_s3tc') || gl.getExtension('MOZ_WEBGL_compressed_texture_s3tc') || gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  10134. break;
  10135. case 'WEBGL_compressed_texture_pvrtc':
  10136. extension = gl.getExtension('WEBGL_compressed_texture_pvrtc') || gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  10137. break;
  10138. default:
  10139. extension = gl.getExtension(name);
  10140. }
  10141. extensions[name] = extension;
  10142. return extension;
  10143. }
  10144. return {
  10145. has: function (name) {
  10146. return getExtension(name) !== null;
  10147. },
  10148. init: function (capabilities) {
  10149. if (capabilities.isWebGL2) {
  10150. getExtension('EXT_color_buffer_float');
  10151. } else {
  10152. getExtension('WEBGL_depth_texture');
  10153. getExtension('OES_texture_float');
  10154. getExtension('OES_texture_half_float');
  10155. getExtension('OES_texture_half_float_linear');
  10156. getExtension('OES_standard_derivatives');
  10157. getExtension('OES_element_index_uint');
  10158. getExtension('OES_vertex_array_object');
  10159. getExtension('ANGLE_instanced_arrays');
  10160. }
  10161. getExtension('OES_texture_float_linear');
  10162. getExtension('EXT_color_buffer_half_float');
  10163. getExtension('WEBGL_multisampled_render_to_texture');
  10164. },
  10165. get: function (name) {
  10166. const extension = getExtension(name);
  10167. if (extension === null) {
  10168. console.warn('THREE.WebGLRenderer: ' + name + ' extension not supported.');
  10169. }
  10170. return extension;
  10171. }
  10172. };
  10173. }
  10174. function WebGLGeometries(gl, attributes, info, bindingStates) {
  10175. const geometries = {};
  10176. const wireframeAttributes = new WeakMap();
  10177. function onGeometryDispose(event) {
  10178. const geometry = event.target;
  10179. if (geometry.index !== null) {
  10180. attributes.remove(geometry.index);
  10181. }
  10182. for (const name in geometry.attributes) {
  10183. attributes.remove(geometry.attributes[name]);
  10184. }
  10185. geometry.removeEventListener('dispose', onGeometryDispose);
  10186. delete geometries[geometry.id];
  10187. const attribute = wireframeAttributes.get(geometry);
  10188. if (attribute) {
  10189. attributes.remove(attribute);
  10190. wireframeAttributes.delete(geometry);
  10191. }
  10192. bindingStates.releaseStatesOfGeometry(geometry);
  10193. if (geometry.isInstancedBufferGeometry === true) {
  10194. delete geometry._maxInstanceCount;
  10195. } //
  10196. info.memory.geometries--;
  10197. }
  10198. function get(object, geometry) {
  10199. if (geometries[geometry.id] === true) return geometry;
  10200. geometry.addEventListener('dispose', onGeometryDispose);
  10201. geometries[geometry.id] = true;
  10202. info.memory.geometries++;
  10203. return geometry;
  10204. }
  10205. function update(geometry) {
  10206. const geometryAttributes = geometry.attributes; // Updating index buffer in VAO now. See WebGLBindingStates.
  10207. for (const name in geometryAttributes) {
  10208. attributes.update(geometryAttributes[name], gl.ARRAY_BUFFER);
  10209. } // morph targets
  10210. const morphAttributes = geometry.morphAttributes;
  10211. for (const name in morphAttributes) {
  10212. const array = morphAttributes[name];
  10213. for (let i = 0, l = array.length; i < l; i++) {
  10214. attributes.update(array[i], gl.ARRAY_BUFFER);
  10215. }
  10216. }
  10217. }
  10218. function updateWireframeAttribute(geometry) {
  10219. const indices = [];
  10220. const geometryIndex = geometry.index;
  10221. const geometryPosition = geometry.attributes.position;
  10222. let version = 0;
  10223. if (geometryIndex !== null) {
  10224. const array = geometryIndex.array;
  10225. version = geometryIndex.version;
  10226. for (let i = 0, l = array.length; i < l; i += 3) {
  10227. const a = array[i + 0];
  10228. const b = array[i + 1];
  10229. const c = array[i + 2];
  10230. indices.push(a, b, b, c, c, a);
  10231. }
  10232. } else {
  10233. const array = geometryPosition.array;
  10234. version = geometryPosition.version;
  10235. for (let i = 0, l = array.length / 3 - 1; i < l; i += 3) {
  10236. const a = i + 0;
  10237. const b = i + 1;
  10238. const c = i + 2;
  10239. indices.push(a, b, b, c, c, a);
  10240. }
  10241. }
  10242. const attribute = new (arrayNeedsUint32(indices) ? Uint32BufferAttribute : Uint16BufferAttribute)(indices, 1);
  10243. attribute.version = version; // Updating index buffer in VAO now. See WebGLBindingStates
  10244. //
  10245. const previousAttribute = wireframeAttributes.get(geometry);
  10246. if (previousAttribute) attributes.remove(previousAttribute); //
  10247. wireframeAttributes.set(geometry, attribute);
  10248. }
  10249. function getWireframeAttribute(geometry) {
  10250. const currentAttribute = wireframeAttributes.get(geometry);
  10251. if (currentAttribute) {
  10252. const geometryIndex = geometry.index;
  10253. if (geometryIndex !== null) {
  10254. // if the attribute is obsolete, create a new one
  10255. if (currentAttribute.version < geometryIndex.version) {
  10256. updateWireframeAttribute(geometry);
  10257. }
  10258. }
  10259. } else {
  10260. updateWireframeAttribute(geometry);
  10261. }
  10262. return wireframeAttributes.get(geometry);
  10263. }
  10264. return {
  10265. get: get,
  10266. update: update,
  10267. getWireframeAttribute: getWireframeAttribute
  10268. };
  10269. }
  10270. function WebGLIndexedBufferRenderer(gl, extensions, info, capabilities) {
  10271. const isWebGL2 = capabilities.isWebGL2;
  10272. let mode;
  10273. function setMode(value) {
  10274. mode = value;
  10275. }
  10276. let type, bytesPerElement;
  10277. function setIndex(value) {
  10278. type = value.type;
  10279. bytesPerElement = value.bytesPerElement;
  10280. }
  10281. function render(start, count) {
  10282. gl.drawElements(mode, count, type, start * bytesPerElement);
  10283. info.update(count, mode, 1);
  10284. }
  10285. function renderInstances(start, count, primcount) {
  10286. if (primcount === 0) return;
  10287. let extension, methodName;
  10288. if (isWebGL2) {
  10289. extension = gl;
  10290. methodName = 'drawElementsInstanced';
  10291. } else {
  10292. extension = extensions.get('ANGLE_instanced_arrays');
  10293. methodName = 'drawElementsInstancedANGLE';
  10294. if (extension === null) {
  10295. console.error('THREE.WebGLIndexedBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.');
  10296. return;
  10297. }
  10298. }
  10299. extension[methodName](mode, count, type, start * bytesPerElement, primcount);
  10300. info.update(count, mode, primcount);
  10301. } //
  10302. this.setMode = setMode;
  10303. this.setIndex = setIndex;
  10304. this.render = render;
  10305. this.renderInstances = renderInstances;
  10306. }
  10307. function WebGLInfo(gl) {
  10308. const memory = {
  10309. geometries: 0,
  10310. textures: 0
  10311. };
  10312. const render = {
  10313. frame: 0,
  10314. calls: 0,
  10315. triangles: 0,
  10316. points: 0,
  10317. lines: 0
  10318. };
  10319. function update(count, mode, instanceCount) {
  10320. render.calls++;
  10321. switch (mode) {
  10322. case gl.TRIANGLES:
  10323. render.triangles += instanceCount * (count / 3);
  10324. break;
  10325. case gl.LINES:
  10326. render.lines += instanceCount * (count / 2);
  10327. break;
  10328. case gl.LINE_STRIP:
  10329. render.lines += instanceCount * (count - 1);
  10330. break;
  10331. case gl.LINE_LOOP:
  10332. render.lines += instanceCount * count;
  10333. break;
  10334. case gl.POINTS:
  10335. render.points += instanceCount * count;
  10336. break;
  10337. default:
  10338. console.error('THREE.WebGLInfo: Unknown draw mode:', mode);
  10339. break;
  10340. }
  10341. }
  10342. function reset() {
  10343. render.frame++;
  10344. render.calls = 0;
  10345. render.triangles = 0;
  10346. render.points = 0;
  10347. render.lines = 0;
  10348. }
  10349. return {
  10350. memory: memory,
  10351. render: render,
  10352. programs: null,
  10353. autoReset: true,
  10354. reset: reset,
  10355. update: update
  10356. };
  10357. }
  10358. function numericalSort(a, b) {
  10359. return a[0] - b[0];
  10360. }
  10361. function absNumericalSort(a, b) {
  10362. return Math.abs(b[1]) - Math.abs(a[1]);
  10363. }
  10364. function WebGLMorphtargets(gl, capabilities, textures) {
  10365. const influencesList = {};
  10366. const morphInfluences = new Float32Array(8);
  10367. const morphTextures = new WeakMap();
  10368. const morph = new Vector4();
  10369. const workInfluences = [];
  10370. for (let i = 0; i < 8; i++) {
  10371. workInfluences[i] = [i, 0];
  10372. }
  10373. function update(object, geometry, material, program) {
  10374. const objectInfluences = object.morphTargetInfluences;
  10375. if (capabilities.isWebGL2 === true) {
  10376. // instead of using attributes, the WebGL 2 code path encodes morph targets
  10377. // into an array of data textures. Each layer represents a single morph target.
  10378. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  10379. const morphTargetsCount = morphAttribute !== undefined ? morphAttribute.length : 0;
  10380. let entry = morphTextures.get(geometry);
  10381. if (entry === undefined || entry.count !== morphTargetsCount) {
  10382. if (entry !== undefined) entry.texture.dispose();
  10383. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  10384. const hasMorphNormals = geometry.morphAttributes.normal !== undefined;
  10385. const hasMorphColors = geometry.morphAttributes.color !== undefined;
  10386. const morphTargets = geometry.morphAttributes.position || [];
  10387. const morphNormals = geometry.morphAttributes.normal || [];
  10388. const morphColors = geometry.morphAttributes.color || [];
  10389. let vertexDataCount = 0;
  10390. if (hasMorphPosition === true) vertexDataCount = 1;
  10391. if (hasMorphNormals === true) vertexDataCount = 2;
  10392. if (hasMorphColors === true) vertexDataCount = 3;
  10393. let width = geometry.attributes.position.count * vertexDataCount;
  10394. let height = 1;
  10395. if (width > capabilities.maxTextureSize) {
  10396. height = Math.ceil(width / capabilities.maxTextureSize);
  10397. width = capabilities.maxTextureSize;
  10398. }
  10399. const buffer = new Float32Array(width * height * 4 * morphTargetsCount);
  10400. const texture = new DataArrayTexture(buffer, width, height, morphTargetsCount);
  10401. texture.type = FloatType;
  10402. texture.needsUpdate = true; // fill buffer
  10403. const vertexDataStride = vertexDataCount * 4;
  10404. for (let i = 0; i < morphTargetsCount; i++) {
  10405. const morphTarget = morphTargets[i];
  10406. const morphNormal = morphNormals[i];
  10407. const morphColor = morphColors[i];
  10408. const offset = width * height * 4 * i;
  10409. for (let j = 0; j < morphTarget.count; j++) {
  10410. const stride = j * vertexDataStride;
  10411. if (hasMorphPosition === true) {
  10412. morph.fromBufferAttribute(morphTarget, j);
  10413. buffer[offset + stride + 0] = morph.x;
  10414. buffer[offset + stride + 1] = morph.y;
  10415. buffer[offset + stride + 2] = morph.z;
  10416. buffer[offset + stride + 3] = 0;
  10417. }
  10418. if (hasMorphNormals === true) {
  10419. morph.fromBufferAttribute(morphNormal, j);
  10420. buffer[offset + stride + 4] = morph.x;
  10421. buffer[offset + stride + 5] = morph.y;
  10422. buffer[offset + stride + 6] = morph.z;
  10423. buffer[offset + stride + 7] = 0;
  10424. }
  10425. if (hasMorphColors === true) {
  10426. morph.fromBufferAttribute(morphColor, j);
  10427. buffer[offset + stride + 8] = morph.x;
  10428. buffer[offset + stride + 9] = morph.y;
  10429. buffer[offset + stride + 10] = morph.z;
  10430. buffer[offset + stride + 11] = morphColor.itemSize === 4 ? morph.w : 1;
  10431. }
  10432. }
  10433. }
  10434. entry = {
  10435. count: morphTargetsCount,
  10436. texture: texture,
  10437. size: new Vector2(width, height)
  10438. };
  10439. morphTextures.set(geometry, entry);
  10440. function disposeTexture() {
  10441. texture.dispose();
  10442. morphTextures.delete(geometry);
  10443. geometry.removeEventListener('dispose', disposeTexture);
  10444. }
  10445. geometry.addEventListener('dispose', disposeTexture);
  10446. } //
  10447. let morphInfluencesSum = 0;
  10448. for (let i = 0; i < objectInfluences.length; i++) {
  10449. morphInfluencesSum += objectInfluences[i];
  10450. }
  10451. const morphBaseInfluence = geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
  10452. program.getUniforms().setValue(gl, 'morphTargetBaseInfluence', morphBaseInfluence);
  10453. program.getUniforms().setValue(gl, 'morphTargetInfluences', objectInfluences);
  10454. program.getUniforms().setValue(gl, 'morphTargetsTexture', entry.texture, textures);
  10455. program.getUniforms().setValue(gl, 'morphTargetsTextureSize', entry.size);
  10456. } else {
  10457. // When object doesn't have morph target influences defined, we treat it as a 0-length array
  10458. // This is important to make sure we set up morphTargetBaseInfluence / morphTargetInfluences
  10459. const length = objectInfluences === undefined ? 0 : objectInfluences.length;
  10460. let influences = influencesList[geometry.id];
  10461. if (influences === undefined || influences.length !== length) {
  10462. // initialise list
  10463. influences = [];
  10464. for (let i = 0; i < length; i++) {
  10465. influences[i] = [i, 0];
  10466. }
  10467. influencesList[geometry.id] = influences;
  10468. } // Collect influences
  10469. for (let i = 0; i < length; i++) {
  10470. const influence = influences[i];
  10471. influence[0] = i;
  10472. influence[1] = objectInfluences[i];
  10473. }
  10474. influences.sort(absNumericalSort);
  10475. for (let i = 0; i < 8; i++) {
  10476. if (i < length && influences[i][1]) {
  10477. workInfluences[i][0] = influences[i][0];
  10478. workInfluences[i][1] = influences[i][1];
  10479. } else {
  10480. workInfluences[i][0] = Number.MAX_SAFE_INTEGER;
  10481. workInfluences[i][1] = 0;
  10482. }
  10483. }
  10484. workInfluences.sort(numericalSort);
  10485. const morphTargets = geometry.morphAttributes.position;
  10486. const morphNormals = geometry.morphAttributes.normal;
  10487. let morphInfluencesSum = 0;
  10488. for (let i = 0; i < 8; i++) {
  10489. const influence = workInfluences[i];
  10490. const index = influence[0];
  10491. const value = influence[1];
  10492. if (index !== Number.MAX_SAFE_INTEGER && value) {
  10493. if (morphTargets && geometry.getAttribute('morphTarget' + i) !== morphTargets[index]) {
  10494. geometry.setAttribute('morphTarget' + i, morphTargets[index]);
  10495. }
  10496. if (morphNormals && geometry.getAttribute('morphNormal' + i) !== morphNormals[index]) {
  10497. geometry.setAttribute('morphNormal' + i, morphNormals[index]);
  10498. }
  10499. morphInfluences[i] = value;
  10500. morphInfluencesSum += value;
  10501. } else {
  10502. if (morphTargets && geometry.hasAttribute('morphTarget' + i) === true) {
  10503. geometry.deleteAttribute('morphTarget' + i);
  10504. }
  10505. if (morphNormals && geometry.hasAttribute('morphNormal' + i) === true) {
  10506. geometry.deleteAttribute('morphNormal' + i);
  10507. }
  10508. morphInfluences[i] = 0;
  10509. }
  10510. } // GLSL shader uses formula baseinfluence * base + sum(target * influence)
  10511. // This allows us to switch between absolute morphs and relative morphs without changing shader code
  10512. // When baseinfluence = 1 - sum(influence), the above is equivalent to sum((target - base) * influence)
  10513. const morphBaseInfluence = geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
  10514. program.getUniforms().setValue(gl, 'morphTargetBaseInfluence', morphBaseInfluence);
  10515. program.getUniforms().setValue(gl, 'morphTargetInfluences', morphInfluences);
  10516. }
  10517. }
  10518. return {
  10519. update: update
  10520. };
  10521. }
  10522. function WebGLObjects(gl, geometries, attributes, info) {
  10523. let updateMap = new WeakMap();
  10524. function update(object) {
  10525. const frame = info.render.frame;
  10526. const geometry = object.geometry;
  10527. const buffergeometry = geometries.get(object, geometry); // Update once per frame
  10528. if (updateMap.get(buffergeometry) !== frame) {
  10529. geometries.update(buffergeometry);
  10530. updateMap.set(buffergeometry, frame);
  10531. }
  10532. if (object.isInstancedMesh) {
  10533. if (object.hasEventListener('dispose', onInstancedMeshDispose) === false) {
  10534. object.addEventListener('dispose', onInstancedMeshDispose);
  10535. }
  10536. attributes.update(object.instanceMatrix, gl.ARRAY_BUFFER);
  10537. if (object.instanceColor !== null) {
  10538. attributes.update(object.instanceColor, gl.ARRAY_BUFFER);
  10539. }
  10540. }
  10541. return buffergeometry;
  10542. }
  10543. function dispose() {
  10544. updateMap = new WeakMap();
  10545. }
  10546. function onInstancedMeshDispose(event) {
  10547. const instancedMesh = event.target;
  10548. instancedMesh.removeEventListener('dispose', onInstancedMeshDispose);
  10549. attributes.remove(instancedMesh.instanceMatrix);
  10550. if (instancedMesh.instanceColor !== null) attributes.remove(instancedMesh.instanceColor);
  10551. }
  10552. return {
  10553. update: update,
  10554. dispose: dispose
  10555. };
  10556. }
  10557. /**
  10558. * Uniforms of a program.
  10559. * Those form a tree structure with a special top-level container for the root,
  10560. * which you get by calling 'new WebGLUniforms( gl, program )'.
  10561. *
  10562. *
  10563. * Properties of inner nodes including the top-level container:
  10564. *
  10565. * .seq - array of nested uniforms
  10566. * .map - nested uniforms by name
  10567. *
  10568. *
  10569. * Methods of all nodes except the top-level container:
  10570. *
  10571. * .setValue( gl, value, [textures] )
  10572. *
  10573. * uploads a uniform value(s)
  10574. * the 'textures' parameter is needed for sampler uniforms
  10575. *
  10576. *
  10577. * Static methods of the top-level container (textures factorizations):
  10578. *
  10579. * .upload( gl, seq, values, textures )
  10580. *
  10581. * sets uniforms in 'seq' to 'values[id].value'
  10582. *
  10583. * .seqWithValue( seq, values ) : filteredSeq
  10584. *
  10585. * filters 'seq' entries with corresponding entry in values
  10586. *
  10587. *
  10588. * Methods of the top-level container (textures factorizations):
  10589. *
  10590. * .setValue( gl, name, value, textures )
  10591. *
  10592. * sets uniform with name 'name' to 'value'
  10593. *
  10594. * .setOptional( gl, obj, prop )
  10595. *
  10596. * like .set for an optional property of the object
  10597. *
  10598. */
  10599. const emptyTexture = /*@__PURE__*/new Texture();
  10600. const emptyArrayTexture = /*@__PURE__*/new DataArrayTexture();
  10601. const empty3dTexture = /*@__PURE__*/new Data3DTexture();
  10602. const emptyCubeTexture = /*@__PURE__*/new CubeTexture(); // --- Utilities ---
  10603. // Array Caches (provide typed arrays for temporary by size)
  10604. const arrayCacheF32 = [];
  10605. const arrayCacheI32 = []; // Float32Array caches used for uploading Matrix uniforms
  10606. const mat4array = new Float32Array(16);
  10607. const mat3array = new Float32Array(9);
  10608. const mat2array = new Float32Array(4); // Flattening for arrays of vectors and matrices
  10609. function flatten(array, nBlocks, blockSize) {
  10610. const firstElem = array[0];
  10611. if (firstElem <= 0 || firstElem > 0) return array; // unoptimized: ! isNaN( firstElem )
  10612. // see http://jacksondunstan.com/articles/983
  10613. const n = nBlocks * blockSize;
  10614. let r = arrayCacheF32[n];
  10615. if (r === undefined) {
  10616. r = new Float32Array(n);
  10617. arrayCacheF32[n] = r;
  10618. }
  10619. if (nBlocks !== 0) {
  10620. firstElem.toArray(r, 0);
  10621. for (let i = 1, offset = 0; i !== nBlocks; ++i) {
  10622. offset += blockSize;
  10623. array[i].toArray(r, offset);
  10624. }
  10625. }
  10626. return r;
  10627. }
  10628. function arraysEqual(a, b) {
  10629. if (a.length !== b.length) return false;
  10630. for (let i = 0, l = a.length; i < l; i++) {
  10631. if (a[i] !== b[i]) return false;
  10632. }
  10633. return true;
  10634. }
  10635. function copyArray(a, b) {
  10636. for (let i = 0, l = b.length; i < l; i++) {
  10637. a[i] = b[i];
  10638. }
  10639. } // Texture unit allocation
  10640. function allocTexUnits(textures, n) {
  10641. let r = arrayCacheI32[n];
  10642. if (r === undefined) {
  10643. r = new Int32Array(n);
  10644. arrayCacheI32[n] = r;
  10645. }
  10646. for (let i = 0; i !== n; ++i) {
  10647. r[i] = textures.allocateTextureUnit();
  10648. }
  10649. return r;
  10650. } // --- Setters ---
  10651. // Note: Defining these methods externally, because they come in a bunch
  10652. // and this way their names minify.
  10653. // Single scalar
  10654. function setValueV1f(gl, v) {
  10655. const cache = this.cache;
  10656. if (cache[0] === v) return;
  10657. gl.uniform1f(this.addr, v);
  10658. cache[0] = v;
  10659. } // Single float vector (from flat array or THREE.VectorN)
  10660. function setValueV2f(gl, v) {
  10661. const cache = this.cache;
  10662. if (v.x !== undefined) {
  10663. if (cache[0] !== v.x || cache[1] !== v.y) {
  10664. gl.uniform2f(this.addr, v.x, v.y);
  10665. cache[0] = v.x;
  10666. cache[1] = v.y;
  10667. }
  10668. } else {
  10669. if (arraysEqual(cache, v)) return;
  10670. gl.uniform2fv(this.addr, v);
  10671. copyArray(cache, v);
  10672. }
  10673. }
  10674. function setValueV3f(gl, v) {
  10675. const cache = this.cache;
  10676. if (v.x !== undefined) {
  10677. if (cache[0] !== v.x || cache[1] !== v.y || cache[2] !== v.z) {
  10678. gl.uniform3f(this.addr, v.x, v.y, v.z);
  10679. cache[0] = v.x;
  10680. cache[1] = v.y;
  10681. cache[2] = v.z;
  10682. }
  10683. } else if (v.r !== undefined) {
  10684. if (cache[0] !== v.r || cache[1] !== v.g || cache[2] !== v.b) {
  10685. gl.uniform3f(this.addr, v.r, v.g, v.b);
  10686. cache[0] = v.r;
  10687. cache[1] = v.g;
  10688. cache[2] = v.b;
  10689. }
  10690. } else {
  10691. if (arraysEqual(cache, v)) return;
  10692. gl.uniform3fv(this.addr, v);
  10693. copyArray(cache, v);
  10694. }
  10695. }
  10696. function setValueV4f(gl, v) {
  10697. const cache = this.cache;
  10698. if (v.x !== undefined) {
  10699. if (cache[0] !== v.x || cache[1] !== v.y || cache[2] !== v.z || cache[3] !== v.w) {
  10700. gl.uniform4f(this.addr, v.x, v.y, v.z, v.w);
  10701. cache[0] = v.x;
  10702. cache[1] = v.y;
  10703. cache[2] = v.z;
  10704. cache[3] = v.w;
  10705. }
  10706. } else {
  10707. if (arraysEqual(cache, v)) return;
  10708. gl.uniform4fv(this.addr, v);
  10709. copyArray(cache, v);
  10710. }
  10711. } // Single matrix (from flat array or THREE.MatrixN)
  10712. function setValueM2(gl, v) {
  10713. const cache = this.cache;
  10714. const elements = v.elements;
  10715. if (elements === undefined) {
  10716. if (arraysEqual(cache, v)) return;
  10717. gl.uniformMatrix2fv(this.addr, false, v);
  10718. copyArray(cache, v);
  10719. } else {
  10720. if (arraysEqual(cache, elements)) return;
  10721. mat2array.set(elements);
  10722. gl.uniformMatrix2fv(this.addr, false, mat2array);
  10723. copyArray(cache, elements);
  10724. }
  10725. }
  10726. function setValueM3(gl, v) {
  10727. const cache = this.cache;
  10728. const elements = v.elements;
  10729. if (elements === undefined) {
  10730. if (arraysEqual(cache, v)) return;
  10731. gl.uniformMatrix3fv(this.addr, false, v);
  10732. copyArray(cache, v);
  10733. } else {
  10734. if (arraysEqual(cache, elements)) return;
  10735. mat3array.set(elements);
  10736. gl.uniformMatrix3fv(this.addr, false, mat3array);
  10737. copyArray(cache, elements);
  10738. }
  10739. }
  10740. function setValueM4(gl, v) {
  10741. const cache = this.cache;
  10742. const elements = v.elements;
  10743. if (elements === undefined) {
  10744. if (arraysEqual(cache, v)) return;
  10745. gl.uniformMatrix4fv(this.addr, false, v);
  10746. copyArray(cache, v);
  10747. } else {
  10748. if (arraysEqual(cache, elements)) return;
  10749. mat4array.set(elements);
  10750. gl.uniformMatrix4fv(this.addr, false, mat4array);
  10751. copyArray(cache, elements);
  10752. }
  10753. } // Single integer / boolean
  10754. function setValueV1i(gl, v) {
  10755. const cache = this.cache;
  10756. if (cache[0] === v) return;
  10757. gl.uniform1i(this.addr, v);
  10758. cache[0] = v;
  10759. } // Single integer / boolean vector (from flat array)
  10760. function setValueV2i(gl, v) {
  10761. const cache = this.cache;
  10762. if (arraysEqual(cache, v)) return;
  10763. gl.uniform2iv(this.addr, v);
  10764. copyArray(cache, v);
  10765. }
  10766. function setValueV3i(gl, v) {
  10767. const cache = this.cache;
  10768. if (arraysEqual(cache, v)) return;
  10769. gl.uniform3iv(this.addr, v);
  10770. copyArray(cache, v);
  10771. }
  10772. function setValueV4i(gl, v) {
  10773. const cache = this.cache;
  10774. if (arraysEqual(cache, v)) return;
  10775. gl.uniform4iv(this.addr, v);
  10776. copyArray(cache, v);
  10777. } // Single unsigned integer
  10778. function setValueV1ui(gl, v) {
  10779. const cache = this.cache;
  10780. if (cache[0] === v) return;
  10781. gl.uniform1ui(this.addr, v);
  10782. cache[0] = v;
  10783. } // Single unsigned integer vector (from flat array)
  10784. function setValueV2ui(gl, v) {
  10785. const cache = this.cache;
  10786. if (arraysEqual(cache, v)) return;
  10787. gl.uniform2uiv(this.addr, v);
  10788. copyArray(cache, v);
  10789. }
  10790. function setValueV3ui(gl, v) {
  10791. const cache = this.cache;
  10792. if (arraysEqual(cache, v)) return;
  10793. gl.uniform3uiv(this.addr, v);
  10794. copyArray(cache, v);
  10795. }
  10796. function setValueV4ui(gl, v) {
  10797. const cache = this.cache;
  10798. if (arraysEqual(cache, v)) return;
  10799. gl.uniform4uiv(this.addr, v);
  10800. copyArray(cache, v);
  10801. } // Single texture (2D / Cube)
  10802. function setValueT1(gl, v, textures) {
  10803. const cache = this.cache;
  10804. const unit = textures.allocateTextureUnit();
  10805. if (cache[0] !== unit) {
  10806. gl.uniform1i(this.addr, unit);
  10807. cache[0] = unit;
  10808. }
  10809. textures.setTexture2D(v || emptyTexture, unit);
  10810. }
  10811. function setValueT3D1(gl, v, textures) {
  10812. const cache = this.cache;
  10813. const unit = textures.allocateTextureUnit();
  10814. if (cache[0] !== unit) {
  10815. gl.uniform1i(this.addr, unit);
  10816. cache[0] = unit;
  10817. }
  10818. textures.setTexture3D(v || empty3dTexture, unit);
  10819. }
  10820. function setValueT6(gl, v, textures) {
  10821. const cache = this.cache;
  10822. const unit = textures.allocateTextureUnit();
  10823. if (cache[0] !== unit) {
  10824. gl.uniform1i(this.addr, unit);
  10825. cache[0] = unit;
  10826. }
  10827. textures.setTextureCube(v || emptyCubeTexture, unit);
  10828. }
  10829. function setValueT2DArray1(gl, v, textures) {
  10830. const cache = this.cache;
  10831. const unit = textures.allocateTextureUnit();
  10832. if (cache[0] !== unit) {
  10833. gl.uniform1i(this.addr, unit);
  10834. cache[0] = unit;
  10835. }
  10836. textures.setTexture2DArray(v || emptyArrayTexture, unit);
  10837. } // Helper to pick the right setter for the singular case
  10838. function getSingularSetter(type) {
  10839. switch (type) {
  10840. case 0x1406:
  10841. return setValueV1f;
  10842. // FLOAT
  10843. case 0x8b50:
  10844. return setValueV2f;
  10845. // _VEC2
  10846. case 0x8b51:
  10847. return setValueV3f;
  10848. // _VEC3
  10849. case 0x8b52:
  10850. return setValueV4f;
  10851. // _VEC4
  10852. case 0x8b5a:
  10853. return setValueM2;
  10854. // _MAT2
  10855. case 0x8b5b:
  10856. return setValueM3;
  10857. // _MAT3
  10858. case 0x8b5c:
  10859. return setValueM4;
  10860. // _MAT4
  10861. case 0x1404:
  10862. case 0x8b56:
  10863. return setValueV1i;
  10864. // INT, BOOL
  10865. case 0x8b53:
  10866. case 0x8b57:
  10867. return setValueV2i;
  10868. // _VEC2
  10869. case 0x8b54:
  10870. case 0x8b58:
  10871. return setValueV3i;
  10872. // _VEC3
  10873. case 0x8b55:
  10874. case 0x8b59:
  10875. return setValueV4i;
  10876. // _VEC4
  10877. case 0x1405:
  10878. return setValueV1ui;
  10879. // UINT
  10880. case 0x8dc6:
  10881. return setValueV2ui;
  10882. // _VEC2
  10883. case 0x8dc7:
  10884. return setValueV3ui;
  10885. // _VEC3
  10886. case 0x8dc8:
  10887. return setValueV4ui;
  10888. // _VEC4
  10889. case 0x8b5e: // SAMPLER_2D
  10890. case 0x8d66: // SAMPLER_EXTERNAL_OES
  10891. case 0x8dca: // INT_SAMPLER_2D
  10892. case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
  10893. case 0x8b62:
  10894. // SAMPLER_2D_SHADOW
  10895. return setValueT1;
  10896. case 0x8b5f: // SAMPLER_3D
  10897. case 0x8dcb: // INT_SAMPLER_3D
  10898. case 0x8dd3:
  10899. // UNSIGNED_INT_SAMPLER_3D
  10900. return setValueT3D1;
  10901. case 0x8b60: // SAMPLER_CUBE
  10902. case 0x8dcc: // INT_SAMPLER_CUBE
  10903. case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
  10904. case 0x8dc5:
  10905. // SAMPLER_CUBE_SHADOW
  10906. return setValueT6;
  10907. case 0x8dc1: // SAMPLER_2D_ARRAY
  10908. case 0x8dcf: // INT_SAMPLER_2D_ARRAY
  10909. case 0x8dd7: // UNSIGNED_INT_SAMPLER_2D_ARRAY
  10910. case 0x8dc4:
  10911. // SAMPLER_2D_ARRAY_SHADOW
  10912. return setValueT2DArray1;
  10913. }
  10914. } // Array of scalars
  10915. function setValueV1fArray(gl, v) {
  10916. gl.uniform1fv(this.addr, v);
  10917. } // Array of vectors (from flat array or array of THREE.VectorN)
  10918. function setValueV2fArray(gl, v) {
  10919. const data = flatten(v, this.size, 2);
  10920. gl.uniform2fv(this.addr, data);
  10921. }
  10922. function setValueV3fArray(gl, v) {
  10923. const data = flatten(v, this.size, 3);
  10924. gl.uniform3fv(this.addr, data);
  10925. }
  10926. function setValueV4fArray(gl, v) {
  10927. const data = flatten(v, this.size, 4);
  10928. gl.uniform4fv(this.addr, data);
  10929. } // Array of matrices (from flat array or array of THREE.MatrixN)
  10930. function setValueM2Array(gl, v) {
  10931. const data = flatten(v, this.size, 4);
  10932. gl.uniformMatrix2fv(this.addr, false, data);
  10933. }
  10934. function setValueM3Array(gl, v) {
  10935. const data = flatten(v, this.size, 9);
  10936. gl.uniformMatrix3fv(this.addr, false, data);
  10937. }
  10938. function setValueM4Array(gl, v) {
  10939. const data = flatten(v, this.size, 16);
  10940. gl.uniformMatrix4fv(this.addr, false, data);
  10941. } // Array of integer / boolean
  10942. function setValueV1iArray(gl, v) {
  10943. gl.uniform1iv(this.addr, v);
  10944. } // Array of integer / boolean vectors (from flat array)
  10945. function setValueV2iArray(gl, v) {
  10946. gl.uniform2iv(this.addr, v);
  10947. }
  10948. function setValueV3iArray(gl, v) {
  10949. gl.uniform3iv(this.addr, v);
  10950. }
  10951. function setValueV4iArray(gl, v) {
  10952. gl.uniform4iv(this.addr, v);
  10953. } // Array of unsigned integer
  10954. function setValueV1uiArray(gl, v) {
  10955. gl.uniform1uiv(this.addr, v);
  10956. } // Array of unsigned integer vectors (from flat array)
  10957. function setValueV2uiArray(gl, v) {
  10958. gl.uniform2uiv(this.addr, v);
  10959. }
  10960. function setValueV3uiArray(gl, v) {
  10961. gl.uniform3uiv(this.addr, v);
  10962. }
  10963. function setValueV4uiArray(gl, v) {
  10964. gl.uniform4uiv(this.addr, v);
  10965. } // Array of textures (2D / 3D / Cube / 2DArray)
  10966. function setValueT1Array(gl, v, textures) {
  10967. const cache = this.cache;
  10968. const n = v.length;
  10969. const units = allocTexUnits(textures, n);
  10970. if (!arraysEqual(cache, units)) {
  10971. gl.uniform1iv(this.addr, units);
  10972. copyArray(cache, units);
  10973. }
  10974. for (let i = 0; i !== n; ++i) {
  10975. textures.setTexture2D(v[i] || emptyTexture, units[i]);
  10976. }
  10977. }
  10978. function setValueT3DArray(gl, v, textures) {
  10979. const cache = this.cache;
  10980. const n = v.length;
  10981. const units = allocTexUnits(textures, n);
  10982. if (!arraysEqual(cache, units)) {
  10983. gl.uniform1iv(this.addr, units);
  10984. copyArray(cache, units);
  10985. }
  10986. for (let i = 0; i !== n; ++i) {
  10987. textures.setTexture3D(v[i] || empty3dTexture, units[i]);
  10988. }
  10989. }
  10990. function setValueT6Array(gl, v, textures) {
  10991. const cache = this.cache;
  10992. const n = v.length;
  10993. const units = allocTexUnits(textures, n);
  10994. if (!arraysEqual(cache, units)) {
  10995. gl.uniform1iv(this.addr, units);
  10996. copyArray(cache, units);
  10997. }
  10998. for (let i = 0; i !== n; ++i) {
  10999. textures.setTextureCube(v[i] || emptyCubeTexture, units[i]);
  11000. }
  11001. }
  11002. function setValueT2DArrayArray(gl, v, textures) {
  11003. const cache = this.cache;
  11004. const n = v.length;
  11005. const units = allocTexUnits(textures, n);
  11006. if (!arraysEqual(cache, units)) {
  11007. gl.uniform1iv(this.addr, units);
  11008. copyArray(cache, units);
  11009. }
  11010. for (let i = 0; i !== n; ++i) {
  11011. textures.setTexture2DArray(v[i] || emptyArrayTexture, units[i]);
  11012. }
  11013. } // Helper to pick the right setter for a pure (bottom-level) array
  11014. function getPureArraySetter(type) {
  11015. switch (type) {
  11016. case 0x1406:
  11017. return setValueV1fArray;
  11018. // FLOAT
  11019. case 0x8b50:
  11020. return setValueV2fArray;
  11021. // _VEC2
  11022. case 0x8b51:
  11023. return setValueV3fArray;
  11024. // _VEC3
  11025. case 0x8b52:
  11026. return setValueV4fArray;
  11027. // _VEC4
  11028. case 0x8b5a:
  11029. return setValueM2Array;
  11030. // _MAT2
  11031. case 0x8b5b:
  11032. return setValueM3Array;
  11033. // _MAT3
  11034. case 0x8b5c:
  11035. return setValueM4Array;
  11036. // _MAT4
  11037. case 0x1404:
  11038. case 0x8b56:
  11039. return setValueV1iArray;
  11040. // INT, BOOL
  11041. case 0x8b53:
  11042. case 0x8b57:
  11043. return setValueV2iArray;
  11044. // _VEC2
  11045. case 0x8b54:
  11046. case 0x8b58:
  11047. return setValueV3iArray;
  11048. // _VEC3
  11049. case 0x8b55:
  11050. case 0x8b59:
  11051. return setValueV4iArray;
  11052. // _VEC4
  11053. case 0x1405:
  11054. return setValueV1uiArray;
  11055. // UINT
  11056. case 0x8dc6:
  11057. return setValueV2uiArray;
  11058. // _VEC2
  11059. case 0x8dc7:
  11060. return setValueV3uiArray;
  11061. // _VEC3
  11062. case 0x8dc8:
  11063. return setValueV4uiArray;
  11064. // _VEC4
  11065. case 0x8b5e: // SAMPLER_2D
  11066. case 0x8d66: // SAMPLER_EXTERNAL_OES
  11067. case 0x8dca: // INT_SAMPLER_2D
  11068. case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
  11069. case 0x8b62:
  11070. // SAMPLER_2D_SHADOW
  11071. return setValueT1Array;
  11072. case 0x8b5f: // SAMPLER_3D
  11073. case 0x8dcb: // INT_SAMPLER_3D
  11074. case 0x8dd3:
  11075. // UNSIGNED_INT_SAMPLER_3D
  11076. return setValueT3DArray;
  11077. case 0x8b60: // SAMPLER_CUBE
  11078. case 0x8dcc: // INT_SAMPLER_CUBE
  11079. case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
  11080. case 0x8dc5:
  11081. // SAMPLER_CUBE_SHADOW
  11082. return setValueT6Array;
  11083. case 0x8dc1: // SAMPLER_2D_ARRAY
  11084. case 0x8dcf: // INT_SAMPLER_2D_ARRAY
  11085. case 0x8dd7: // UNSIGNED_INT_SAMPLER_2D_ARRAY
  11086. case 0x8dc4:
  11087. // SAMPLER_2D_ARRAY_SHADOW
  11088. return setValueT2DArrayArray;
  11089. }
  11090. } // --- Uniform Classes ---
  11091. class SingleUniform {
  11092. constructor(id, activeInfo, addr) {
  11093. this.id = id;
  11094. this.addr = addr;
  11095. this.cache = [];
  11096. this.setValue = getSingularSetter(activeInfo.type); // this.path = activeInfo.name; // DEBUG
  11097. }
  11098. }
  11099. class PureArrayUniform {
  11100. constructor(id, activeInfo, addr) {
  11101. this.id = id;
  11102. this.addr = addr;
  11103. this.cache = [];
  11104. this.size = activeInfo.size;
  11105. this.setValue = getPureArraySetter(activeInfo.type); // this.path = activeInfo.name; // DEBUG
  11106. }
  11107. }
  11108. class StructuredUniform {
  11109. constructor(id) {
  11110. this.id = id;
  11111. this.seq = [];
  11112. this.map = {};
  11113. }
  11114. setValue(gl, value, textures) {
  11115. const seq = this.seq;
  11116. for (let i = 0, n = seq.length; i !== n; ++i) {
  11117. const u = seq[i];
  11118. u.setValue(gl, value[u.id], textures);
  11119. }
  11120. }
  11121. } // --- Top-level ---
  11122. // Parser - builds up the property tree from the path strings
  11123. const RePathPart = /(\w+)(\])?(\[|\.)?/g; // extracts
  11124. // - the identifier (member name or array index)
  11125. // - followed by an optional right bracket (found when array index)
  11126. // - followed by an optional left bracket or dot (type of subscript)
  11127. //
  11128. // Note: These portions can be read in a non-overlapping fashion and
  11129. // allow straightforward parsing of the hierarchy that WebGL encodes
  11130. // in the uniform names.
  11131. function addUniform(container, uniformObject) {
  11132. container.seq.push(uniformObject);
  11133. container.map[uniformObject.id] = uniformObject;
  11134. }
  11135. function parseUniform(activeInfo, addr, container) {
  11136. const path = activeInfo.name,
  11137. pathLength = path.length; // reset RegExp object, because of the early exit of a previous run
  11138. RePathPart.lastIndex = 0;
  11139. while (true) {
  11140. const match = RePathPart.exec(path),
  11141. matchEnd = RePathPart.lastIndex;
  11142. let id = match[1];
  11143. const idIsIndex = match[2] === ']',
  11144. subscript = match[3];
  11145. if (idIsIndex) id = id | 0; // convert to integer
  11146. if (subscript === undefined || subscript === '[' && matchEnd + 2 === pathLength) {
  11147. // bare name or "pure" bottom-level array "[0]" suffix
  11148. addUniform(container, subscript === undefined ? new SingleUniform(id, activeInfo, addr) : new PureArrayUniform(id, activeInfo, addr));
  11149. break;
  11150. } else {
  11151. // step into inner node / create it in case it doesn't exist
  11152. const map = container.map;
  11153. let next = map[id];
  11154. if (next === undefined) {
  11155. next = new StructuredUniform(id);
  11156. addUniform(container, next);
  11157. }
  11158. container = next;
  11159. }
  11160. }
  11161. } // Root Container
  11162. class WebGLUniforms {
  11163. constructor(gl, program) {
  11164. this.seq = [];
  11165. this.map = {};
  11166. const n = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS);
  11167. for (let i = 0; i < n; ++i) {
  11168. const info = gl.getActiveUniform(program, i),
  11169. addr = gl.getUniformLocation(program, info.name);
  11170. parseUniform(info, addr, this);
  11171. }
  11172. }
  11173. setValue(gl, name, value, textures) {
  11174. const u = this.map[name];
  11175. if (u !== undefined) u.setValue(gl, value, textures);
  11176. }
  11177. setOptional(gl, object, name) {
  11178. const v = object[name];
  11179. if (v !== undefined) this.setValue(gl, name, v);
  11180. }
  11181. static upload(gl, seq, values, textures) {
  11182. for (let i = 0, n = seq.length; i !== n; ++i) {
  11183. const u = seq[i],
  11184. v = values[u.id];
  11185. if (v.needsUpdate !== false) {
  11186. // note: always updating when .needsUpdate is undefined
  11187. u.setValue(gl, v.value, textures);
  11188. }
  11189. }
  11190. }
  11191. static seqWithValue(seq, values) {
  11192. const r = [];
  11193. for (let i = 0, n = seq.length; i !== n; ++i) {
  11194. const u = seq[i];
  11195. if (u.id in values) r.push(u);
  11196. }
  11197. return r;
  11198. }
  11199. }
  11200. function WebGLShader(gl, type, string) {
  11201. const shader = gl.createShader(type);
  11202. gl.shaderSource(shader, string);
  11203. gl.compileShader(shader);
  11204. return shader;
  11205. }
  11206. let programIdCount = 0;
  11207. function handleSource(string, errorLine) {
  11208. const lines = string.split('\n');
  11209. const lines2 = [];
  11210. const from = Math.max(errorLine - 6, 0);
  11211. const to = Math.min(errorLine + 6, lines.length);
  11212. for (let i = from; i < to; i++) {
  11213. const line = i + 1;
  11214. lines2.push(`${line === errorLine ? '>' : ' '} ${line}: ${lines[i]}`);
  11215. }
  11216. return lines2.join('\n');
  11217. }
  11218. function getEncodingComponents(encoding) {
  11219. switch (encoding) {
  11220. case LinearEncoding:
  11221. return ['Linear', '( value )'];
  11222. case sRGBEncoding:
  11223. return ['sRGB', '( value )'];
  11224. default:
  11225. console.warn('THREE.WebGLProgram: Unsupported encoding:', encoding);
  11226. return ['Linear', '( value )'];
  11227. }
  11228. }
  11229. function getShaderErrors(gl, shader, type) {
  11230. const status = gl.getShaderParameter(shader, gl.COMPILE_STATUS);
  11231. const errors = gl.getShaderInfoLog(shader).trim();
  11232. if (status && errors === '') return '';
  11233. const errorMatches = /ERROR: 0:(\d+)/.exec(errors);
  11234. if (errorMatches) {
  11235. // --enable-privileged-webgl-extension
  11236. // console.log( '**' + type + '**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) );
  11237. const errorLine = parseInt(errorMatches[1]);
  11238. return type.toUpperCase() + '\n\n' + errors + '\n\n' + handleSource(gl.getShaderSource(shader), errorLine);
  11239. } else {
  11240. return errors;
  11241. }
  11242. }
  11243. function getTexelEncodingFunction(functionName, encoding) {
  11244. const components = getEncodingComponents(encoding);
  11245. return 'vec4 ' + functionName + '( vec4 value ) { return LinearTo' + components[0] + components[1] + '; }';
  11246. }
  11247. function getToneMappingFunction(functionName, toneMapping) {
  11248. let toneMappingName;
  11249. switch (toneMapping) {
  11250. case LinearToneMapping:
  11251. toneMappingName = 'Linear';
  11252. break;
  11253. case ReinhardToneMapping:
  11254. toneMappingName = 'Reinhard';
  11255. break;
  11256. case CineonToneMapping:
  11257. toneMappingName = 'OptimizedCineon';
  11258. break;
  11259. case ACESFilmicToneMapping:
  11260. toneMappingName = 'ACESFilmic';
  11261. break;
  11262. case CustomToneMapping:
  11263. toneMappingName = 'Custom';
  11264. break;
  11265. default:
  11266. console.warn('THREE.WebGLProgram: Unsupported toneMapping:', toneMapping);
  11267. toneMappingName = 'Linear';
  11268. }
  11269. return 'vec3 ' + functionName + '( vec3 color ) { return ' + toneMappingName + 'ToneMapping( color ); }';
  11270. }
  11271. function generateExtensions(parameters) {
  11272. const chunks = [parameters.extensionDerivatives || !!parameters.envMapCubeUVHeight || parameters.bumpMap || parameters.tangentSpaceNormalMap || parameters.clearcoatNormalMap || parameters.flatShading || parameters.shaderID === 'physical' ? '#extension GL_OES_standard_derivatives : enable' : '', (parameters.extensionFragDepth || parameters.logarithmicDepthBuffer) && parameters.rendererExtensionFragDepth ? '#extension GL_EXT_frag_depth : enable' : '', parameters.extensionDrawBuffers && parameters.rendererExtensionDrawBuffers ? '#extension GL_EXT_draw_buffers : require' : '', (parameters.extensionShaderTextureLOD || parameters.envMap || parameters.transmission) && parameters.rendererExtensionShaderTextureLod ? '#extension GL_EXT_shader_texture_lod : enable' : ''];
  11273. return chunks.filter(filterEmptyLine).join('\n');
  11274. }
  11275. function generateDefines(defines) {
  11276. const chunks = [];
  11277. for (const name in defines) {
  11278. const value = defines[name];
  11279. if (value === false) continue;
  11280. chunks.push('#define ' + name + ' ' + value);
  11281. }
  11282. return chunks.join('\n');
  11283. }
  11284. function fetchAttributeLocations(gl, program) {
  11285. const attributes = {};
  11286. const n = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES);
  11287. for (let i = 0; i < n; i++) {
  11288. const info = gl.getActiveAttrib(program, i);
  11289. const name = info.name;
  11290. let locationSize = 1;
  11291. if (info.type === gl.FLOAT_MAT2) locationSize = 2;
  11292. if (info.type === gl.FLOAT_MAT3) locationSize = 3;
  11293. if (info.type === gl.FLOAT_MAT4) locationSize = 4; // console.log( 'THREE.WebGLProgram: ACTIVE VERTEX ATTRIBUTE:', name, i );
  11294. attributes[name] = {
  11295. type: info.type,
  11296. location: gl.getAttribLocation(program, name),
  11297. locationSize: locationSize
  11298. };
  11299. }
  11300. return attributes;
  11301. }
  11302. function filterEmptyLine(string) {
  11303. return string !== '';
  11304. }
  11305. function replaceLightNums(string, parameters) {
  11306. const numSpotLightCoords = parameters.numSpotLightShadows + parameters.numSpotLightMaps - parameters.numSpotLightShadowsWithMaps;
  11307. return string.replace(/NUM_DIR_LIGHTS/g, parameters.numDirLights).replace(/NUM_SPOT_LIGHTS/g, parameters.numSpotLights).replace(/NUM_SPOT_LIGHT_MAPS/g, parameters.numSpotLightMaps).replace(/NUM_SPOT_LIGHT_COORDS/g, numSpotLightCoords).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_WITH_MAPS/g, parameters.numSpotLightShadowsWithMaps).replace(/NUM_SPOT_LIGHT_SHADOWS/g, parameters.numSpotLightShadows).replace(/NUM_POINT_LIGHT_SHADOWS/g, parameters.numPointLightShadows);
  11308. }
  11309. function replaceClippingPlaneNums(string, parameters) {
  11310. return string.replace(/NUM_CLIPPING_PLANES/g, parameters.numClippingPlanes).replace(/UNION_CLIPPING_PLANES/g, parameters.numClippingPlanes - parameters.numClipIntersection);
  11311. } // Resolve Includes
  11312. const includePattern = /^[ \t]*#include +<([\w\d./]+)>/gm;
  11313. function resolveIncludes(string) {
  11314. return string.replace(includePattern, includeReplacer);
  11315. }
  11316. function includeReplacer(match, include) {
  11317. const string = ShaderChunk[include];
  11318. if (string === undefined) {
  11319. throw new Error('Can not resolve #include <' + include + '>');
  11320. }
  11321. return resolveIncludes(string);
  11322. } // Unroll Loops
  11323. const unrollLoopPattern = /#pragma unroll_loop_start\s+for\s*\(\s*int\s+i\s*=\s*(\d+)\s*;\s*i\s*<\s*(\d+)\s*;\s*i\s*\+\+\s*\)\s*{([\s\S]+?)}\s+#pragma unroll_loop_end/g;
  11324. function unrollLoops(string) {
  11325. return string.replace(unrollLoopPattern, loopReplacer);
  11326. }
  11327. function loopReplacer(match, start, end, snippet) {
  11328. let string = '';
  11329. for (let i = parseInt(start); i < parseInt(end); i++) {
  11330. string += snippet.replace(/\[\s*i\s*\]/g, '[ ' + i + ' ]').replace(/UNROLLED_LOOP_INDEX/g, i);
  11331. }
  11332. return string;
  11333. } //
  11334. function generatePrecision(parameters) {
  11335. let precisionstring = 'precision ' + parameters.precision + ' float;\nprecision ' + parameters.precision + ' int;';
  11336. if (parameters.precision === 'highp') {
  11337. precisionstring += '\n#define HIGH_PRECISION';
  11338. } else if (parameters.precision === 'mediump') {
  11339. precisionstring += '\n#define MEDIUM_PRECISION';
  11340. } else if (parameters.precision === 'lowp') {
  11341. precisionstring += '\n#define LOW_PRECISION';
  11342. }
  11343. return precisionstring;
  11344. }
  11345. function generateShadowMapTypeDefine(parameters) {
  11346. let shadowMapTypeDefine = 'SHADOWMAP_TYPE_BASIC';
  11347. if (parameters.shadowMapType === PCFShadowMap) {
  11348. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF';
  11349. } else if (parameters.shadowMapType === PCFSoftShadowMap) {
  11350. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF_SOFT';
  11351. } else if (parameters.shadowMapType === VSMShadowMap) {
  11352. shadowMapTypeDefine = 'SHADOWMAP_TYPE_VSM';
  11353. }
  11354. return shadowMapTypeDefine;
  11355. }
  11356. function generateEnvMapTypeDefine(parameters) {
  11357. let envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  11358. if (parameters.envMap) {
  11359. switch (parameters.envMapMode) {
  11360. case CubeReflectionMapping:
  11361. case CubeRefractionMapping:
  11362. envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  11363. break;
  11364. case CubeUVReflectionMapping:
  11365. envMapTypeDefine = 'ENVMAP_TYPE_CUBE_UV';
  11366. break;
  11367. }
  11368. }
  11369. return envMapTypeDefine;
  11370. }
  11371. function generateEnvMapModeDefine(parameters) {
  11372. let envMapModeDefine = 'ENVMAP_MODE_REFLECTION';
  11373. if (parameters.envMap) {
  11374. switch (parameters.envMapMode) {
  11375. case CubeRefractionMapping:
  11376. envMapModeDefine = 'ENVMAP_MODE_REFRACTION';
  11377. break;
  11378. }
  11379. }
  11380. return envMapModeDefine;
  11381. }
  11382. function generateEnvMapBlendingDefine(parameters) {
  11383. let envMapBlendingDefine = 'ENVMAP_BLENDING_NONE';
  11384. if (parameters.envMap) {
  11385. switch (parameters.combine) {
  11386. case MultiplyOperation:
  11387. envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  11388. break;
  11389. case MixOperation:
  11390. envMapBlendingDefine = 'ENVMAP_BLENDING_MIX';
  11391. break;
  11392. case AddOperation:
  11393. envMapBlendingDefine = 'ENVMAP_BLENDING_ADD';
  11394. break;
  11395. }
  11396. }
  11397. return envMapBlendingDefine;
  11398. }
  11399. function generateCubeUVSize(parameters) {
  11400. const imageHeight = parameters.envMapCubeUVHeight;
  11401. if (imageHeight === null) return null;
  11402. const maxMip = Math.log2(imageHeight) - 2;
  11403. const texelHeight = 1.0 / imageHeight;
  11404. const texelWidth = 1.0 / (3 * Math.max(Math.pow(2, maxMip), 7 * 16));
  11405. return {
  11406. texelWidth,
  11407. texelHeight,
  11408. maxMip
  11409. };
  11410. }
  11411. function WebGLProgram(renderer, cacheKey, parameters, bindingStates) {
  11412. // TODO Send this event to Three.js DevTools
  11413. // console.log( 'WebGLProgram', cacheKey );
  11414. const gl = renderer.getContext();
  11415. const defines = parameters.defines;
  11416. let vertexShader = parameters.vertexShader;
  11417. let fragmentShader = parameters.fragmentShader;
  11418. const shadowMapTypeDefine = generateShadowMapTypeDefine(parameters);
  11419. const envMapTypeDefine = generateEnvMapTypeDefine(parameters);
  11420. const envMapModeDefine = generateEnvMapModeDefine(parameters);
  11421. const envMapBlendingDefine = generateEnvMapBlendingDefine(parameters);
  11422. const envMapCubeUVSize = generateCubeUVSize(parameters);
  11423. const customExtensions = parameters.isWebGL2 ? '' : generateExtensions(parameters);
  11424. const customDefines = generateDefines(defines);
  11425. const program = gl.createProgram();
  11426. let prefixVertex, prefixFragment;
  11427. let versionString = parameters.glslVersion ? '#version ' + parameters.glslVersion + '\n' : '';
  11428. if (parameters.isRawShaderMaterial) {
  11429. prefixVertex = [customDefines].filter(filterEmptyLine).join('\n');
  11430. if (prefixVertex.length > 0) {
  11431. prefixVertex += '\n';
  11432. }
  11433. prefixFragment = [customExtensions, customDefines].filter(filterEmptyLine).join('\n');
  11434. if (prefixFragment.length > 0) {
  11435. prefixFragment += '\n';
  11436. }
  11437. } else {
  11438. prefixVertex = [generatePrecision(parameters), '#define SHADER_NAME ' + parameters.shaderName, customDefines, parameters.instancing ? '#define USE_INSTANCING' : '', parameters.instancingColor ? '#define USE_INSTANCING_COLOR' : '', parameters.supportsVertexTextures ? '#define VERTEX_TEXTURES' : '', parameters.useFog && parameters.fog ? '#define USE_FOG' : '', parameters.useFog && parameters.fogExp2 ? '#define FOG_EXP2' : '', parameters.map ? '#define USE_MAP' : '', parameters.envMap ? '#define USE_ENVMAP' : '', parameters.envMap ? '#define ' + envMapModeDefine : '', parameters.lightMap ? '#define USE_LIGHTMAP' : '', parameters.aoMap ? '#define USE_AOMAP' : '', parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '', parameters.bumpMap ? '#define USE_BUMPMAP' : '', parameters.normalMap ? '#define USE_NORMALMAP' : '', parameters.normalMap && parameters.objectSpaceNormalMap ? '#define OBJECTSPACE_NORMALMAP' : '', parameters.normalMap && parameters.tangentSpaceNormalMap ? '#define TANGENTSPACE_NORMALMAP' : '', parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '', parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '', parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '', parameters.iridescenceMap ? '#define USE_IRIDESCENCEMAP' : '', parameters.iridescenceThicknessMap ? '#define USE_IRIDESCENCE_THICKNESSMAP' : '', parameters.displacementMap && parameters.supportsVertexTextures ? '#define USE_DISPLACEMENTMAP' : '', parameters.specularMap ? '#define USE_SPECULARMAP' : '', parameters.specularIntensityMap ? '#define USE_SPECULARINTENSITYMAP' : '', parameters.specularColorMap ? '#define USE_SPECULARCOLORMAP' : '', parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '', parameters.metalnessMap ? '#define USE_METALNESSMAP' : '', parameters.alphaMap ? '#define USE_ALPHAMAP' : '', parameters.transmission ? '#define USE_TRANSMISSION' : '', parameters.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '', parameters.thicknessMap ? '#define USE_THICKNESSMAP' : '', parameters.sheenColorMap ? '#define USE_SHEENCOLORMAP' : '', parameters.sheenRoughnessMap ? '#define USE_SHEENROUGHNESSMAP' : '', parameters.vertexTangents ? '#define USE_TANGENT' : '', parameters.vertexColors ? '#define USE_COLOR' : '', parameters.vertexAlphas ? '#define USE_COLOR_ALPHA' : '', parameters.vertexUvs ? '#define USE_UV' : '', parameters.uvsVertexOnly ? '#define UVS_VERTEX_ONLY' : '', parameters.flatShading ? '#define FLAT_SHADED' : '', parameters.skinning ? '#define USE_SKINNING' : '', parameters.morphTargets ? '#define USE_MORPHTARGETS' : '', parameters.morphNormals && parameters.flatShading === false ? '#define USE_MORPHNORMALS' : '', parameters.morphColors && parameters.isWebGL2 ? '#define USE_MORPHCOLORS' : '', parameters.morphTargetsCount > 0 && parameters.isWebGL2 ? '#define MORPHTARGETS_TEXTURE' : '', parameters.morphTargetsCount > 0 && parameters.isWebGL2 ? '#define MORPHTARGETS_TEXTURE_STRIDE ' + parameters.morphTextureStride : '', parameters.morphTargetsCount > 0 && parameters.isWebGL2 ? '#define MORPHTARGETS_COUNT ' + parameters.morphTargetsCount : '', parameters.doubleSided ? '#define DOUBLE_SIDED' : '', parameters.flipSided ? '#define FLIP_SIDED' : '', parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '', parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '', parameters.sizeAttenuation ? '#define USE_SIZEATTENUATION' : '', parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '', parameters.logarithmicDepthBuffer && parameters.rendererExtensionFragDepth ? '#define USE_LOGDEPTHBUF_EXT' : '', 'uniform mat4 modelMatrix;', 'uniform mat4 modelViewMatrix;', 'uniform mat4 projectionMatrix;', 'uniform mat4 viewMatrix;', 'uniform mat3 normalMatrix;', 'uniform vec3 cameraPosition;', 'uniform bool isOrthographic;', '#ifdef USE_INSTANCING', ' attribute mat4 instanceMatrix;', '#endif', '#ifdef USE_INSTANCING_COLOR', ' attribute vec3 instanceColor;', '#endif', 'attribute vec3 position;', 'attribute vec3 normal;', 'attribute vec2 uv;', '#ifdef USE_TANGENT', ' attribute vec4 tangent;', '#endif', '#if defined( USE_COLOR_ALPHA )', ' attribute vec4 color;', '#elif defined( USE_COLOR )', ' attribute vec3 color;', '#endif', '#if ( defined( USE_MORPHTARGETS ) && ! defined( MORPHTARGETS_TEXTURE ) )', ' 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');
  11439. prefixFragment = [customExtensions, generatePrecision(parameters), '#define SHADER_NAME ' + parameters.shaderName, customDefines, 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 : '', envMapCubeUVSize ? '#define CUBEUV_TEXEL_WIDTH ' + envMapCubeUVSize.texelWidth : '', envMapCubeUVSize ? '#define CUBEUV_TEXEL_HEIGHT ' + envMapCubeUVSize.texelHeight : '', envMapCubeUVSize ? '#define CUBEUV_MAX_MIP ' + envMapCubeUVSize.maxMip + '.0' : '', 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.clearcoat ? '#define USE_CLEARCOAT' : '', parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '', parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '', parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '', parameters.iridescence ? '#define USE_IRIDESCENCE' : '', parameters.iridescenceMap ? '#define USE_IRIDESCENCEMAP' : '', parameters.iridescenceThicknessMap ? '#define USE_IRIDESCENCE_THICKNESSMAP' : '', parameters.specularMap ? '#define USE_SPECULARMAP' : '', parameters.specularIntensityMap ? '#define USE_SPECULARINTENSITYMAP' : '', parameters.specularColorMap ? '#define USE_SPECULARCOLORMAP' : '', parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '', parameters.metalnessMap ? '#define USE_METALNESSMAP' : '', parameters.alphaMap ? '#define USE_ALPHAMAP' : '', parameters.alphaTest ? '#define USE_ALPHATEST' : '', parameters.sheen ? '#define USE_SHEEN' : '', parameters.sheenColorMap ? '#define USE_SHEENCOLORMAP' : '', parameters.sheenRoughnessMap ? '#define USE_SHEENROUGHNESSMAP' : '', parameters.transmission ? '#define USE_TRANSMISSION' : '', parameters.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '', parameters.thicknessMap ? '#define USE_THICKNESSMAP' : '', parameters.decodeVideoTexture ? '#define DECODE_VIDEO_TEXTURE' : '', parameters.vertexTangents ? '#define USE_TANGENT' : '', parameters.vertexColors || parameters.instancingColor ? '#define USE_COLOR' : '', parameters.vertexAlphas ? '#define USE_COLOR_ALPHA' : '', parameters.vertexUvs ? '#define USE_UV' : '', parameters.uvsVertexOnly ? '#define UVS_VERTEX_ONLY' : '', parameters.gradientMap ? '#define USE_GRADIENTMAP' : '', parameters.flatShading ? '#define FLAT_SHADED' : '', parameters.doubleSided ? '#define DOUBLE_SIDED' : '', parameters.flipSided ? '#define FLIP_SIDED' : '', parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '', parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '', parameters.premultipliedAlpha ? '#define PREMULTIPLIED_ALPHA' : '', parameters.physicallyCorrectLights ? '#define PHYSICALLY_CORRECT_LIGHTS' : '', parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '', parameters.logarithmicDepthBuffer && parameters.rendererExtensionFragDepth ? '#define USE_LOGDEPTHBUF_EXT' : '', 'uniform mat4 viewMatrix;', 'uniform vec3 cameraPosition;', 'uniform bool isOrthographic;', parameters.toneMapping !== NoToneMapping ? '#define TONE_MAPPING' : '', parameters.toneMapping !== NoToneMapping ? ShaderChunk['tonemapping_pars_fragment'] : '', // this code is required here because it is used by the toneMapping() function defined below
  11440. parameters.toneMapping !== NoToneMapping ? getToneMappingFunction('toneMapping', parameters.toneMapping) : '', parameters.dithering ? '#define DITHERING' : '', parameters.opaque ? '#define OPAQUE' : '', ShaderChunk['encodings_pars_fragment'], // this code is required here because it is used by the various encoding/decoding function defined below
  11441. getTexelEncodingFunction('linearToOutputTexel', parameters.outputEncoding), parameters.useDepthPacking ? '#define DEPTH_PACKING ' + parameters.depthPacking : '', '\n'].filter(filterEmptyLine).join('\n');
  11442. }
  11443. vertexShader = resolveIncludes(vertexShader);
  11444. vertexShader = replaceLightNums(vertexShader, parameters);
  11445. vertexShader = replaceClippingPlaneNums(vertexShader, parameters);
  11446. fragmentShader = resolveIncludes(fragmentShader);
  11447. fragmentShader = replaceLightNums(fragmentShader, parameters);
  11448. fragmentShader = replaceClippingPlaneNums(fragmentShader, parameters);
  11449. vertexShader = unrollLoops(vertexShader);
  11450. fragmentShader = unrollLoops(fragmentShader);
  11451. if (parameters.isWebGL2 && parameters.isRawShaderMaterial !== true) {
  11452. // GLSL 3.0 conversion for built-in materials and ShaderMaterial
  11453. versionString = '#version 300 es\n';
  11454. prefixVertex = ['precision mediump sampler2DArray;', '#define attribute in', '#define varying out', '#define texture2D texture'].join('\n') + '\n' + prefixVertex;
  11455. prefixFragment = ['#define varying in', parameters.glslVersion === GLSL3 ? '' : 'layout(location = 0) out highp vec4 pc_fragColor;', parameters.glslVersion === GLSL3 ? '' : '#define gl_FragColor pc_fragColor', '#define gl_FragDepthEXT gl_FragDepth', '#define texture2D texture', '#define textureCube texture', '#define texture2DProj textureProj', '#define texture2DLodEXT textureLod', '#define texture2DProjLodEXT textureProjLod', '#define textureCubeLodEXT textureLod', '#define texture2DGradEXT textureGrad', '#define texture2DProjGradEXT textureProjGrad', '#define textureCubeGradEXT textureGrad'].join('\n') + '\n' + prefixFragment;
  11456. }
  11457. const vertexGlsl = versionString + prefixVertex + vertexShader;
  11458. const fragmentGlsl = versionString + prefixFragment + fragmentShader; // console.log( '*VERTEX*', vertexGlsl );
  11459. // console.log( '*FRAGMENT*', fragmentGlsl );
  11460. const glVertexShader = WebGLShader(gl, gl.VERTEX_SHADER, vertexGlsl);
  11461. const glFragmentShader = WebGLShader(gl, gl.FRAGMENT_SHADER, fragmentGlsl);
  11462. gl.attachShader(program, glVertexShader);
  11463. gl.attachShader(program, glFragmentShader); // Force a particular attribute to index 0.
  11464. if (parameters.index0AttributeName !== undefined) {
  11465. gl.bindAttribLocation(program, 0, parameters.index0AttributeName);
  11466. } else if (parameters.morphTargets === true) {
  11467. // programs with morphTargets displace position out of attribute 0
  11468. gl.bindAttribLocation(program, 0, 'position');
  11469. }
  11470. gl.linkProgram(program); // check for link errors
  11471. if (renderer.debug.checkShaderErrors) {
  11472. const programLog = gl.getProgramInfoLog(program).trim();
  11473. const vertexLog = gl.getShaderInfoLog(glVertexShader).trim();
  11474. const fragmentLog = gl.getShaderInfoLog(glFragmentShader).trim();
  11475. let runnable = true;
  11476. let haveDiagnostics = true;
  11477. if (gl.getProgramParameter(program, gl.LINK_STATUS) === false) {
  11478. runnable = false;
  11479. const vertexErrors = getShaderErrors(gl, glVertexShader, 'vertex');
  11480. const fragmentErrors = getShaderErrors(gl, glFragmentShader, 'fragment');
  11481. console.error('THREE.WebGLProgram: Shader Error ' + gl.getError() + ' - ' + 'VALIDATE_STATUS ' + gl.getProgramParameter(program, gl.VALIDATE_STATUS) + '\n\n' + 'Program Info Log: ' + programLog + '\n' + vertexErrors + '\n' + fragmentErrors);
  11482. } else if (programLog !== '') {
  11483. console.warn('THREE.WebGLProgram: Program Info Log:', programLog);
  11484. } else if (vertexLog === '' || fragmentLog === '') {
  11485. haveDiagnostics = false;
  11486. }
  11487. if (haveDiagnostics) {
  11488. this.diagnostics = {
  11489. runnable: runnable,
  11490. programLog: programLog,
  11491. vertexShader: {
  11492. log: vertexLog,
  11493. prefix: prefixVertex
  11494. },
  11495. fragmentShader: {
  11496. log: fragmentLog,
  11497. prefix: prefixFragment
  11498. }
  11499. };
  11500. }
  11501. } // Clean up
  11502. // Crashes in iOS9 and iOS10. #18402
  11503. // gl.detachShader( program, glVertexShader );
  11504. // gl.detachShader( program, glFragmentShader );
  11505. gl.deleteShader(glVertexShader);
  11506. gl.deleteShader(glFragmentShader); // set up caching for uniform locations
  11507. let cachedUniforms;
  11508. this.getUniforms = function () {
  11509. if (cachedUniforms === undefined) {
  11510. cachedUniforms = new WebGLUniforms(gl, program);
  11511. }
  11512. return cachedUniforms;
  11513. }; // set up caching for attribute locations
  11514. let cachedAttributes;
  11515. this.getAttributes = function () {
  11516. if (cachedAttributes === undefined) {
  11517. cachedAttributes = fetchAttributeLocations(gl, program);
  11518. }
  11519. return cachedAttributes;
  11520. }; // free resource
  11521. this.destroy = function () {
  11522. bindingStates.releaseStatesOfProgram(this);
  11523. gl.deleteProgram(program);
  11524. this.program = undefined;
  11525. }; //
  11526. this.name = parameters.shaderName;
  11527. this.id = programIdCount++;
  11528. this.cacheKey = cacheKey;
  11529. this.usedTimes = 1;
  11530. this.program = program;
  11531. this.vertexShader = glVertexShader;
  11532. this.fragmentShader = glFragmentShader;
  11533. return this;
  11534. }
  11535. let _id = 0;
  11536. class WebGLShaderCache {
  11537. constructor() {
  11538. this.shaderCache = new Map();
  11539. this.materialCache = new Map();
  11540. }
  11541. update(material) {
  11542. const vertexShader = material.vertexShader;
  11543. const fragmentShader = material.fragmentShader;
  11544. const vertexShaderStage = this._getShaderStage(vertexShader);
  11545. const fragmentShaderStage = this._getShaderStage(fragmentShader);
  11546. const materialShaders = this._getShaderCacheForMaterial(material);
  11547. if (materialShaders.has(vertexShaderStage) === false) {
  11548. materialShaders.add(vertexShaderStage);
  11549. vertexShaderStage.usedTimes++;
  11550. }
  11551. if (materialShaders.has(fragmentShaderStage) === false) {
  11552. materialShaders.add(fragmentShaderStage);
  11553. fragmentShaderStage.usedTimes++;
  11554. }
  11555. return this;
  11556. }
  11557. remove(material) {
  11558. const materialShaders = this.materialCache.get(material);
  11559. for (const shaderStage of materialShaders) {
  11560. shaderStage.usedTimes--;
  11561. if (shaderStage.usedTimes === 0) this.shaderCache.delete(shaderStage.code);
  11562. }
  11563. this.materialCache.delete(material);
  11564. return this;
  11565. }
  11566. getVertexShaderID(material) {
  11567. return this._getShaderStage(material.vertexShader).id;
  11568. }
  11569. getFragmentShaderID(material) {
  11570. return this._getShaderStage(material.fragmentShader).id;
  11571. }
  11572. dispose() {
  11573. this.shaderCache.clear();
  11574. this.materialCache.clear();
  11575. }
  11576. _getShaderCacheForMaterial(material) {
  11577. const cache = this.materialCache;
  11578. let set = cache.get(material);
  11579. if (set === undefined) {
  11580. set = new Set();
  11581. cache.set(material, set);
  11582. }
  11583. return set;
  11584. }
  11585. _getShaderStage(code) {
  11586. const cache = this.shaderCache;
  11587. let stage = cache.get(code);
  11588. if (stage === undefined) {
  11589. stage = new WebGLShaderStage(code);
  11590. cache.set(code, stage);
  11591. }
  11592. return stage;
  11593. }
  11594. }
  11595. class WebGLShaderStage {
  11596. constructor(code) {
  11597. this.id = _id++;
  11598. this.code = code;
  11599. this.usedTimes = 0;
  11600. }
  11601. }
  11602. function WebGLPrograms(renderer, cubemaps, cubeuvmaps, extensions, capabilities, bindingStates, clipping) {
  11603. const _programLayers = new Layers();
  11604. const _customShaders = new WebGLShaderCache();
  11605. const programs = [];
  11606. const isWebGL2 = capabilities.isWebGL2;
  11607. const logarithmicDepthBuffer = capabilities.logarithmicDepthBuffer;
  11608. const vertexTextures = capabilities.vertexTextures;
  11609. let precision = capabilities.precision;
  11610. const shaderIDs = {
  11611. MeshDepthMaterial: 'depth',
  11612. MeshDistanceMaterial: 'distanceRGBA',
  11613. MeshNormalMaterial: 'normal',
  11614. MeshBasicMaterial: 'basic',
  11615. MeshLambertMaterial: 'lambert',
  11616. MeshPhongMaterial: 'phong',
  11617. MeshToonMaterial: 'toon',
  11618. MeshStandardMaterial: 'physical',
  11619. MeshPhysicalMaterial: 'physical',
  11620. MeshMatcapMaterial: 'matcap',
  11621. LineBasicMaterial: 'basic',
  11622. LineDashedMaterial: 'dashed',
  11623. PointsMaterial: 'points',
  11624. ShadowMaterial: 'shadow',
  11625. SpriteMaterial: 'sprite'
  11626. };
  11627. function getParameters(material, lights, shadows, scene, object) {
  11628. const fog = scene.fog;
  11629. const geometry = object.geometry;
  11630. const environment = material.isMeshStandardMaterial ? scene.environment : null;
  11631. const envMap = (material.isMeshStandardMaterial ? cubeuvmaps : cubemaps).get(material.envMap || environment);
  11632. const envMapCubeUVHeight = !!envMap && envMap.mapping === CubeUVReflectionMapping ? envMap.image.height : null;
  11633. const shaderID = shaderIDs[material.type]; // heuristics to create shader parameters according to lights in the scene
  11634. // (not to blow over maxLights budget)
  11635. if (material.precision !== null) {
  11636. precision = capabilities.getMaxPrecision(material.precision);
  11637. if (precision !== material.precision) {
  11638. console.warn('THREE.WebGLProgram.getParameters:', material.precision, 'not supported, using', precision, 'instead.');
  11639. }
  11640. } //
  11641. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  11642. const morphTargetsCount = morphAttribute !== undefined ? morphAttribute.length : 0;
  11643. let morphTextureStride = 0;
  11644. if (geometry.morphAttributes.position !== undefined) morphTextureStride = 1;
  11645. if (geometry.morphAttributes.normal !== undefined) morphTextureStride = 2;
  11646. if (geometry.morphAttributes.color !== undefined) morphTextureStride = 3; //
  11647. let vertexShader, fragmentShader;
  11648. let customVertexShaderID, customFragmentShaderID;
  11649. if (shaderID) {
  11650. const shader = ShaderLib[shaderID];
  11651. vertexShader = shader.vertexShader;
  11652. fragmentShader = shader.fragmentShader;
  11653. } else {
  11654. vertexShader = material.vertexShader;
  11655. fragmentShader = material.fragmentShader;
  11656. _customShaders.update(material);
  11657. customVertexShaderID = _customShaders.getVertexShaderID(material);
  11658. customFragmentShaderID = _customShaders.getFragmentShaderID(material);
  11659. }
  11660. const currentRenderTarget = renderer.getRenderTarget();
  11661. const useAlphaTest = material.alphaTest > 0;
  11662. const useClearcoat = material.clearcoat > 0;
  11663. const useIridescence = material.iridescence > 0;
  11664. const parameters = {
  11665. isWebGL2: isWebGL2,
  11666. shaderID: shaderID,
  11667. shaderName: material.type,
  11668. vertexShader: vertexShader,
  11669. fragmentShader: fragmentShader,
  11670. defines: material.defines,
  11671. customVertexShaderID: customVertexShaderID,
  11672. customFragmentShaderID: customFragmentShaderID,
  11673. isRawShaderMaterial: material.isRawShaderMaterial === true,
  11674. glslVersion: material.glslVersion,
  11675. precision: precision,
  11676. instancing: object.isInstancedMesh === true,
  11677. instancingColor: object.isInstancedMesh === true && object.instanceColor !== null,
  11678. supportsVertexTextures: vertexTextures,
  11679. outputEncoding: currentRenderTarget === null ? renderer.outputEncoding : currentRenderTarget.isXRRenderTarget === true ? currentRenderTarget.texture.encoding : LinearEncoding,
  11680. map: !!material.map,
  11681. matcap: !!material.matcap,
  11682. envMap: !!envMap,
  11683. envMapMode: envMap && envMap.mapping,
  11684. envMapCubeUVHeight: envMapCubeUVHeight,
  11685. lightMap: !!material.lightMap,
  11686. aoMap: !!material.aoMap,
  11687. emissiveMap: !!material.emissiveMap,
  11688. bumpMap: !!material.bumpMap,
  11689. normalMap: !!material.normalMap,
  11690. objectSpaceNormalMap: material.normalMapType === ObjectSpaceNormalMap,
  11691. tangentSpaceNormalMap: material.normalMapType === TangentSpaceNormalMap,
  11692. decodeVideoTexture: !!material.map && material.map.isVideoTexture === true && material.map.encoding === sRGBEncoding,
  11693. clearcoat: useClearcoat,
  11694. clearcoatMap: useClearcoat && !!material.clearcoatMap,
  11695. clearcoatRoughnessMap: useClearcoat && !!material.clearcoatRoughnessMap,
  11696. clearcoatNormalMap: useClearcoat && !!material.clearcoatNormalMap,
  11697. iridescence: useIridescence,
  11698. iridescenceMap: useIridescence && !!material.iridescenceMap,
  11699. iridescenceThicknessMap: useIridescence && !!material.iridescenceThicknessMap,
  11700. displacementMap: !!material.displacementMap,
  11701. roughnessMap: !!material.roughnessMap,
  11702. metalnessMap: !!material.metalnessMap,
  11703. specularMap: !!material.specularMap,
  11704. specularIntensityMap: !!material.specularIntensityMap,
  11705. specularColorMap: !!material.specularColorMap,
  11706. opaque: material.transparent === false && material.blending === NormalBlending,
  11707. alphaMap: !!material.alphaMap,
  11708. alphaTest: useAlphaTest,
  11709. gradientMap: !!material.gradientMap,
  11710. sheen: material.sheen > 0,
  11711. sheenColorMap: !!material.sheenColorMap,
  11712. sheenRoughnessMap: !!material.sheenRoughnessMap,
  11713. transmission: material.transmission > 0,
  11714. transmissionMap: !!material.transmissionMap,
  11715. thicknessMap: !!material.thicknessMap,
  11716. combine: material.combine,
  11717. vertexTangents: !!material.normalMap && !!geometry.attributes.tangent,
  11718. vertexColors: material.vertexColors,
  11719. vertexAlphas: material.vertexColors === true && !!geometry.attributes.color && geometry.attributes.color.itemSize === 4,
  11720. vertexUvs: !!material.map || !!material.bumpMap || !!material.normalMap || !!material.specularMap || !!material.alphaMap || !!material.emissiveMap || !!material.roughnessMap || !!material.metalnessMap || !!material.clearcoatMap || !!material.clearcoatRoughnessMap || !!material.clearcoatNormalMap || !!material.iridescenceMap || !!material.iridescenceThicknessMap || !!material.displacementMap || !!material.transmissionMap || !!material.thicknessMap || !!material.specularIntensityMap || !!material.specularColorMap || !!material.sheenColorMap || !!material.sheenRoughnessMap,
  11721. uvsVertexOnly: !(!!material.map || !!material.bumpMap || !!material.normalMap || !!material.specularMap || !!material.alphaMap || !!material.emissiveMap || !!material.roughnessMap || !!material.metalnessMap || !!material.clearcoatNormalMap || !!material.iridescenceMap || !!material.iridescenceThicknessMap || material.transmission > 0 || !!material.transmissionMap || !!material.thicknessMap || !!material.specularIntensityMap || !!material.specularColorMap || material.sheen > 0 || !!material.sheenColorMap || !!material.sheenRoughnessMap) && !!material.displacementMap,
  11722. fog: !!fog,
  11723. useFog: material.fog === true,
  11724. fogExp2: fog && fog.isFogExp2,
  11725. flatShading: !!material.flatShading,
  11726. sizeAttenuation: material.sizeAttenuation,
  11727. logarithmicDepthBuffer: logarithmicDepthBuffer,
  11728. skinning: object.isSkinnedMesh === true,
  11729. morphTargets: geometry.morphAttributes.position !== undefined,
  11730. morphNormals: geometry.morphAttributes.normal !== undefined,
  11731. morphColors: geometry.morphAttributes.color !== undefined,
  11732. morphTargetsCount: morphTargetsCount,
  11733. morphTextureStride: morphTextureStride,
  11734. numDirLights: lights.directional.length,
  11735. numPointLights: lights.point.length,
  11736. numSpotLights: lights.spot.length,
  11737. numSpotLightMaps: lights.spotLightMap.length,
  11738. numRectAreaLights: lights.rectArea.length,
  11739. numHemiLights: lights.hemi.length,
  11740. numDirLightShadows: lights.directionalShadowMap.length,
  11741. numPointLightShadows: lights.pointShadowMap.length,
  11742. numSpotLightShadows: lights.spotShadowMap.length,
  11743. numSpotLightShadowsWithMaps: lights.numSpotLightShadowsWithMaps,
  11744. numClippingPlanes: clipping.numPlanes,
  11745. numClipIntersection: clipping.numIntersection,
  11746. dithering: material.dithering,
  11747. shadowMapEnabled: renderer.shadowMap.enabled && shadows.length > 0,
  11748. shadowMapType: renderer.shadowMap.type,
  11749. toneMapping: material.toneMapped ? renderer.toneMapping : NoToneMapping,
  11750. physicallyCorrectLights: renderer.physicallyCorrectLights,
  11751. premultipliedAlpha: material.premultipliedAlpha,
  11752. doubleSided: material.side === DoubleSide,
  11753. flipSided: material.side === BackSide,
  11754. useDepthPacking: !!material.depthPacking,
  11755. depthPacking: material.depthPacking || 0,
  11756. index0AttributeName: material.index0AttributeName,
  11757. extensionDerivatives: material.extensions && material.extensions.derivatives,
  11758. extensionFragDepth: material.extensions && material.extensions.fragDepth,
  11759. extensionDrawBuffers: material.extensions && material.extensions.drawBuffers,
  11760. extensionShaderTextureLOD: material.extensions && material.extensions.shaderTextureLOD,
  11761. rendererExtensionFragDepth: isWebGL2 || extensions.has('EXT_frag_depth'),
  11762. rendererExtensionDrawBuffers: isWebGL2 || extensions.has('WEBGL_draw_buffers'),
  11763. rendererExtensionShaderTextureLod: isWebGL2 || extensions.has('EXT_shader_texture_lod'),
  11764. customProgramCacheKey: material.customProgramCacheKey()
  11765. };
  11766. return parameters;
  11767. }
  11768. function getProgramCacheKey(parameters) {
  11769. const array = [];
  11770. if (parameters.shaderID) {
  11771. array.push(parameters.shaderID);
  11772. } else {
  11773. array.push(parameters.customVertexShaderID);
  11774. array.push(parameters.customFragmentShaderID);
  11775. }
  11776. if (parameters.defines !== undefined) {
  11777. for (const name in parameters.defines) {
  11778. array.push(name);
  11779. array.push(parameters.defines[name]);
  11780. }
  11781. }
  11782. if (parameters.isRawShaderMaterial === false) {
  11783. getProgramCacheKeyParameters(array, parameters);
  11784. getProgramCacheKeyBooleans(array, parameters);
  11785. array.push(renderer.outputEncoding);
  11786. }
  11787. array.push(parameters.customProgramCacheKey);
  11788. return array.join();
  11789. }
  11790. function getProgramCacheKeyParameters(array, parameters) {
  11791. array.push(parameters.precision);
  11792. array.push(parameters.outputEncoding);
  11793. array.push(parameters.envMapMode);
  11794. array.push(parameters.envMapCubeUVHeight);
  11795. array.push(parameters.combine);
  11796. array.push(parameters.vertexUvs);
  11797. array.push(parameters.fogExp2);
  11798. array.push(parameters.sizeAttenuation);
  11799. array.push(parameters.morphTargetsCount);
  11800. array.push(parameters.morphAttributeCount);
  11801. array.push(parameters.numDirLights);
  11802. array.push(parameters.numPointLights);
  11803. array.push(parameters.numSpotLights);
  11804. array.push(parameters.numSpotLightMaps);
  11805. array.push(parameters.numHemiLights);
  11806. array.push(parameters.numRectAreaLights);
  11807. array.push(parameters.numDirLightShadows);
  11808. array.push(parameters.numPointLightShadows);
  11809. array.push(parameters.numSpotLightShadows);
  11810. array.push(parameters.numSpotLightShadowsWithMaps);
  11811. array.push(parameters.shadowMapType);
  11812. array.push(parameters.toneMapping);
  11813. array.push(parameters.numClippingPlanes);
  11814. array.push(parameters.numClipIntersection);
  11815. array.push(parameters.depthPacking);
  11816. }
  11817. function getProgramCacheKeyBooleans(array, parameters) {
  11818. _programLayers.disableAll();
  11819. if (parameters.isWebGL2) _programLayers.enable(0);
  11820. if (parameters.supportsVertexTextures) _programLayers.enable(1);
  11821. if (parameters.instancing) _programLayers.enable(2);
  11822. if (parameters.instancingColor) _programLayers.enable(3);
  11823. if (parameters.map) _programLayers.enable(4);
  11824. if (parameters.matcap) _programLayers.enable(5);
  11825. if (parameters.envMap) _programLayers.enable(6);
  11826. if (parameters.lightMap) _programLayers.enable(7);
  11827. if (parameters.aoMap) _programLayers.enable(8);
  11828. if (parameters.emissiveMap) _programLayers.enable(9);
  11829. if (parameters.bumpMap) _programLayers.enable(10);
  11830. if (parameters.normalMap) _programLayers.enable(11);
  11831. if (parameters.objectSpaceNormalMap) _programLayers.enable(12);
  11832. if (parameters.tangentSpaceNormalMap) _programLayers.enable(13);
  11833. if (parameters.clearcoat) _programLayers.enable(14);
  11834. if (parameters.clearcoatMap) _programLayers.enable(15);
  11835. if (parameters.clearcoatRoughnessMap) _programLayers.enable(16);
  11836. if (parameters.clearcoatNormalMap) _programLayers.enable(17);
  11837. if (parameters.iridescence) _programLayers.enable(18);
  11838. if (parameters.iridescenceMap) _programLayers.enable(19);
  11839. if (parameters.iridescenceThicknessMap) _programLayers.enable(20);
  11840. if (parameters.displacementMap) _programLayers.enable(21);
  11841. if (parameters.specularMap) _programLayers.enable(22);
  11842. if (parameters.roughnessMap) _programLayers.enable(23);
  11843. if (parameters.metalnessMap) _programLayers.enable(24);
  11844. if (parameters.gradientMap) _programLayers.enable(25);
  11845. if (parameters.alphaMap) _programLayers.enable(26);
  11846. if (parameters.alphaTest) _programLayers.enable(27);
  11847. if (parameters.vertexColors) _programLayers.enable(28);
  11848. if (parameters.vertexAlphas) _programLayers.enable(29);
  11849. if (parameters.vertexUvs) _programLayers.enable(30);
  11850. if (parameters.vertexTangents) _programLayers.enable(31);
  11851. if (parameters.uvsVertexOnly) _programLayers.enable(32);
  11852. array.push(_programLayers.mask);
  11853. _programLayers.disableAll();
  11854. if (parameters.fog) _programLayers.enable(0);
  11855. if (parameters.useFog) _programLayers.enable(1);
  11856. if (parameters.flatShading) _programLayers.enable(2);
  11857. if (parameters.logarithmicDepthBuffer) _programLayers.enable(3);
  11858. if (parameters.skinning) _programLayers.enable(4);
  11859. if (parameters.morphTargets) _programLayers.enable(5);
  11860. if (parameters.morphNormals) _programLayers.enable(6);
  11861. if (parameters.morphColors) _programLayers.enable(7);
  11862. if (parameters.premultipliedAlpha) _programLayers.enable(8);
  11863. if (parameters.shadowMapEnabled) _programLayers.enable(9);
  11864. if (parameters.physicallyCorrectLights) _programLayers.enable(10);
  11865. if (parameters.doubleSided) _programLayers.enable(11);
  11866. if (parameters.flipSided) _programLayers.enable(12);
  11867. if (parameters.useDepthPacking) _programLayers.enable(13);
  11868. if (parameters.dithering) _programLayers.enable(14);
  11869. if (parameters.specularIntensityMap) _programLayers.enable(15);
  11870. if (parameters.specularColorMap) _programLayers.enable(16);
  11871. if (parameters.transmission) _programLayers.enable(17);
  11872. if (parameters.transmissionMap) _programLayers.enable(18);
  11873. if (parameters.thicknessMap) _programLayers.enable(19);
  11874. if (parameters.sheen) _programLayers.enable(20);
  11875. if (parameters.sheenColorMap) _programLayers.enable(21);
  11876. if (parameters.sheenRoughnessMap) _programLayers.enable(22);
  11877. if (parameters.decodeVideoTexture) _programLayers.enable(23);
  11878. if (parameters.opaque) _programLayers.enable(24);
  11879. array.push(_programLayers.mask);
  11880. }
  11881. function getUniforms(material) {
  11882. const shaderID = shaderIDs[material.type];
  11883. let uniforms;
  11884. if (shaderID) {
  11885. const shader = ShaderLib[shaderID];
  11886. uniforms = UniformsUtils.clone(shader.uniforms);
  11887. } else {
  11888. uniforms = material.uniforms;
  11889. }
  11890. return uniforms;
  11891. }
  11892. function acquireProgram(parameters, cacheKey) {
  11893. let program; // Check if code has been already compiled
  11894. for (let p = 0, pl = programs.length; p < pl; p++) {
  11895. const preexistingProgram = programs[p];
  11896. if (preexistingProgram.cacheKey === cacheKey) {
  11897. program = preexistingProgram;
  11898. ++program.usedTimes;
  11899. break;
  11900. }
  11901. }
  11902. if (program === undefined) {
  11903. program = new WebGLProgram(renderer, cacheKey, parameters, bindingStates);
  11904. programs.push(program);
  11905. }
  11906. return program;
  11907. }
  11908. function releaseProgram(program) {
  11909. if (--program.usedTimes === 0) {
  11910. // Remove from unordered set
  11911. const i = programs.indexOf(program);
  11912. programs[i] = programs[programs.length - 1];
  11913. programs.pop(); // Free WebGL resources
  11914. program.destroy();
  11915. }
  11916. }
  11917. function releaseShaderCache(material) {
  11918. _customShaders.remove(material);
  11919. }
  11920. function dispose() {
  11921. _customShaders.dispose();
  11922. }
  11923. return {
  11924. getParameters: getParameters,
  11925. getProgramCacheKey: getProgramCacheKey,
  11926. getUniforms: getUniforms,
  11927. acquireProgram: acquireProgram,
  11928. releaseProgram: releaseProgram,
  11929. releaseShaderCache: releaseShaderCache,
  11930. // Exposed for resource monitoring & error feedback via renderer.info:
  11931. programs: programs,
  11932. dispose: dispose
  11933. };
  11934. }
  11935. function WebGLProperties() {
  11936. let properties = new WeakMap();
  11937. function get(object) {
  11938. let map = properties.get(object);
  11939. if (map === undefined) {
  11940. map = {};
  11941. properties.set(object, map);
  11942. }
  11943. return map;
  11944. }
  11945. function remove(object) {
  11946. properties.delete(object);
  11947. }
  11948. function update(object, key, value) {
  11949. properties.get(object)[key] = value;
  11950. }
  11951. function dispose() {
  11952. properties = new WeakMap();
  11953. }
  11954. return {
  11955. get: get,
  11956. remove: remove,
  11957. update: update,
  11958. dispose: dispose
  11959. };
  11960. }
  11961. function painterSortStable(a, b) {
  11962. if (a.groupOrder !== b.groupOrder) {
  11963. return a.groupOrder - b.groupOrder;
  11964. } else if (a.renderOrder !== b.renderOrder) {
  11965. return a.renderOrder - b.renderOrder;
  11966. } else if (a.material.id !== b.material.id) {
  11967. return a.material.id - b.material.id;
  11968. } else if (a.z !== b.z) {
  11969. return a.z - b.z;
  11970. } else {
  11971. return a.id - b.id;
  11972. }
  11973. }
  11974. function reversePainterSortStable(a, b) {
  11975. if (a.groupOrder !== b.groupOrder) {
  11976. return a.groupOrder - b.groupOrder;
  11977. } else if (a.renderOrder !== b.renderOrder) {
  11978. return a.renderOrder - b.renderOrder;
  11979. } else if (a.z !== b.z) {
  11980. return b.z - a.z;
  11981. } else {
  11982. return a.id - b.id;
  11983. }
  11984. }
  11985. function WebGLRenderList() {
  11986. const renderItems = [];
  11987. let renderItemsIndex = 0;
  11988. const opaque = [];
  11989. const transmissive = [];
  11990. const transparent = [];
  11991. function init() {
  11992. renderItemsIndex = 0;
  11993. opaque.length = 0;
  11994. transmissive.length = 0;
  11995. transparent.length = 0;
  11996. }
  11997. function getNextRenderItem(object, geometry, material, groupOrder, z, group) {
  11998. let renderItem = renderItems[renderItemsIndex];
  11999. if (renderItem === undefined) {
  12000. renderItem = {
  12001. id: object.id,
  12002. object: object,
  12003. geometry: geometry,
  12004. material: material,
  12005. groupOrder: groupOrder,
  12006. renderOrder: object.renderOrder,
  12007. z: z,
  12008. group: group
  12009. };
  12010. renderItems[renderItemsIndex] = renderItem;
  12011. } else {
  12012. renderItem.id = object.id;
  12013. renderItem.object = object;
  12014. renderItem.geometry = geometry;
  12015. renderItem.material = material;
  12016. renderItem.groupOrder = groupOrder;
  12017. renderItem.renderOrder = object.renderOrder;
  12018. renderItem.z = z;
  12019. renderItem.group = group;
  12020. }
  12021. renderItemsIndex++;
  12022. return renderItem;
  12023. }
  12024. function push(object, geometry, material, groupOrder, z, group) {
  12025. const renderItem = getNextRenderItem(object, geometry, material, groupOrder, z, group);
  12026. if (material.transmission > 0.0) {
  12027. transmissive.push(renderItem);
  12028. } else if (material.transparent === true) {
  12029. transparent.push(renderItem);
  12030. } else {
  12031. opaque.push(renderItem);
  12032. }
  12033. }
  12034. function unshift(object, geometry, material, groupOrder, z, group) {
  12035. const renderItem = getNextRenderItem(object, geometry, material, groupOrder, z, group);
  12036. if (material.transmission > 0.0) {
  12037. transmissive.unshift(renderItem);
  12038. } else if (material.transparent === true) {
  12039. transparent.unshift(renderItem);
  12040. } else {
  12041. opaque.unshift(renderItem);
  12042. }
  12043. }
  12044. function sort(customOpaqueSort, customTransparentSort) {
  12045. if (opaque.length > 1) opaque.sort(customOpaqueSort || painterSortStable);
  12046. if (transmissive.length > 1) transmissive.sort(customTransparentSort || reversePainterSortStable);
  12047. if (transparent.length > 1) transparent.sort(customTransparentSort || reversePainterSortStable);
  12048. }
  12049. function finish() {
  12050. // Clear references from inactive renderItems in the list
  12051. for (let i = renderItemsIndex, il = renderItems.length; i < il; i++) {
  12052. const renderItem = renderItems[i];
  12053. if (renderItem.id === null) break;
  12054. renderItem.id = null;
  12055. renderItem.object = null;
  12056. renderItem.geometry = null;
  12057. renderItem.material = null;
  12058. renderItem.group = null;
  12059. }
  12060. }
  12061. return {
  12062. opaque: opaque,
  12063. transmissive: transmissive,
  12064. transparent: transparent,
  12065. init: init,
  12066. push: push,
  12067. unshift: unshift,
  12068. finish: finish,
  12069. sort: sort
  12070. };
  12071. }
  12072. function WebGLRenderLists() {
  12073. let lists = new WeakMap();
  12074. function get(scene, renderCallDepth) {
  12075. const listArray = lists.get(scene);
  12076. let list;
  12077. if (listArray === undefined) {
  12078. list = new WebGLRenderList();
  12079. lists.set(scene, [list]);
  12080. } else {
  12081. if (renderCallDepth >= listArray.length) {
  12082. list = new WebGLRenderList();
  12083. listArray.push(list);
  12084. } else {
  12085. list = listArray[renderCallDepth];
  12086. }
  12087. }
  12088. return list;
  12089. }
  12090. function dispose() {
  12091. lists = new WeakMap();
  12092. }
  12093. return {
  12094. get: get,
  12095. dispose: dispose
  12096. };
  12097. }
  12098. function UniformsCache() {
  12099. const lights = {};
  12100. return {
  12101. get: function (light) {
  12102. if (lights[light.id] !== undefined) {
  12103. return lights[light.id];
  12104. }
  12105. let uniforms;
  12106. switch (light.type) {
  12107. case 'DirectionalLight':
  12108. uniforms = {
  12109. direction: new Vector3(),
  12110. color: new Color()
  12111. };
  12112. break;
  12113. case 'SpotLight':
  12114. uniforms = {
  12115. position: new Vector3(),
  12116. direction: new Vector3(),
  12117. color: new Color(),
  12118. distance: 0,
  12119. coneCos: 0,
  12120. penumbraCos: 0,
  12121. decay: 0
  12122. };
  12123. break;
  12124. case 'PointLight':
  12125. uniforms = {
  12126. position: new Vector3(),
  12127. color: new Color(),
  12128. distance: 0,
  12129. decay: 0
  12130. };
  12131. break;
  12132. case 'HemisphereLight':
  12133. uniforms = {
  12134. direction: new Vector3(),
  12135. skyColor: new Color(),
  12136. groundColor: new Color()
  12137. };
  12138. break;
  12139. case 'RectAreaLight':
  12140. uniforms = {
  12141. color: new Color(),
  12142. position: new Vector3(),
  12143. halfWidth: new Vector3(),
  12144. halfHeight: new Vector3()
  12145. };
  12146. break;
  12147. }
  12148. lights[light.id] = uniforms;
  12149. return uniforms;
  12150. }
  12151. };
  12152. }
  12153. function ShadowUniformsCache() {
  12154. const lights = {};
  12155. return {
  12156. get: function (light) {
  12157. if (lights[light.id] !== undefined) {
  12158. return lights[light.id];
  12159. }
  12160. let uniforms;
  12161. switch (light.type) {
  12162. case 'DirectionalLight':
  12163. uniforms = {
  12164. shadowBias: 0,
  12165. shadowNormalBias: 0,
  12166. shadowRadius: 1,
  12167. shadowMapSize: new Vector2()
  12168. };
  12169. break;
  12170. case 'SpotLight':
  12171. uniforms = {
  12172. shadowBias: 0,
  12173. shadowNormalBias: 0,
  12174. shadowRadius: 1,
  12175. shadowMapSize: new Vector2()
  12176. };
  12177. break;
  12178. case 'PointLight':
  12179. uniforms = {
  12180. shadowBias: 0,
  12181. shadowNormalBias: 0,
  12182. shadowRadius: 1,
  12183. shadowMapSize: new Vector2(),
  12184. shadowCameraNear: 1,
  12185. shadowCameraFar: 1000
  12186. };
  12187. break;
  12188. // TODO (abelnation): set RectAreaLight shadow uniforms
  12189. }
  12190. lights[light.id] = uniforms;
  12191. return uniforms;
  12192. }
  12193. };
  12194. }
  12195. let nextVersion = 0;
  12196. function shadowCastingAndTexturingLightsFirst(lightA, lightB) {
  12197. return (lightB.castShadow ? 2 : 0) - (lightA.castShadow ? 2 : 0) + (lightB.map ? 1 : 0) - (lightA.map ? 1 : 0);
  12198. }
  12199. function WebGLLights(extensions, capabilities) {
  12200. const cache = new UniformsCache();
  12201. const shadowCache = ShadowUniformsCache();
  12202. const state = {
  12203. version: 0,
  12204. hash: {
  12205. directionalLength: -1,
  12206. pointLength: -1,
  12207. spotLength: -1,
  12208. rectAreaLength: -1,
  12209. hemiLength: -1,
  12210. numDirectionalShadows: -1,
  12211. numPointShadows: -1,
  12212. numSpotShadows: -1,
  12213. numSpotMaps: -1
  12214. },
  12215. ambient: [0, 0, 0],
  12216. probe: [],
  12217. directional: [],
  12218. directionalShadow: [],
  12219. directionalShadowMap: [],
  12220. directionalShadowMatrix: [],
  12221. spot: [],
  12222. spotLightMap: [],
  12223. spotShadow: [],
  12224. spotShadowMap: [],
  12225. spotLightMatrix: [],
  12226. rectArea: [],
  12227. rectAreaLTC1: null,
  12228. rectAreaLTC2: null,
  12229. point: [],
  12230. pointShadow: [],
  12231. pointShadowMap: [],
  12232. pointShadowMatrix: [],
  12233. hemi: [],
  12234. numSpotLightShadowsWithMaps: 0
  12235. };
  12236. for (let i = 0; i < 9; i++) state.probe.push(new Vector3());
  12237. const vector3 = new Vector3();
  12238. const matrix4 = new Matrix4();
  12239. const matrix42 = new Matrix4();
  12240. function setup(lights, physicallyCorrectLights) {
  12241. let r = 0,
  12242. g = 0,
  12243. b = 0;
  12244. for (let i = 0; i < 9; i++) state.probe[i].set(0, 0, 0);
  12245. let directionalLength = 0;
  12246. let pointLength = 0;
  12247. let spotLength = 0;
  12248. let rectAreaLength = 0;
  12249. let hemiLength = 0;
  12250. let numDirectionalShadows = 0;
  12251. let numPointShadows = 0;
  12252. let numSpotShadows = 0;
  12253. let numSpotMaps = 0;
  12254. let numSpotShadowsWithMaps = 0; // ordering : [shadow casting + map texturing, map texturing, shadow casting, none ]
  12255. lights.sort(shadowCastingAndTexturingLightsFirst); // artist-friendly light intensity scaling factor
  12256. const scaleFactor = physicallyCorrectLights !== true ? Math.PI : 1;
  12257. for (let i = 0, l = lights.length; i < l; i++) {
  12258. const light = lights[i];
  12259. const color = light.color;
  12260. const intensity = light.intensity;
  12261. const distance = light.distance;
  12262. const shadowMap = light.shadow && light.shadow.map ? light.shadow.map.texture : null;
  12263. if (light.isAmbientLight) {
  12264. r += color.r * intensity * scaleFactor;
  12265. g += color.g * intensity * scaleFactor;
  12266. b += color.b * intensity * scaleFactor;
  12267. } else if (light.isLightProbe) {
  12268. for (let j = 0; j < 9; j++) {
  12269. state.probe[j].addScaledVector(light.sh.coefficients[j], intensity);
  12270. }
  12271. } else if (light.isDirectionalLight) {
  12272. const uniforms = cache.get(light);
  12273. uniforms.color.copy(light.color).multiplyScalar(light.intensity * scaleFactor);
  12274. if (light.castShadow) {
  12275. const shadow = light.shadow;
  12276. const shadowUniforms = shadowCache.get(light);
  12277. shadowUniforms.shadowBias = shadow.bias;
  12278. shadowUniforms.shadowNormalBias = shadow.normalBias;
  12279. shadowUniforms.shadowRadius = shadow.radius;
  12280. shadowUniforms.shadowMapSize = shadow.mapSize;
  12281. state.directionalShadow[directionalLength] = shadowUniforms;
  12282. state.directionalShadowMap[directionalLength] = shadowMap;
  12283. state.directionalShadowMatrix[directionalLength] = light.shadow.matrix;
  12284. numDirectionalShadows++;
  12285. }
  12286. state.directional[directionalLength] = uniforms;
  12287. directionalLength++;
  12288. } else if (light.isSpotLight) {
  12289. const uniforms = cache.get(light);
  12290. uniforms.position.setFromMatrixPosition(light.matrixWorld);
  12291. uniforms.color.copy(color).multiplyScalar(intensity * scaleFactor);
  12292. uniforms.distance = distance;
  12293. uniforms.coneCos = Math.cos(light.angle);
  12294. uniforms.penumbraCos = Math.cos(light.angle * (1 - light.penumbra));
  12295. uniforms.decay = light.decay;
  12296. state.spot[spotLength] = uniforms;
  12297. const shadow = light.shadow;
  12298. if (light.map) {
  12299. state.spotLightMap[numSpotMaps] = light.map;
  12300. numSpotMaps++; // make sure the lightMatrix is up to date
  12301. // TODO : do it if required only
  12302. shadow.updateMatrices(light);
  12303. if (light.castShadow) numSpotShadowsWithMaps++;
  12304. }
  12305. state.spotLightMatrix[spotLength] = shadow.matrix;
  12306. if (light.castShadow) {
  12307. const shadowUniforms = shadowCache.get(light);
  12308. shadowUniforms.shadowBias = shadow.bias;
  12309. shadowUniforms.shadowNormalBias = shadow.normalBias;
  12310. shadowUniforms.shadowRadius = shadow.radius;
  12311. shadowUniforms.shadowMapSize = shadow.mapSize;
  12312. state.spotShadow[spotLength] = shadowUniforms;
  12313. state.spotShadowMap[spotLength] = shadowMap;
  12314. numSpotShadows++;
  12315. }
  12316. spotLength++;
  12317. } else if (light.isRectAreaLight) {
  12318. const uniforms = cache.get(light); // (a) intensity is the total visible light emitted
  12319. //uniforms.color.copy( color ).multiplyScalar( intensity / ( light.width * light.height * Math.PI ) );
  12320. // (b) intensity is the brightness of the light
  12321. uniforms.color.copy(color).multiplyScalar(intensity);
  12322. uniforms.halfWidth.set(light.width * 0.5, 0.0, 0.0);
  12323. uniforms.halfHeight.set(0.0, light.height * 0.5, 0.0);
  12324. state.rectArea[rectAreaLength] = uniforms;
  12325. rectAreaLength++;
  12326. } else if (light.isPointLight) {
  12327. const uniforms = cache.get(light);
  12328. uniforms.color.copy(light.color).multiplyScalar(light.intensity * scaleFactor);
  12329. uniforms.distance = light.distance;
  12330. uniforms.decay = light.decay;
  12331. if (light.castShadow) {
  12332. const shadow = light.shadow;
  12333. const shadowUniforms = shadowCache.get(light);
  12334. shadowUniforms.shadowBias = shadow.bias;
  12335. shadowUniforms.shadowNormalBias = shadow.normalBias;
  12336. shadowUniforms.shadowRadius = shadow.radius;
  12337. shadowUniforms.shadowMapSize = shadow.mapSize;
  12338. shadowUniforms.shadowCameraNear = shadow.camera.near;
  12339. shadowUniforms.shadowCameraFar = shadow.camera.far;
  12340. state.pointShadow[pointLength] = shadowUniforms;
  12341. state.pointShadowMap[pointLength] = shadowMap;
  12342. state.pointShadowMatrix[pointLength] = light.shadow.matrix;
  12343. numPointShadows++;
  12344. }
  12345. state.point[pointLength] = uniforms;
  12346. pointLength++;
  12347. } else if (light.isHemisphereLight) {
  12348. const uniforms = cache.get(light);
  12349. uniforms.skyColor.copy(light.color).multiplyScalar(intensity * scaleFactor);
  12350. uniforms.groundColor.copy(light.groundColor).multiplyScalar(intensity * scaleFactor);
  12351. state.hemi[hemiLength] = uniforms;
  12352. hemiLength++;
  12353. }
  12354. }
  12355. if (rectAreaLength > 0) {
  12356. if (capabilities.isWebGL2) {
  12357. // WebGL 2
  12358. state.rectAreaLTC1 = UniformsLib.LTC_FLOAT_1;
  12359. state.rectAreaLTC2 = UniformsLib.LTC_FLOAT_2;
  12360. } else {
  12361. // WebGL 1
  12362. if (extensions.has('OES_texture_float_linear') === true) {
  12363. state.rectAreaLTC1 = UniformsLib.LTC_FLOAT_1;
  12364. state.rectAreaLTC2 = UniformsLib.LTC_FLOAT_2;
  12365. } else if (extensions.has('OES_texture_half_float_linear') === true) {
  12366. state.rectAreaLTC1 = UniformsLib.LTC_HALF_1;
  12367. state.rectAreaLTC2 = UniformsLib.LTC_HALF_2;
  12368. } else {
  12369. console.error('THREE.WebGLRenderer: Unable to use RectAreaLight. Missing WebGL extensions.');
  12370. }
  12371. }
  12372. }
  12373. state.ambient[0] = r;
  12374. state.ambient[1] = g;
  12375. state.ambient[2] = b;
  12376. const hash = state.hash;
  12377. 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 || hash.numSpotMaps !== numSpotMaps) {
  12378. state.directional.length = directionalLength;
  12379. state.spot.length = spotLength;
  12380. state.rectArea.length = rectAreaLength;
  12381. state.point.length = pointLength;
  12382. state.hemi.length = hemiLength;
  12383. state.directionalShadow.length = numDirectionalShadows;
  12384. state.directionalShadowMap.length = numDirectionalShadows;
  12385. state.pointShadow.length = numPointShadows;
  12386. state.pointShadowMap.length = numPointShadows;
  12387. state.spotShadow.length = numSpotShadows;
  12388. state.spotShadowMap.length = numSpotShadows;
  12389. state.directionalShadowMatrix.length = numDirectionalShadows;
  12390. state.pointShadowMatrix.length = numPointShadows;
  12391. state.spotLightMatrix.length = numSpotShadows + numSpotMaps - numSpotShadowsWithMaps;
  12392. state.spotLightMap.length = numSpotMaps;
  12393. state.numSpotLightShadowsWithMaps = numSpotShadowsWithMaps;
  12394. hash.directionalLength = directionalLength;
  12395. hash.pointLength = pointLength;
  12396. hash.spotLength = spotLength;
  12397. hash.rectAreaLength = rectAreaLength;
  12398. hash.hemiLength = hemiLength;
  12399. hash.numDirectionalShadows = numDirectionalShadows;
  12400. hash.numPointShadows = numPointShadows;
  12401. hash.numSpotShadows = numSpotShadows;
  12402. hash.numSpotMaps = numSpotMaps;
  12403. state.version = nextVersion++;
  12404. }
  12405. }
  12406. function setupView(lights, camera) {
  12407. let directionalLength = 0;
  12408. let pointLength = 0;
  12409. let spotLength = 0;
  12410. let rectAreaLength = 0;
  12411. let hemiLength = 0;
  12412. const viewMatrix = camera.matrixWorldInverse;
  12413. for (let i = 0, l = lights.length; i < l; i++) {
  12414. const light = lights[i];
  12415. if (light.isDirectionalLight) {
  12416. const uniforms = state.directional[directionalLength];
  12417. uniforms.direction.setFromMatrixPosition(light.matrixWorld);
  12418. vector3.setFromMatrixPosition(light.target.matrixWorld);
  12419. uniforms.direction.sub(vector3);
  12420. uniforms.direction.transformDirection(viewMatrix);
  12421. directionalLength++;
  12422. } else if (light.isSpotLight) {
  12423. const uniforms = state.spot[spotLength];
  12424. uniforms.position.setFromMatrixPosition(light.matrixWorld);
  12425. uniforms.position.applyMatrix4(viewMatrix);
  12426. uniforms.direction.setFromMatrixPosition(light.matrixWorld);
  12427. vector3.setFromMatrixPosition(light.target.matrixWorld);
  12428. uniforms.direction.sub(vector3);
  12429. uniforms.direction.transformDirection(viewMatrix);
  12430. spotLength++;
  12431. } else if (light.isRectAreaLight) {
  12432. const uniforms = state.rectArea[rectAreaLength];
  12433. uniforms.position.setFromMatrixPosition(light.matrixWorld);
  12434. uniforms.position.applyMatrix4(viewMatrix); // extract local rotation of light to derive width/height half vectors
  12435. matrix42.identity();
  12436. matrix4.copy(light.matrixWorld);
  12437. matrix4.premultiply(viewMatrix);
  12438. matrix42.extractRotation(matrix4);
  12439. uniforms.halfWidth.set(light.width * 0.5, 0.0, 0.0);
  12440. uniforms.halfHeight.set(0.0, light.height * 0.5, 0.0);
  12441. uniforms.halfWidth.applyMatrix4(matrix42);
  12442. uniforms.halfHeight.applyMatrix4(matrix42);
  12443. rectAreaLength++;
  12444. } else if (light.isPointLight) {
  12445. const uniforms = state.point[pointLength];
  12446. uniforms.position.setFromMatrixPosition(light.matrixWorld);
  12447. uniforms.position.applyMatrix4(viewMatrix);
  12448. pointLength++;
  12449. } else if (light.isHemisphereLight) {
  12450. const uniforms = state.hemi[hemiLength];
  12451. uniforms.direction.setFromMatrixPosition(light.matrixWorld);
  12452. uniforms.direction.transformDirection(viewMatrix);
  12453. hemiLength++;
  12454. }
  12455. }
  12456. }
  12457. return {
  12458. setup: setup,
  12459. setupView: setupView,
  12460. state: state
  12461. };
  12462. }
  12463. function WebGLRenderState(extensions, capabilities) {
  12464. const lights = new WebGLLights(extensions, capabilities);
  12465. const lightsArray = [];
  12466. const shadowsArray = [];
  12467. function init() {
  12468. lightsArray.length = 0;
  12469. shadowsArray.length = 0;
  12470. }
  12471. function pushLight(light) {
  12472. lightsArray.push(light);
  12473. }
  12474. function pushShadow(shadowLight) {
  12475. shadowsArray.push(shadowLight);
  12476. }
  12477. function setupLights(physicallyCorrectLights) {
  12478. lights.setup(lightsArray, physicallyCorrectLights);
  12479. }
  12480. function setupLightsView(camera) {
  12481. lights.setupView(lightsArray, camera);
  12482. }
  12483. const state = {
  12484. lightsArray: lightsArray,
  12485. shadowsArray: shadowsArray,
  12486. lights: lights
  12487. };
  12488. return {
  12489. init: init,
  12490. state: state,
  12491. setupLights: setupLights,
  12492. setupLightsView: setupLightsView,
  12493. pushLight: pushLight,
  12494. pushShadow: pushShadow
  12495. };
  12496. }
  12497. function WebGLRenderStates(extensions, capabilities) {
  12498. let renderStates = new WeakMap();
  12499. function get(scene, renderCallDepth = 0) {
  12500. const renderStateArray = renderStates.get(scene);
  12501. let renderState;
  12502. if (renderStateArray === undefined) {
  12503. renderState = new WebGLRenderState(extensions, capabilities);
  12504. renderStates.set(scene, [renderState]);
  12505. } else {
  12506. if (renderCallDepth >= renderStateArray.length) {
  12507. renderState = new WebGLRenderState(extensions, capabilities);
  12508. renderStateArray.push(renderState);
  12509. } else {
  12510. renderState = renderStateArray[renderCallDepth];
  12511. }
  12512. }
  12513. return renderState;
  12514. }
  12515. function dispose() {
  12516. renderStates = new WeakMap();
  12517. }
  12518. return {
  12519. get: get,
  12520. dispose: dispose
  12521. };
  12522. }
  12523. class MeshDepthMaterial extends Material {
  12524. constructor(parameters) {
  12525. super();
  12526. this.isMeshDepthMaterial = true;
  12527. this.type = 'MeshDepthMaterial';
  12528. this.depthPacking = BasicDepthPacking;
  12529. this.map = null;
  12530. this.alphaMap = null;
  12531. this.displacementMap = null;
  12532. this.displacementScale = 1;
  12533. this.displacementBias = 0;
  12534. this.wireframe = false;
  12535. this.wireframeLinewidth = 1;
  12536. this.setValues(parameters);
  12537. }
  12538. copy(source) {
  12539. super.copy(source);
  12540. this.depthPacking = source.depthPacking;
  12541. this.map = source.map;
  12542. this.alphaMap = source.alphaMap;
  12543. this.displacementMap = source.displacementMap;
  12544. this.displacementScale = source.displacementScale;
  12545. this.displacementBias = source.displacementBias;
  12546. this.wireframe = source.wireframe;
  12547. this.wireframeLinewidth = source.wireframeLinewidth;
  12548. return this;
  12549. }
  12550. }
  12551. class MeshDistanceMaterial extends Material {
  12552. constructor(parameters) {
  12553. super();
  12554. this.isMeshDistanceMaterial = true;
  12555. this.type = 'MeshDistanceMaterial';
  12556. this.referencePosition = new Vector3();
  12557. this.nearDistance = 1;
  12558. this.farDistance = 1000;
  12559. this.map = null;
  12560. this.alphaMap = null;
  12561. this.displacementMap = null;
  12562. this.displacementScale = 1;
  12563. this.displacementBias = 0;
  12564. this.setValues(parameters);
  12565. }
  12566. copy(source) {
  12567. super.copy(source);
  12568. this.referencePosition.copy(source.referencePosition);
  12569. this.nearDistance = source.nearDistance;
  12570. this.farDistance = source.farDistance;
  12571. this.map = source.map;
  12572. this.alphaMap = source.alphaMap;
  12573. this.displacementMap = source.displacementMap;
  12574. this.displacementScale = source.displacementScale;
  12575. this.displacementBias = source.displacementBias;
  12576. return this;
  12577. }
  12578. }
  12579. const vertex = "void main() {\n\tgl_Position = vec4( position, 1.0 );\n}";
  12580. const fragment = "uniform sampler2D shadow_pass;\nuniform vec2 resolution;\nuniform float radius;\n#include <packing>\nvoid main() {\n\tconst float samples = float( VSM_SAMPLES );\n\tfloat mean = 0.0;\n\tfloat squared_mean = 0.0;\n\tfloat uvStride = samples <= 1.0 ? 0.0 : 2.0 / ( samples - 1.0 );\n\tfloat uvStart = samples <= 1.0 ? 0.0 : - 1.0;\n\tfor ( float i = 0.0; i < samples; i ++ ) {\n\t\tfloat uvOffset = uvStart + i * uvStride;\n\t\t#ifdef HORIZONTAL_PASS\n\t\t\tvec2 distribution = unpackRGBATo2Half( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( uvOffset, 0.0 ) * radius ) / resolution ) );\n\t\t\tmean += distribution.x;\n\t\t\tsquared_mean += distribution.y * distribution.y + distribution.x * distribution.x;\n\t\t#else\n\t\t\tfloat depth = unpackRGBAToDepth( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( 0.0, uvOffset ) * radius ) / resolution ) );\n\t\t\tmean += depth;\n\t\t\tsquared_mean += depth * depth;\n\t\t#endif\n\t}\n\tmean = mean / samples;\n\tsquared_mean = squared_mean / samples;\n\tfloat std_dev = sqrt( squared_mean - mean * mean );\n\tgl_FragColor = pack2HalfToRGBA( vec2( mean, std_dev ) );\n}";
  12581. function WebGLShadowMap(_renderer, _objects, _capabilities) {
  12582. let _frustum = new Frustum();
  12583. const _shadowMapSize = new Vector2(),
  12584. _viewportSize = new Vector2(),
  12585. _viewport = new Vector4(),
  12586. _depthMaterial = new MeshDepthMaterial({
  12587. depthPacking: RGBADepthPacking
  12588. }),
  12589. _distanceMaterial = new MeshDistanceMaterial(),
  12590. _materialCache = {},
  12591. _maxTextureSize = _capabilities.maxTextureSize;
  12592. const shadowSide = {
  12593. 0: BackSide,
  12594. 1: FrontSide,
  12595. 2: DoubleSide
  12596. };
  12597. const shadowMaterialVertical = new ShaderMaterial({
  12598. defines: {
  12599. VSM_SAMPLES: 8
  12600. },
  12601. uniforms: {
  12602. shadow_pass: {
  12603. value: null
  12604. },
  12605. resolution: {
  12606. value: new Vector2()
  12607. },
  12608. radius: {
  12609. value: 4.0
  12610. }
  12611. },
  12612. vertexShader: vertex,
  12613. fragmentShader: fragment
  12614. });
  12615. const shadowMaterialHorizontal = shadowMaterialVertical.clone();
  12616. shadowMaterialHorizontal.defines.HORIZONTAL_PASS = 1;
  12617. const fullScreenTri = new BufferGeometry();
  12618. fullScreenTri.setAttribute('position', new BufferAttribute(new Float32Array([-1, -1, 0.5, 3, -1, 0.5, -1, 3, 0.5]), 3));
  12619. const fullScreenMesh = new Mesh(fullScreenTri, shadowMaterialVertical);
  12620. const scope = this;
  12621. this.enabled = false;
  12622. this.autoUpdate = true;
  12623. this.needsUpdate = false;
  12624. this.type = PCFShadowMap;
  12625. this.render = function (lights, scene, camera) {
  12626. if (scope.enabled === false) return;
  12627. if (scope.autoUpdate === false && scope.needsUpdate === false) return;
  12628. if (lights.length === 0) return;
  12629. const currentRenderTarget = _renderer.getRenderTarget();
  12630. const activeCubeFace = _renderer.getActiveCubeFace();
  12631. const activeMipmapLevel = _renderer.getActiveMipmapLevel();
  12632. const _state = _renderer.state; // Set GL state for depth map.
  12633. _state.setBlending(NoBlending);
  12634. _state.buffers.color.setClear(1, 1, 1, 1);
  12635. _state.buffers.depth.setTest(true);
  12636. _state.setScissorTest(false); // render depth map
  12637. for (let i = 0, il = lights.length; i < il; i++) {
  12638. const light = lights[i];
  12639. const shadow = light.shadow;
  12640. if (shadow === undefined) {
  12641. console.warn('THREE.WebGLShadowMap:', light, 'has no shadow.');
  12642. continue;
  12643. }
  12644. if (shadow.autoUpdate === false && shadow.needsUpdate === false) continue;
  12645. _shadowMapSize.copy(shadow.mapSize);
  12646. const shadowFrameExtents = shadow.getFrameExtents();
  12647. _shadowMapSize.multiply(shadowFrameExtents);
  12648. _viewportSize.copy(shadow.mapSize);
  12649. if (_shadowMapSize.x > _maxTextureSize || _shadowMapSize.y > _maxTextureSize) {
  12650. if (_shadowMapSize.x > _maxTextureSize) {
  12651. _viewportSize.x = Math.floor(_maxTextureSize / shadowFrameExtents.x);
  12652. _shadowMapSize.x = _viewportSize.x * shadowFrameExtents.x;
  12653. shadow.mapSize.x = _viewportSize.x;
  12654. }
  12655. if (_shadowMapSize.y > _maxTextureSize) {
  12656. _viewportSize.y = Math.floor(_maxTextureSize / shadowFrameExtents.y);
  12657. _shadowMapSize.y = _viewportSize.y * shadowFrameExtents.y;
  12658. shadow.mapSize.y = _viewportSize.y;
  12659. }
  12660. }
  12661. if (shadow.map === null) {
  12662. const pars = this.type !== VSMShadowMap ? {
  12663. minFilter: NearestFilter,
  12664. magFilter: NearestFilter
  12665. } : {};
  12666. shadow.map = new WebGLRenderTarget(_shadowMapSize.x, _shadowMapSize.y, pars);
  12667. shadow.map.texture.name = light.name + '.shadowMap';
  12668. shadow.camera.updateProjectionMatrix();
  12669. }
  12670. _renderer.setRenderTarget(shadow.map);
  12671. _renderer.clear();
  12672. const viewportCount = shadow.getViewportCount();
  12673. for (let vp = 0; vp < viewportCount; vp++) {
  12674. const viewport = shadow.getViewport(vp);
  12675. _viewport.set(_viewportSize.x * viewport.x, _viewportSize.y * viewport.y, _viewportSize.x * viewport.z, _viewportSize.y * viewport.w);
  12676. _state.viewport(_viewport);
  12677. shadow.updateMatrices(light, vp);
  12678. _frustum = shadow.getFrustum();
  12679. renderObject(scene, camera, shadow.camera, light, this.type);
  12680. } // do blur pass for VSM
  12681. if (shadow.isPointLightShadow !== true && this.type === VSMShadowMap) {
  12682. VSMPass(shadow, camera);
  12683. }
  12684. shadow.needsUpdate = false;
  12685. }
  12686. scope.needsUpdate = false;
  12687. _renderer.setRenderTarget(currentRenderTarget, activeCubeFace, activeMipmapLevel);
  12688. };
  12689. function VSMPass(shadow, camera) {
  12690. const geometry = _objects.update(fullScreenMesh);
  12691. if (shadowMaterialVertical.defines.VSM_SAMPLES !== shadow.blurSamples) {
  12692. shadowMaterialVertical.defines.VSM_SAMPLES = shadow.blurSamples;
  12693. shadowMaterialHorizontal.defines.VSM_SAMPLES = shadow.blurSamples;
  12694. shadowMaterialVertical.needsUpdate = true;
  12695. shadowMaterialHorizontal.needsUpdate = true;
  12696. }
  12697. if (shadow.mapPass === null) {
  12698. shadow.mapPass = new WebGLRenderTarget(_shadowMapSize.x, _shadowMapSize.y);
  12699. } // vertical pass
  12700. shadowMaterialVertical.uniforms.shadow_pass.value = shadow.map.texture;
  12701. shadowMaterialVertical.uniforms.resolution.value = shadow.mapSize;
  12702. shadowMaterialVertical.uniforms.radius.value = shadow.radius;
  12703. _renderer.setRenderTarget(shadow.mapPass);
  12704. _renderer.clear();
  12705. _renderer.renderBufferDirect(camera, null, geometry, shadowMaterialVertical, fullScreenMesh, null); // horizontal pass
  12706. shadowMaterialHorizontal.uniforms.shadow_pass.value = shadow.mapPass.texture;
  12707. shadowMaterialHorizontal.uniforms.resolution.value = shadow.mapSize;
  12708. shadowMaterialHorizontal.uniforms.radius.value = shadow.radius;
  12709. _renderer.setRenderTarget(shadow.map);
  12710. _renderer.clear();
  12711. _renderer.renderBufferDirect(camera, null, geometry, shadowMaterialHorizontal, fullScreenMesh, null);
  12712. }
  12713. function getDepthMaterial(object, material, light, shadowCameraNear, shadowCameraFar, type) {
  12714. let result = null;
  12715. const customMaterial = light.isPointLight === true ? object.customDistanceMaterial : object.customDepthMaterial;
  12716. if (customMaterial !== undefined) {
  12717. result = customMaterial;
  12718. } else {
  12719. result = light.isPointLight === true ? _distanceMaterial : _depthMaterial;
  12720. }
  12721. if (_renderer.localClippingEnabled && material.clipShadows === true && Array.isArray(material.clippingPlanes) && material.clippingPlanes.length !== 0 || material.displacementMap && material.displacementScale !== 0 || material.alphaMap && material.alphaTest > 0) {
  12722. // in this case we need a unique material instance reflecting the
  12723. // appropriate state
  12724. const keyA = result.uuid,
  12725. keyB = material.uuid;
  12726. let materialsForVariant = _materialCache[keyA];
  12727. if (materialsForVariant === undefined) {
  12728. materialsForVariant = {};
  12729. _materialCache[keyA] = materialsForVariant;
  12730. }
  12731. let cachedMaterial = materialsForVariant[keyB];
  12732. if (cachedMaterial === undefined) {
  12733. cachedMaterial = result.clone();
  12734. materialsForVariant[keyB] = cachedMaterial;
  12735. }
  12736. result = cachedMaterial;
  12737. }
  12738. result.visible = material.visible;
  12739. result.wireframe = material.wireframe;
  12740. if (type === VSMShadowMap) {
  12741. result.side = material.shadowSide !== null ? material.shadowSide : material.side;
  12742. } else {
  12743. result.side = material.shadowSide !== null ? material.shadowSide : shadowSide[material.side];
  12744. }
  12745. result.alphaMap = material.alphaMap;
  12746. result.alphaTest = material.alphaTest;
  12747. result.clipShadows = material.clipShadows;
  12748. result.clippingPlanes = material.clippingPlanes;
  12749. result.clipIntersection = material.clipIntersection;
  12750. result.displacementMap = material.displacementMap;
  12751. result.displacementScale = material.displacementScale;
  12752. result.displacementBias = material.displacementBias;
  12753. result.wireframeLinewidth = material.wireframeLinewidth;
  12754. result.linewidth = material.linewidth;
  12755. if (light.isPointLight === true && result.isMeshDistanceMaterial === true) {
  12756. result.referencePosition.setFromMatrixPosition(light.matrixWorld);
  12757. result.nearDistance = shadowCameraNear;
  12758. result.farDistance = shadowCameraFar;
  12759. }
  12760. return result;
  12761. }
  12762. function renderObject(object, camera, shadowCamera, light, type) {
  12763. if (object.visible === false) return;
  12764. const visible = object.layers.test(camera.layers);
  12765. if (visible && (object.isMesh || object.isLine || object.isPoints)) {
  12766. if ((object.castShadow || object.receiveShadow && type === VSMShadowMap) && (!object.frustumCulled || _frustum.intersectsObject(object))) {
  12767. object.modelViewMatrix.multiplyMatrices(shadowCamera.matrixWorldInverse, object.matrixWorld);
  12768. const geometry = _objects.update(object);
  12769. const material = object.material;
  12770. if (Array.isArray(material)) {
  12771. const groups = geometry.groups;
  12772. for (let k = 0, kl = groups.length; k < kl; k++) {
  12773. const group = groups[k];
  12774. const groupMaterial = material[group.materialIndex];
  12775. if (groupMaterial && groupMaterial.visible) {
  12776. const depthMaterial = getDepthMaterial(object, groupMaterial, light, shadowCamera.near, shadowCamera.far, type);
  12777. _renderer.renderBufferDirect(shadowCamera, null, geometry, depthMaterial, object, group);
  12778. }
  12779. }
  12780. } else if (material.visible) {
  12781. const depthMaterial = getDepthMaterial(object, material, light, shadowCamera.near, shadowCamera.far, type);
  12782. _renderer.renderBufferDirect(shadowCamera, null, geometry, depthMaterial, object, null);
  12783. }
  12784. }
  12785. }
  12786. const children = object.children;
  12787. for (let i = 0, l = children.length; i < l; i++) {
  12788. renderObject(children[i], camera, shadowCamera, light, type);
  12789. }
  12790. }
  12791. }
  12792. function WebGLState(gl, extensions, capabilities) {
  12793. const isWebGL2 = capabilities.isWebGL2;
  12794. function ColorBuffer() {
  12795. let locked = false;
  12796. const color = new Vector4();
  12797. let currentColorMask = null;
  12798. const currentColorClear = new Vector4(0, 0, 0, 0);
  12799. return {
  12800. setMask: function (colorMask) {
  12801. if (currentColorMask !== colorMask && !locked) {
  12802. gl.colorMask(colorMask, colorMask, colorMask, colorMask);
  12803. currentColorMask = colorMask;
  12804. }
  12805. },
  12806. setLocked: function (lock) {
  12807. locked = lock;
  12808. },
  12809. setClear: function (r, g, b, a, premultipliedAlpha) {
  12810. if (premultipliedAlpha === true) {
  12811. r *= a;
  12812. g *= a;
  12813. b *= a;
  12814. }
  12815. color.set(r, g, b, a);
  12816. if (currentColorClear.equals(color) === false) {
  12817. gl.clearColor(r, g, b, a);
  12818. currentColorClear.copy(color);
  12819. }
  12820. },
  12821. reset: function () {
  12822. locked = false;
  12823. currentColorMask = null;
  12824. currentColorClear.set(-1, 0, 0, 0); // set to invalid state
  12825. }
  12826. };
  12827. }
  12828. function DepthBuffer() {
  12829. let locked = false;
  12830. let currentDepthMask = null;
  12831. let currentDepthFunc = null;
  12832. let currentDepthClear = null;
  12833. return {
  12834. setTest: function (depthTest) {
  12835. if (depthTest) {
  12836. enable(gl.DEPTH_TEST);
  12837. } else {
  12838. disable(gl.DEPTH_TEST);
  12839. }
  12840. },
  12841. setMask: function (depthMask) {
  12842. if (currentDepthMask !== depthMask && !locked) {
  12843. gl.depthMask(depthMask);
  12844. currentDepthMask = depthMask;
  12845. }
  12846. },
  12847. setFunc: function (depthFunc) {
  12848. if (currentDepthFunc !== depthFunc) {
  12849. switch (depthFunc) {
  12850. case NeverDepth:
  12851. gl.depthFunc(gl.NEVER);
  12852. break;
  12853. case AlwaysDepth:
  12854. gl.depthFunc(gl.ALWAYS);
  12855. break;
  12856. case LessDepth:
  12857. gl.depthFunc(gl.LESS);
  12858. break;
  12859. case LessEqualDepth:
  12860. gl.depthFunc(gl.LEQUAL);
  12861. break;
  12862. case EqualDepth:
  12863. gl.depthFunc(gl.EQUAL);
  12864. break;
  12865. case GreaterEqualDepth:
  12866. gl.depthFunc(gl.GEQUAL);
  12867. break;
  12868. case GreaterDepth:
  12869. gl.depthFunc(gl.GREATER);
  12870. break;
  12871. case NotEqualDepth:
  12872. gl.depthFunc(gl.NOTEQUAL);
  12873. break;
  12874. default:
  12875. gl.depthFunc(gl.LEQUAL);
  12876. }
  12877. currentDepthFunc = depthFunc;
  12878. }
  12879. },
  12880. setLocked: function (lock) {
  12881. locked = lock;
  12882. },
  12883. setClear: function (depth) {
  12884. if (currentDepthClear !== depth) {
  12885. gl.clearDepth(depth);
  12886. currentDepthClear = depth;
  12887. }
  12888. },
  12889. reset: function () {
  12890. locked = false;
  12891. currentDepthMask = null;
  12892. currentDepthFunc = null;
  12893. currentDepthClear = null;
  12894. }
  12895. };
  12896. }
  12897. function StencilBuffer() {
  12898. let locked = false;
  12899. let currentStencilMask = null;
  12900. let currentStencilFunc = null;
  12901. let currentStencilRef = null;
  12902. let currentStencilFuncMask = null;
  12903. let currentStencilFail = null;
  12904. let currentStencilZFail = null;
  12905. let currentStencilZPass = null;
  12906. let currentStencilClear = null;
  12907. return {
  12908. setTest: function (stencilTest) {
  12909. if (!locked) {
  12910. if (stencilTest) {
  12911. enable(gl.STENCIL_TEST);
  12912. } else {
  12913. disable(gl.STENCIL_TEST);
  12914. }
  12915. }
  12916. },
  12917. setMask: function (stencilMask) {
  12918. if (currentStencilMask !== stencilMask && !locked) {
  12919. gl.stencilMask(stencilMask);
  12920. currentStencilMask = stencilMask;
  12921. }
  12922. },
  12923. setFunc: function (stencilFunc, stencilRef, stencilMask) {
  12924. if (currentStencilFunc !== stencilFunc || currentStencilRef !== stencilRef || currentStencilFuncMask !== stencilMask) {
  12925. gl.stencilFunc(stencilFunc, stencilRef, stencilMask);
  12926. currentStencilFunc = stencilFunc;
  12927. currentStencilRef = stencilRef;
  12928. currentStencilFuncMask = stencilMask;
  12929. }
  12930. },
  12931. setOp: function (stencilFail, stencilZFail, stencilZPass) {
  12932. if (currentStencilFail !== stencilFail || currentStencilZFail !== stencilZFail || currentStencilZPass !== stencilZPass) {
  12933. gl.stencilOp(stencilFail, stencilZFail, stencilZPass);
  12934. currentStencilFail = stencilFail;
  12935. currentStencilZFail = stencilZFail;
  12936. currentStencilZPass = stencilZPass;
  12937. }
  12938. },
  12939. setLocked: function (lock) {
  12940. locked = lock;
  12941. },
  12942. setClear: function (stencil) {
  12943. if (currentStencilClear !== stencil) {
  12944. gl.clearStencil(stencil);
  12945. currentStencilClear = stencil;
  12946. }
  12947. },
  12948. reset: function () {
  12949. locked = false;
  12950. currentStencilMask = null;
  12951. currentStencilFunc = null;
  12952. currentStencilRef = null;
  12953. currentStencilFuncMask = null;
  12954. currentStencilFail = null;
  12955. currentStencilZFail = null;
  12956. currentStencilZPass = null;
  12957. currentStencilClear = null;
  12958. }
  12959. };
  12960. } //
  12961. const colorBuffer = new ColorBuffer();
  12962. const depthBuffer = new DepthBuffer();
  12963. const stencilBuffer = new StencilBuffer();
  12964. const uboBindings = new WeakMap();
  12965. const uboProgamMap = new WeakMap();
  12966. let enabledCapabilities = {};
  12967. let currentBoundFramebuffers = {};
  12968. let currentDrawbuffers = new WeakMap();
  12969. let defaultDrawbuffers = [];
  12970. let currentProgram = null;
  12971. let currentBlendingEnabled = false;
  12972. let currentBlending = null;
  12973. let currentBlendEquation = null;
  12974. let currentBlendSrc = null;
  12975. let currentBlendDst = null;
  12976. let currentBlendEquationAlpha = null;
  12977. let currentBlendSrcAlpha = null;
  12978. let currentBlendDstAlpha = null;
  12979. let currentPremultipledAlpha = false;
  12980. let currentFlipSided = null;
  12981. let currentCullFace = null;
  12982. let currentLineWidth = null;
  12983. let currentPolygonOffsetFactor = null;
  12984. let currentPolygonOffsetUnits = null;
  12985. const maxTextures = gl.getParameter(gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  12986. let lineWidthAvailable = false;
  12987. let version = 0;
  12988. const glVersion = gl.getParameter(gl.VERSION);
  12989. if (glVersion.indexOf('WebGL') !== -1) {
  12990. version = parseFloat(/^WebGL (\d)/.exec(glVersion)[1]);
  12991. lineWidthAvailable = version >= 1.0;
  12992. } else if (glVersion.indexOf('OpenGL ES') !== -1) {
  12993. version = parseFloat(/^OpenGL ES (\d)/.exec(glVersion)[1]);
  12994. lineWidthAvailable = version >= 2.0;
  12995. }
  12996. let currentTextureSlot = null;
  12997. let currentBoundTextures = {};
  12998. const scissorParam = gl.getParameter(gl.SCISSOR_BOX);
  12999. const viewportParam = gl.getParameter(gl.VIEWPORT);
  13000. const currentScissor = new Vector4().fromArray(scissorParam);
  13001. const currentViewport = new Vector4().fromArray(viewportParam);
  13002. function createTexture(type, target, count) {
  13003. const data = new Uint8Array(4); // 4 is required to match default unpack alignment of 4.
  13004. const texture = gl.createTexture();
  13005. gl.bindTexture(type, texture);
  13006. gl.texParameteri(type, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  13007. gl.texParameteri(type, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  13008. for (let i = 0; i < count; i++) {
  13009. gl.texImage2D(target + i, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data);
  13010. }
  13011. return texture;
  13012. }
  13013. const emptyTextures = {};
  13014. emptyTextures[gl.TEXTURE_2D] = createTexture(gl.TEXTURE_2D, gl.TEXTURE_2D, 1);
  13015. emptyTextures[gl.TEXTURE_CUBE_MAP] = createTexture(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_CUBE_MAP_POSITIVE_X, 6); // init
  13016. colorBuffer.setClear(0, 0, 0, 1);
  13017. depthBuffer.setClear(1);
  13018. stencilBuffer.setClear(0);
  13019. enable(gl.DEPTH_TEST);
  13020. depthBuffer.setFunc(LessEqualDepth);
  13021. setFlipSided(false);
  13022. setCullFace(CullFaceBack);
  13023. enable(gl.CULL_FACE);
  13024. setBlending(NoBlending); //
  13025. function enable(id) {
  13026. if (enabledCapabilities[id] !== true) {
  13027. gl.enable(id);
  13028. enabledCapabilities[id] = true;
  13029. }
  13030. }
  13031. function disable(id) {
  13032. if (enabledCapabilities[id] !== false) {
  13033. gl.disable(id);
  13034. enabledCapabilities[id] = false;
  13035. }
  13036. }
  13037. function bindFramebuffer(target, framebuffer) {
  13038. if (currentBoundFramebuffers[target] !== framebuffer) {
  13039. gl.bindFramebuffer(target, framebuffer);
  13040. currentBoundFramebuffers[target] = framebuffer;
  13041. if (isWebGL2) {
  13042. // gl.DRAW_FRAMEBUFFER is equivalent to gl.FRAMEBUFFER
  13043. if (target === gl.DRAW_FRAMEBUFFER) {
  13044. currentBoundFramebuffers[gl.FRAMEBUFFER] = framebuffer;
  13045. }
  13046. if (target === gl.FRAMEBUFFER) {
  13047. currentBoundFramebuffers[gl.DRAW_FRAMEBUFFER] = framebuffer;
  13048. }
  13049. }
  13050. return true;
  13051. }
  13052. return false;
  13053. }
  13054. function drawBuffers(renderTarget, framebuffer) {
  13055. let drawBuffers = defaultDrawbuffers;
  13056. let needsUpdate = false;
  13057. if (renderTarget) {
  13058. drawBuffers = currentDrawbuffers.get(framebuffer);
  13059. if (drawBuffers === undefined) {
  13060. drawBuffers = [];
  13061. currentDrawbuffers.set(framebuffer, drawBuffers);
  13062. }
  13063. if (renderTarget.isWebGLMultipleRenderTargets) {
  13064. const textures = renderTarget.texture;
  13065. if (drawBuffers.length !== textures.length || drawBuffers[0] !== gl.COLOR_ATTACHMENT0) {
  13066. for (let i = 0, il = textures.length; i < il; i++) {
  13067. drawBuffers[i] = gl.COLOR_ATTACHMENT0 + i;
  13068. }
  13069. drawBuffers.length = textures.length;
  13070. needsUpdate = true;
  13071. }
  13072. } else {
  13073. if (drawBuffers[0] !== gl.COLOR_ATTACHMENT0) {
  13074. drawBuffers[0] = gl.COLOR_ATTACHMENT0;
  13075. needsUpdate = true;
  13076. }
  13077. }
  13078. } else {
  13079. if (drawBuffers[0] !== gl.BACK) {
  13080. drawBuffers[0] = gl.BACK;
  13081. needsUpdate = true;
  13082. }
  13083. }
  13084. if (needsUpdate) {
  13085. if (capabilities.isWebGL2) {
  13086. gl.drawBuffers(drawBuffers);
  13087. } else {
  13088. extensions.get('WEBGL_draw_buffers').drawBuffersWEBGL(drawBuffers);
  13089. }
  13090. }
  13091. }
  13092. function useProgram(program) {
  13093. if (currentProgram !== program) {
  13094. gl.useProgram(program);
  13095. currentProgram = program;
  13096. return true;
  13097. }
  13098. return false;
  13099. }
  13100. const equationToGL = {
  13101. [AddEquation]: gl.FUNC_ADD,
  13102. [SubtractEquation]: gl.FUNC_SUBTRACT,
  13103. [ReverseSubtractEquation]: gl.FUNC_REVERSE_SUBTRACT
  13104. };
  13105. if (isWebGL2) {
  13106. equationToGL[MinEquation] = gl.MIN;
  13107. equationToGL[MaxEquation] = gl.MAX;
  13108. } else {
  13109. const extension = extensions.get('EXT_blend_minmax');
  13110. if (extension !== null) {
  13111. equationToGL[MinEquation] = extension.MIN_EXT;
  13112. equationToGL[MaxEquation] = extension.MAX_EXT;
  13113. }
  13114. }
  13115. const factorToGL = {
  13116. [ZeroFactor]: gl.ZERO,
  13117. [OneFactor]: gl.ONE,
  13118. [SrcColorFactor]: gl.SRC_COLOR,
  13119. [SrcAlphaFactor]: gl.SRC_ALPHA,
  13120. [SrcAlphaSaturateFactor]: gl.SRC_ALPHA_SATURATE,
  13121. [DstColorFactor]: gl.DST_COLOR,
  13122. [DstAlphaFactor]: gl.DST_ALPHA,
  13123. [OneMinusSrcColorFactor]: gl.ONE_MINUS_SRC_COLOR,
  13124. [OneMinusSrcAlphaFactor]: gl.ONE_MINUS_SRC_ALPHA,
  13125. [OneMinusDstColorFactor]: gl.ONE_MINUS_DST_COLOR,
  13126. [OneMinusDstAlphaFactor]: gl.ONE_MINUS_DST_ALPHA
  13127. };
  13128. function setBlending(blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha) {
  13129. if (blending === NoBlending) {
  13130. if (currentBlendingEnabled === true) {
  13131. disable(gl.BLEND);
  13132. currentBlendingEnabled = false;
  13133. }
  13134. return;
  13135. }
  13136. if (currentBlendingEnabled === false) {
  13137. enable(gl.BLEND);
  13138. currentBlendingEnabled = true;
  13139. }
  13140. if (blending !== CustomBlending) {
  13141. if (blending !== currentBlending || premultipliedAlpha !== currentPremultipledAlpha) {
  13142. if (currentBlendEquation !== AddEquation || currentBlendEquationAlpha !== AddEquation) {
  13143. gl.blendEquation(gl.FUNC_ADD);
  13144. currentBlendEquation = AddEquation;
  13145. currentBlendEquationAlpha = AddEquation;
  13146. }
  13147. if (premultipliedAlpha) {
  13148. switch (blending) {
  13149. case NormalBlending:
  13150. gl.blendFuncSeparate(gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
  13151. break;
  13152. case AdditiveBlending:
  13153. gl.blendFunc(gl.ONE, gl.ONE);
  13154. break;
  13155. case SubtractiveBlending:
  13156. gl.blendFuncSeparate(gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE);
  13157. break;
  13158. case MultiplyBlending:
  13159. gl.blendFuncSeparate(gl.ZERO, gl.SRC_COLOR, gl.ZERO, gl.SRC_ALPHA);
  13160. break;
  13161. default:
  13162. console.error('THREE.WebGLState: Invalid blending: ', blending);
  13163. break;
  13164. }
  13165. } else {
  13166. switch (blending) {
  13167. case NormalBlending:
  13168. gl.blendFuncSeparate(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
  13169. break;
  13170. case AdditiveBlending:
  13171. gl.blendFunc(gl.SRC_ALPHA, gl.ONE);
  13172. break;
  13173. case SubtractiveBlending:
  13174. gl.blendFuncSeparate(gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE);
  13175. break;
  13176. case MultiplyBlending:
  13177. gl.blendFunc(gl.ZERO, gl.SRC_COLOR);
  13178. break;
  13179. default:
  13180. console.error('THREE.WebGLState: Invalid blending: ', blending);
  13181. break;
  13182. }
  13183. }
  13184. currentBlendSrc = null;
  13185. currentBlendDst = null;
  13186. currentBlendSrcAlpha = null;
  13187. currentBlendDstAlpha = null;
  13188. currentBlending = blending;
  13189. currentPremultipledAlpha = premultipliedAlpha;
  13190. }
  13191. return;
  13192. } // custom blending
  13193. blendEquationAlpha = blendEquationAlpha || blendEquation;
  13194. blendSrcAlpha = blendSrcAlpha || blendSrc;
  13195. blendDstAlpha = blendDstAlpha || blendDst;
  13196. if (blendEquation !== currentBlendEquation || blendEquationAlpha !== currentBlendEquationAlpha) {
  13197. gl.blendEquationSeparate(equationToGL[blendEquation], equationToGL[blendEquationAlpha]);
  13198. currentBlendEquation = blendEquation;
  13199. currentBlendEquationAlpha = blendEquationAlpha;
  13200. }
  13201. if (blendSrc !== currentBlendSrc || blendDst !== currentBlendDst || blendSrcAlpha !== currentBlendSrcAlpha || blendDstAlpha !== currentBlendDstAlpha) {
  13202. gl.blendFuncSeparate(factorToGL[blendSrc], factorToGL[blendDst], factorToGL[blendSrcAlpha], factorToGL[blendDstAlpha]);
  13203. currentBlendSrc = blendSrc;
  13204. currentBlendDst = blendDst;
  13205. currentBlendSrcAlpha = blendSrcAlpha;
  13206. currentBlendDstAlpha = blendDstAlpha;
  13207. }
  13208. currentBlending = blending;
  13209. currentPremultipledAlpha = null;
  13210. }
  13211. function setMaterial(material, frontFaceCW) {
  13212. material.side === DoubleSide ? disable(gl.CULL_FACE) : enable(gl.CULL_FACE);
  13213. let flipSided = material.side === BackSide;
  13214. if (frontFaceCW) flipSided = !flipSided;
  13215. setFlipSided(flipSided);
  13216. 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);
  13217. depthBuffer.setFunc(material.depthFunc);
  13218. depthBuffer.setTest(material.depthTest);
  13219. depthBuffer.setMask(material.depthWrite);
  13220. colorBuffer.setMask(material.colorWrite);
  13221. const stencilWrite = material.stencilWrite;
  13222. stencilBuffer.setTest(stencilWrite);
  13223. if (stencilWrite) {
  13224. stencilBuffer.setMask(material.stencilWriteMask);
  13225. stencilBuffer.setFunc(material.stencilFunc, material.stencilRef, material.stencilFuncMask);
  13226. stencilBuffer.setOp(material.stencilFail, material.stencilZFail, material.stencilZPass);
  13227. }
  13228. setPolygonOffset(material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits);
  13229. material.alphaToCoverage === true ? enable(gl.SAMPLE_ALPHA_TO_COVERAGE) : disable(gl.SAMPLE_ALPHA_TO_COVERAGE);
  13230. } //
  13231. function setFlipSided(flipSided) {
  13232. if (currentFlipSided !== flipSided) {
  13233. if (flipSided) {
  13234. gl.frontFace(gl.CW);
  13235. } else {
  13236. gl.frontFace(gl.CCW);
  13237. }
  13238. currentFlipSided = flipSided;
  13239. }
  13240. }
  13241. function setCullFace(cullFace) {
  13242. if (cullFace !== CullFaceNone) {
  13243. enable(gl.CULL_FACE);
  13244. if (cullFace !== currentCullFace) {
  13245. if (cullFace === CullFaceBack) {
  13246. gl.cullFace(gl.BACK);
  13247. } else if (cullFace === CullFaceFront) {
  13248. gl.cullFace(gl.FRONT);
  13249. } else {
  13250. gl.cullFace(gl.FRONT_AND_BACK);
  13251. }
  13252. }
  13253. } else {
  13254. disable(gl.CULL_FACE);
  13255. }
  13256. currentCullFace = cullFace;
  13257. }
  13258. function setLineWidth(width) {
  13259. if (width !== currentLineWidth) {
  13260. if (lineWidthAvailable) gl.lineWidth(width);
  13261. currentLineWidth = width;
  13262. }
  13263. }
  13264. function setPolygonOffset(polygonOffset, factor, units) {
  13265. if (polygonOffset) {
  13266. enable(gl.POLYGON_OFFSET_FILL);
  13267. if (currentPolygonOffsetFactor !== factor || currentPolygonOffsetUnits !== units) {
  13268. gl.polygonOffset(factor, units);
  13269. currentPolygonOffsetFactor = factor;
  13270. currentPolygonOffsetUnits = units;
  13271. }
  13272. } else {
  13273. disable(gl.POLYGON_OFFSET_FILL);
  13274. }
  13275. }
  13276. function setScissorTest(scissorTest) {
  13277. if (scissorTest) {
  13278. enable(gl.SCISSOR_TEST);
  13279. } else {
  13280. disable(gl.SCISSOR_TEST);
  13281. }
  13282. } // texture
  13283. function activeTexture(webglSlot) {
  13284. if (webglSlot === undefined) webglSlot = gl.TEXTURE0 + maxTextures - 1;
  13285. if (currentTextureSlot !== webglSlot) {
  13286. gl.activeTexture(webglSlot);
  13287. currentTextureSlot = webglSlot;
  13288. }
  13289. }
  13290. function bindTexture(webglType, webglTexture, webglSlot) {
  13291. if (webglSlot === undefined) {
  13292. if (currentTextureSlot === null) {
  13293. webglSlot = gl.TEXTURE0 + maxTextures - 1;
  13294. } else {
  13295. webglSlot = currentTextureSlot;
  13296. }
  13297. }
  13298. let boundTexture = currentBoundTextures[webglSlot];
  13299. if (boundTexture === undefined) {
  13300. boundTexture = {
  13301. type: undefined,
  13302. texture: undefined
  13303. };
  13304. currentBoundTextures[webglSlot] = boundTexture;
  13305. }
  13306. if (boundTexture.type !== webglType || boundTexture.texture !== webglTexture) {
  13307. if (currentTextureSlot !== webglSlot) {
  13308. gl.activeTexture(webglSlot);
  13309. currentTextureSlot = webglSlot;
  13310. }
  13311. gl.bindTexture(webglType, webglTexture || emptyTextures[webglType]);
  13312. boundTexture.type = webglType;
  13313. boundTexture.texture = webglTexture;
  13314. }
  13315. }
  13316. function unbindTexture() {
  13317. const boundTexture = currentBoundTextures[currentTextureSlot];
  13318. if (boundTexture !== undefined && boundTexture.type !== undefined) {
  13319. gl.bindTexture(boundTexture.type, null);
  13320. boundTexture.type = undefined;
  13321. boundTexture.texture = undefined;
  13322. }
  13323. }
  13324. function compressedTexImage2D() {
  13325. try {
  13326. gl.compressedTexImage2D.apply(gl, arguments);
  13327. } catch (error) {
  13328. console.error('THREE.WebGLState:', error);
  13329. }
  13330. }
  13331. function texSubImage2D() {
  13332. try {
  13333. gl.texSubImage2D.apply(gl, arguments);
  13334. } catch (error) {
  13335. console.error('THREE.WebGLState:', error);
  13336. }
  13337. }
  13338. function texSubImage3D() {
  13339. try {
  13340. gl.texSubImage3D.apply(gl, arguments);
  13341. } catch (error) {
  13342. console.error('THREE.WebGLState:', error);
  13343. }
  13344. }
  13345. function compressedTexSubImage2D() {
  13346. try {
  13347. gl.compressedTexSubImage2D.apply(gl, arguments);
  13348. } catch (error) {
  13349. console.error('THREE.WebGLState:', error);
  13350. }
  13351. }
  13352. function texStorage2D() {
  13353. try {
  13354. gl.texStorage2D.apply(gl, arguments);
  13355. } catch (error) {
  13356. console.error('THREE.WebGLState:', error);
  13357. }
  13358. }
  13359. function texStorage3D() {
  13360. try {
  13361. gl.texStorage3D.apply(gl, arguments);
  13362. } catch (error) {
  13363. console.error('THREE.WebGLState:', error);
  13364. }
  13365. }
  13366. function texImage2D() {
  13367. try {
  13368. gl.texImage2D.apply(gl, arguments);
  13369. } catch (error) {
  13370. console.error('THREE.WebGLState:', error);
  13371. }
  13372. }
  13373. function texImage3D() {
  13374. try {
  13375. gl.texImage3D.apply(gl, arguments);
  13376. } catch (error) {
  13377. console.error('THREE.WebGLState:', error);
  13378. }
  13379. } //
  13380. function scissor(scissor) {
  13381. if (currentScissor.equals(scissor) === false) {
  13382. gl.scissor(scissor.x, scissor.y, scissor.z, scissor.w);
  13383. currentScissor.copy(scissor);
  13384. }
  13385. }
  13386. function viewport(viewport) {
  13387. if (currentViewport.equals(viewport) === false) {
  13388. gl.viewport(viewport.x, viewport.y, viewport.z, viewport.w);
  13389. currentViewport.copy(viewport);
  13390. }
  13391. }
  13392. function updateUBOMapping(uniformsGroup, program) {
  13393. let mapping = uboProgamMap.get(program);
  13394. if (mapping === undefined) {
  13395. mapping = new WeakMap();
  13396. uboProgamMap.set(program, mapping);
  13397. }
  13398. let blockIndex = mapping.get(uniformsGroup);
  13399. if (blockIndex === undefined) {
  13400. blockIndex = gl.getUniformBlockIndex(program, uniformsGroup.name);
  13401. mapping.set(uniformsGroup, blockIndex);
  13402. }
  13403. }
  13404. function uniformBlockBinding(uniformsGroup, program) {
  13405. const mapping = uboProgamMap.get(program);
  13406. const blockIndex = mapping.get(uniformsGroup);
  13407. if (uboBindings.get(uniformsGroup) !== blockIndex) {
  13408. // bind shader specific block index to global block point
  13409. gl.uniformBlockBinding(program, blockIndex, uniformsGroup.__bindingPointIndex);
  13410. uboBindings.set(uniformsGroup, blockIndex);
  13411. }
  13412. } //
  13413. function reset() {
  13414. // reset state
  13415. gl.disable(gl.BLEND);
  13416. gl.disable(gl.CULL_FACE);
  13417. gl.disable(gl.DEPTH_TEST);
  13418. gl.disable(gl.POLYGON_OFFSET_FILL);
  13419. gl.disable(gl.SCISSOR_TEST);
  13420. gl.disable(gl.STENCIL_TEST);
  13421. gl.disable(gl.SAMPLE_ALPHA_TO_COVERAGE);
  13422. gl.blendEquation(gl.FUNC_ADD);
  13423. gl.blendFunc(gl.ONE, gl.ZERO);
  13424. gl.blendFuncSeparate(gl.ONE, gl.ZERO, gl.ONE, gl.ZERO);
  13425. gl.colorMask(true, true, true, true);
  13426. gl.clearColor(0, 0, 0, 0);
  13427. gl.depthMask(true);
  13428. gl.depthFunc(gl.LESS);
  13429. gl.clearDepth(1);
  13430. gl.stencilMask(0xffffffff);
  13431. gl.stencilFunc(gl.ALWAYS, 0, 0xffffffff);
  13432. gl.stencilOp(gl.KEEP, gl.KEEP, gl.KEEP);
  13433. gl.clearStencil(0);
  13434. gl.cullFace(gl.BACK);
  13435. gl.frontFace(gl.CCW);
  13436. gl.polygonOffset(0, 0);
  13437. gl.activeTexture(gl.TEXTURE0);
  13438. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  13439. if (isWebGL2 === true) {
  13440. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, null);
  13441. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, null);
  13442. }
  13443. gl.useProgram(null);
  13444. gl.lineWidth(1);
  13445. gl.scissor(0, 0, gl.canvas.width, gl.canvas.height);
  13446. gl.viewport(0, 0, gl.canvas.width, gl.canvas.height); // reset internals
  13447. enabledCapabilities = {};
  13448. currentTextureSlot = null;
  13449. currentBoundTextures = {};
  13450. currentBoundFramebuffers = {};
  13451. currentDrawbuffers = new WeakMap();
  13452. defaultDrawbuffers = [];
  13453. currentProgram = null;
  13454. currentBlendingEnabled = false;
  13455. currentBlending = null;
  13456. currentBlendEquation = null;
  13457. currentBlendSrc = null;
  13458. currentBlendDst = null;
  13459. currentBlendEquationAlpha = null;
  13460. currentBlendSrcAlpha = null;
  13461. currentBlendDstAlpha = null;
  13462. currentPremultipledAlpha = false;
  13463. currentFlipSided = null;
  13464. currentCullFace = null;
  13465. currentLineWidth = null;
  13466. currentPolygonOffsetFactor = null;
  13467. currentPolygonOffsetUnits = null;
  13468. currentScissor.set(0, 0, gl.canvas.width, gl.canvas.height);
  13469. currentViewport.set(0, 0, gl.canvas.width, gl.canvas.height);
  13470. colorBuffer.reset();
  13471. depthBuffer.reset();
  13472. stencilBuffer.reset();
  13473. }
  13474. return {
  13475. buffers: {
  13476. color: colorBuffer,
  13477. depth: depthBuffer,
  13478. stencil: stencilBuffer
  13479. },
  13480. enable: enable,
  13481. disable: disable,
  13482. bindFramebuffer: bindFramebuffer,
  13483. drawBuffers: drawBuffers,
  13484. useProgram: useProgram,
  13485. setBlending: setBlending,
  13486. setMaterial: setMaterial,
  13487. setFlipSided: setFlipSided,
  13488. setCullFace: setCullFace,
  13489. setLineWidth: setLineWidth,
  13490. setPolygonOffset: setPolygonOffset,
  13491. setScissorTest: setScissorTest,
  13492. activeTexture: activeTexture,
  13493. bindTexture: bindTexture,
  13494. unbindTexture: unbindTexture,
  13495. compressedTexImage2D: compressedTexImage2D,
  13496. texImage2D: texImage2D,
  13497. texImage3D: texImage3D,
  13498. updateUBOMapping: updateUBOMapping,
  13499. uniformBlockBinding: uniformBlockBinding,
  13500. texStorage2D: texStorage2D,
  13501. texStorage3D: texStorage3D,
  13502. texSubImage2D: texSubImage2D,
  13503. texSubImage3D: texSubImage3D,
  13504. compressedTexSubImage2D: compressedTexSubImage2D,
  13505. scissor: scissor,
  13506. viewport: viewport,
  13507. reset: reset
  13508. };
  13509. }
  13510. function WebGLTextures(_gl, extensions, state, properties, capabilities, utils, info) {
  13511. const isWebGL2 = capabilities.isWebGL2;
  13512. const maxTextures = capabilities.maxTextures;
  13513. const maxCubemapSize = capabilities.maxCubemapSize;
  13514. const maxTextureSize = capabilities.maxTextureSize;
  13515. const maxSamples = capabilities.maxSamples;
  13516. const multisampledRTTExt = extensions.has('WEBGL_multisampled_render_to_texture') ? extensions.get('WEBGL_multisampled_render_to_texture') : null;
  13517. const supportsInvalidateFramebuffer = /OculusBrowser/g.test(typeof navigator === 'undefined' ? '' : navigator.userAgent);
  13518. const _videoTextures = new WeakMap();
  13519. let _canvas;
  13520. const _sources = new WeakMap(); // maps WebglTexture objects to instances of Source
  13521. // cordova iOS (as of 5.0) still uses UIWebView, which provides OffscreenCanvas,
  13522. // also OffscreenCanvas.getContext("webgl"), but not OffscreenCanvas.getContext("2d")!
  13523. // Some implementations may only implement OffscreenCanvas partially (e.g. lacking 2d).
  13524. let useOffscreenCanvas = false;
  13525. try {
  13526. useOffscreenCanvas = typeof OffscreenCanvas !== 'undefined' // eslint-disable-next-line compat/compat
  13527. && new OffscreenCanvas(1, 1).getContext('2d') !== null;
  13528. } catch (err) {// Ignore any errors
  13529. }
  13530. function createCanvas(width, height) {
  13531. // Use OffscreenCanvas when available. Specially needed in web workers
  13532. return useOffscreenCanvas ? // eslint-disable-next-line compat/compat
  13533. new OffscreenCanvas(width, height) : createElementNS('canvas');
  13534. }
  13535. function resizeImage(image, needsPowerOfTwo, needsNewCanvas, maxSize) {
  13536. let scale = 1; // handle case if texture exceeds max size
  13537. if (image.width > maxSize || image.height > maxSize) {
  13538. scale = maxSize / Math.max(image.width, image.height);
  13539. } // only perform resize if necessary
  13540. if (scale < 1 || needsPowerOfTwo === true) {
  13541. // only perform resize for certain image types
  13542. if (typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement || typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement || typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap) {
  13543. const floor = needsPowerOfTwo ? floorPowerOfTwo : Math.floor;
  13544. const width = floor(scale * image.width);
  13545. const height = floor(scale * image.height);
  13546. if (_canvas === undefined) _canvas = createCanvas(width, height); // cube textures can't reuse the same canvas
  13547. const canvas = needsNewCanvas ? createCanvas(width, height) : _canvas;
  13548. canvas.width = width;
  13549. canvas.height = height;
  13550. const context = canvas.getContext('2d');
  13551. context.drawImage(image, 0, 0, width, height);
  13552. console.warn('THREE.WebGLRenderer: Texture has been resized from (' + image.width + 'x' + image.height + ') to (' + width + 'x' + height + ').');
  13553. return canvas;
  13554. } else {
  13555. if ('data' in image) {
  13556. console.warn('THREE.WebGLRenderer: Image in DataTexture is too big (' + image.width + 'x' + image.height + ').');
  13557. }
  13558. return image;
  13559. }
  13560. }
  13561. return image;
  13562. }
  13563. function isPowerOfTwo$1(image) {
  13564. return isPowerOfTwo(image.width) && isPowerOfTwo(image.height);
  13565. }
  13566. function textureNeedsPowerOfTwo(texture) {
  13567. if (isWebGL2) return false;
  13568. return texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping || texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter;
  13569. }
  13570. function textureNeedsGenerateMipmaps(texture, supportsMips) {
  13571. return texture.generateMipmaps && supportsMips && texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter;
  13572. }
  13573. function generateMipmap(target) {
  13574. _gl.generateMipmap(target);
  13575. }
  13576. function getInternalFormat(internalFormatName, glFormat, glType, encoding, forceLinearEncoding = false) {
  13577. if (isWebGL2 === false) return glFormat;
  13578. if (internalFormatName !== null) {
  13579. if (_gl[internalFormatName] !== undefined) return _gl[internalFormatName];
  13580. console.warn('THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\'');
  13581. }
  13582. let internalFormat = glFormat;
  13583. if (glFormat === _gl.RED) {
  13584. if (glType === _gl.FLOAT) internalFormat = _gl.R32F;
  13585. if (glType === _gl.HALF_FLOAT) internalFormat = _gl.R16F;
  13586. if (glType === _gl.UNSIGNED_BYTE) internalFormat = _gl.R8;
  13587. }
  13588. if (glFormat === _gl.RG) {
  13589. if (glType === _gl.FLOAT) internalFormat = _gl.RG32F;
  13590. if (glType === _gl.HALF_FLOAT) internalFormat = _gl.RG16F;
  13591. if (glType === _gl.UNSIGNED_BYTE) internalFormat = _gl.RG8;
  13592. }
  13593. if (glFormat === _gl.RGBA) {
  13594. if (glType === _gl.FLOAT) internalFormat = _gl.RGBA32F;
  13595. if (glType === _gl.HALF_FLOAT) internalFormat = _gl.RGBA16F;
  13596. if (glType === _gl.UNSIGNED_BYTE) internalFormat = encoding === sRGBEncoding && forceLinearEncoding === false ? _gl.SRGB8_ALPHA8 : _gl.RGBA8;
  13597. if (glType === _gl.UNSIGNED_SHORT_4_4_4_4) internalFormat = _gl.RGBA4;
  13598. if (glType === _gl.UNSIGNED_SHORT_5_5_5_1) internalFormat = _gl.RGB5_A1;
  13599. }
  13600. if (internalFormat === _gl.R16F || internalFormat === _gl.R32F || internalFormat === _gl.RG16F || internalFormat === _gl.RG32F || internalFormat === _gl.RGBA16F || internalFormat === _gl.RGBA32F) {
  13601. extensions.get('EXT_color_buffer_float');
  13602. }
  13603. return internalFormat;
  13604. }
  13605. function getMipLevels(texture, image, supportsMips) {
  13606. if (textureNeedsGenerateMipmaps(texture, supportsMips) === true || texture.isFramebufferTexture && texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter) {
  13607. return Math.log2(Math.max(image.width, image.height)) + 1;
  13608. } else if (texture.mipmaps !== undefined && texture.mipmaps.length > 0) {
  13609. // user-defined mipmaps
  13610. return texture.mipmaps.length;
  13611. } else if (texture.isCompressedTexture && Array.isArray(texture.image)) {
  13612. return image.mipmaps.length;
  13613. } else {
  13614. // texture without mipmaps (only base level)
  13615. return 1;
  13616. }
  13617. } // Fallback filters for non-power-of-2 textures
  13618. function filterFallback(f) {
  13619. if (f === NearestFilter || f === NearestMipmapNearestFilter || f === NearestMipmapLinearFilter) {
  13620. return _gl.NEAREST;
  13621. }
  13622. return _gl.LINEAR;
  13623. } //
  13624. function onTextureDispose(event) {
  13625. const texture = event.target;
  13626. texture.removeEventListener('dispose', onTextureDispose);
  13627. deallocateTexture(texture);
  13628. if (texture.isVideoTexture) {
  13629. _videoTextures.delete(texture);
  13630. }
  13631. }
  13632. function onRenderTargetDispose(event) {
  13633. const renderTarget = event.target;
  13634. renderTarget.removeEventListener('dispose', onRenderTargetDispose);
  13635. deallocateRenderTarget(renderTarget);
  13636. } //
  13637. function deallocateTexture(texture) {
  13638. const textureProperties = properties.get(texture);
  13639. if (textureProperties.__webglInit === undefined) return; // check if it's necessary to remove the WebGLTexture object
  13640. const source = texture.source;
  13641. const webglTextures = _sources.get(source);
  13642. if (webglTextures) {
  13643. const webglTexture = webglTextures[textureProperties.__cacheKey];
  13644. webglTexture.usedTimes--; // the WebGLTexture object is not used anymore, remove it
  13645. if (webglTexture.usedTimes === 0) {
  13646. deleteTexture(texture);
  13647. } // remove the weak map entry if no WebGLTexture uses the source anymore
  13648. if (Object.keys(webglTextures).length === 0) {
  13649. _sources.delete(source);
  13650. }
  13651. }
  13652. properties.remove(texture);
  13653. }
  13654. function deleteTexture(texture) {
  13655. const textureProperties = properties.get(texture);
  13656. _gl.deleteTexture(textureProperties.__webglTexture);
  13657. const source = texture.source;
  13658. const webglTextures = _sources.get(source);
  13659. delete webglTextures[textureProperties.__cacheKey];
  13660. info.memory.textures--;
  13661. }
  13662. function deallocateRenderTarget(renderTarget) {
  13663. const texture = renderTarget.texture;
  13664. const renderTargetProperties = properties.get(renderTarget);
  13665. const textureProperties = properties.get(texture);
  13666. if (textureProperties.__webglTexture !== undefined) {
  13667. _gl.deleteTexture(textureProperties.__webglTexture);
  13668. info.memory.textures--;
  13669. }
  13670. if (renderTarget.depthTexture) {
  13671. renderTarget.depthTexture.dispose();
  13672. }
  13673. if (renderTarget.isWebGLCubeRenderTarget) {
  13674. for (let i = 0; i < 6; i++) {
  13675. _gl.deleteFramebuffer(renderTargetProperties.__webglFramebuffer[i]);
  13676. if (renderTargetProperties.__webglDepthbuffer) _gl.deleteRenderbuffer(renderTargetProperties.__webglDepthbuffer[i]);
  13677. }
  13678. } else {
  13679. _gl.deleteFramebuffer(renderTargetProperties.__webglFramebuffer);
  13680. if (renderTargetProperties.__webglDepthbuffer) _gl.deleteRenderbuffer(renderTargetProperties.__webglDepthbuffer);
  13681. if (renderTargetProperties.__webglMultisampledFramebuffer) _gl.deleteFramebuffer(renderTargetProperties.__webglMultisampledFramebuffer);
  13682. if (renderTargetProperties.__webglColorRenderbuffer) {
  13683. for (let i = 0; i < renderTargetProperties.__webglColorRenderbuffer.length; i++) {
  13684. if (renderTargetProperties.__webglColorRenderbuffer[i]) _gl.deleteRenderbuffer(renderTargetProperties.__webglColorRenderbuffer[i]);
  13685. }
  13686. }
  13687. if (renderTargetProperties.__webglDepthRenderbuffer) _gl.deleteRenderbuffer(renderTargetProperties.__webglDepthRenderbuffer);
  13688. }
  13689. if (renderTarget.isWebGLMultipleRenderTargets) {
  13690. for (let i = 0, il = texture.length; i < il; i++) {
  13691. const attachmentProperties = properties.get(texture[i]);
  13692. if (attachmentProperties.__webglTexture) {
  13693. _gl.deleteTexture(attachmentProperties.__webglTexture);
  13694. info.memory.textures--;
  13695. }
  13696. properties.remove(texture[i]);
  13697. }
  13698. }
  13699. properties.remove(texture);
  13700. properties.remove(renderTarget);
  13701. } //
  13702. let textureUnits = 0;
  13703. function resetTextureUnits() {
  13704. textureUnits = 0;
  13705. }
  13706. function allocateTextureUnit() {
  13707. const textureUnit = textureUnits;
  13708. if (textureUnit >= maxTextures) {
  13709. console.warn('THREE.WebGLTextures: Trying to use ' + textureUnit + ' texture units while this GPU supports only ' + maxTextures);
  13710. }
  13711. textureUnits += 1;
  13712. return textureUnit;
  13713. }
  13714. function getTextureCacheKey(texture) {
  13715. const array = [];
  13716. array.push(texture.wrapS);
  13717. array.push(texture.wrapT);
  13718. array.push(texture.magFilter);
  13719. array.push(texture.minFilter);
  13720. array.push(texture.anisotropy);
  13721. array.push(texture.internalFormat);
  13722. array.push(texture.format);
  13723. array.push(texture.type);
  13724. array.push(texture.generateMipmaps);
  13725. array.push(texture.premultiplyAlpha);
  13726. array.push(texture.flipY);
  13727. array.push(texture.unpackAlignment);
  13728. array.push(texture.encoding);
  13729. return array.join();
  13730. } //
  13731. function setTexture2D(texture, slot) {
  13732. const textureProperties = properties.get(texture);
  13733. if (texture.isVideoTexture) updateVideoTexture(texture);
  13734. if (texture.isRenderTargetTexture === false && texture.version > 0 && textureProperties.__version !== texture.version) {
  13735. const image = texture.image;
  13736. if (image === null) {
  13737. console.warn('THREE.WebGLRenderer: Texture marked for update but no image data found.');
  13738. } else if (image.complete === false) {
  13739. console.warn('THREE.WebGLRenderer: Texture marked for update but image is incomplete');
  13740. } else {
  13741. uploadTexture(textureProperties, texture, slot);
  13742. return;
  13743. }
  13744. }
  13745. state.bindTexture(_gl.TEXTURE_2D, textureProperties.__webglTexture, _gl.TEXTURE0 + slot);
  13746. }
  13747. function setTexture2DArray(texture, slot) {
  13748. const textureProperties = properties.get(texture);
  13749. if (texture.version > 0 && textureProperties.__version !== texture.version) {
  13750. uploadTexture(textureProperties, texture, slot);
  13751. return;
  13752. }
  13753. state.bindTexture(_gl.TEXTURE_2D_ARRAY, textureProperties.__webglTexture, _gl.TEXTURE0 + slot);
  13754. }
  13755. function setTexture3D(texture, slot) {
  13756. const textureProperties = properties.get(texture);
  13757. if (texture.version > 0 && textureProperties.__version !== texture.version) {
  13758. uploadTexture(textureProperties, texture, slot);
  13759. return;
  13760. }
  13761. state.bindTexture(_gl.TEXTURE_3D, textureProperties.__webglTexture, _gl.TEXTURE0 + slot);
  13762. }
  13763. function setTextureCube(texture, slot) {
  13764. const textureProperties = properties.get(texture);
  13765. if (texture.version > 0 && textureProperties.__version !== texture.version) {
  13766. uploadCubeTexture(textureProperties, texture, slot);
  13767. return;
  13768. }
  13769. state.bindTexture(_gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture, _gl.TEXTURE0 + slot);
  13770. }
  13771. const wrappingToGL = {
  13772. [RepeatWrapping]: _gl.REPEAT,
  13773. [ClampToEdgeWrapping]: _gl.CLAMP_TO_EDGE,
  13774. [MirroredRepeatWrapping]: _gl.MIRRORED_REPEAT
  13775. };
  13776. const filterToGL = {
  13777. [NearestFilter]: _gl.NEAREST,
  13778. [NearestMipmapNearestFilter]: _gl.NEAREST_MIPMAP_NEAREST,
  13779. [NearestMipmapLinearFilter]: _gl.NEAREST_MIPMAP_LINEAR,
  13780. [LinearFilter]: _gl.LINEAR,
  13781. [LinearMipmapNearestFilter]: _gl.LINEAR_MIPMAP_NEAREST,
  13782. [LinearMipmapLinearFilter]: _gl.LINEAR_MIPMAP_LINEAR
  13783. };
  13784. function setTextureParameters(textureType, texture, supportsMips) {
  13785. if (supportsMips) {
  13786. _gl.texParameteri(textureType, _gl.TEXTURE_WRAP_S, wrappingToGL[texture.wrapS]);
  13787. _gl.texParameteri(textureType, _gl.TEXTURE_WRAP_T, wrappingToGL[texture.wrapT]);
  13788. if (textureType === _gl.TEXTURE_3D || textureType === _gl.TEXTURE_2D_ARRAY) {
  13789. _gl.texParameteri(textureType, _gl.TEXTURE_WRAP_R, wrappingToGL[texture.wrapR]);
  13790. }
  13791. _gl.texParameteri(textureType, _gl.TEXTURE_MAG_FILTER, filterToGL[texture.magFilter]);
  13792. _gl.texParameteri(textureType, _gl.TEXTURE_MIN_FILTER, filterToGL[texture.minFilter]);
  13793. } else {
  13794. _gl.texParameteri(textureType, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE);
  13795. _gl.texParameteri(textureType, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE);
  13796. if (textureType === _gl.TEXTURE_3D || textureType === _gl.TEXTURE_2D_ARRAY) {
  13797. _gl.texParameteri(textureType, _gl.TEXTURE_WRAP_R, _gl.CLAMP_TO_EDGE);
  13798. }
  13799. if (texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping) {
  13800. console.warn('THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping.');
  13801. }
  13802. _gl.texParameteri(textureType, _gl.TEXTURE_MAG_FILTER, filterFallback(texture.magFilter));
  13803. _gl.texParameteri(textureType, _gl.TEXTURE_MIN_FILTER, filterFallback(texture.minFilter));
  13804. if (texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter) {
  13805. console.warn('THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.');
  13806. }
  13807. }
  13808. if (extensions.has('EXT_texture_filter_anisotropic') === true) {
  13809. const extension = extensions.get('EXT_texture_filter_anisotropic');
  13810. if (texture.type === FloatType && extensions.has('OES_texture_float_linear') === false) return; // verify extension for WebGL 1 and WebGL 2
  13811. if (isWebGL2 === false && texture.type === HalfFloatType && extensions.has('OES_texture_half_float_linear') === false) return; // verify extension for WebGL 1 only
  13812. if (texture.anisotropy > 1 || properties.get(texture).__currentAnisotropy) {
  13813. _gl.texParameterf(textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(texture.anisotropy, capabilities.getMaxAnisotropy()));
  13814. properties.get(texture).__currentAnisotropy = texture.anisotropy;
  13815. }
  13816. }
  13817. }
  13818. function initTexture(textureProperties, texture) {
  13819. let forceUpload = false;
  13820. if (textureProperties.__webglInit === undefined) {
  13821. textureProperties.__webglInit = true;
  13822. texture.addEventListener('dispose', onTextureDispose);
  13823. } // create Source <-> WebGLTextures mapping if necessary
  13824. const source = texture.source;
  13825. let webglTextures = _sources.get(source);
  13826. if (webglTextures === undefined) {
  13827. webglTextures = {};
  13828. _sources.set(source, webglTextures);
  13829. } // check if there is already a WebGLTexture object for the given texture parameters
  13830. const textureCacheKey = getTextureCacheKey(texture);
  13831. if (textureCacheKey !== textureProperties.__cacheKey) {
  13832. // if not, create a new instance of WebGLTexture
  13833. if (webglTextures[textureCacheKey] === undefined) {
  13834. // create new entry
  13835. webglTextures[textureCacheKey] = {
  13836. texture: _gl.createTexture(),
  13837. usedTimes: 0
  13838. };
  13839. info.memory.textures++; // when a new instance of WebGLTexture was created, a texture upload is required
  13840. // even if the image contents are identical
  13841. forceUpload = true;
  13842. }
  13843. webglTextures[textureCacheKey].usedTimes++; // every time the texture cache key changes, it's necessary to check if an instance of
  13844. // WebGLTexture can be deleted in order to avoid a memory leak.
  13845. const webglTexture = webglTextures[textureProperties.__cacheKey];
  13846. if (webglTexture !== undefined) {
  13847. webglTextures[textureProperties.__cacheKey].usedTimes--;
  13848. if (webglTexture.usedTimes === 0) {
  13849. deleteTexture(texture);
  13850. }
  13851. } // store references to cache key and WebGLTexture object
  13852. textureProperties.__cacheKey = textureCacheKey;
  13853. textureProperties.__webglTexture = webglTextures[textureCacheKey].texture;
  13854. }
  13855. return forceUpload;
  13856. }
  13857. function uploadTexture(textureProperties, texture, slot) {
  13858. let textureType = _gl.TEXTURE_2D;
  13859. if (texture.isDataArrayTexture) textureType = _gl.TEXTURE_2D_ARRAY;
  13860. if (texture.isData3DTexture) textureType = _gl.TEXTURE_3D;
  13861. const forceUpload = initTexture(textureProperties, texture);
  13862. const source = texture.source;
  13863. state.bindTexture(textureType, textureProperties.__webglTexture, _gl.TEXTURE0 + slot);
  13864. const sourceProperties = properties.get(source);
  13865. if (source.version !== sourceProperties.__version || forceUpload === true) {
  13866. state.activeTexture(_gl.TEXTURE0 + slot);
  13867. _gl.pixelStorei(_gl.UNPACK_FLIP_Y_WEBGL, texture.flipY);
  13868. _gl.pixelStorei(_gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha);
  13869. _gl.pixelStorei(_gl.UNPACK_ALIGNMENT, texture.unpackAlignment);
  13870. _gl.pixelStorei(_gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, _gl.NONE);
  13871. const needsPowerOfTwo = textureNeedsPowerOfTwo(texture) && isPowerOfTwo$1(texture.image) === false;
  13872. let image = resizeImage(texture.image, needsPowerOfTwo, false, maxTextureSize);
  13873. image = verifyColorSpace(texture, image);
  13874. const supportsMips = isPowerOfTwo$1(image) || isWebGL2,
  13875. glFormat = utils.convert(texture.format, texture.encoding);
  13876. let glType = utils.convert(texture.type),
  13877. glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType, texture.encoding, texture.isVideoTexture);
  13878. setTextureParameters(textureType, texture, supportsMips);
  13879. let mipmap;
  13880. const mipmaps = texture.mipmaps;
  13881. const useTexStorage = isWebGL2 && texture.isVideoTexture !== true;
  13882. const allocateMemory = sourceProperties.__version === undefined || forceUpload === true;
  13883. const levels = getMipLevels(texture, image, supportsMips);
  13884. if (texture.isDepthTexture) {
  13885. // populate depth texture with dummy data
  13886. glInternalFormat = _gl.DEPTH_COMPONENT;
  13887. if (isWebGL2) {
  13888. if (texture.type === FloatType) {
  13889. glInternalFormat = _gl.DEPTH_COMPONENT32F;
  13890. } else if (texture.type === UnsignedIntType) {
  13891. glInternalFormat = _gl.DEPTH_COMPONENT24;
  13892. } else if (texture.type === UnsignedInt248Type) {
  13893. glInternalFormat = _gl.DEPTH24_STENCIL8;
  13894. } else {
  13895. glInternalFormat = _gl.DEPTH_COMPONENT16; // WebGL2 requires sized internalformat for glTexImage2D
  13896. }
  13897. } else {
  13898. if (texture.type === FloatType) {
  13899. console.error('WebGLRenderer: Floating point depth texture requires WebGL2.');
  13900. }
  13901. } // validation checks for WebGL 1
  13902. if (texture.format === DepthFormat && glInternalFormat === _gl.DEPTH_COMPONENT) {
  13903. // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  13904. // DEPTH_COMPONENT and type is not UNSIGNED_SHORT or UNSIGNED_INT
  13905. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  13906. if (texture.type !== UnsignedShortType && texture.type !== UnsignedIntType) {
  13907. console.warn('THREE.WebGLRenderer: Use UnsignedShortType or UnsignedIntType for DepthFormat DepthTexture.');
  13908. texture.type = UnsignedIntType;
  13909. glType = utils.convert(texture.type);
  13910. }
  13911. }
  13912. if (texture.format === DepthStencilFormat && glInternalFormat === _gl.DEPTH_COMPONENT) {
  13913. // Depth stencil textures need the DEPTH_STENCIL internal format
  13914. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  13915. glInternalFormat = _gl.DEPTH_STENCIL; // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  13916. // DEPTH_STENCIL and type is not UNSIGNED_INT_24_8_WEBGL.
  13917. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  13918. if (texture.type !== UnsignedInt248Type) {
  13919. console.warn('THREE.WebGLRenderer: Use UnsignedInt248Type for DepthStencilFormat DepthTexture.');
  13920. texture.type = UnsignedInt248Type;
  13921. glType = utils.convert(texture.type);
  13922. }
  13923. } //
  13924. if (allocateMemory) {
  13925. if (useTexStorage) {
  13926. state.texStorage2D(_gl.TEXTURE_2D, 1, glInternalFormat, image.width, image.height);
  13927. } else {
  13928. state.texImage2D(_gl.TEXTURE_2D, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, null);
  13929. }
  13930. }
  13931. } else if (texture.isDataTexture) {
  13932. // use manually created mipmaps if available
  13933. // if there are no manual mipmaps
  13934. // set 0 level mipmap and then use GL to generate other mipmap levels
  13935. if (mipmaps.length > 0 && supportsMips) {
  13936. if (useTexStorage && allocateMemory) {
  13937. state.texStorage2D(_gl.TEXTURE_2D, levels, glInternalFormat, mipmaps[0].width, mipmaps[0].height);
  13938. }
  13939. for (let i = 0, il = mipmaps.length; i < il; i++) {
  13940. mipmap = mipmaps[i];
  13941. if (useTexStorage) {
  13942. state.texSubImage2D(_gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data);
  13943. } else {
  13944. state.texImage2D(_gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data);
  13945. }
  13946. }
  13947. texture.generateMipmaps = false;
  13948. } else {
  13949. if (useTexStorage) {
  13950. if (allocateMemory) {
  13951. state.texStorage2D(_gl.TEXTURE_2D, levels, glInternalFormat, image.width, image.height);
  13952. }
  13953. state.texSubImage2D(_gl.TEXTURE_2D, 0, 0, 0, image.width, image.height, glFormat, glType, image.data);
  13954. } else {
  13955. state.texImage2D(_gl.TEXTURE_2D, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, image.data);
  13956. }
  13957. }
  13958. } else if (texture.isCompressedTexture) {
  13959. if (useTexStorage && allocateMemory) {
  13960. state.texStorage2D(_gl.TEXTURE_2D, levels, glInternalFormat, mipmaps[0].width, mipmaps[0].height);
  13961. }
  13962. for (let i = 0, il = mipmaps.length; i < il; i++) {
  13963. mipmap = mipmaps[i];
  13964. if (texture.format !== RGBAFormat) {
  13965. if (glFormat !== null) {
  13966. if (useTexStorage) {
  13967. state.compressedTexSubImage2D(_gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data);
  13968. } else {
  13969. state.compressedTexImage2D(_gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data);
  13970. }
  13971. } else {
  13972. console.warn('THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()');
  13973. }
  13974. } else {
  13975. if (useTexStorage) {
  13976. state.texSubImage2D(_gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data);
  13977. } else {
  13978. state.texImage2D(_gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data);
  13979. }
  13980. }
  13981. }
  13982. } else if (texture.isDataArrayTexture) {
  13983. if (useTexStorage) {
  13984. if (allocateMemory) {
  13985. state.texStorage3D(_gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, image.width, image.height, image.depth);
  13986. }
  13987. state.texSubImage3D(_gl.TEXTURE_2D_ARRAY, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data);
  13988. } else {
  13989. state.texImage3D(_gl.TEXTURE_2D_ARRAY, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data);
  13990. }
  13991. } else if (texture.isData3DTexture) {
  13992. if (useTexStorage) {
  13993. if (allocateMemory) {
  13994. state.texStorage3D(_gl.TEXTURE_3D, levels, glInternalFormat, image.width, image.height, image.depth);
  13995. }
  13996. state.texSubImage3D(_gl.TEXTURE_3D, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data);
  13997. } else {
  13998. state.texImage3D(_gl.TEXTURE_3D, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data);
  13999. }
  14000. } else if (texture.isFramebufferTexture) {
  14001. if (allocateMemory) {
  14002. if (useTexStorage) {
  14003. state.texStorage2D(_gl.TEXTURE_2D, levels, glInternalFormat, image.width, image.height);
  14004. } else {
  14005. let width = image.width,
  14006. height = image.height;
  14007. for (let i = 0; i < levels; i++) {
  14008. state.texImage2D(_gl.TEXTURE_2D, i, glInternalFormat, width, height, 0, glFormat, glType, null);
  14009. width >>= 1;
  14010. height >>= 1;
  14011. }
  14012. }
  14013. }
  14014. } else {
  14015. // regular Texture (image, video, canvas)
  14016. // use manually created mipmaps if available
  14017. // if there are no manual mipmaps
  14018. // set 0 level mipmap and then use GL to generate other mipmap levels
  14019. if (mipmaps.length > 0 && supportsMips) {
  14020. if (useTexStorage && allocateMemory) {
  14021. state.texStorage2D(_gl.TEXTURE_2D, levels, glInternalFormat, mipmaps[0].width, mipmaps[0].height);
  14022. }
  14023. for (let i = 0, il = mipmaps.length; i < il; i++) {
  14024. mipmap = mipmaps[i];
  14025. if (useTexStorage) {
  14026. state.texSubImage2D(_gl.TEXTURE_2D, i, 0, 0, glFormat, glType, mipmap);
  14027. } else {
  14028. state.texImage2D(_gl.TEXTURE_2D, i, glInternalFormat, glFormat, glType, mipmap);
  14029. }
  14030. }
  14031. texture.generateMipmaps = false;
  14032. } else {
  14033. if (useTexStorage) {
  14034. if (allocateMemory) {
  14035. state.texStorage2D(_gl.TEXTURE_2D, levels, glInternalFormat, image.width, image.height);
  14036. }
  14037. state.texSubImage2D(_gl.TEXTURE_2D, 0, 0, 0, glFormat, glType, image);
  14038. } else {
  14039. state.texImage2D(_gl.TEXTURE_2D, 0, glInternalFormat, glFormat, glType, image);
  14040. }
  14041. }
  14042. }
  14043. if (textureNeedsGenerateMipmaps(texture, supportsMips)) {
  14044. generateMipmap(textureType);
  14045. }
  14046. sourceProperties.__version = source.version;
  14047. if (texture.onUpdate) texture.onUpdate(texture);
  14048. }
  14049. textureProperties.__version = texture.version;
  14050. }
  14051. function uploadCubeTexture(textureProperties, texture, slot) {
  14052. if (texture.image.length !== 6) return;
  14053. const forceUpload = initTexture(textureProperties, texture);
  14054. const source = texture.source;
  14055. state.bindTexture(_gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture, _gl.TEXTURE0 + slot);
  14056. const sourceProperties = properties.get(source);
  14057. if (source.version !== sourceProperties.__version || forceUpload === true) {
  14058. state.activeTexture(_gl.TEXTURE0 + slot);
  14059. _gl.pixelStorei(_gl.UNPACK_FLIP_Y_WEBGL, texture.flipY);
  14060. _gl.pixelStorei(_gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha);
  14061. _gl.pixelStorei(_gl.UNPACK_ALIGNMENT, texture.unpackAlignment);
  14062. _gl.pixelStorei(_gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, _gl.NONE);
  14063. const isCompressed = texture.isCompressedTexture || texture.image[0].isCompressedTexture;
  14064. const isDataTexture = texture.image[0] && texture.image[0].isDataTexture;
  14065. const cubeImage = [];
  14066. for (let i = 0; i < 6; i++) {
  14067. if (!isCompressed && !isDataTexture) {
  14068. cubeImage[i] = resizeImage(texture.image[i], false, true, maxCubemapSize);
  14069. } else {
  14070. cubeImage[i] = isDataTexture ? texture.image[i].image : texture.image[i];
  14071. }
  14072. cubeImage[i] = verifyColorSpace(texture, cubeImage[i]);
  14073. }
  14074. const image = cubeImage[0],
  14075. supportsMips = isPowerOfTwo$1(image) || isWebGL2,
  14076. glFormat = utils.convert(texture.format, texture.encoding),
  14077. glType = utils.convert(texture.type),
  14078. glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType, texture.encoding);
  14079. const useTexStorage = isWebGL2 && texture.isVideoTexture !== true;
  14080. const allocateMemory = sourceProperties.__version === undefined || forceUpload === true;
  14081. let levels = getMipLevels(texture, image, supportsMips);
  14082. setTextureParameters(_gl.TEXTURE_CUBE_MAP, texture, supportsMips);
  14083. let mipmaps;
  14084. if (isCompressed) {
  14085. if (useTexStorage && allocateMemory) {
  14086. state.texStorage2D(_gl.TEXTURE_CUBE_MAP, levels, glInternalFormat, image.width, image.height);
  14087. }
  14088. for (let i = 0; i < 6; i++) {
  14089. mipmaps = cubeImage[i].mipmaps;
  14090. for (let j = 0; j < mipmaps.length; j++) {
  14091. const mipmap = mipmaps[j];
  14092. if (texture.format !== RGBAFormat) {
  14093. if (glFormat !== null) {
  14094. if (useTexStorage) {
  14095. state.compressedTexSubImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data);
  14096. } else {
  14097. state.compressedTexImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data);
  14098. }
  14099. } else {
  14100. console.warn('THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()');
  14101. }
  14102. } else {
  14103. if (useTexStorage) {
  14104. state.texSubImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data);
  14105. } else {
  14106. state.texImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data);
  14107. }
  14108. }
  14109. }
  14110. }
  14111. } else {
  14112. mipmaps = texture.mipmaps;
  14113. if (useTexStorage && allocateMemory) {
  14114. // TODO: Uniformly handle mipmap definitions
  14115. // Normal textures and compressed cube textures define base level + mips with their mipmap array
  14116. // Uncompressed cube textures use their mipmap array only for mips (no base level)
  14117. if (mipmaps.length > 0) levels++;
  14118. state.texStorage2D(_gl.TEXTURE_CUBE_MAP, levels, glInternalFormat, cubeImage[0].width, cubeImage[0].height);
  14119. }
  14120. for (let i = 0; i < 6; i++) {
  14121. if (isDataTexture) {
  14122. if (useTexStorage) {
  14123. state.texSubImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, cubeImage[i].width, cubeImage[i].height, glFormat, glType, cubeImage[i].data);
  14124. } else {
  14125. state.texImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glInternalFormat, cubeImage[i].width, cubeImage[i].height, 0, glFormat, glType, cubeImage[i].data);
  14126. }
  14127. for (let j = 0; j < mipmaps.length; j++) {
  14128. const mipmap = mipmaps[j];
  14129. const mipmapImage = mipmap.image[i].image;
  14130. if (useTexStorage) {
  14131. state.texSubImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, 0, 0, mipmapImage.width, mipmapImage.height, glFormat, glType, mipmapImage.data);
  14132. } else {
  14133. state.texImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, glInternalFormat, mipmapImage.width, mipmapImage.height, 0, glFormat, glType, mipmapImage.data);
  14134. }
  14135. }
  14136. } else {
  14137. if (useTexStorage) {
  14138. state.texSubImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, glFormat, glType, cubeImage[i]);
  14139. } else {
  14140. state.texImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glInternalFormat, glFormat, glType, cubeImage[i]);
  14141. }
  14142. for (let j = 0; j < mipmaps.length; j++) {
  14143. const mipmap = mipmaps[j];
  14144. if (useTexStorage) {
  14145. state.texSubImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, 0, 0, glFormat, glType, mipmap.image[i]);
  14146. } else {
  14147. state.texImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, glInternalFormat, glFormat, glType, mipmap.image[i]);
  14148. }
  14149. }
  14150. }
  14151. }
  14152. }
  14153. if (textureNeedsGenerateMipmaps(texture, supportsMips)) {
  14154. // We assume images for cube map have the same size.
  14155. generateMipmap(_gl.TEXTURE_CUBE_MAP);
  14156. }
  14157. sourceProperties.__version = source.version;
  14158. if (texture.onUpdate) texture.onUpdate(texture);
  14159. }
  14160. textureProperties.__version = texture.version;
  14161. } // Render targets
  14162. // Setup storage for target texture and bind it to correct framebuffer
  14163. function setupFrameBufferTexture(framebuffer, renderTarget, texture, attachment, textureTarget) {
  14164. const glFormat = utils.convert(texture.format, texture.encoding);
  14165. const glType = utils.convert(texture.type);
  14166. const glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType, texture.encoding);
  14167. const renderTargetProperties = properties.get(renderTarget);
  14168. if (!renderTargetProperties.__hasExternalTextures) {
  14169. if (textureTarget === _gl.TEXTURE_3D || textureTarget === _gl.TEXTURE_2D_ARRAY) {
  14170. state.texImage3D(textureTarget, 0, glInternalFormat, renderTarget.width, renderTarget.height, renderTarget.depth, 0, glFormat, glType, null);
  14171. } else {
  14172. state.texImage2D(textureTarget, 0, glInternalFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null);
  14173. }
  14174. }
  14175. state.bindFramebuffer(_gl.FRAMEBUFFER, framebuffer);
  14176. if (useMultisampledRTT(renderTarget)) {
  14177. multisampledRTTExt.framebufferTexture2DMultisampleEXT(_gl.FRAMEBUFFER, attachment, textureTarget, properties.get(texture).__webglTexture, 0, getRenderTargetSamples(renderTarget));
  14178. } else {
  14179. _gl.framebufferTexture2D(_gl.FRAMEBUFFER, attachment, textureTarget, properties.get(texture).__webglTexture, 0);
  14180. }
  14181. state.bindFramebuffer(_gl.FRAMEBUFFER, null);
  14182. } // Setup storage for internal depth/stencil buffers and bind to correct framebuffer
  14183. function setupRenderBufferStorage(renderbuffer, renderTarget, isMultisample) {
  14184. _gl.bindRenderbuffer(_gl.RENDERBUFFER, renderbuffer);
  14185. if (renderTarget.depthBuffer && !renderTarget.stencilBuffer) {
  14186. let glInternalFormat = _gl.DEPTH_COMPONENT16;
  14187. if (isMultisample || useMultisampledRTT(renderTarget)) {
  14188. const depthTexture = renderTarget.depthTexture;
  14189. if (depthTexture && depthTexture.isDepthTexture) {
  14190. if (depthTexture.type === FloatType) {
  14191. glInternalFormat = _gl.DEPTH_COMPONENT32F;
  14192. } else if (depthTexture.type === UnsignedIntType) {
  14193. glInternalFormat = _gl.DEPTH_COMPONENT24;
  14194. }
  14195. }
  14196. const samples = getRenderTargetSamples(renderTarget);
  14197. if (useMultisampledRTT(renderTarget)) {
  14198. multisampledRTTExt.renderbufferStorageMultisampleEXT(_gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height);
  14199. } else {
  14200. _gl.renderbufferStorageMultisample(_gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height);
  14201. }
  14202. } else {
  14203. _gl.renderbufferStorage(_gl.RENDERBUFFER, glInternalFormat, renderTarget.width, renderTarget.height);
  14204. }
  14205. _gl.framebufferRenderbuffer(_gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer);
  14206. } else if (renderTarget.depthBuffer && renderTarget.stencilBuffer) {
  14207. const samples = getRenderTargetSamples(renderTarget);
  14208. if (isMultisample && useMultisampledRTT(renderTarget) === false) {
  14209. _gl.renderbufferStorageMultisample(_gl.RENDERBUFFER, samples, _gl.DEPTH24_STENCIL8, renderTarget.width, renderTarget.height);
  14210. } else if (useMultisampledRTT(renderTarget)) {
  14211. multisampledRTTExt.renderbufferStorageMultisampleEXT(_gl.RENDERBUFFER, samples, _gl.DEPTH24_STENCIL8, renderTarget.width, renderTarget.height);
  14212. } else {
  14213. _gl.renderbufferStorage(_gl.RENDERBUFFER, _gl.DEPTH_STENCIL, renderTarget.width, renderTarget.height);
  14214. }
  14215. _gl.framebufferRenderbuffer(_gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer);
  14216. } else {
  14217. const textures = renderTarget.isWebGLMultipleRenderTargets === true ? renderTarget.texture : [renderTarget.texture];
  14218. for (let i = 0; i < textures.length; i++) {
  14219. const texture = textures[i];
  14220. const glFormat = utils.convert(texture.format, texture.encoding);
  14221. const glType = utils.convert(texture.type);
  14222. const glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType, texture.encoding);
  14223. const samples = getRenderTargetSamples(renderTarget);
  14224. if (isMultisample && useMultisampledRTT(renderTarget) === false) {
  14225. _gl.renderbufferStorageMultisample(_gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height);
  14226. } else if (useMultisampledRTT(renderTarget)) {
  14227. multisampledRTTExt.renderbufferStorageMultisampleEXT(_gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height);
  14228. } else {
  14229. _gl.renderbufferStorage(_gl.RENDERBUFFER, glInternalFormat, renderTarget.width, renderTarget.height);
  14230. }
  14231. }
  14232. }
  14233. _gl.bindRenderbuffer(_gl.RENDERBUFFER, null);
  14234. } // Setup resources for a Depth Texture for a FBO (needs an extension)
  14235. function setupDepthTexture(framebuffer, renderTarget) {
  14236. const isCube = renderTarget && renderTarget.isWebGLCubeRenderTarget;
  14237. if (isCube) throw new Error('Depth Texture with cube render targets is not supported');
  14238. state.bindFramebuffer(_gl.FRAMEBUFFER, framebuffer);
  14239. if (!(renderTarget.depthTexture && renderTarget.depthTexture.isDepthTexture)) {
  14240. throw new Error('renderTarget.depthTexture must be an instance of THREE.DepthTexture');
  14241. } // upload an empty depth texture with framebuffer size
  14242. if (!properties.get(renderTarget.depthTexture).__webglTexture || renderTarget.depthTexture.image.width !== renderTarget.width || renderTarget.depthTexture.image.height !== renderTarget.height) {
  14243. renderTarget.depthTexture.image.width = renderTarget.width;
  14244. renderTarget.depthTexture.image.height = renderTarget.height;
  14245. renderTarget.depthTexture.needsUpdate = true;
  14246. }
  14247. setTexture2D(renderTarget.depthTexture, 0);
  14248. const webglDepthTexture = properties.get(renderTarget.depthTexture).__webglTexture;
  14249. const samples = getRenderTargetSamples(renderTarget);
  14250. if (renderTarget.depthTexture.format === DepthFormat) {
  14251. if (useMultisampledRTT(renderTarget)) {
  14252. multisampledRTTExt.framebufferTexture2DMultisampleEXT(_gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0, samples);
  14253. } else {
  14254. _gl.framebufferTexture2D(_gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0);
  14255. }
  14256. } else if (renderTarget.depthTexture.format === DepthStencilFormat) {
  14257. if (useMultisampledRTT(renderTarget)) {
  14258. multisampledRTTExt.framebufferTexture2DMultisampleEXT(_gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0, samples);
  14259. } else {
  14260. _gl.framebufferTexture2D(_gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0);
  14261. }
  14262. } else {
  14263. throw new Error('Unknown depthTexture format');
  14264. }
  14265. } // Setup GL resources for a non-texture depth buffer
  14266. function setupDepthRenderbuffer(renderTarget) {
  14267. const renderTargetProperties = properties.get(renderTarget);
  14268. const isCube = renderTarget.isWebGLCubeRenderTarget === true;
  14269. if (renderTarget.depthTexture && !renderTargetProperties.__autoAllocateDepthBuffer) {
  14270. if (isCube) throw new Error('target.depthTexture not supported in Cube render targets');
  14271. setupDepthTexture(renderTargetProperties.__webglFramebuffer, renderTarget);
  14272. } else {
  14273. if (isCube) {
  14274. renderTargetProperties.__webglDepthbuffer = [];
  14275. for (let i = 0; i < 6; i++) {
  14276. state.bindFramebuffer(_gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer[i]);
  14277. renderTargetProperties.__webglDepthbuffer[i] = _gl.createRenderbuffer();
  14278. setupRenderBufferStorage(renderTargetProperties.__webglDepthbuffer[i], renderTarget, false);
  14279. }
  14280. } else {
  14281. state.bindFramebuffer(_gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer);
  14282. renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer();
  14283. setupRenderBufferStorage(renderTargetProperties.__webglDepthbuffer, renderTarget, false);
  14284. }
  14285. }
  14286. state.bindFramebuffer(_gl.FRAMEBUFFER, null);
  14287. } // rebind framebuffer with external textures
  14288. function rebindTextures(renderTarget, colorTexture, depthTexture) {
  14289. const renderTargetProperties = properties.get(renderTarget);
  14290. if (colorTexture !== undefined) {
  14291. setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer, renderTarget, renderTarget.texture, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D);
  14292. }
  14293. if (depthTexture !== undefined) {
  14294. setupDepthRenderbuffer(renderTarget);
  14295. }
  14296. } // Set up GL resources for the render target
  14297. function setupRenderTarget(renderTarget) {
  14298. const texture = renderTarget.texture;
  14299. const renderTargetProperties = properties.get(renderTarget);
  14300. const textureProperties = properties.get(texture);
  14301. renderTarget.addEventListener('dispose', onRenderTargetDispose);
  14302. if (renderTarget.isWebGLMultipleRenderTargets !== true) {
  14303. if (textureProperties.__webglTexture === undefined) {
  14304. textureProperties.__webglTexture = _gl.createTexture();
  14305. }
  14306. textureProperties.__version = texture.version;
  14307. info.memory.textures++;
  14308. }
  14309. const isCube = renderTarget.isWebGLCubeRenderTarget === true;
  14310. const isMultipleRenderTargets = renderTarget.isWebGLMultipleRenderTargets === true;
  14311. const supportsMips = isPowerOfTwo$1(renderTarget) || isWebGL2; // Setup framebuffer
  14312. if (isCube) {
  14313. renderTargetProperties.__webglFramebuffer = [];
  14314. for (let i = 0; i < 6; i++) {
  14315. renderTargetProperties.__webglFramebuffer[i] = _gl.createFramebuffer();
  14316. }
  14317. } else {
  14318. renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer();
  14319. if (isMultipleRenderTargets) {
  14320. if (capabilities.drawBuffers) {
  14321. const textures = renderTarget.texture;
  14322. for (let i = 0, il = textures.length; i < il; i++) {
  14323. const attachmentProperties = properties.get(textures[i]);
  14324. if (attachmentProperties.__webglTexture === undefined) {
  14325. attachmentProperties.__webglTexture = _gl.createTexture();
  14326. info.memory.textures++;
  14327. }
  14328. }
  14329. } else {
  14330. console.warn('THREE.WebGLRenderer: WebGLMultipleRenderTargets can only be used with WebGL2 or WEBGL_draw_buffers extension.');
  14331. }
  14332. }
  14333. if (isWebGL2 && renderTarget.samples > 0 && useMultisampledRTT(renderTarget) === false) {
  14334. const textures = isMultipleRenderTargets ? texture : [texture];
  14335. renderTargetProperties.__webglMultisampledFramebuffer = _gl.createFramebuffer();
  14336. renderTargetProperties.__webglColorRenderbuffer = [];
  14337. state.bindFramebuffer(_gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer);
  14338. for (let i = 0; i < textures.length; i++) {
  14339. const texture = textures[i];
  14340. renderTargetProperties.__webglColorRenderbuffer[i] = _gl.createRenderbuffer();
  14341. _gl.bindRenderbuffer(_gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[i]);
  14342. const glFormat = utils.convert(texture.format, texture.encoding);
  14343. const glType = utils.convert(texture.type);
  14344. const glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType, texture.encoding, renderTarget.isXRRenderTarget === true);
  14345. const samples = getRenderTargetSamples(renderTarget);
  14346. _gl.renderbufferStorageMultisample(_gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height);
  14347. _gl.framebufferRenderbuffer(_gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[i]);
  14348. }
  14349. _gl.bindRenderbuffer(_gl.RENDERBUFFER, null);
  14350. if (renderTarget.depthBuffer) {
  14351. renderTargetProperties.__webglDepthRenderbuffer = _gl.createRenderbuffer();
  14352. setupRenderBufferStorage(renderTargetProperties.__webglDepthRenderbuffer, renderTarget, true);
  14353. }
  14354. state.bindFramebuffer(_gl.FRAMEBUFFER, null);
  14355. }
  14356. } // Setup color buffer
  14357. if (isCube) {
  14358. state.bindTexture(_gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture);
  14359. setTextureParameters(_gl.TEXTURE_CUBE_MAP, texture, supportsMips);
  14360. for (let i = 0; i < 6; i++) {
  14361. setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer[i], renderTarget, texture, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i);
  14362. }
  14363. if (textureNeedsGenerateMipmaps(texture, supportsMips)) {
  14364. generateMipmap(_gl.TEXTURE_CUBE_MAP);
  14365. }
  14366. state.unbindTexture();
  14367. } else if (isMultipleRenderTargets) {
  14368. const textures = renderTarget.texture;
  14369. for (let i = 0, il = textures.length; i < il; i++) {
  14370. const attachment = textures[i];
  14371. const attachmentProperties = properties.get(attachment);
  14372. state.bindTexture(_gl.TEXTURE_2D, attachmentProperties.__webglTexture);
  14373. setTextureParameters(_gl.TEXTURE_2D, attachment, supportsMips);
  14374. setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer, renderTarget, attachment, _gl.COLOR_ATTACHMENT0 + i, _gl.TEXTURE_2D);
  14375. if (textureNeedsGenerateMipmaps(attachment, supportsMips)) {
  14376. generateMipmap(_gl.TEXTURE_2D);
  14377. }
  14378. }
  14379. state.unbindTexture();
  14380. } else {
  14381. let glTextureType = _gl.TEXTURE_2D;
  14382. if (renderTarget.isWebGL3DRenderTarget || renderTarget.isWebGLArrayRenderTarget) {
  14383. if (isWebGL2) {
  14384. glTextureType = renderTarget.isWebGL3DRenderTarget ? _gl.TEXTURE_3D : _gl.TEXTURE_2D_ARRAY;
  14385. } else {
  14386. console.error('THREE.WebGLTextures: THREE.Data3DTexture and THREE.DataArrayTexture only supported with WebGL2.');
  14387. }
  14388. }
  14389. state.bindTexture(glTextureType, textureProperties.__webglTexture);
  14390. setTextureParameters(glTextureType, texture, supportsMips);
  14391. setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer, renderTarget, texture, _gl.COLOR_ATTACHMENT0, glTextureType);
  14392. if (textureNeedsGenerateMipmaps(texture, supportsMips)) {
  14393. generateMipmap(glTextureType);
  14394. }
  14395. state.unbindTexture();
  14396. } // Setup depth and stencil buffers
  14397. if (renderTarget.depthBuffer) {
  14398. setupDepthRenderbuffer(renderTarget);
  14399. }
  14400. }
  14401. function updateRenderTargetMipmap(renderTarget) {
  14402. const supportsMips = isPowerOfTwo$1(renderTarget) || isWebGL2;
  14403. const textures = renderTarget.isWebGLMultipleRenderTargets === true ? renderTarget.texture : [renderTarget.texture];
  14404. for (let i = 0, il = textures.length; i < il; i++) {
  14405. const texture = textures[i];
  14406. if (textureNeedsGenerateMipmaps(texture, supportsMips)) {
  14407. const target = renderTarget.isWebGLCubeRenderTarget ? _gl.TEXTURE_CUBE_MAP : _gl.TEXTURE_2D;
  14408. const webglTexture = properties.get(texture).__webglTexture;
  14409. state.bindTexture(target, webglTexture);
  14410. generateMipmap(target);
  14411. state.unbindTexture();
  14412. }
  14413. }
  14414. }
  14415. function updateMultisampleRenderTarget(renderTarget) {
  14416. if (isWebGL2 && renderTarget.samples > 0 && useMultisampledRTT(renderTarget) === false) {
  14417. const textures = renderTarget.isWebGLMultipleRenderTargets ? renderTarget.texture : [renderTarget.texture];
  14418. const width = renderTarget.width;
  14419. const height = renderTarget.height;
  14420. let mask = _gl.COLOR_BUFFER_BIT;
  14421. const invalidationArray = [];
  14422. const depthStyle = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT;
  14423. const renderTargetProperties = properties.get(renderTarget);
  14424. const isMultipleRenderTargets = renderTarget.isWebGLMultipleRenderTargets === true; // If MRT we need to remove FBO attachments
  14425. if (isMultipleRenderTargets) {
  14426. for (let i = 0; i < textures.length; i++) {
  14427. state.bindFramebuffer(_gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer);
  14428. _gl.framebufferRenderbuffer(_gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.RENDERBUFFER, null);
  14429. state.bindFramebuffer(_gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer);
  14430. _gl.framebufferTexture2D(_gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.TEXTURE_2D, null, 0);
  14431. }
  14432. }
  14433. state.bindFramebuffer(_gl.READ_FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer);
  14434. state.bindFramebuffer(_gl.DRAW_FRAMEBUFFER, renderTargetProperties.__webglFramebuffer);
  14435. for (let i = 0; i < textures.length; i++) {
  14436. invalidationArray.push(_gl.COLOR_ATTACHMENT0 + i);
  14437. if (renderTarget.depthBuffer) {
  14438. invalidationArray.push(depthStyle);
  14439. }
  14440. const ignoreDepthValues = renderTargetProperties.__ignoreDepthValues !== undefined ? renderTargetProperties.__ignoreDepthValues : false;
  14441. if (ignoreDepthValues === false) {
  14442. if (renderTarget.depthBuffer) mask |= _gl.DEPTH_BUFFER_BIT;
  14443. if (renderTarget.stencilBuffer) mask |= _gl.STENCIL_BUFFER_BIT;
  14444. }
  14445. if (isMultipleRenderTargets) {
  14446. _gl.framebufferRenderbuffer(_gl.READ_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[i]);
  14447. }
  14448. if (ignoreDepthValues === true) {
  14449. _gl.invalidateFramebuffer(_gl.READ_FRAMEBUFFER, [depthStyle]);
  14450. _gl.invalidateFramebuffer(_gl.DRAW_FRAMEBUFFER, [depthStyle]);
  14451. }
  14452. if (isMultipleRenderTargets) {
  14453. const webglTexture = properties.get(textures[i]).__webglTexture;
  14454. _gl.framebufferTexture2D(_gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, webglTexture, 0);
  14455. }
  14456. _gl.blitFramebuffer(0, 0, width, height, 0, 0, width, height, mask, _gl.NEAREST);
  14457. if (supportsInvalidateFramebuffer) {
  14458. _gl.invalidateFramebuffer(_gl.READ_FRAMEBUFFER, invalidationArray);
  14459. }
  14460. }
  14461. state.bindFramebuffer(_gl.READ_FRAMEBUFFER, null);
  14462. state.bindFramebuffer(_gl.DRAW_FRAMEBUFFER, null); // If MRT since pre-blit we removed the FBO we need to reconstruct the attachments
  14463. if (isMultipleRenderTargets) {
  14464. for (let i = 0; i < textures.length; i++) {
  14465. state.bindFramebuffer(_gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer);
  14466. _gl.framebufferRenderbuffer(_gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[i]);
  14467. const webglTexture = properties.get(textures[i]).__webglTexture;
  14468. state.bindFramebuffer(_gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer);
  14469. _gl.framebufferTexture2D(_gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.TEXTURE_2D, webglTexture, 0);
  14470. }
  14471. }
  14472. state.bindFramebuffer(_gl.DRAW_FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer);
  14473. }
  14474. }
  14475. function getRenderTargetSamples(renderTarget) {
  14476. return Math.min(maxSamples, renderTarget.samples);
  14477. }
  14478. function useMultisampledRTT(renderTarget) {
  14479. const renderTargetProperties = properties.get(renderTarget);
  14480. return isWebGL2 && renderTarget.samples > 0 && extensions.has('WEBGL_multisampled_render_to_texture') === true && renderTargetProperties.__useRenderToTexture !== false;
  14481. }
  14482. function updateVideoTexture(texture) {
  14483. const frame = info.render.frame; // Check the last frame we updated the VideoTexture
  14484. if (_videoTextures.get(texture) !== frame) {
  14485. _videoTextures.set(texture, frame);
  14486. texture.update();
  14487. }
  14488. }
  14489. function verifyColorSpace(texture, image) {
  14490. const encoding = texture.encoding;
  14491. const format = texture.format;
  14492. const type = texture.type;
  14493. if (texture.isCompressedTexture === true || texture.isVideoTexture === true || texture.format === _SRGBAFormat) return image;
  14494. if (encoding !== LinearEncoding) {
  14495. // sRGB
  14496. if (encoding === sRGBEncoding) {
  14497. if (isWebGL2 === false) {
  14498. // in WebGL 1, try to use EXT_sRGB extension and unsized formats
  14499. if (extensions.has('EXT_sRGB') === true && format === RGBAFormat) {
  14500. texture.format = _SRGBAFormat; // it's not possible to generate mips in WebGL 1 with this extension
  14501. texture.minFilter = LinearFilter;
  14502. texture.generateMipmaps = false;
  14503. } else {
  14504. // slow fallback (CPU decode)
  14505. image = ImageUtils.sRGBToLinear(image);
  14506. }
  14507. } else {
  14508. // in WebGL 2 uncompressed textures can only be sRGB encoded if they have the RGBA8 format
  14509. if (format !== RGBAFormat || type !== UnsignedByteType) {
  14510. console.warn('THREE.WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType.');
  14511. }
  14512. }
  14513. } else {
  14514. console.error('THREE.WebGLTextures: Unsupported texture encoding:', encoding);
  14515. }
  14516. }
  14517. return image;
  14518. } //
  14519. this.allocateTextureUnit = allocateTextureUnit;
  14520. this.resetTextureUnits = resetTextureUnits;
  14521. this.setTexture2D = setTexture2D;
  14522. this.setTexture2DArray = setTexture2DArray;
  14523. this.setTexture3D = setTexture3D;
  14524. this.setTextureCube = setTextureCube;
  14525. this.rebindTextures = rebindTextures;
  14526. this.setupRenderTarget = setupRenderTarget;
  14527. this.updateRenderTargetMipmap = updateRenderTargetMipmap;
  14528. this.updateMultisampleRenderTarget = updateMultisampleRenderTarget;
  14529. this.setupDepthRenderbuffer = setupDepthRenderbuffer;
  14530. this.setupFrameBufferTexture = setupFrameBufferTexture;
  14531. this.useMultisampledRTT = useMultisampledRTT;
  14532. }
  14533. function WebGLUtils(gl, extensions, capabilities) {
  14534. const isWebGL2 = capabilities.isWebGL2;
  14535. function convert(p, encoding = null) {
  14536. let extension;
  14537. if (p === UnsignedByteType) return gl.UNSIGNED_BYTE;
  14538. if (p === UnsignedShort4444Type) return gl.UNSIGNED_SHORT_4_4_4_4;
  14539. if (p === UnsignedShort5551Type) return gl.UNSIGNED_SHORT_5_5_5_1;
  14540. if (p === ByteType) return gl.BYTE;
  14541. if (p === ShortType) return gl.SHORT;
  14542. if (p === UnsignedShortType) return gl.UNSIGNED_SHORT;
  14543. if (p === IntType) return gl.INT;
  14544. if (p === UnsignedIntType) return gl.UNSIGNED_INT;
  14545. if (p === FloatType) return gl.FLOAT;
  14546. if (p === HalfFloatType) {
  14547. if (isWebGL2) return gl.HALF_FLOAT;
  14548. extension = extensions.get('OES_texture_half_float');
  14549. if (extension !== null) {
  14550. return extension.HALF_FLOAT_OES;
  14551. } else {
  14552. return null;
  14553. }
  14554. }
  14555. if (p === AlphaFormat) return gl.ALPHA;
  14556. if (p === RGBAFormat) return gl.RGBA;
  14557. if (p === LuminanceFormat) return gl.LUMINANCE;
  14558. if (p === LuminanceAlphaFormat) return gl.LUMINANCE_ALPHA;
  14559. if (p === DepthFormat) return gl.DEPTH_COMPONENT;
  14560. if (p === DepthStencilFormat) return gl.DEPTH_STENCIL;
  14561. if (p === RedFormat) return gl.RED; // @deprecated since r137
  14562. if (p === RGBFormat) {
  14563. console.warn('THREE.WebGLRenderer: THREE.RGBFormat has been removed. Use THREE.RGBAFormat instead. https://github.com/mrdoob/three.js/pull/23228');
  14564. return gl.RGBA;
  14565. } // WebGL 1 sRGB fallback
  14566. if (p === _SRGBAFormat) {
  14567. extension = extensions.get('EXT_sRGB');
  14568. if (extension !== null) {
  14569. return extension.SRGB_ALPHA_EXT;
  14570. } else {
  14571. return null;
  14572. }
  14573. } // WebGL2 formats.
  14574. if (p === RedIntegerFormat) return gl.RED_INTEGER;
  14575. if (p === RGFormat) return gl.RG;
  14576. if (p === RGIntegerFormat) return gl.RG_INTEGER;
  14577. if (p === RGBAIntegerFormat) return gl.RGBA_INTEGER; // S3TC
  14578. if (p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format) {
  14579. if (encoding === sRGBEncoding) {
  14580. extension = extensions.get('WEBGL_compressed_texture_s3tc_srgb');
  14581. if (extension !== null) {
  14582. if (p === RGB_S3TC_DXT1_Format) return extension.COMPRESSED_SRGB_S3TC_DXT1_EXT;
  14583. if (p === RGBA_S3TC_DXT1_Format) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;
  14584. if (p === RGBA_S3TC_DXT3_Format) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;
  14585. if (p === RGBA_S3TC_DXT5_Format) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT;
  14586. } else {
  14587. return null;
  14588. }
  14589. } else {
  14590. extension = extensions.get('WEBGL_compressed_texture_s3tc');
  14591. if (extension !== null) {
  14592. if (p === RGB_S3TC_DXT1_Format) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  14593. if (p === RGBA_S3TC_DXT1_Format) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  14594. if (p === RGBA_S3TC_DXT3_Format) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  14595. if (p === RGBA_S3TC_DXT5_Format) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  14596. } else {
  14597. return null;
  14598. }
  14599. }
  14600. } // PVRTC
  14601. if (p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format) {
  14602. extension = extensions.get('WEBGL_compressed_texture_pvrtc');
  14603. if (extension !== null) {
  14604. if (p === RGB_PVRTC_4BPPV1_Format) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  14605. if (p === RGB_PVRTC_2BPPV1_Format) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  14606. if (p === RGBA_PVRTC_4BPPV1_Format) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  14607. if (p === RGBA_PVRTC_2BPPV1_Format) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  14608. } else {
  14609. return null;
  14610. }
  14611. } // ETC1
  14612. if (p === RGB_ETC1_Format) {
  14613. extension = extensions.get('WEBGL_compressed_texture_etc1');
  14614. if (extension !== null) {
  14615. return extension.COMPRESSED_RGB_ETC1_WEBGL;
  14616. } else {
  14617. return null;
  14618. }
  14619. } // ETC2
  14620. if (p === RGB_ETC2_Format || p === RGBA_ETC2_EAC_Format) {
  14621. extension = extensions.get('WEBGL_compressed_texture_etc');
  14622. if (extension !== null) {
  14623. if (p === RGB_ETC2_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB8_ETC2 : extension.COMPRESSED_RGB8_ETC2;
  14624. if (p === RGBA_ETC2_EAC_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC : extension.COMPRESSED_RGBA8_ETC2_EAC;
  14625. } else {
  14626. return null;
  14627. }
  14628. } // ASTC
  14629. 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) {
  14630. extension = extensions.get('WEBGL_compressed_texture_astc');
  14631. if (extension !== null) {
  14632. if (p === RGBA_ASTC_4x4_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR : extension.COMPRESSED_RGBA_ASTC_4x4_KHR;
  14633. if (p === RGBA_ASTC_5x4_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR : extension.COMPRESSED_RGBA_ASTC_5x4_KHR;
  14634. if (p === RGBA_ASTC_5x5_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR : extension.COMPRESSED_RGBA_ASTC_5x5_KHR;
  14635. if (p === RGBA_ASTC_6x5_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR : extension.COMPRESSED_RGBA_ASTC_6x5_KHR;
  14636. if (p === RGBA_ASTC_6x6_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR : extension.COMPRESSED_RGBA_ASTC_6x6_KHR;
  14637. if (p === RGBA_ASTC_8x5_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR : extension.COMPRESSED_RGBA_ASTC_8x5_KHR;
  14638. if (p === RGBA_ASTC_8x6_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR : extension.COMPRESSED_RGBA_ASTC_8x6_KHR;
  14639. if (p === RGBA_ASTC_8x8_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR : extension.COMPRESSED_RGBA_ASTC_8x8_KHR;
  14640. if (p === RGBA_ASTC_10x5_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR : extension.COMPRESSED_RGBA_ASTC_10x5_KHR;
  14641. if (p === RGBA_ASTC_10x6_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR : extension.COMPRESSED_RGBA_ASTC_10x6_KHR;
  14642. if (p === RGBA_ASTC_10x8_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR : extension.COMPRESSED_RGBA_ASTC_10x8_KHR;
  14643. if (p === RGBA_ASTC_10x10_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR : extension.COMPRESSED_RGBA_ASTC_10x10_KHR;
  14644. if (p === RGBA_ASTC_12x10_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR : extension.COMPRESSED_RGBA_ASTC_12x10_KHR;
  14645. if (p === RGBA_ASTC_12x12_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR : extension.COMPRESSED_RGBA_ASTC_12x12_KHR;
  14646. } else {
  14647. return null;
  14648. }
  14649. } // BPTC
  14650. if (p === RGBA_BPTC_Format) {
  14651. extension = extensions.get('EXT_texture_compression_bptc');
  14652. if (extension !== null) {
  14653. if (p === RGBA_BPTC_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT : extension.COMPRESSED_RGBA_BPTC_UNORM_EXT;
  14654. } else {
  14655. return null;
  14656. }
  14657. } //
  14658. if (p === UnsignedInt248Type) {
  14659. if (isWebGL2) return gl.UNSIGNED_INT_24_8;
  14660. extension = extensions.get('WEBGL_depth_texture');
  14661. if (extension !== null) {
  14662. return extension.UNSIGNED_INT_24_8_WEBGL;
  14663. } else {
  14664. return null;
  14665. }
  14666. } // if "p" can't be resolved, assume the user defines a WebGL constant as a string (fallback/workaround for packed RGB formats)
  14667. return gl[p] !== undefined ? gl[p] : null;
  14668. }
  14669. return {
  14670. convert: convert
  14671. };
  14672. }
  14673. class ArrayCamera extends PerspectiveCamera {
  14674. constructor(array = []) {
  14675. super();
  14676. this.isArrayCamera = true;
  14677. this.cameras = array;
  14678. }
  14679. }
  14680. class Group extends Object3D {
  14681. constructor() {
  14682. super();
  14683. this.isGroup = true;
  14684. this.type = 'Group';
  14685. }
  14686. }
  14687. const _moveEvent = {
  14688. type: 'move'
  14689. };
  14690. class WebXRController {
  14691. constructor() {
  14692. this._targetRay = null;
  14693. this._grip = null;
  14694. this._hand = null;
  14695. }
  14696. getHandSpace() {
  14697. if (this._hand === null) {
  14698. this._hand = new Group();
  14699. this._hand.matrixAutoUpdate = false;
  14700. this._hand.visible = false;
  14701. this._hand.joints = {};
  14702. this._hand.inputState = {
  14703. pinching: false
  14704. };
  14705. }
  14706. return this._hand;
  14707. }
  14708. getTargetRaySpace() {
  14709. if (this._targetRay === null) {
  14710. this._targetRay = new Group();
  14711. this._targetRay.matrixAutoUpdate = false;
  14712. this._targetRay.visible = false;
  14713. this._targetRay.hasLinearVelocity = false;
  14714. this._targetRay.linearVelocity = new Vector3();
  14715. this._targetRay.hasAngularVelocity = false;
  14716. this._targetRay.angularVelocity = new Vector3();
  14717. }
  14718. return this._targetRay;
  14719. }
  14720. getGripSpace() {
  14721. if (this._grip === null) {
  14722. this._grip = new Group();
  14723. this._grip.matrixAutoUpdate = false;
  14724. this._grip.visible = false;
  14725. this._grip.hasLinearVelocity = false;
  14726. this._grip.linearVelocity = new Vector3();
  14727. this._grip.hasAngularVelocity = false;
  14728. this._grip.angularVelocity = new Vector3();
  14729. }
  14730. return this._grip;
  14731. }
  14732. dispatchEvent(event) {
  14733. if (this._targetRay !== null) {
  14734. this._targetRay.dispatchEvent(event);
  14735. }
  14736. if (this._grip !== null) {
  14737. this._grip.dispatchEvent(event);
  14738. }
  14739. if (this._hand !== null) {
  14740. this._hand.dispatchEvent(event);
  14741. }
  14742. return this;
  14743. }
  14744. disconnect(inputSource) {
  14745. this.dispatchEvent({
  14746. type: 'disconnected',
  14747. data: inputSource
  14748. });
  14749. if (this._targetRay !== null) {
  14750. this._targetRay.visible = false;
  14751. }
  14752. if (this._grip !== null) {
  14753. this._grip.visible = false;
  14754. }
  14755. if (this._hand !== null) {
  14756. this._hand.visible = false;
  14757. }
  14758. return this;
  14759. }
  14760. update(inputSource, frame, referenceSpace) {
  14761. let inputPose = null;
  14762. let gripPose = null;
  14763. let handPose = null;
  14764. const targetRay = this._targetRay;
  14765. const grip = this._grip;
  14766. const hand = this._hand;
  14767. if (inputSource && frame.session.visibilityState !== 'visible-blurred') {
  14768. if (hand && inputSource.hand) {
  14769. handPose = true;
  14770. for (const inputjoint of inputSource.hand.values()) {
  14771. // Update the joints groups with the XRJoint poses
  14772. const jointPose = frame.getJointPose(inputjoint, referenceSpace);
  14773. if (hand.joints[inputjoint.jointName] === undefined) {
  14774. // The transform of this joint will be updated with the joint pose on each frame
  14775. const joint = new Group();
  14776. joint.matrixAutoUpdate = false;
  14777. joint.visible = false;
  14778. hand.joints[inputjoint.jointName] = joint; // ??
  14779. hand.add(joint);
  14780. }
  14781. const joint = hand.joints[inputjoint.jointName];
  14782. if (jointPose !== null) {
  14783. joint.matrix.fromArray(jointPose.transform.matrix);
  14784. joint.matrix.decompose(joint.position, joint.rotation, joint.scale);
  14785. joint.jointRadius = jointPose.radius;
  14786. }
  14787. joint.visible = jointPose !== null;
  14788. } // Custom events
  14789. // Check pinchz
  14790. const indexTip = hand.joints['index-finger-tip'];
  14791. const thumbTip = hand.joints['thumb-tip'];
  14792. const distance = indexTip.position.distanceTo(thumbTip.position);
  14793. const distanceToPinch = 0.02;
  14794. const threshold = 0.005;
  14795. if (hand.inputState.pinching && distance > distanceToPinch + threshold) {
  14796. hand.inputState.pinching = false;
  14797. this.dispatchEvent({
  14798. type: 'pinchend',
  14799. handedness: inputSource.handedness,
  14800. target: this
  14801. });
  14802. } else if (!hand.inputState.pinching && distance <= distanceToPinch - threshold) {
  14803. hand.inputState.pinching = true;
  14804. this.dispatchEvent({
  14805. type: 'pinchstart',
  14806. handedness: inputSource.handedness,
  14807. target: this
  14808. });
  14809. }
  14810. } else {
  14811. if (grip !== null && inputSource.gripSpace) {
  14812. gripPose = frame.getPose(inputSource.gripSpace, referenceSpace);
  14813. if (gripPose !== null) {
  14814. grip.matrix.fromArray(gripPose.transform.matrix);
  14815. grip.matrix.decompose(grip.position, grip.rotation, grip.scale);
  14816. if (gripPose.linearVelocity) {
  14817. grip.hasLinearVelocity = true;
  14818. grip.linearVelocity.copy(gripPose.linearVelocity);
  14819. } else {
  14820. grip.hasLinearVelocity = false;
  14821. }
  14822. if (gripPose.angularVelocity) {
  14823. grip.hasAngularVelocity = true;
  14824. grip.angularVelocity.copy(gripPose.angularVelocity);
  14825. } else {
  14826. grip.hasAngularVelocity = false;
  14827. }
  14828. }
  14829. }
  14830. }
  14831. if (targetRay !== null) {
  14832. inputPose = frame.getPose(inputSource.targetRaySpace, referenceSpace); // Some runtimes (namely Vive Cosmos with Vive OpenXR Runtime) have only grip space and ray space is equal to it
  14833. if (inputPose === null && gripPose !== null) {
  14834. inputPose = gripPose;
  14835. }
  14836. if (inputPose !== null) {
  14837. targetRay.matrix.fromArray(inputPose.transform.matrix);
  14838. targetRay.matrix.decompose(targetRay.position, targetRay.rotation, targetRay.scale);
  14839. if (inputPose.linearVelocity) {
  14840. targetRay.hasLinearVelocity = true;
  14841. targetRay.linearVelocity.copy(inputPose.linearVelocity);
  14842. } else {
  14843. targetRay.hasLinearVelocity = false;
  14844. }
  14845. if (inputPose.angularVelocity) {
  14846. targetRay.hasAngularVelocity = true;
  14847. targetRay.angularVelocity.copy(inputPose.angularVelocity);
  14848. } else {
  14849. targetRay.hasAngularVelocity = false;
  14850. }
  14851. this.dispatchEvent(_moveEvent);
  14852. }
  14853. }
  14854. }
  14855. if (targetRay !== null) {
  14856. targetRay.visible = inputPose !== null;
  14857. }
  14858. if (grip !== null) {
  14859. grip.visible = gripPose !== null;
  14860. }
  14861. if (hand !== null) {
  14862. hand.visible = handPose !== null;
  14863. }
  14864. return this;
  14865. }
  14866. }
  14867. class DepthTexture extends Texture {
  14868. constructor(width, height, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, format) {
  14869. format = format !== undefined ? format : DepthFormat;
  14870. if (format !== DepthFormat && format !== DepthStencilFormat) {
  14871. throw new Error('DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat');
  14872. }
  14873. if (type === undefined && format === DepthFormat) type = UnsignedIntType;
  14874. if (type === undefined && format === DepthStencilFormat) type = UnsignedInt248Type;
  14875. super(null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy);
  14876. this.isDepthTexture = true;
  14877. this.image = {
  14878. width: width,
  14879. height: height
  14880. };
  14881. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  14882. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  14883. this.flipY = false;
  14884. this.generateMipmaps = false;
  14885. }
  14886. }
  14887. class WebXRManager extends EventDispatcher {
  14888. constructor(renderer, gl) {
  14889. super();
  14890. const scope = this;
  14891. let session = null;
  14892. let framebufferScaleFactor = 1.0;
  14893. let referenceSpace = null;
  14894. let referenceSpaceType = 'local-floor';
  14895. let customReferenceSpace = null;
  14896. let pose = null;
  14897. let glBinding = null;
  14898. let glProjLayer = null;
  14899. let glBaseLayer = null;
  14900. let xrFrame = null;
  14901. const attributes = gl.getContextAttributes();
  14902. let initialRenderTarget = null;
  14903. let newRenderTarget = null;
  14904. const controllers = [];
  14905. const controllerInputSources = []; //
  14906. const cameraL = new PerspectiveCamera();
  14907. cameraL.layers.enable(1);
  14908. cameraL.viewport = new Vector4();
  14909. const cameraR = new PerspectiveCamera();
  14910. cameraR.layers.enable(2);
  14911. cameraR.viewport = new Vector4();
  14912. const cameras = [cameraL, cameraR];
  14913. const cameraVR = new ArrayCamera();
  14914. cameraVR.layers.enable(1);
  14915. cameraVR.layers.enable(2);
  14916. let _currentDepthNear = null;
  14917. let _currentDepthFar = null; //
  14918. this.cameraAutoUpdate = true;
  14919. this.enabled = false;
  14920. this.isPresenting = false;
  14921. this.getController = function (index) {
  14922. let controller = controllers[index];
  14923. if (controller === undefined) {
  14924. controller = new WebXRController();
  14925. controllers[index] = controller;
  14926. }
  14927. return controller.getTargetRaySpace();
  14928. };
  14929. this.getControllerGrip = function (index) {
  14930. let controller = controllers[index];
  14931. if (controller === undefined) {
  14932. controller = new WebXRController();
  14933. controllers[index] = controller;
  14934. }
  14935. return controller.getGripSpace();
  14936. };
  14937. this.getHand = function (index) {
  14938. let controller = controllers[index];
  14939. if (controller === undefined) {
  14940. controller = new WebXRController();
  14941. controllers[index] = controller;
  14942. }
  14943. return controller.getHandSpace();
  14944. }; //
  14945. function onSessionEvent(event) {
  14946. const controllerIndex = controllerInputSources.indexOf(event.inputSource);
  14947. if (controllerIndex === -1) {
  14948. return;
  14949. }
  14950. const controller = controllers[controllerIndex];
  14951. if (controller !== undefined) {
  14952. controller.dispatchEvent({
  14953. type: event.type,
  14954. data: event.inputSource
  14955. });
  14956. }
  14957. }
  14958. function onSessionEnd() {
  14959. session.removeEventListener('select', onSessionEvent);
  14960. session.removeEventListener('selectstart', onSessionEvent);
  14961. session.removeEventListener('selectend', onSessionEvent);
  14962. session.removeEventListener('squeeze', onSessionEvent);
  14963. session.removeEventListener('squeezestart', onSessionEvent);
  14964. session.removeEventListener('squeezeend', onSessionEvent);
  14965. session.removeEventListener('end', onSessionEnd);
  14966. session.removeEventListener('inputsourceschange', onInputSourcesChange);
  14967. for (let i = 0; i < controllers.length; i++) {
  14968. const inputSource = controllerInputSources[i];
  14969. if (inputSource === null) continue;
  14970. controllerInputSources[i] = null;
  14971. controllers[i].disconnect(inputSource);
  14972. }
  14973. _currentDepthNear = null;
  14974. _currentDepthFar = null; // restore framebuffer/rendering state
  14975. renderer.setRenderTarget(initialRenderTarget);
  14976. glBaseLayer = null;
  14977. glProjLayer = null;
  14978. glBinding = null;
  14979. session = null;
  14980. newRenderTarget = null; //
  14981. animation.stop();
  14982. scope.isPresenting = false;
  14983. scope.dispatchEvent({
  14984. type: 'sessionend'
  14985. });
  14986. }
  14987. this.setFramebufferScaleFactor = function (value) {
  14988. framebufferScaleFactor = value;
  14989. if (scope.isPresenting === true) {
  14990. console.warn('THREE.WebXRManager: Cannot change framebuffer scale while presenting.');
  14991. }
  14992. };
  14993. this.setReferenceSpaceType = function (value) {
  14994. referenceSpaceType = value;
  14995. if (scope.isPresenting === true) {
  14996. console.warn('THREE.WebXRManager: Cannot change reference space type while presenting.');
  14997. }
  14998. };
  14999. this.getReferenceSpace = function () {
  15000. return customReferenceSpace || referenceSpace;
  15001. };
  15002. this.setReferenceSpace = function (space) {
  15003. customReferenceSpace = space;
  15004. };
  15005. this.getBaseLayer = function () {
  15006. return glProjLayer !== null ? glProjLayer : glBaseLayer;
  15007. };
  15008. this.getBinding = function () {
  15009. return glBinding;
  15010. };
  15011. this.getFrame = function () {
  15012. return xrFrame;
  15013. };
  15014. this.getSession = function () {
  15015. return session;
  15016. };
  15017. this.setSession = async function (value) {
  15018. session = value;
  15019. if (session !== null) {
  15020. initialRenderTarget = renderer.getRenderTarget();
  15021. session.addEventListener('select', onSessionEvent);
  15022. session.addEventListener('selectstart', onSessionEvent);
  15023. session.addEventListener('selectend', onSessionEvent);
  15024. session.addEventListener('squeeze', onSessionEvent);
  15025. session.addEventListener('squeezestart', onSessionEvent);
  15026. session.addEventListener('squeezeend', onSessionEvent);
  15027. session.addEventListener('end', onSessionEnd);
  15028. session.addEventListener('inputsourceschange', onInputSourcesChange);
  15029. if (attributes.xrCompatible !== true) {
  15030. await gl.makeXRCompatible();
  15031. }
  15032. if (session.renderState.layers === undefined || renderer.capabilities.isWebGL2 === false) {
  15033. const layerInit = {
  15034. antialias: session.renderState.layers === undefined ? attributes.antialias : true,
  15035. alpha: attributes.alpha,
  15036. depth: attributes.depth,
  15037. stencil: attributes.stencil,
  15038. framebufferScaleFactor: framebufferScaleFactor
  15039. };
  15040. glBaseLayer = new XRWebGLLayer(session, gl, layerInit);
  15041. session.updateRenderState({
  15042. baseLayer: glBaseLayer
  15043. });
  15044. newRenderTarget = new WebGLRenderTarget(glBaseLayer.framebufferWidth, glBaseLayer.framebufferHeight, {
  15045. format: RGBAFormat,
  15046. type: UnsignedByteType,
  15047. encoding: renderer.outputEncoding,
  15048. stencilBuffer: attributes.stencil
  15049. });
  15050. } else {
  15051. let depthFormat = null;
  15052. let depthType = null;
  15053. let glDepthFormat = null;
  15054. if (attributes.depth) {
  15055. glDepthFormat = attributes.stencil ? gl.DEPTH24_STENCIL8 : gl.DEPTH_COMPONENT24;
  15056. depthFormat = attributes.stencil ? DepthStencilFormat : DepthFormat;
  15057. depthType = attributes.stencil ? UnsignedInt248Type : UnsignedIntType;
  15058. }
  15059. const projectionlayerInit = {
  15060. colorFormat: gl.RGBA8,
  15061. depthFormat: glDepthFormat,
  15062. scaleFactor: framebufferScaleFactor
  15063. };
  15064. glBinding = new XRWebGLBinding(session, gl);
  15065. glProjLayer = glBinding.createProjectionLayer(projectionlayerInit);
  15066. session.updateRenderState({
  15067. layers: [glProjLayer]
  15068. });
  15069. newRenderTarget = new WebGLRenderTarget(glProjLayer.textureWidth, glProjLayer.textureHeight, {
  15070. format: RGBAFormat,
  15071. type: UnsignedByteType,
  15072. depthTexture: new DepthTexture(glProjLayer.textureWidth, glProjLayer.textureHeight, depthType, undefined, undefined, undefined, undefined, undefined, undefined, depthFormat),
  15073. stencilBuffer: attributes.stencil,
  15074. encoding: renderer.outputEncoding,
  15075. samples: attributes.antialias ? 4 : 0
  15076. });
  15077. const renderTargetProperties = renderer.properties.get(newRenderTarget);
  15078. renderTargetProperties.__ignoreDepthValues = glProjLayer.ignoreDepthValues;
  15079. }
  15080. newRenderTarget.isXRRenderTarget = true; // TODO Remove this when possible, see #23278
  15081. // Set foveation to maximum.
  15082. this.setFoveation(1.0);
  15083. customReferenceSpace = null;
  15084. referenceSpace = await session.requestReferenceSpace(referenceSpaceType);
  15085. animation.setContext(session);
  15086. animation.start();
  15087. scope.isPresenting = true;
  15088. scope.dispatchEvent({
  15089. type: 'sessionstart'
  15090. });
  15091. }
  15092. };
  15093. function onInputSourcesChange(event) {
  15094. // Notify disconnected
  15095. for (let i = 0; i < event.removed.length; i++) {
  15096. const inputSource = event.removed[i];
  15097. const index = controllerInputSources.indexOf(inputSource);
  15098. if (index >= 0) {
  15099. controllerInputSources[index] = null;
  15100. controllers[index].dispatchEvent({
  15101. type: 'disconnected',
  15102. data: inputSource
  15103. });
  15104. }
  15105. } // Notify connected
  15106. for (let i = 0; i < event.added.length; i++) {
  15107. const inputSource = event.added[i];
  15108. let controllerIndex = controllerInputSources.indexOf(inputSource);
  15109. if (controllerIndex === -1) {
  15110. // Assign input source a controller that currently has no input source
  15111. for (let i = 0; i < controllers.length; i++) {
  15112. if (i >= controllerInputSources.length) {
  15113. controllerInputSources.push(inputSource);
  15114. controllerIndex = i;
  15115. break;
  15116. } else if (controllerInputSources[i] === null) {
  15117. controllerInputSources[i] = inputSource;
  15118. controllerIndex = i;
  15119. break;
  15120. }
  15121. } // If all controllers do currently receive input we ignore new ones
  15122. if (controllerIndex === -1) break;
  15123. }
  15124. const controller = controllers[controllerIndex];
  15125. if (controller) {
  15126. controller.dispatchEvent({
  15127. type: 'connected',
  15128. data: inputSource
  15129. });
  15130. }
  15131. }
  15132. } //
  15133. const cameraLPos = new Vector3();
  15134. const cameraRPos = new Vector3();
  15135. /**
  15136. * Assumes 2 cameras that are parallel and share an X-axis, and that
  15137. * the cameras' projection and world matrices have already been set.
  15138. * And that near and far planes are identical for both cameras.
  15139. * Visualization of this technique: https://computergraphics.stackexchange.com/a/4765
  15140. */
  15141. function setProjectionFromUnion(camera, cameraL, cameraR) {
  15142. cameraLPos.setFromMatrixPosition(cameraL.matrixWorld);
  15143. cameraRPos.setFromMatrixPosition(cameraR.matrixWorld);
  15144. const ipd = cameraLPos.distanceTo(cameraRPos);
  15145. const projL = cameraL.projectionMatrix.elements;
  15146. const projR = cameraR.projectionMatrix.elements; // VR systems will have identical far and near planes, and
  15147. // most likely identical top and bottom frustum extents.
  15148. // Use the left camera for these values.
  15149. const near = projL[14] / (projL[10] - 1);
  15150. const far = projL[14] / (projL[10] + 1);
  15151. const topFov = (projL[9] + 1) / projL[5];
  15152. const bottomFov = (projL[9] - 1) / projL[5];
  15153. const leftFov = (projL[8] - 1) / projL[0];
  15154. const rightFov = (projR[8] + 1) / projR[0];
  15155. const left = near * leftFov;
  15156. const right = near * rightFov; // Calculate the new camera's position offset from the
  15157. // left camera. xOffset should be roughly half `ipd`.
  15158. const zOffset = ipd / (-leftFov + rightFov);
  15159. const xOffset = zOffset * -leftFov; // TODO: Better way to apply this offset?
  15160. cameraL.matrixWorld.decompose(camera.position, camera.quaternion, camera.scale);
  15161. camera.translateX(xOffset);
  15162. camera.translateZ(zOffset);
  15163. camera.matrixWorld.compose(camera.position, camera.quaternion, camera.scale);
  15164. camera.matrixWorldInverse.copy(camera.matrixWorld).invert(); // Find the union of the frustum values of the cameras and scale
  15165. // the values so that the near plane's position does not change in world space,
  15166. // although must now be relative to the new union camera.
  15167. const near2 = near + zOffset;
  15168. const far2 = far + zOffset;
  15169. const left2 = left - xOffset;
  15170. const right2 = right + (ipd - xOffset);
  15171. const top2 = topFov * far / far2 * near2;
  15172. const bottom2 = bottomFov * far / far2 * near2;
  15173. camera.projectionMatrix.makePerspective(left2, right2, top2, bottom2, near2, far2);
  15174. }
  15175. function updateCamera(camera, parent) {
  15176. if (parent === null) {
  15177. camera.matrixWorld.copy(camera.matrix);
  15178. } else {
  15179. camera.matrixWorld.multiplyMatrices(parent.matrixWorld, camera.matrix);
  15180. }
  15181. camera.matrixWorldInverse.copy(camera.matrixWorld).invert();
  15182. }
  15183. this.updateCamera = function (camera) {
  15184. if (session === null) return;
  15185. cameraVR.near = cameraR.near = cameraL.near = camera.near;
  15186. cameraVR.far = cameraR.far = cameraL.far = camera.far;
  15187. if (_currentDepthNear !== cameraVR.near || _currentDepthFar !== cameraVR.far) {
  15188. // Note that the new renderState won't apply until the next frame. See #18320
  15189. session.updateRenderState({
  15190. depthNear: cameraVR.near,
  15191. depthFar: cameraVR.far
  15192. });
  15193. _currentDepthNear = cameraVR.near;
  15194. _currentDepthFar = cameraVR.far;
  15195. }
  15196. const parent = camera.parent;
  15197. const cameras = cameraVR.cameras;
  15198. updateCamera(cameraVR, parent);
  15199. for (let i = 0; i < cameras.length; i++) {
  15200. updateCamera(cameras[i], parent);
  15201. }
  15202. cameraVR.matrixWorld.decompose(cameraVR.position, cameraVR.quaternion, cameraVR.scale); // update user camera and its children
  15203. camera.matrix.copy(cameraVR.matrix);
  15204. camera.matrix.decompose(camera.position, camera.quaternion, camera.scale);
  15205. const children = camera.children;
  15206. for (let i = 0, l = children.length; i < l; i++) {
  15207. children[i].updateMatrixWorld(true);
  15208. } // update projection matrix for proper view frustum culling
  15209. if (cameras.length === 2) {
  15210. setProjectionFromUnion(cameraVR, cameraL, cameraR);
  15211. } else {
  15212. // assume single camera setup (AR)
  15213. cameraVR.projectionMatrix.copy(cameraL.projectionMatrix);
  15214. }
  15215. };
  15216. this.getCamera = function () {
  15217. return cameraVR;
  15218. };
  15219. this.getFoveation = function () {
  15220. if (glProjLayer !== null) {
  15221. return glProjLayer.fixedFoveation;
  15222. }
  15223. if (glBaseLayer !== null) {
  15224. return glBaseLayer.fixedFoveation;
  15225. }
  15226. return undefined;
  15227. };
  15228. this.setFoveation = function (foveation) {
  15229. // 0 = no foveation = full resolution
  15230. // 1 = maximum foveation = the edges render at lower resolution
  15231. if (glProjLayer !== null) {
  15232. glProjLayer.fixedFoveation = foveation;
  15233. }
  15234. if (glBaseLayer !== null && glBaseLayer.fixedFoveation !== undefined) {
  15235. glBaseLayer.fixedFoveation = foveation;
  15236. }
  15237. }; // Animation Loop
  15238. let onAnimationFrameCallback = null;
  15239. function onAnimationFrame(time, frame) {
  15240. pose = frame.getViewerPose(customReferenceSpace || referenceSpace);
  15241. xrFrame = frame;
  15242. if (pose !== null) {
  15243. const views = pose.views;
  15244. if (glBaseLayer !== null) {
  15245. renderer.setRenderTargetFramebuffer(newRenderTarget, glBaseLayer.framebuffer);
  15246. renderer.setRenderTarget(newRenderTarget);
  15247. }
  15248. let cameraVRNeedsUpdate = false; // check if it's necessary to rebuild cameraVR's camera list
  15249. if (views.length !== cameraVR.cameras.length) {
  15250. cameraVR.cameras.length = 0;
  15251. cameraVRNeedsUpdate = true;
  15252. }
  15253. for (let i = 0; i < views.length; i++) {
  15254. const view = views[i];
  15255. let viewport = null;
  15256. if (glBaseLayer !== null) {
  15257. viewport = glBaseLayer.getViewport(view);
  15258. } else {
  15259. const glSubImage = glBinding.getViewSubImage(glProjLayer, view);
  15260. viewport = glSubImage.viewport; // For side-by-side projection, we only produce a single texture for both eyes.
  15261. if (i === 0) {
  15262. renderer.setRenderTargetTextures(newRenderTarget, glSubImage.colorTexture, glProjLayer.ignoreDepthValues ? undefined : glSubImage.depthStencilTexture);
  15263. renderer.setRenderTarget(newRenderTarget);
  15264. }
  15265. }
  15266. let camera = cameras[i];
  15267. if (camera === undefined) {
  15268. camera = new PerspectiveCamera();
  15269. camera.layers.enable(i);
  15270. camera.viewport = new Vector4();
  15271. cameras[i] = camera;
  15272. }
  15273. camera.matrix.fromArray(view.transform.matrix);
  15274. camera.projectionMatrix.fromArray(view.projectionMatrix);
  15275. camera.viewport.set(viewport.x, viewport.y, viewport.width, viewport.height);
  15276. if (i === 0) {
  15277. cameraVR.matrix.copy(camera.matrix);
  15278. }
  15279. if (cameraVRNeedsUpdate === true) {
  15280. cameraVR.cameras.push(camera);
  15281. }
  15282. }
  15283. } //
  15284. for (let i = 0; i < controllers.length; i++) {
  15285. const inputSource = controllerInputSources[i];
  15286. const controller = controllers[i];
  15287. if (inputSource !== null && controller !== undefined) {
  15288. controller.update(inputSource, frame, customReferenceSpace || referenceSpace);
  15289. }
  15290. }
  15291. if (onAnimationFrameCallback) onAnimationFrameCallback(time, frame);
  15292. xrFrame = null;
  15293. }
  15294. const animation = new WebGLAnimation();
  15295. animation.setAnimationLoop(onAnimationFrame);
  15296. this.setAnimationLoop = function (callback) {
  15297. onAnimationFrameCallback = callback;
  15298. };
  15299. this.dispose = function () {};
  15300. }
  15301. }
  15302. function WebGLMaterials(renderer, properties) {
  15303. function refreshFogUniforms(uniforms, fog) {
  15304. uniforms.fogColor.value.copy(fog.color);
  15305. if (fog.isFog) {
  15306. uniforms.fogNear.value = fog.near;
  15307. uniforms.fogFar.value = fog.far;
  15308. } else if (fog.isFogExp2) {
  15309. uniforms.fogDensity.value = fog.density;
  15310. }
  15311. }
  15312. function refreshMaterialUniforms(uniforms, material, pixelRatio, height, transmissionRenderTarget) {
  15313. if (material.isMeshBasicMaterial) {
  15314. refreshUniformsCommon(uniforms, material);
  15315. } else if (material.isMeshLambertMaterial) {
  15316. refreshUniformsCommon(uniforms, material);
  15317. } else if (material.isMeshToonMaterial) {
  15318. refreshUniformsCommon(uniforms, material);
  15319. refreshUniformsToon(uniforms, material);
  15320. } else if (material.isMeshPhongMaterial) {
  15321. refreshUniformsCommon(uniforms, material);
  15322. refreshUniformsPhong(uniforms, material);
  15323. } else if (material.isMeshStandardMaterial) {
  15324. refreshUniformsCommon(uniforms, material);
  15325. refreshUniformsStandard(uniforms, material);
  15326. if (material.isMeshPhysicalMaterial) {
  15327. refreshUniformsPhysical(uniforms, material, transmissionRenderTarget);
  15328. }
  15329. } else if (material.isMeshMatcapMaterial) {
  15330. refreshUniformsCommon(uniforms, material);
  15331. refreshUniformsMatcap(uniforms, material);
  15332. } else if (material.isMeshDepthMaterial) {
  15333. refreshUniformsCommon(uniforms, material);
  15334. } else if (material.isMeshDistanceMaterial) {
  15335. refreshUniformsCommon(uniforms, material);
  15336. refreshUniformsDistance(uniforms, material);
  15337. } else if (material.isMeshNormalMaterial) {
  15338. refreshUniformsCommon(uniforms, material);
  15339. } else if (material.isLineBasicMaterial) {
  15340. refreshUniformsLine(uniforms, material);
  15341. if (material.isLineDashedMaterial) {
  15342. refreshUniformsDash(uniforms, material);
  15343. }
  15344. } else if (material.isPointsMaterial) {
  15345. refreshUniformsPoints(uniforms, material, pixelRatio, height);
  15346. } else if (material.isSpriteMaterial) {
  15347. refreshUniformsSprites(uniforms, material);
  15348. } else if (material.isShadowMaterial) {
  15349. uniforms.color.value.copy(material.color);
  15350. uniforms.opacity.value = material.opacity;
  15351. } else if (material.isShaderMaterial) {
  15352. material.uniformsNeedUpdate = false; // #15581
  15353. }
  15354. }
  15355. function refreshUniformsCommon(uniforms, material) {
  15356. uniforms.opacity.value = material.opacity;
  15357. if (material.color) {
  15358. uniforms.diffuse.value.copy(material.color);
  15359. }
  15360. if (material.emissive) {
  15361. uniforms.emissive.value.copy(material.emissive).multiplyScalar(material.emissiveIntensity);
  15362. }
  15363. if (material.map) {
  15364. uniforms.map.value = material.map;
  15365. }
  15366. if (material.alphaMap) {
  15367. uniforms.alphaMap.value = material.alphaMap;
  15368. }
  15369. if (material.bumpMap) {
  15370. uniforms.bumpMap.value = material.bumpMap;
  15371. uniforms.bumpScale.value = material.bumpScale;
  15372. if (material.side === BackSide) uniforms.bumpScale.value *= -1;
  15373. }
  15374. if (material.displacementMap) {
  15375. uniforms.displacementMap.value = material.displacementMap;
  15376. uniforms.displacementScale.value = material.displacementScale;
  15377. uniforms.displacementBias.value = material.displacementBias;
  15378. }
  15379. if (material.emissiveMap) {
  15380. uniforms.emissiveMap.value = material.emissiveMap;
  15381. }
  15382. if (material.normalMap) {
  15383. uniforms.normalMap.value = material.normalMap;
  15384. uniforms.normalScale.value.copy(material.normalScale);
  15385. if (material.side === BackSide) uniforms.normalScale.value.negate();
  15386. }
  15387. if (material.specularMap) {
  15388. uniforms.specularMap.value = material.specularMap;
  15389. }
  15390. if (material.alphaTest > 0) {
  15391. uniforms.alphaTest.value = material.alphaTest;
  15392. }
  15393. const envMap = properties.get(material).envMap;
  15394. if (envMap) {
  15395. uniforms.envMap.value = envMap;
  15396. uniforms.flipEnvMap.value = envMap.isCubeTexture && envMap.isRenderTargetTexture === false ? -1 : 1;
  15397. uniforms.reflectivity.value = material.reflectivity;
  15398. uniforms.ior.value = material.ior;
  15399. uniforms.refractionRatio.value = material.refractionRatio;
  15400. }
  15401. if (material.lightMap) {
  15402. uniforms.lightMap.value = material.lightMap; // artist-friendly light intensity scaling factor
  15403. const scaleFactor = renderer.physicallyCorrectLights !== true ? Math.PI : 1;
  15404. uniforms.lightMapIntensity.value = material.lightMapIntensity * scaleFactor;
  15405. }
  15406. if (material.aoMap) {
  15407. uniforms.aoMap.value = material.aoMap;
  15408. uniforms.aoMapIntensity.value = material.aoMapIntensity;
  15409. } // uv repeat and offset setting priorities
  15410. // 1. color map
  15411. // 2. specular map
  15412. // 3. displacementMap map
  15413. // 4. normal map
  15414. // 5. bump map
  15415. // 6. roughnessMap map
  15416. // 7. metalnessMap map
  15417. // 8. alphaMap map
  15418. // 9. emissiveMap map
  15419. // 10. clearcoat map
  15420. // 11. clearcoat normal map
  15421. // 12. clearcoat roughnessMap map
  15422. // 13. iridescence map
  15423. // 14. iridescence thickness map
  15424. // 15. specular intensity map
  15425. // 16. specular tint map
  15426. // 17. transmission map
  15427. // 18. thickness map
  15428. let uvScaleMap;
  15429. if (material.map) {
  15430. uvScaleMap = material.map;
  15431. } else if (material.specularMap) {
  15432. uvScaleMap = material.specularMap;
  15433. } else if (material.displacementMap) {
  15434. uvScaleMap = material.displacementMap;
  15435. } else if (material.normalMap) {
  15436. uvScaleMap = material.normalMap;
  15437. } else if (material.bumpMap) {
  15438. uvScaleMap = material.bumpMap;
  15439. } else if (material.roughnessMap) {
  15440. uvScaleMap = material.roughnessMap;
  15441. } else if (material.metalnessMap) {
  15442. uvScaleMap = material.metalnessMap;
  15443. } else if (material.alphaMap) {
  15444. uvScaleMap = material.alphaMap;
  15445. } else if (material.emissiveMap) {
  15446. uvScaleMap = material.emissiveMap;
  15447. } else if (material.clearcoatMap) {
  15448. uvScaleMap = material.clearcoatMap;
  15449. } else if (material.clearcoatNormalMap) {
  15450. uvScaleMap = material.clearcoatNormalMap;
  15451. } else if (material.clearcoatRoughnessMap) {
  15452. uvScaleMap = material.clearcoatRoughnessMap;
  15453. } else if (material.iridescenceMap) {
  15454. uvScaleMap = material.iridescenceMap;
  15455. } else if (material.iridescenceThicknessMap) {
  15456. uvScaleMap = material.iridescenceThicknessMap;
  15457. } else if (material.specularIntensityMap) {
  15458. uvScaleMap = material.specularIntensityMap;
  15459. } else if (material.specularColorMap) {
  15460. uvScaleMap = material.specularColorMap;
  15461. } else if (material.transmissionMap) {
  15462. uvScaleMap = material.transmissionMap;
  15463. } else if (material.thicknessMap) {
  15464. uvScaleMap = material.thicknessMap;
  15465. } else if (material.sheenColorMap) {
  15466. uvScaleMap = material.sheenColorMap;
  15467. } else if (material.sheenRoughnessMap) {
  15468. uvScaleMap = material.sheenRoughnessMap;
  15469. }
  15470. if (uvScaleMap !== undefined) {
  15471. // backwards compatibility
  15472. if (uvScaleMap.isWebGLRenderTarget) {
  15473. uvScaleMap = uvScaleMap.texture;
  15474. }
  15475. if (uvScaleMap.matrixAutoUpdate === true) {
  15476. uvScaleMap.updateMatrix();
  15477. }
  15478. uniforms.uvTransform.value.copy(uvScaleMap.matrix);
  15479. } // uv repeat and offset setting priorities for uv2
  15480. // 1. ao map
  15481. // 2. light map
  15482. let uv2ScaleMap;
  15483. if (material.aoMap) {
  15484. uv2ScaleMap = material.aoMap;
  15485. } else if (material.lightMap) {
  15486. uv2ScaleMap = material.lightMap;
  15487. }
  15488. if (uv2ScaleMap !== undefined) {
  15489. // backwards compatibility
  15490. if (uv2ScaleMap.isWebGLRenderTarget) {
  15491. uv2ScaleMap = uv2ScaleMap.texture;
  15492. }
  15493. if (uv2ScaleMap.matrixAutoUpdate === true) {
  15494. uv2ScaleMap.updateMatrix();
  15495. }
  15496. uniforms.uv2Transform.value.copy(uv2ScaleMap.matrix);
  15497. }
  15498. }
  15499. function refreshUniformsLine(uniforms, material) {
  15500. uniforms.diffuse.value.copy(material.color);
  15501. uniforms.opacity.value = material.opacity;
  15502. }
  15503. function refreshUniformsDash(uniforms, material) {
  15504. uniforms.dashSize.value = material.dashSize;
  15505. uniforms.totalSize.value = material.dashSize + material.gapSize;
  15506. uniforms.scale.value = material.scale;
  15507. }
  15508. function refreshUniformsPoints(uniforms, material, pixelRatio, height) {
  15509. uniforms.diffuse.value.copy(material.color);
  15510. uniforms.opacity.value = material.opacity;
  15511. uniforms.size.value = material.size * pixelRatio;
  15512. uniforms.scale.value = height * 0.5;
  15513. if (material.map) {
  15514. uniforms.map.value = material.map;
  15515. }
  15516. if (material.alphaMap) {
  15517. uniforms.alphaMap.value = material.alphaMap;
  15518. }
  15519. if (material.alphaTest > 0) {
  15520. uniforms.alphaTest.value = material.alphaTest;
  15521. } // uv repeat and offset setting priorities
  15522. // 1. color map
  15523. // 2. alpha map
  15524. let uvScaleMap;
  15525. if (material.map) {
  15526. uvScaleMap = material.map;
  15527. } else if (material.alphaMap) {
  15528. uvScaleMap = material.alphaMap;
  15529. }
  15530. if (uvScaleMap !== undefined) {
  15531. if (uvScaleMap.matrixAutoUpdate === true) {
  15532. uvScaleMap.updateMatrix();
  15533. }
  15534. uniforms.uvTransform.value.copy(uvScaleMap.matrix);
  15535. }
  15536. }
  15537. function refreshUniformsSprites(uniforms, material) {
  15538. uniforms.diffuse.value.copy(material.color);
  15539. uniforms.opacity.value = material.opacity;
  15540. uniforms.rotation.value = material.rotation;
  15541. if (material.map) {
  15542. uniforms.map.value = material.map;
  15543. }
  15544. if (material.alphaMap) {
  15545. uniforms.alphaMap.value = material.alphaMap;
  15546. }
  15547. if (material.alphaTest > 0) {
  15548. uniforms.alphaTest.value = material.alphaTest;
  15549. } // uv repeat and offset setting priorities
  15550. // 1. color map
  15551. // 2. alpha map
  15552. let uvScaleMap;
  15553. if (material.map) {
  15554. uvScaleMap = material.map;
  15555. } else if (material.alphaMap) {
  15556. uvScaleMap = material.alphaMap;
  15557. }
  15558. if (uvScaleMap !== undefined) {
  15559. if (uvScaleMap.matrixAutoUpdate === true) {
  15560. uvScaleMap.updateMatrix();
  15561. }
  15562. uniforms.uvTransform.value.copy(uvScaleMap.matrix);
  15563. }
  15564. }
  15565. function refreshUniformsPhong(uniforms, material) {
  15566. uniforms.specular.value.copy(material.specular);
  15567. uniforms.shininess.value = Math.max(material.shininess, 1e-4); // to prevent pow( 0.0, 0.0 )
  15568. }
  15569. function refreshUniformsToon(uniforms, material) {
  15570. if (material.gradientMap) {
  15571. uniforms.gradientMap.value = material.gradientMap;
  15572. }
  15573. }
  15574. function refreshUniformsStandard(uniforms, material) {
  15575. uniforms.roughness.value = material.roughness;
  15576. uniforms.metalness.value = material.metalness;
  15577. if (material.roughnessMap) {
  15578. uniforms.roughnessMap.value = material.roughnessMap;
  15579. }
  15580. if (material.metalnessMap) {
  15581. uniforms.metalnessMap.value = material.metalnessMap;
  15582. }
  15583. const envMap = properties.get(material).envMap;
  15584. if (envMap) {
  15585. //uniforms.envMap.value = material.envMap; // part of uniforms common
  15586. uniforms.envMapIntensity.value = material.envMapIntensity;
  15587. }
  15588. }
  15589. function refreshUniformsPhysical(uniforms, material, transmissionRenderTarget) {
  15590. uniforms.ior.value = material.ior; // also part of uniforms common
  15591. if (material.sheen > 0) {
  15592. uniforms.sheenColor.value.copy(material.sheenColor).multiplyScalar(material.sheen);
  15593. uniforms.sheenRoughness.value = material.sheenRoughness;
  15594. if (material.sheenColorMap) {
  15595. uniforms.sheenColorMap.value = material.sheenColorMap;
  15596. }
  15597. if (material.sheenRoughnessMap) {
  15598. uniforms.sheenRoughnessMap.value = material.sheenRoughnessMap;
  15599. }
  15600. }
  15601. if (material.clearcoat > 0) {
  15602. uniforms.clearcoat.value = material.clearcoat;
  15603. uniforms.clearcoatRoughness.value = material.clearcoatRoughness;
  15604. if (material.clearcoatMap) {
  15605. uniforms.clearcoatMap.value = material.clearcoatMap;
  15606. }
  15607. if (material.clearcoatRoughnessMap) {
  15608. uniforms.clearcoatRoughnessMap.value = material.clearcoatRoughnessMap;
  15609. }
  15610. if (material.clearcoatNormalMap) {
  15611. uniforms.clearcoatNormalScale.value.copy(material.clearcoatNormalScale);
  15612. uniforms.clearcoatNormalMap.value = material.clearcoatNormalMap;
  15613. if (material.side === BackSide) {
  15614. uniforms.clearcoatNormalScale.value.negate();
  15615. }
  15616. }
  15617. }
  15618. if (material.iridescence > 0) {
  15619. uniforms.iridescence.value = material.iridescence;
  15620. uniforms.iridescenceIOR.value = material.iridescenceIOR;
  15621. uniforms.iridescenceThicknessMinimum.value = material.iridescenceThicknessRange[0];
  15622. uniforms.iridescenceThicknessMaximum.value = material.iridescenceThicknessRange[1];
  15623. if (material.iridescenceMap) {
  15624. uniforms.iridescenceMap.value = material.iridescenceMap;
  15625. }
  15626. if (material.iridescenceThicknessMap) {
  15627. uniforms.iridescenceThicknessMap.value = material.iridescenceThicknessMap;
  15628. }
  15629. }
  15630. if (material.transmission > 0) {
  15631. uniforms.transmission.value = material.transmission;
  15632. uniforms.transmissionSamplerMap.value = transmissionRenderTarget.texture;
  15633. uniforms.transmissionSamplerSize.value.set(transmissionRenderTarget.width, transmissionRenderTarget.height);
  15634. if (material.transmissionMap) {
  15635. uniforms.transmissionMap.value = material.transmissionMap;
  15636. }
  15637. uniforms.thickness.value = material.thickness;
  15638. if (material.thicknessMap) {
  15639. uniforms.thicknessMap.value = material.thicknessMap;
  15640. }
  15641. uniforms.attenuationDistance.value = material.attenuationDistance;
  15642. uniforms.attenuationColor.value.copy(material.attenuationColor);
  15643. }
  15644. uniforms.specularIntensity.value = material.specularIntensity;
  15645. uniforms.specularColor.value.copy(material.specularColor);
  15646. if (material.specularIntensityMap) {
  15647. uniforms.specularIntensityMap.value = material.specularIntensityMap;
  15648. }
  15649. if (material.specularColorMap) {
  15650. uniforms.specularColorMap.value = material.specularColorMap;
  15651. }
  15652. }
  15653. function refreshUniformsMatcap(uniforms, material) {
  15654. if (material.matcap) {
  15655. uniforms.matcap.value = material.matcap;
  15656. }
  15657. }
  15658. function refreshUniformsDistance(uniforms, material) {
  15659. uniforms.referencePosition.value.copy(material.referencePosition);
  15660. uniforms.nearDistance.value = material.nearDistance;
  15661. uniforms.farDistance.value = material.farDistance;
  15662. }
  15663. return {
  15664. refreshFogUniforms: refreshFogUniforms,
  15665. refreshMaterialUniforms: refreshMaterialUniforms
  15666. };
  15667. }
  15668. function WebGLUniformsGroups(gl, info, capabilities, state) {
  15669. let buffers = {};
  15670. let updateList = {};
  15671. let allocatedBindingPoints = [];
  15672. const maxBindingPoints = capabilities.isWebGL2 ? gl.getParameter(gl.MAX_UNIFORM_BUFFER_BINDINGS) : 0; // binding points are global whereas block indices are per shader program
  15673. function bind(uniformsGroup, program) {
  15674. const webglProgram = program.program;
  15675. state.uniformBlockBinding(uniformsGroup, webglProgram);
  15676. }
  15677. function update(uniformsGroup, program) {
  15678. let buffer = buffers[uniformsGroup.id];
  15679. if (buffer === undefined) {
  15680. prepareUniformsGroup(uniformsGroup);
  15681. buffer = createBuffer(uniformsGroup);
  15682. buffers[uniformsGroup.id] = buffer;
  15683. uniformsGroup.addEventListener('dispose', onUniformsGroupsDispose);
  15684. } // ensure to update the binding points/block indices mapping for this program
  15685. const webglProgram = program.program;
  15686. state.updateUBOMapping(uniformsGroup, webglProgram); // update UBO once per frame
  15687. const frame = info.render.frame;
  15688. if (updateList[uniformsGroup.id] !== frame) {
  15689. updateBufferData(uniformsGroup);
  15690. updateList[uniformsGroup.id] = frame;
  15691. }
  15692. }
  15693. function createBuffer(uniformsGroup) {
  15694. // the setup of an UBO is independent of a particular shader program but global
  15695. const bindingPointIndex = allocateBindingPointIndex();
  15696. uniformsGroup.__bindingPointIndex = bindingPointIndex;
  15697. const buffer = gl.createBuffer();
  15698. const size = uniformsGroup.__size;
  15699. const usage = uniformsGroup.usage;
  15700. gl.bindBuffer(gl.UNIFORM_BUFFER, buffer);
  15701. gl.bufferData(gl.UNIFORM_BUFFER, size, usage);
  15702. gl.bindBuffer(gl.UNIFORM_BUFFER, null);
  15703. gl.bindBufferBase(gl.UNIFORM_BUFFER, bindingPointIndex, buffer);
  15704. return buffer;
  15705. }
  15706. function allocateBindingPointIndex() {
  15707. for (let i = 0; i < maxBindingPoints; i++) {
  15708. if (allocatedBindingPoints.indexOf(i) === -1) {
  15709. allocatedBindingPoints.push(i);
  15710. return i;
  15711. }
  15712. }
  15713. console.error('THREE.WebGLRenderer: Maximum number of simultaneously usable uniforms groups reached.');
  15714. return 0;
  15715. }
  15716. function updateBufferData(uniformsGroup) {
  15717. const buffer = buffers[uniformsGroup.id];
  15718. const uniforms = uniformsGroup.uniforms;
  15719. const cache = uniformsGroup.__cache;
  15720. gl.bindBuffer(gl.UNIFORM_BUFFER, buffer);
  15721. for (let i = 0, il = uniforms.length; i < il; i++) {
  15722. const uniform = uniforms[i]; // partly update the buffer if necessary
  15723. if (hasUniformChanged(uniform, i, cache) === true) {
  15724. const value = uniform.value;
  15725. const offset = uniform.__offset;
  15726. if (typeof value === 'number') {
  15727. uniform.__data[0] = value;
  15728. gl.bufferSubData(gl.UNIFORM_BUFFER, offset, uniform.__data);
  15729. } else {
  15730. if (uniform.value.isMatrix3) {
  15731. // manually converting 3x3 to 3x4
  15732. uniform.__data[0] = uniform.value.elements[0];
  15733. uniform.__data[1] = uniform.value.elements[1];
  15734. uniform.__data[2] = uniform.value.elements[2];
  15735. uniform.__data[3] = uniform.value.elements[0];
  15736. uniform.__data[4] = uniform.value.elements[3];
  15737. uniform.__data[5] = uniform.value.elements[4];
  15738. uniform.__data[6] = uniform.value.elements[5];
  15739. uniform.__data[7] = uniform.value.elements[0];
  15740. uniform.__data[8] = uniform.value.elements[6];
  15741. uniform.__data[9] = uniform.value.elements[7];
  15742. uniform.__data[10] = uniform.value.elements[8];
  15743. uniform.__data[11] = uniform.value.elements[0];
  15744. } else {
  15745. value.toArray(uniform.__data);
  15746. }
  15747. gl.bufferSubData(gl.UNIFORM_BUFFER, offset, uniform.__data);
  15748. }
  15749. }
  15750. }
  15751. gl.bindBuffer(gl.UNIFORM_BUFFER, null);
  15752. }
  15753. function hasUniformChanged(uniform, index, cache) {
  15754. const value = uniform.value;
  15755. if (cache[index] === undefined) {
  15756. // cache entry does not exist so far
  15757. if (typeof value === 'number') {
  15758. cache[index] = value;
  15759. } else {
  15760. cache[index] = value.clone();
  15761. }
  15762. return true;
  15763. } else {
  15764. // compare current value with cached entry
  15765. if (typeof value === 'number') {
  15766. if (cache[index] !== value) {
  15767. cache[index] = value;
  15768. return true;
  15769. }
  15770. } else {
  15771. const cachedObject = cache[index];
  15772. if (cachedObject.equals(value) === false) {
  15773. cachedObject.copy(value);
  15774. return true;
  15775. }
  15776. }
  15777. }
  15778. return false;
  15779. }
  15780. function prepareUniformsGroup(uniformsGroup) {
  15781. // determine total buffer size according to the STD140 layout
  15782. // Hint: STD140 is the only supported layout in WebGL 2
  15783. const uniforms = uniformsGroup.uniforms;
  15784. let offset = 0; // global buffer offset in bytes
  15785. const chunkSize = 16; // size of a chunk in bytes
  15786. let chunkOffset = 0; // offset within a single chunk in bytes
  15787. for (let i = 0, l = uniforms.length; i < l; i++) {
  15788. const uniform = uniforms[i];
  15789. const info = getUniformSize(uniform); // the following two properties will be used for partial buffer updates
  15790. uniform.__data = new Float32Array(info.storage / Float32Array.BYTES_PER_ELEMENT);
  15791. uniform.__offset = offset; //
  15792. if (i > 0) {
  15793. chunkOffset = offset % chunkSize;
  15794. const remainingSizeInChunk = chunkSize - chunkOffset; // check for chunk overflow
  15795. if (chunkOffset !== 0 && remainingSizeInChunk - info.boundary < 0) {
  15796. // add padding and adjust offset
  15797. offset += chunkSize - chunkOffset;
  15798. uniform.__offset = offset;
  15799. }
  15800. }
  15801. offset += info.storage;
  15802. } // ensure correct final padding
  15803. chunkOffset = offset % chunkSize;
  15804. if (chunkOffset > 0) offset += chunkSize - chunkOffset; //
  15805. uniformsGroup.__size = offset;
  15806. uniformsGroup.__cache = {};
  15807. return this;
  15808. }
  15809. function getUniformSize(uniform) {
  15810. const value = uniform.value;
  15811. const info = {
  15812. boundary: 0,
  15813. // bytes
  15814. storage: 0 // bytes
  15815. }; // determine sizes according to STD140
  15816. if (typeof value === 'number') {
  15817. // float/int
  15818. info.boundary = 4;
  15819. info.storage = 4;
  15820. } else if (value.isVector2) {
  15821. // vec2
  15822. info.boundary = 8;
  15823. info.storage = 8;
  15824. } else if (value.isVector3 || value.isColor) {
  15825. // vec3
  15826. info.boundary = 16;
  15827. info.storage = 12; // evil: vec3 must start on a 16-byte boundary but it only consumes 12 bytes
  15828. } else if (value.isVector4) {
  15829. // vec4
  15830. info.boundary = 16;
  15831. info.storage = 16;
  15832. } else if (value.isMatrix3) {
  15833. // mat3 (in STD140 a 3x3 matrix is represented as 3x4)
  15834. info.boundary = 48;
  15835. info.storage = 48;
  15836. } else if (value.isMatrix4) {
  15837. // mat4
  15838. info.boundary = 64;
  15839. info.storage = 64;
  15840. } else if (value.isTexture) {
  15841. console.warn('THREE.WebGLRenderer: Texture samplers can not be part of an uniforms group.');
  15842. } else {
  15843. console.warn('THREE.WebGLRenderer: Unsupported uniform value type.', value);
  15844. }
  15845. return info;
  15846. }
  15847. function onUniformsGroupsDispose(event) {
  15848. const uniformsGroup = event.target;
  15849. uniformsGroup.removeEventListener('dispose', onUniformsGroupsDispose);
  15850. const index = allocatedBindingPoints.indexOf(uniformsGroup.__bindingPointIndex);
  15851. allocatedBindingPoints.splice(index, 1);
  15852. gl.deleteBuffer(buffers[uniformsGroup.id]);
  15853. delete buffers[uniformsGroup.id];
  15854. delete updateList[uniformsGroup.id];
  15855. }
  15856. function dispose() {
  15857. for (const id in buffers) {
  15858. gl.deleteBuffer(buffers[id]);
  15859. }
  15860. allocatedBindingPoints = [];
  15861. buffers = {};
  15862. updateList = {};
  15863. }
  15864. return {
  15865. bind: bind,
  15866. update: update,
  15867. dispose: dispose
  15868. };
  15869. }
  15870. function createCanvasElement() {
  15871. const canvas = createElementNS('canvas');
  15872. canvas.style.display = 'block';
  15873. return canvas;
  15874. }
  15875. function WebGLRenderer(parameters = {}) {
  15876. this.isWebGLRenderer = true;
  15877. const _canvas = parameters.canvas !== undefined ? parameters.canvas : createCanvasElement(),
  15878. _context = parameters.context !== undefined ? parameters.context : null,
  15879. _depth = parameters.depth !== undefined ? parameters.depth : true,
  15880. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  15881. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  15882. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  15883. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false,
  15884. _powerPreference = parameters.powerPreference !== undefined ? parameters.powerPreference : 'default',
  15885. _failIfMajorPerformanceCaveat = parameters.failIfMajorPerformanceCaveat !== undefined ? parameters.failIfMajorPerformanceCaveat : false;
  15886. let _alpha;
  15887. if (_context !== null) {
  15888. _alpha = _context.getContextAttributes().alpha;
  15889. } else {
  15890. _alpha = parameters.alpha !== undefined ? parameters.alpha : false;
  15891. }
  15892. let currentRenderList = null;
  15893. let currentRenderState = null; // render() can be called from within a callback triggered by another render.
  15894. // We track this so that the nested render call gets its list and state isolated from the parent render call.
  15895. const renderListStack = [];
  15896. const renderStateStack = []; // public properties
  15897. this.domElement = _canvas; // Debug configuration container
  15898. this.debug = {
  15899. /**
  15900. * Enables error checking and reporting when shader programs are being compiled
  15901. * @type {boolean}
  15902. */
  15903. checkShaderErrors: true
  15904. }; // clearing
  15905. this.autoClear = true;
  15906. this.autoClearColor = true;
  15907. this.autoClearDepth = true;
  15908. this.autoClearStencil = true; // scene graph
  15909. this.sortObjects = true; // user-defined clipping
  15910. this.clippingPlanes = [];
  15911. this.localClippingEnabled = false; // physically based shading
  15912. this.outputEncoding = LinearEncoding; // physical lights
  15913. this.physicallyCorrectLights = false; // tone mapping
  15914. this.toneMapping = NoToneMapping;
  15915. this.toneMappingExposure = 1.0; //
  15916. Object.defineProperties(this, {
  15917. // @deprecated since r136, 0e21088102b4de7e0a0a33140620b7a3424b9e6d
  15918. gammaFactor: {
  15919. get: function () {
  15920. console.warn('THREE.WebGLRenderer: .gammaFactor has been removed.');
  15921. return 2;
  15922. },
  15923. set: function () {
  15924. console.warn('THREE.WebGLRenderer: .gammaFactor has been removed.');
  15925. }
  15926. }
  15927. }); // internal properties
  15928. const _this = this;
  15929. let _isContextLost = false; // internal state cache
  15930. let _currentActiveCubeFace = 0;
  15931. let _currentActiveMipmapLevel = 0;
  15932. let _currentRenderTarget = null;
  15933. let _currentMaterialId = -1;
  15934. let _currentCamera = null;
  15935. const _currentViewport = new Vector4();
  15936. const _currentScissor = new Vector4();
  15937. let _currentScissorTest = null; //
  15938. let _width = _canvas.width;
  15939. let _height = _canvas.height;
  15940. let _pixelRatio = 1;
  15941. let _opaqueSort = null;
  15942. let _transparentSort = null;
  15943. const _viewport = new Vector4(0, 0, _width, _height);
  15944. const _scissor = new Vector4(0, 0, _width, _height);
  15945. let _scissorTest = false; // frustum
  15946. const _frustum = new Frustum(); // clipping
  15947. let _clippingEnabled = false;
  15948. let _localClippingEnabled = false; // transmission
  15949. let _transmissionRenderTarget = null; // camera matrices cache
  15950. const _projScreenMatrix = new Matrix4();
  15951. const _vector2 = new Vector2();
  15952. const _vector3 = new Vector3();
  15953. const _emptyScene = {
  15954. background: null,
  15955. fog: null,
  15956. environment: null,
  15957. overrideMaterial: null,
  15958. isScene: true
  15959. };
  15960. function getTargetPixelRatio() {
  15961. return _currentRenderTarget === null ? _pixelRatio : 1;
  15962. } // initialize
  15963. let _gl = _context;
  15964. function getContext(contextNames, contextAttributes) {
  15965. for (let i = 0; i < contextNames.length; i++) {
  15966. const contextName = contextNames[i];
  15967. const context = _canvas.getContext(contextName, contextAttributes);
  15968. if (context !== null) return context;
  15969. }
  15970. return null;
  15971. }
  15972. try {
  15973. const contextAttributes = {
  15974. alpha: true,
  15975. depth: _depth,
  15976. stencil: _stencil,
  15977. antialias: _antialias,
  15978. premultipliedAlpha: _premultipliedAlpha,
  15979. preserveDrawingBuffer: _preserveDrawingBuffer,
  15980. powerPreference: _powerPreference,
  15981. failIfMajorPerformanceCaveat: _failIfMajorPerformanceCaveat
  15982. }; // OffscreenCanvas does not have setAttribute, see #22811
  15983. if ('setAttribute' in _canvas) _canvas.setAttribute('data-engine', `three.js r${REVISION}`); // event listeners must be registered before WebGL context is created, see #12753
  15984. _canvas.addEventListener('webglcontextlost', onContextLost, false);
  15985. _canvas.addEventListener('webglcontextrestored', onContextRestore, false);
  15986. _canvas.addEventListener('webglcontextcreationerror', onContextCreationError, false);
  15987. if (_gl === null) {
  15988. const contextNames = ['webgl2', 'webgl', 'experimental-webgl'];
  15989. if (_this.isWebGL1Renderer === true) {
  15990. contextNames.shift();
  15991. }
  15992. _gl = getContext(contextNames, contextAttributes);
  15993. if (_gl === null) {
  15994. if (getContext(contextNames)) {
  15995. throw new Error('Error creating WebGL context with your selected attributes.');
  15996. } else {
  15997. throw new Error('Error creating WebGL context.');
  15998. }
  15999. }
  16000. } // Some experimental-webgl implementations do not have getShaderPrecisionFormat
  16001. if (_gl.getShaderPrecisionFormat === undefined) {
  16002. _gl.getShaderPrecisionFormat = function () {
  16003. return {
  16004. 'rangeMin': 1,
  16005. 'rangeMax': 1,
  16006. 'precision': 1
  16007. };
  16008. };
  16009. }
  16010. } catch (error) {
  16011. console.error('THREE.WebGLRenderer: ' + error.message);
  16012. throw error;
  16013. }
  16014. let extensions, capabilities, state, info;
  16015. let properties, textures, cubemaps, cubeuvmaps, attributes, geometries, objects;
  16016. let programCache, materials, renderLists, renderStates, clipping, shadowMap;
  16017. let background, morphtargets, bufferRenderer, indexedBufferRenderer;
  16018. let utils, bindingStates, uniformsGroups;
  16019. function initGLContext() {
  16020. extensions = new WebGLExtensions(_gl);
  16021. capabilities = new WebGLCapabilities(_gl, extensions, parameters);
  16022. extensions.init(capabilities);
  16023. utils = new WebGLUtils(_gl, extensions, capabilities);
  16024. state = new WebGLState(_gl, extensions, capabilities);
  16025. info = new WebGLInfo(_gl);
  16026. properties = new WebGLProperties();
  16027. textures = new WebGLTextures(_gl, extensions, state, properties, capabilities, utils, info);
  16028. cubemaps = new WebGLCubeMaps(_this);
  16029. cubeuvmaps = new WebGLCubeUVMaps(_this);
  16030. attributes = new WebGLAttributes(_gl, capabilities);
  16031. bindingStates = new WebGLBindingStates(_gl, extensions, attributes, capabilities);
  16032. geometries = new WebGLGeometries(_gl, attributes, info, bindingStates);
  16033. objects = new WebGLObjects(_gl, geometries, attributes, info);
  16034. morphtargets = new WebGLMorphtargets(_gl, capabilities, textures);
  16035. clipping = new WebGLClipping(properties);
  16036. programCache = new WebGLPrograms(_this, cubemaps, cubeuvmaps, extensions, capabilities, bindingStates, clipping);
  16037. materials = new WebGLMaterials(_this, properties);
  16038. renderLists = new WebGLRenderLists();
  16039. renderStates = new WebGLRenderStates(extensions, capabilities);
  16040. background = new WebGLBackground(_this, cubemaps, state, objects, _alpha, _premultipliedAlpha);
  16041. shadowMap = new WebGLShadowMap(_this, objects, capabilities);
  16042. uniformsGroups = new WebGLUniformsGroups(_gl, info, capabilities, state);
  16043. bufferRenderer = new WebGLBufferRenderer(_gl, extensions, info, capabilities);
  16044. indexedBufferRenderer = new WebGLIndexedBufferRenderer(_gl, extensions, info, capabilities);
  16045. info.programs = programCache.programs;
  16046. _this.capabilities = capabilities;
  16047. _this.extensions = extensions;
  16048. _this.properties = properties;
  16049. _this.renderLists = renderLists;
  16050. _this.shadowMap = shadowMap;
  16051. _this.state = state;
  16052. _this.info = info;
  16053. }
  16054. initGLContext(); // xr
  16055. const xr = new WebXRManager(_this, _gl);
  16056. this.xr = xr; // API
  16057. this.getContext = function () {
  16058. return _gl;
  16059. };
  16060. this.getContextAttributes = function () {
  16061. return _gl.getContextAttributes();
  16062. };
  16063. this.forceContextLoss = function () {
  16064. const extension = extensions.get('WEBGL_lose_context');
  16065. if (extension) extension.loseContext();
  16066. };
  16067. this.forceContextRestore = function () {
  16068. const extension = extensions.get('WEBGL_lose_context');
  16069. if (extension) extension.restoreContext();
  16070. };
  16071. this.getPixelRatio = function () {
  16072. return _pixelRatio;
  16073. };
  16074. this.setPixelRatio = function (value) {
  16075. if (value === undefined) return;
  16076. _pixelRatio = value;
  16077. this.setSize(_width, _height, false);
  16078. };
  16079. this.getSize = function (target) {
  16080. return target.set(_width, _height);
  16081. };
  16082. this.setSize = function (width, height, updateStyle) {
  16083. if (xr.isPresenting) {
  16084. console.warn('THREE.WebGLRenderer: Can\'t change size while VR device is presenting.');
  16085. return;
  16086. }
  16087. _width = width;
  16088. _height = height;
  16089. _canvas.width = Math.floor(width * _pixelRatio);
  16090. _canvas.height = Math.floor(height * _pixelRatio);
  16091. if (updateStyle !== false) {
  16092. _canvas.style.width = width + 'px';
  16093. _canvas.style.height = height + 'px';
  16094. }
  16095. this.setViewport(0, 0, width, height);
  16096. };
  16097. this.getDrawingBufferSize = function (target) {
  16098. return target.set(_width * _pixelRatio, _height * _pixelRatio).floor();
  16099. };
  16100. this.setDrawingBufferSize = function (width, height, pixelRatio) {
  16101. _width = width;
  16102. _height = height;
  16103. _pixelRatio = pixelRatio;
  16104. _canvas.width = Math.floor(width * pixelRatio);
  16105. _canvas.height = Math.floor(height * pixelRatio);
  16106. this.setViewport(0, 0, width, height);
  16107. };
  16108. this.getCurrentViewport = function (target) {
  16109. return target.copy(_currentViewport);
  16110. };
  16111. this.getViewport = function (target) {
  16112. return target.copy(_viewport);
  16113. };
  16114. this.setViewport = function (x, y, width, height) {
  16115. if (x.isVector4) {
  16116. _viewport.set(x.x, x.y, x.z, x.w);
  16117. } else {
  16118. _viewport.set(x, y, width, height);
  16119. }
  16120. state.viewport(_currentViewport.copy(_viewport).multiplyScalar(_pixelRatio).floor());
  16121. };
  16122. this.getScissor = function (target) {
  16123. return target.copy(_scissor);
  16124. };
  16125. this.setScissor = function (x, y, width, height) {
  16126. if (x.isVector4) {
  16127. _scissor.set(x.x, x.y, x.z, x.w);
  16128. } else {
  16129. _scissor.set(x, y, width, height);
  16130. }
  16131. state.scissor(_currentScissor.copy(_scissor).multiplyScalar(_pixelRatio).floor());
  16132. };
  16133. this.getScissorTest = function () {
  16134. return _scissorTest;
  16135. };
  16136. this.setScissorTest = function (boolean) {
  16137. state.setScissorTest(_scissorTest = boolean);
  16138. };
  16139. this.setOpaqueSort = function (method) {
  16140. _opaqueSort = method;
  16141. };
  16142. this.setTransparentSort = function (method) {
  16143. _transparentSort = method;
  16144. }; // Clearing
  16145. this.getClearColor = function (target) {
  16146. return target.copy(background.getClearColor());
  16147. };
  16148. this.setClearColor = function () {
  16149. background.setClearColor.apply(background, arguments);
  16150. };
  16151. this.getClearAlpha = function () {
  16152. return background.getClearAlpha();
  16153. };
  16154. this.setClearAlpha = function () {
  16155. background.setClearAlpha.apply(background, arguments);
  16156. };
  16157. this.clear = function (color = true, depth = true, stencil = true) {
  16158. let bits = 0;
  16159. if (color) bits |= _gl.COLOR_BUFFER_BIT;
  16160. if (depth) bits |= _gl.DEPTH_BUFFER_BIT;
  16161. if (stencil) bits |= _gl.STENCIL_BUFFER_BIT;
  16162. _gl.clear(bits);
  16163. };
  16164. this.clearColor = function () {
  16165. this.clear(true, false, false);
  16166. };
  16167. this.clearDepth = function () {
  16168. this.clear(false, true, false);
  16169. };
  16170. this.clearStencil = function () {
  16171. this.clear(false, false, true);
  16172. }; //
  16173. this.dispose = function () {
  16174. _canvas.removeEventListener('webglcontextlost', onContextLost, false);
  16175. _canvas.removeEventListener('webglcontextrestored', onContextRestore, false);
  16176. _canvas.removeEventListener('webglcontextcreationerror', onContextCreationError, false);
  16177. renderLists.dispose();
  16178. renderStates.dispose();
  16179. properties.dispose();
  16180. cubemaps.dispose();
  16181. cubeuvmaps.dispose();
  16182. objects.dispose();
  16183. bindingStates.dispose();
  16184. uniformsGroups.dispose();
  16185. programCache.dispose();
  16186. xr.dispose();
  16187. xr.removeEventListener('sessionstart', onXRSessionStart);
  16188. xr.removeEventListener('sessionend', onXRSessionEnd);
  16189. if (_transmissionRenderTarget) {
  16190. _transmissionRenderTarget.dispose();
  16191. _transmissionRenderTarget = null;
  16192. }
  16193. animation.stop();
  16194. }; // Events
  16195. function onContextLost(event) {
  16196. event.preventDefault();
  16197. console.log('THREE.WebGLRenderer: Context Lost.');
  16198. _isContextLost = true;
  16199. }
  16200. function
  16201. /* event */
  16202. onContextRestore() {
  16203. console.log('THREE.WebGLRenderer: Context Restored.');
  16204. _isContextLost = false;
  16205. const infoAutoReset = info.autoReset;
  16206. const shadowMapEnabled = shadowMap.enabled;
  16207. const shadowMapAutoUpdate = shadowMap.autoUpdate;
  16208. const shadowMapNeedsUpdate = shadowMap.needsUpdate;
  16209. const shadowMapType = shadowMap.type;
  16210. initGLContext();
  16211. info.autoReset = infoAutoReset;
  16212. shadowMap.enabled = shadowMapEnabled;
  16213. shadowMap.autoUpdate = shadowMapAutoUpdate;
  16214. shadowMap.needsUpdate = shadowMapNeedsUpdate;
  16215. shadowMap.type = shadowMapType;
  16216. }
  16217. function onContextCreationError(event) {
  16218. console.error('THREE.WebGLRenderer: A WebGL context could not be created. Reason: ', event.statusMessage);
  16219. }
  16220. function onMaterialDispose(event) {
  16221. const material = event.target;
  16222. material.removeEventListener('dispose', onMaterialDispose);
  16223. deallocateMaterial(material);
  16224. } // Buffer deallocation
  16225. function deallocateMaterial(material) {
  16226. releaseMaterialProgramReferences(material);
  16227. properties.remove(material);
  16228. }
  16229. function releaseMaterialProgramReferences(material) {
  16230. const programs = properties.get(material).programs;
  16231. if (programs !== undefined) {
  16232. programs.forEach(function (program) {
  16233. programCache.releaseProgram(program);
  16234. });
  16235. if (material.isShaderMaterial) {
  16236. programCache.releaseShaderCache(material);
  16237. }
  16238. }
  16239. } // Buffer rendering
  16240. this.renderBufferDirect = function (camera, scene, geometry, material, object, group) {
  16241. if (scene === null) scene = _emptyScene; // renderBufferDirect second parameter used to be fog (could be null)
  16242. const frontFaceCW = object.isMesh && object.matrixWorld.determinant() < 0;
  16243. const program = setProgram(camera, scene, geometry, material, object);
  16244. state.setMaterial(material, frontFaceCW); //
  16245. let index = geometry.index;
  16246. const position = geometry.attributes.position; //
  16247. if (index === null) {
  16248. if (position === undefined || position.count === 0) return;
  16249. } else if (index.count === 0) {
  16250. return;
  16251. } //
  16252. let rangeFactor = 1;
  16253. if (material.wireframe === true) {
  16254. index = geometries.getWireframeAttribute(geometry);
  16255. rangeFactor = 2;
  16256. }
  16257. bindingStates.setup(object, material, program, geometry, index);
  16258. let attribute;
  16259. let renderer = bufferRenderer;
  16260. if (index !== null) {
  16261. attribute = attributes.get(index);
  16262. renderer = indexedBufferRenderer;
  16263. renderer.setIndex(attribute);
  16264. } //
  16265. const dataCount = index !== null ? index.count : position.count;
  16266. const rangeStart = geometry.drawRange.start * rangeFactor;
  16267. const rangeCount = geometry.drawRange.count * rangeFactor;
  16268. const groupStart = group !== null ? group.start * rangeFactor : 0;
  16269. const groupCount = group !== null ? group.count * rangeFactor : Infinity;
  16270. const drawStart = Math.max(rangeStart, groupStart);
  16271. const drawEnd = Math.min(dataCount, rangeStart + rangeCount, groupStart + groupCount) - 1;
  16272. const drawCount = Math.max(0, drawEnd - drawStart + 1);
  16273. if (drawCount === 0) return; //
  16274. if (object.isMesh) {
  16275. if (material.wireframe === true) {
  16276. state.setLineWidth(material.wireframeLinewidth * getTargetPixelRatio());
  16277. renderer.setMode(_gl.LINES);
  16278. } else {
  16279. renderer.setMode(_gl.TRIANGLES);
  16280. }
  16281. } else if (object.isLine) {
  16282. let lineWidth = material.linewidth;
  16283. if (lineWidth === undefined) lineWidth = 1; // Not using Line*Material
  16284. state.setLineWidth(lineWidth * getTargetPixelRatio());
  16285. if (object.isLineSegments) {
  16286. renderer.setMode(_gl.LINES);
  16287. } else if (object.isLineLoop) {
  16288. renderer.setMode(_gl.LINE_LOOP);
  16289. } else {
  16290. renderer.setMode(_gl.LINE_STRIP);
  16291. }
  16292. } else if (object.isPoints) {
  16293. renderer.setMode(_gl.POINTS);
  16294. } else if (object.isSprite) {
  16295. renderer.setMode(_gl.TRIANGLES);
  16296. }
  16297. if (object.isInstancedMesh) {
  16298. renderer.renderInstances(drawStart, drawCount, object.count);
  16299. } else if (geometry.isInstancedBufferGeometry) {
  16300. const instanceCount = Math.min(geometry.instanceCount, geometry._maxInstanceCount);
  16301. renderer.renderInstances(drawStart, drawCount, instanceCount);
  16302. } else {
  16303. renderer.render(drawStart, drawCount);
  16304. }
  16305. }; // Compile
  16306. this.compile = function (scene, camera) {
  16307. function prepare(material, scene, object) {
  16308. if (material.transparent === true && material.side === DoubleSide) {
  16309. material.side = BackSide;
  16310. material.needsUpdate = true;
  16311. getProgram(material, scene, object);
  16312. material.side = FrontSide;
  16313. material.needsUpdate = true;
  16314. getProgram(material, scene, object);
  16315. material.side = DoubleSide;
  16316. } else {
  16317. getProgram(material, scene, object);
  16318. }
  16319. }
  16320. currentRenderState = renderStates.get(scene);
  16321. currentRenderState.init();
  16322. renderStateStack.push(currentRenderState);
  16323. scene.traverseVisible(function (object) {
  16324. if (object.isLight && object.layers.test(camera.layers)) {
  16325. currentRenderState.pushLight(object);
  16326. if (object.castShadow) {
  16327. currentRenderState.pushShadow(object);
  16328. }
  16329. }
  16330. });
  16331. currentRenderState.setupLights(_this.physicallyCorrectLights);
  16332. scene.traverse(function (object) {
  16333. const material = object.material;
  16334. if (material) {
  16335. if (Array.isArray(material)) {
  16336. for (let i = 0; i < material.length; i++) {
  16337. const material2 = material[i];
  16338. prepare(material2, scene, object);
  16339. }
  16340. } else {
  16341. prepare(material, scene, object);
  16342. }
  16343. }
  16344. });
  16345. renderStateStack.pop();
  16346. currentRenderState = null;
  16347. }; // Animation Loop
  16348. let onAnimationFrameCallback = null;
  16349. function onAnimationFrame(time) {
  16350. if (onAnimationFrameCallback) onAnimationFrameCallback(time);
  16351. }
  16352. function onXRSessionStart() {
  16353. animation.stop();
  16354. }
  16355. function onXRSessionEnd() {
  16356. animation.start();
  16357. }
  16358. const animation = new WebGLAnimation();
  16359. animation.setAnimationLoop(onAnimationFrame);
  16360. if (typeof self !== 'undefined') animation.setContext(self);
  16361. this.setAnimationLoop = function (callback) {
  16362. onAnimationFrameCallback = callback;
  16363. xr.setAnimationLoop(callback);
  16364. callback === null ? animation.stop() : animation.start();
  16365. };
  16366. xr.addEventListener('sessionstart', onXRSessionStart);
  16367. xr.addEventListener('sessionend', onXRSessionEnd); // Rendering
  16368. this.render = function (scene, camera) {
  16369. if (camera !== undefined && camera.isCamera !== true) {
  16370. console.error('THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.');
  16371. return;
  16372. }
  16373. if (_isContextLost === true) return; // update scene graph
  16374. if (scene.matrixWorldAutoUpdate === true) scene.updateMatrixWorld(); // update camera matrices and frustum
  16375. if (camera.parent === null && camera.matrixWorldAutoUpdate === true) camera.updateMatrixWorld();
  16376. if (xr.enabled === true && xr.isPresenting === true) {
  16377. if (xr.cameraAutoUpdate === true) xr.updateCamera(camera);
  16378. camera = xr.getCamera(); // use XR camera for rendering
  16379. } //
  16380. if (scene.isScene === true) scene.onBeforeRender(_this, scene, camera, _currentRenderTarget);
  16381. currentRenderState = renderStates.get(scene, renderStateStack.length);
  16382. currentRenderState.init();
  16383. renderStateStack.push(currentRenderState);
  16384. _projScreenMatrix.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse);
  16385. _frustum.setFromProjectionMatrix(_projScreenMatrix);
  16386. _localClippingEnabled = this.localClippingEnabled;
  16387. _clippingEnabled = clipping.init(this.clippingPlanes, _localClippingEnabled, camera);
  16388. currentRenderList = renderLists.get(scene, renderListStack.length);
  16389. currentRenderList.init();
  16390. renderListStack.push(currentRenderList);
  16391. projectObject(scene, camera, 0, _this.sortObjects);
  16392. currentRenderList.finish();
  16393. if (_this.sortObjects === true) {
  16394. currentRenderList.sort(_opaqueSort, _transparentSort);
  16395. } //
  16396. if (_clippingEnabled === true) clipping.beginShadows();
  16397. const shadowsArray = currentRenderState.state.shadowsArray;
  16398. shadowMap.render(shadowsArray, scene, camera);
  16399. if (_clippingEnabled === true) clipping.endShadows(); //
  16400. if (this.info.autoReset === true) this.info.reset(); //
  16401. background.render(currentRenderList, scene); // render scene
  16402. currentRenderState.setupLights(_this.physicallyCorrectLights);
  16403. if (camera.isArrayCamera) {
  16404. const cameras = camera.cameras;
  16405. for (let i = 0, l = cameras.length; i < l; i++) {
  16406. const camera2 = cameras[i];
  16407. renderScene(currentRenderList, scene, camera2, camera2.viewport);
  16408. }
  16409. } else {
  16410. renderScene(currentRenderList, scene, camera);
  16411. } //
  16412. if (_currentRenderTarget !== null) {
  16413. // resolve multisample renderbuffers to a single-sample texture if necessary
  16414. textures.updateMultisampleRenderTarget(_currentRenderTarget); // Generate mipmap if we're using any kind of mipmap filtering
  16415. textures.updateRenderTargetMipmap(_currentRenderTarget);
  16416. } //
  16417. if (scene.isScene === true) scene.onAfterRender(_this, scene, camera); // _gl.finish();
  16418. bindingStates.resetDefaultState();
  16419. _currentMaterialId = -1;
  16420. _currentCamera = null;
  16421. renderStateStack.pop();
  16422. if (renderStateStack.length > 0) {
  16423. currentRenderState = renderStateStack[renderStateStack.length - 1];
  16424. } else {
  16425. currentRenderState = null;
  16426. }
  16427. renderListStack.pop();
  16428. if (renderListStack.length > 0) {
  16429. currentRenderList = renderListStack[renderListStack.length - 1];
  16430. } else {
  16431. currentRenderList = null;
  16432. }
  16433. };
  16434. function projectObject(object, camera, groupOrder, sortObjects) {
  16435. if (object.visible === false) return;
  16436. const visible = object.layers.test(camera.layers);
  16437. if (visible) {
  16438. if (object.isGroup) {
  16439. groupOrder = object.renderOrder;
  16440. } else if (object.isLOD) {
  16441. if (object.autoUpdate === true) object.update(camera);
  16442. } else if (object.isLight) {
  16443. currentRenderState.pushLight(object);
  16444. if (object.castShadow) {
  16445. currentRenderState.pushShadow(object);
  16446. }
  16447. } else if (object.isSprite) {
  16448. if (!object.frustumCulled || _frustum.intersectsSprite(object)) {
  16449. if (sortObjects) {
  16450. _vector3.setFromMatrixPosition(object.matrixWorld).applyMatrix4(_projScreenMatrix);
  16451. }
  16452. const geometry = objects.update(object);
  16453. const material = object.material;
  16454. if (material.visible) {
  16455. currentRenderList.push(object, geometry, material, groupOrder, _vector3.z, null);
  16456. }
  16457. }
  16458. } else if (object.isMesh || object.isLine || object.isPoints) {
  16459. if (object.isSkinnedMesh) {
  16460. // update skeleton only once in a frame
  16461. if (object.skeleton.frame !== info.render.frame) {
  16462. object.skeleton.update();
  16463. object.skeleton.frame = info.render.frame;
  16464. }
  16465. }
  16466. if (!object.frustumCulled || _frustum.intersectsObject(object)) {
  16467. if (sortObjects) {
  16468. _vector3.setFromMatrixPosition(object.matrixWorld).applyMatrix4(_projScreenMatrix);
  16469. }
  16470. const geometry = objects.update(object);
  16471. const material = object.material;
  16472. if (Array.isArray(material)) {
  16473. const groups = geometry.groups;
  16474. for (let i = 0, l = groups.length; i < l; i++) {
  16475. const group = groups[i];
  16476. const groupMaterial = material[group.materialIndex];
  16477. if (groupMaterial && groupMaterial.visible) {
  16478. currentRenderList.push(object, geometry, groupMaterial, groupOrder, _vector3.z, group);
  16479. }
  16480. }
  16481. } else if (material.visible) {
  16482. currentRenderList.push(object, geometry, material, groupOrder, _vector3.z, null);
  16483. }
  16484. }
  16485. }
  16486. }
  16487. const children = object.children;
  16488. for (let i = 0, l = children.length; i < l; i++) {
  16489. projectObject(children[i], camera, groupOrder, sortObjects);
  16490. }
  16491. }
  16492. function renderScene(currentRenderList, scene, camera, viewport) {
  16493. const opaqueObjects = currentRenderList.opaque;
  16494. const transmissiveObjects = currentRenderList.transmissive;
  16495. const transparentObjects = currentRenderList.transparent;
  16496. currentRenderState.setupLightsView(camera);
  16497. if (transmissiveObjects.length > 0) renderTransmissionPass(opaqueObjects, scene, camera);
  16498. if (viewport) state.viewport(_currentViewport.copy(viewport));
  16499. if (opaqueObjects.length > 0) renderObjects(opaqueObjects, scene, camera);
  16500. if (transmissiveObjects.length > 0) renderObjects(transmissiveObjects, scene, camera);
  16501. if (transparentObjects.length > 0) renderObjects(transparentObjects, scene, camera); // Ensure depth buffer writing is enabled so it can be cleared on next render
  16502. state.buffers.depth.setTest(true);
  16503. state.buffers.depth.setMask(true);
  16504. state.buffers.color.setMask(true);
  16505. state.setPolygonOffset(false);
  16506. }
  16507. function renderTransmissionPass(opaqueObjects, scene, camera) {
  16508. const isWebGL2 = capabilities.isWebGL2;
  16509. if (_transmissionRenderTarget === null) {
  16510. _transmissionRenderTarget = new WebGLRenderTarget(1, 1, {
  16511. generateMipmaps: true,
  16512. type: extensions.has('EXT_color_buffer_half_float') ? HalfFloatType : UnsignedByteType,
  16513. minFilter: LinearMipmapLinearFilter,
  16514. samples: isWebGL2 && _antialias === true ? 4 : 0
  16515. });
  16516. }
  16517. _this.getDrawingBufferSize(_vector2);
  16518. if (isWebGL2) {
  16519. _transmissionRenderTarget.setSize(_vector2.x, _vector2.y);
  16520. } else {
  16521. _transmissionRenderTarget.setSize(floorPowerOfTwo(_vector2.x), floorPowerOfTwo(_vector2.y));
  16522. } //
  16523. const currentRenderTarget = _this.getRenderTarget();
  16524. _this.setRenderTarget(_transmissionRenderTarget);
  16525. _this.clear(); // Turn off the features which can affect the frag color for opaque objects pass.
  16526. // Otherwise they are applied twice in opaque objects pass and transmission objects pass.
  16527. const currentToneMapping = _this.toneMapping;
  16528. _this.toneMapping = NoToneMapping;
  16529. renderObjects(opaqueObjects, scene, camera);
  16530. _this.toneMapping = currentToneMapping;
  16531. textures.updateMultisampleRenderTarget(_transmissionRenderTarget);
  16532. textures.updateRenderTargetMipmap(_transmissionRenderTarget);
  16533. _this.setRenderTarget(currentRenderTarget);
  16534. }
  16535. function renderObjects(renderList, scene, camera) {
  16536. const overrideMaterial = scene.isScene === true ? scene.overrideMaterial : null;
  16537. for (let i = 0, l = renderList.length; i < l; i++) {
  16538. const renderItem = renderList[i];
  16539. const object = renderItem.object;
  16540. const geometry = renderItem.geometry;
  16541. const material = overrideMaterial === null ? renderItem.material : overrideMaterial;
  16542. const group = renderItem.group;
  16543. if (object.layers.test(camera.layers)) {
  16544. renderObject(object, scene, camera, geometry, material, group);
  16545. }
  16546. }
  16547. }
  16548. function renderObject(object, scene, camera, geometry, material, group) {
  16549. object.onBeforeRender(_this, scene, camera, geometry, material, group);
  16550. object.modelViewMatrix.multiplyMatrices(camera.matrixWorldInverse, object.matrixWorld);
  16551. object.normalMatrix.getNormalMatrix(object.modelViewMatrix);
  16552. material.onBeforeRender(_this, scene, camera, geometry, object, group);
  16553. if (material.transparent === true && material.side === DoubleSide) {
  16554. material.side = BackSide;
  16555. material.needsUpdate = true;
  16556. _this.renderBufferDirect(camera, scene, geometry, material, object, group);
  16557. material.side = FrontSide;
  16558. material.needsUpdate = true;
  16559. _this.renderBufferDirect(camera, scene, geometry, material, object, group);
  16560. material.side = DoubleSide;
  16561. } else {
  16562. _this.renderBufferDirect(camera, scene, geometry, material, object, group);
  16563. }
  16564. object.onAfterRender(_this, scene, camera, geometry, material, group);
  16565. }
  16566. function getProgram(material, scene, object) {
  16567. if (scene.isScene !== true) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...
  16568. const materialProperties = properties.get(material);
  16569. const lights = currentRenderState.state.lights;
  16570. const shadowsArray = currentRenderState.state.shadowsArray;
  16571. const lightsStateVersion = lights.state.version;
  16572. const parameters = programCache.getParameters(material, lights.state, shadowsArray, scene, object);
  16573. const programCacheKey = programCache.getProgramCacheKey(parameters);
  16574. let programs = materialProperties.programs; // always update environment and fog - changing these trigger an getProgram call, but it's possible that the program doesn't change
  16575. materialProperties.environment = material.isMeshStandardMaterial ? scene.environment : null;
  16576. materialProperties.fog = scene.fog;
  16577. materialProperties.envMap = (material.isMeshStandardMaterial ? cubeuvmaps : cubemaps).get(material.envMap || materialProperties.environment);
  16578. if (programs === undefined) {
  16579. // new material
  16580. material.addEventListener('dispose', onMaterialDispose);
  16581. programs = new Map();
  16582. materialProperties.programs = programs;
  16583. }
  16584. let program = programs.get(programCacheKey);
  16585. if (program !== undefined) {
  16586. // early out if program and light state is identical
  16587. if (materialProperties.currentProgram === program && materialProperties.lightsStateVersion === lightsStateVersion) {
  16588. updateCommonMaterialProperties(material, parameters);
  16589. return program;
  16590. }
  16591. } else {
  16592. parameters.uniforms = programCache.getUniforms(material);
  16593. material.onBuild(object, parameters, _this);
  16594. material.onBeforeCompile(parameters, _this);
  16595. program = programCache.acquireProgram(parameters, programCacheKey);
  16596. programs.set(programCacheKey, program);
  16597. materialProperties.uniforms = parameters.uniforms;
  16598. }
  16599. const uniforms = materialProperties.uniforms;
  16600. if (!material.isShaderMaterial && !material.isRawShaderMaterial || material.clipping === true) {
  16601. uniforms.clippingPlanes = clipping.uniform;
  16602. }
  16603. updateCommonMaterialProperties(material, parameters); // store the light setup it was created for
  16604. materialProperties.needsLights = materialNeedsLights(material);
  16605. materialProperties.lightsStateVersion = lightsStateVersion;
  16606. if (materialProperties.needsLights) {
  16607. // wire up the material to this renderer's lighting state
  16608. uniforms.ambientLightColor.value = lights.state.ambient;
  16609. uniforms.lightProbe.value = lights.state.probe;
  16610. uniforms.directionalLights.value = lights.state.directional;
  16611. uniforms.directionalLightShadows.value = lights.state.directionalShadow;
  16612. uniforms.spotLights.value = lights.state.spot;
  16613. uniforms.spotLightShadows.value = lights.state.spotShadow;
  16614. uniforms.rectAreaLights.value = lights.state.rectArea;
  16615. uniforms.ltc_1.value = lights.state.rectAreaLTC1;
  16616. uniforms.ltc_2.value = lights.state.rectAreaLTC2;
  16617. uniforms.pointLights.value = lights.state.point;
  16618. uniforms.pointLightShadows.value = lights.state.pointShadow;
  16619. uniforms.hemisphereLights.value = lights.state.hemi;
  16620. uniforms.directionalShadowMap.value = lights.state.directionalShadowMap;
  16621. uniforms.directionalShadowMatrix.value = lights.state.directionalShadowMatrix;
  16622. uniforms.spotShadowMap.value = lights.state.spotShadowMap;
  16623. uniforms.spotLightMatrix.value = lights.state.spotLightMatrix;
  16624. uniforms.spotLightMap.value = lights.state.spotLightMap;
  16625. uniforms.pointShadowMap.value = lights.state.pointShadowMap;
  16626. uniforms.pointShadowMatrix.value = lights.state.pointShadowMatrix; // TODO (abelnation): add area lights shadow info to uniforms
  16627. }
  16628. const progUniforms = program.getUniforms();
  16629. const uniformsList = WebGLUniforms.seqWithValue(progUniforms.seq, uniforms);
  16630. materialProperties.currentProgram = program;
  16631. materialProperties.uniformsList = uniformsList;
  16632. return program;
  16633. }
  16634. function updateCommonMaterialProperties(material, parameters) {
  16635. const materialProperties = properties.get(material);
  16636. materialProperties.outputEncoding = parameters.outputEncoding;
  16637. materialProperties.instancing = parameters.instancing;
  16638. materialProperties.skinning = parameters.skinning;
  16639. materialProperties.morphTargets = parameters.morphTargets;
  16640. materialProperties.morphNormals = parameters.morphNormals;
  16641. materialProperties.morphColors = parameters.morphColors;
  16642. materialProperties.morphTargetsCount = parameters.morphTargetsCount;
  16643. materialProperties.numClippingPlanes = parameters.numClippingPlanes;
  16644. materialProperties.numIntersection = parameters.numClipIntersection;
  16645. materialProperties.vertexAlphas = parameters.vertexAlphas;
  16646. materialProperties.vertexTangents = parameters.vertexTangents;
  16647. materialProperties.toneMapping = parameters.toneMapping;
  16648. }
  16649. function setProgram(camera, scene, geometry, material, object) {
  16650. if (scene.isScene !== true) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...
  16651. textures.resetTextureUnits();
  16652. const fog = scene.fog;
  16653. const environment = material.isMeshStandardMaterial ? scene.environment : null;
  16654. const encoding = _currentRenderTarget === null ? _this.outputEncoding : _currentRenderTarget.isXRRenderTarget === true ? _currentRenderTarget.texture.encoding : LinearEncoding;
  16655. const envMap = (material.isMeshStandardMaterial ? cubeuvmaps : cubemaps).get(material.envMap || environment);
  16656. const vertexAlphas = material.vertexColors === true && !!geometry.attributes.color && geometry.attributes.color.itemSize === 4;
  16657. const vertexTangents = !!material.normalMap && !!geometry.attributes.tangent;
  16658. const morphTargets = !!geometry.morphAttributes.position;
  16659. const morphNormals = !!geometry.morphAttributes.normal;
  16660. const morphColors = !!geometry.morphAttributes.color;
  16661. const toneMapping = material.toneMapped ? _this.toneMapping : NoToneMapping;
  16662. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  16663. const morphTargetsCount = morphAttribute !== undefined ? morphAttribute.length : 0;
  16664. const materialProperties = properties.get(material);
  16665. const lights = currentRenderState.state.lights;
  16666. if (_clippingEnabled === true) {
  16667. if (_localClippingEnabled === true || camera !== _currentCamera) {
  16668. const useCache = camera === _currentCamera && material.id === _currentMaterialId; // we might want to call this function with some ClippingGroup
  16669. // object instead of the material, once it becomes feasible
  16670. // (#8465, #8379)
  16671. clipping.setState(material, camera, useCache);
  16672. }
  16673. } //
  16674. let needsProgramChange = false;
  16675. if (material.version === materialProperties.__version) {
  16676. if (materialProperties.needsLights && materialProperties.lightsStateVersion !== lights.state.version) {
  16677. needsProgramChange = true;
  16678. } else if (materialProperties.outputEncoding !== encoding) {
  16679. needsProgramChange = true;
  16680. } else if (object.isInstancedMesh && materialProperties.instancing === false) {
  16681. needsProgramChange = true;
  16682. } else if (!object.isInstancedMesh && materialProperties.instancing === true) {
  16683. needsProgramChange = true;
  16684. } else if (object.isSkinnedMesh && materialProperties.skinning === false) {
  16685. needsProgramChange = true;
  16686. } else if (!object.isSkinnedMesh && materialProperties.skinning === true) {
  16687. needsProgramChange = true;
  16688. } else if (materialProperties.envMap !== envMap) {
  16689. needsProgramChange = true;
  16690. } else if (material.fog === true && materialProperties.fog !== fog) {
  16691. needsProgramChange = true;
  16692. } else if (materialProperties.numClippingPlanes !== undefined && (materialProperties.numClippingPlanes !== clipping.numPlanes || materialProperties.numIntersection !== clipping.numIntersection)) {
  16693. needsProgramChange = true;
  16694. } else if (materialProperties.vertexAlphas !== vertexAlphas) {
  16695. needsProgramChange = true;
  16696. } else if (materialProperties.vertexTangents !== vertexTangents) {
  16697. needsProgramChange = true;
  16698. } else if (materialProperties.morphTargets !== morphTargets) {
  16699. needsProgramChange = true;
  16700. } else if (materialProperties.morphNormals !== morphNormals) {
  16701. needsProgramChange = true;
  16702. } else if (materialProperties.morphColors !== morphColors) {
  16703. needsProgramChange = true;
  16704. } else if (materialProperties.toneMapping !== toneMapping) {
  16705. needsProgramChange = true;
  16706. } else if (capabilities.isWebGL2 === true && materialProperties.morphTargetsCount !== morphTargetsCount) {
  16707. needsProgramChange = true;
  16708. }
  16709. } else {
  16710. needsProgramChange = true;
  16711. materialProperties.__version = material.version;
  16712. } //
  16713. let program = materialProperties.currentProgram;
  16714. if (needsProgramChange === true) {
  16715. program = getProgram(material, scene, object);
  16716. }
  16717. let refreshProgram = false;
  16718. let refreshMaterial = false;
  16719. let refreshLights = false;
  16720. const p_uniforms = program.getUniforms(),
  16721. m_uniforms = materialProperties.uniforms;
  16722. if (state.useProgram(program.program)) {
  16723. refreshProgram = true;
  16724. refreshMaterial = true;
  16725. refreshLights = true;
  16726. }
  16727. if (material.id !== _currentMaterialId) {
  16728. _currentMaterialId = material.id;
  16729. refreshMaterial = true;
  16730. }
  16731. if (refreshProgram || _currentCamera !== camera) {
  16732. p_uniforms.setValue(_gl, 'projectionMatrix', camera.projectionMatrix);
  16733. if (capabilities.logarithmicDepthBuffer) {
  16734. p_uniforms.setValue(_gl, 'logDepthBufFC', 2.0 / (Math.log(camera.far + 1.0) / Math.LN2));
  16735. }
  16736. if (_currentCamera !== camera) {
  16737. _currentCamera = camera; // lighting uniforms depend on the camera so enforce an update
  16738. // now, in case this material supports lights - or later, when
  16739. // the next material that does gets activated:
  16740. refreshMaterial = true; // set to true on material change
  16741. refreshLights = true; // remains set until update done
  16742. } // load material specific uniforms
  16743. // (shader material also gets them for the sake of genericity)
  16744. if (material.isShaderMaterial || material.isMeshPhongMaterial || material.isMeshToonMaterial || material.isMeshStandardMaterial || material.envMap) {
  16745. const uCamPos = p_uniforms.map.cameraPosition;
  16746. if (uCamPos !== undefined) {
  16747. uCamPos.setValue(_gl, _vector3.setFromMatrixPosition(camera.matrixWorld));
  16748. }
  16749. }
  16750. if (material.isMeshPhongMaterial || material.isMeshToonMaterial || material.isMeshLambertMaterial || material.isMeshBasicMaterial || material.isMeshStandardMaterial || material.isShaderMaterial) {
  16751. p_uniforms.setValue(_gl, 'isOrthographic', camera.isOrthographicCamera === true);
  16752. }
  16753. if (material.isMeshPhongMaterial || material.isMeshToonMaterial || material.isMeshLambertMaterial || material.isMeshBasicMaterial || material.isMeshStandardMaterial || material.isShaderMaterial || material.isShadowMaterial || object.isSkinnedMesh) {
  16754. p_uniforms.setValue(_gl, 'viewMatrix', camera.matrixWorldInverse);
  16755. }
  16756. } // skinning and morph target uniforms must be set even if material didn't change
  16757. // auto-setting of texture unit for bone and morph texture must go before other textures
  16758. // otherwise textures used for skinning and morphing can take over texture units reserved for other material textures
  16759. if (object.isSkinnedMesh) {
  16760. p_uniforms.setOptional(_gl, object, 'bindMatrix');
  16761. p_uniforms.setOptional(_gl, object, 'bindMatrixInverse');
  16762. const skeleton = object.skeleton;
  16763. if (skeleton) {
  16764. if (capabilities.floatVertexTextures) {
  16765. if (skeleton.boneTexture === null) skeleton.computeBoneTexture();
  16766. p_uniforms.setValue(_gl, 'boneTexture', skeleton.boneTexture, textures);
  16767. p_uniforms.setValue(_gl, 'boneTextureSize', skeleton.boneTextureSize);
  16768. } else {
  16769. console.warn('THREE.WebGLRenderer: SkinnedMesh can only be used with WebGL 2. With WebGL 1 OES_texture_float and vertex textures support is required.');
  16770. }
  16771. }
  16772. }
  16773. const morphAttributes = geometry.morphAttributes;
  16774. if (morphAttributes.position !== undefined || morphAttributes.normal !== undefined || morphAttributes.color !== undefined && capabilities.isWebGL2 === true) {
  16775. morphtargets.update(object, geometry, material, program);
  16776. }
  16777. if (refreshMaterial || materialProperties.receiveShadow !== object.receiveShadow) {
  16778. materialProperties.receiveShadow = object.receiveShadow;
  16779. p_uniforms.setValue(_gl, 'receiveShadow', object.receiveShadow);
  16780. } // https://github.com/mrdoob/three.js/pull/24467#issuecomment-1209031512
  16781. if (material.isMeshGouraudMaterial && material.envMap !== null) {
  16782. m_uniforms.envMap.value = envMap;
  16783. m_uniforms.flipEnvMap.value = envMap.isCubeTexture && envMap.isRenderTargetTexture === false ? -1 : 1;
  16784. }
  16785. if (refreshMaterial) {
  16786. p_uniforms.setValue(_gl, 'toneMappingExposure', _this.toneMappingExposure);
  16787. if (materialProperties.needsLights) {
  16788. // the current material requires lighting info
  16789. // note: all lighting uniforms are always set correctly
  16790. // they simply reference the renderer's state for their
  16791. // values
  16792. //
  16793. // use the current material's .needsUpdate flags to set
  16794. // the GL state when required
  16795. markUniformsLightsNeedsUpdate(m_uniforms, refreshLights);
  16796. } // refresh uniforms common to several materials
  16797. if (fog && material.fog === true) {
  16798. materials.refreshFogUniforms(m_uniforms, fog);
  16799. }
  16800. materials.refreshMaterialUniforms(m_uniforms, material, _pixelRatio, _height, _transmissionRenderTarget);
  16801. WebGLUniforms.upload(_gl, materialProperties.uniformsList, m_uniforms, textures);
  16802. }
  16803. if (material.isShaderMaterial && material.uniformsNeedUpdate === true) {
  16804. WebGLUniforms.upload(_gl, materialProperties.uniformsList, m_uniforms, textures);
  16805. material.uniformsNeedUpdate = false;
  16806. }
  16807. if (material.isSpriteMaterial) {
  16808. p_uniforms.setValue(_gl, 'center', object.center);
  16809. } // common matrices
  16810. p_uniforms.setValue(_gl, 'modelViewMatrix', object.modelViewMatrix);
  16811. p_uniforms.setValue(_gl, 'normalMatrix', object.normalMatrix);
  16812. p_uniforms.setValue(_gl, 'modelMatrix', object.matrixWorld); // UBOs
  16813. if (material.isShaderMaterial || material.isRawShaderMaterial) {
  16814. const groups = material.uniformsGroups;
  16815. for (let i = 0, l = groups.length; i < l; i++) {
  16816. if (capabilities.isWebGL2) {
  16817. const group = groups[i];
  16818. uniformsGroups.update(group, program);
  16819. uniformsGroups.bind(group, program);
  16820. } else {
  16821. console.warn('THREE.WebGLRenderer: Uniform Buffer Objects can only be used with WebGL 2.');
  16822. }
  16823. }
  16824. }
  16825. return program;
  16826. } // If uniforms are marked as clean, they don't need to be loaded to the GPU.
  16827. function markUniformsLightsNeedsUpdate(uniforms, value) {
  16828. uniforms.ambientLightColor.needsUpdate = value;
  16829. uniforms.lightProbe.needsUpdate = value;
  16830. uniforms.directionalLights.needsUpdate = value;
  16831. uniforms.directionalLightShadows.needsUpdate = value;
  16832. uniforms.pointLights.needsUpdate = value;
  16833. uniforms.pointLightShadows.needsUpdate = value;
  16834. uniforms.spotLights.needsUpdate = value;
  16835. uniforms.spotLightShadows.needsUpdate = value;
  16836. uniforms.rectAreaLights.needsUpdate = value;
  16837. uniforms.hemisphereLights.needsUpdate = value;
  16838. }
  16839. function materialNeedsLights(material) {
  16840. return material.isMeshLambertMaterial || material.isMeshToonMaterial || material.isMeshPhongMaterial || material.isMeshStandardMaterial || material.isShadowMaterial || material.isShaderMaterial && material.lights === true;
  16841. }
  16842. this.getActiveCubeFace = function () {
  16843. return _currentActiveCubeFace;
  16844. };
  16845. this.getActiveMipmapLevel = function () {
  16846. return _currentActiveMipmapLevel;
  16847. };
  16848. this.getRenderTarget = function () {
  16849. return _currentRenderTarget;
  16850. };
  16851. this.setRenderTargetTextures = function (renderTarget, colorTexture, depthTexture) {
  16852. properties.get(renderTarget.texture).__webglTexture = colorTexture;
  16853. properties.get(renderTarget.depthTexture).__webglTexture = depthTexture;
  16854. const renderTargetProperties = properties.get(renderTarget);
  16855. renderTargetProperties.__hasExternalTextures = true;
  16856. if (renderTargetProperties.__hasExternalTextures) {
  16857. renderTargetProperties.__autoAllocateDepthBuffer = depthTexture === undefined;
  16858. if (!renderTargetProperties.__autoAllocateDepthBuffer) {
  16859. // The multisample_render_to_texture extension doesn't work properly if there
  16860. // are midframe flushes and an external depth buffer. Disable use of the extension.
  16861. if (extensions.has('WEBGL_multisampled_render_to_texture') === true) {
  16862. console.warn('THREE.WebGLRenderer: Render-to-texture extension was disabled because an external texture was provided');
  16863. renderTargetProperties.__useRenderToTexture = false;
  16864. }
  16865. }
  16866. }
  16867. };
  16868. this.setRenderTargetFramebuffer = function (renderTarget, defaultFramebuffer) {
  16869. const renderTargetProperties = properties.get(renderTarget);
  16870. renderTargetProperties.__webglFramebuffer = defaultFramebuffer;
  16871. renderTargetProperties.__useDefaultFramebuffer = defaultFramebuffer === undefined;
  16872. };
  16873. this.setRenderTarget = function (renderTarget, activeCubeFace = 0, activeMipmapLevel = 0) {
  16874. _currentRenderTarget = renderTarget;
  16875. _currentActiveCubeFace = activeCubeFace;
  16876. _currentActiveMipmapLevel = activeMipmapLevel;
  16877. let useDefaultFramebuffer = true;
  16878. if (renderTarget) {
  16879. const renderTargetProperties = properties.get(renderTarget);
  16880. if (renderTargetProperties.__useDefaultFramebuffer !== undefined) {
  16881. // We need to make sure to rebind the framebuffer.
  16882. state.bindFramebuffer(_gl.FRAMEBUFFER, null);
  16883. useDefaultFramebuffer = false;
  16884. } else if (renderTargetProperties.__webglFramebuffer === undefined) {
  16885. textures.setupRenderTarget(renderTarget);
  16886. } else if (renderTargetProperties.__hasExternalTextures) {
  16887. // Color and depth texture must be rebound in order for the swapchain to update.
  16888. textures.rebindTextures(renderTarget, properties.get(renderTarget.texture).__webglTexture, properties.get(renderTarget.depthTexture).__webglTexture);
  16889. }
  16890. }
  16891. let framebuffer = null;
  16892. let isCube = false;
  16893. let isRenderTarget3D = false;
  16894. if (renderTarget) {
  16895. const texture = renderTarget.texture;
  16896. if (texture.isData3DTexture || texture.isDataArrayTexture) {
  16897. isRenderTarget3D = true;
  16898. }
  16899. const __webglFramebuffer = properties.get(renderTarget).__webglFramebuffer;
  16900. if (renderTarget.isWebGLCubeRenderTarget) {
  16901. framebuffer = __webglFramebuffer[activeCubeFace];
  16902. isCube = true;
  16903. } else if (capabilities.isWebGL2 && renderTarget.samples > 0 && textures.useMultisampledRTT(renderTarget) === false) {
  16904. framebuffer = properties.get(renderTarget).__webglMultisampledFramebuffer;
  16905. } else {
  16906. framebuffer = __webglFramebuffer;
  16907. }
  16908. _currentViewport.copy(renderTarget.viewport);
  16909. _currentScissor.copy(renderTarget.scissor);
  16910. _currentScissorTest = renderTarget.scissorTest;
  16911. } else {
  16912. _currentViewport.copy(_viewport).multiplyScalar(_pixelRatio).floor();
  16913. _currentScissor.copy(_scissor).multiplyScalar(_pixelRatio).floor();
  16914. _currentScissorTest = _scissorTest;
  16915. }
  16916. const framebufferBound = state.bindFramebuffer(_gl.FRAMEBUFFER, framebuffer);
  16917. if (framebufferBound && capabilities.drawBuffers && useDefaultFramebuffer) {
  16918. state.drawBuffers(renderTarget, framebuffer);
  16919. }
  16920. state.viewport(_currentViewport);
  16921. state.scissor(_currentScissor);
  16922. state.setScissorTest(_currentScissorTest);
  16923. if (isCube) {
  16924. const textureProperties = properties.get(renderTarget.texture);
  16925. _gl.framebufferTexture2D(_gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + activeCubeFace, textureProperties.__webglTexture, activeMipmapLevel);
  16926. } else if (isRenderTarget3D) {
  16927. const textureProperties = properties.get(renderTarget.texture);
  16928. const layer = activeCubeFace || 0;
  16929. _gl.framebufferTextureLayer(_gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, textureProperties.__webglTexture, activeMipmapLevel || 0, layer);
  16930. }
  16931. _currentMaterialId = -1; // reset current material to ensure correct uniform bindings
  16932. };
  16933. this.readRenderTargetPixels = function (renderTarget, x, y, width, height, buffer, activeCubeFaceIndex) {
  16934. if (!(renderTarget && renderTarget.isWebGLRenderTarget)) {
  16935. console.error('THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.');
  16936. return;
  16937. }
  16938. let framebuffer = properties.get(renderTarget).__webglFramebuffer;
  16939. if (renderTarget.isWebGLCubeRenderTarget && activeCubeFaceIndex !== undefined) {
  16940. framebuffer = framebuffer[activeCubeFaceIndex];
  16941. }
  16942. if (framebuffer) {
  16943. state.bindFramebuffer(_gl.FRAMEBUFFER, framebuffer);
  16944. try {
  16945. const texture = renderTarget.texture;
  16946. const textureFormat = texture.format;
  16947. const textureType = texture.type;
  16948. if (textureFormat !== RGBAFormat && utils.convert(textureFormat) !== _gl.getParameter(_gl.IMPLEMENTATION_COLOR_READ_FORMAT)) {
  16949. console.error('THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.');
  16950. return;
  16951. }
  16952. const halfFloatSupportedByExt = textureType === HalfFloatType && (extensions.has('EXT_color_buffer_half_float') || capabilities.isWebGL2 && extensions.has('EXT_color_buffer_float'));
  16953. if (textureType !== UnsignedByteType && utils.convert(textureType) !== _gl.getParameter(_gl.IMPLEMENTATION_COLOR_READ_TYPE) && // Edge and Chrome Mac < 52 (#9513)
  16954. !(textureType === FloatType && (capabilities.isWebGL2 || extensions.has('OES_texture_float') || extensions.has('WEBGL_color_buffer_float'))) && // Chrome Mac >= 52 and Firefox
  16955. !halfFloatSupportedByExt) {
  16956. console.error('THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.');
  16957. return;
  16958. } // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604)
  16959. if (x >= 0 && x <= renderTarget.width - width && y >= 0 && y <= renderTarget.height - height) {
  16960. _gl.readPixels(x, y, width, height, utils.convert(textureFormat), utils.convert(textureType), buffer);
  16961. }
  16962. } finally {
  16963. // restore framebuffer of current render target if necessary
  16964. const framebuffer = _currentRenderTarget !== null ? properties.get(_currentRenderTarget).__webglFramebuffer : null;
  16965. state.bindFramebuffer(_gl.FRAMEBUFFER, framebuffer);
  16966. }
  16967. }
  16968. };
  16969. this.copyFramebufferToTexture = function (position, texture, level = 0) {
  16970. const levelScale = Math.pow(2, -level);
  16971. const width = Math.floor(texture.image.width * levelScale);
  16972. const height = Math.floor(texture.image.height * levelScale);
  16973. textures.setTexture2D(texture, 0);
  16974. _gl.copyTexSubImage2D(_gl.TEXTURE_2D, level, 0, 0, position.x, position.y, width, height);
  16975. state.unbindTexture();
  16976. };
  16977. this.copyTextureToTexture = function (position, srcTexture, dstTexture, level = 0) {
  16978. const width = srcTexture.image.width;
  16979. const height = srcTexture.image.height;
  16980. const glFormat = utils.convert(dstTexture.format);
  16981. const glType = utils.convert(dstTexture.type);
  16982. textures.setTexture2D(dstTexture, 0); // As another texture upload may have changed pixelStorei
  16983. // parameters, make sure they are correct for the dstTexture
  16984. _gl.pixelStorei(_gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY);
  16985. _gl.pixelStorei(_gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha);
  16986. _gl.pixelStorei(_gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment);
  16987. if (srcTexture.isDataTexture) {
  16988. _gl.texSubImage2D(_gl.TEXTURE_2D, level, position.x, position.y, width, height, glFormat, glType, srcTexture.image.data);
  16989. } else {
  16990. if (srcTexture.isCompressedTexture) {
  16991. _gl.compressedTexSubImage2D(_gl.TEXTURE_2D, level, position.x, position.y, srcTexture.mipmaps[0].width, srcTexture.mipmaps[0].height, glFormat, srcTexture.mipmaps[0].data);
  16992. } else {
  16993. _gl.texSubImage2D(_gl.TEXTURE_2D, level, position.x, position.y, glFormat, glType, srcTexture.image);
  16994. }
  16995. } // Generate mipmaps only when copying level 0
  16996. if (level === 0 && dstTexture.generateMipmaps) _gl.generateMipmap(_gl.TEXTURE_2D);
  16997. state.unbindTexture();
  16998. };
  16999. this.copyTextureToTexture3D = function (sourceBox, position, srcTexture, dstTexture, level = 0) {
  17000. if (_this.isWebGL1Renderer) {
  17001. console.warn('THREE.WebGLRenderer.copyTextureToTexture3D: can only be used with WebGL2.');
  17002. return;
  17003. }
  17004. const width = sourceBox.max.x - sourceBox.min.x + 1;
  17005. const height = sourceBox.max.y - sourceBox.min.y + 1;
  17006. const depth = sourceBox.max.z - sourceBox.min.z + 1;
  17007. const glFormat = utils.convert(dstTexture.format);
  17008. const glType = utils.convert(dstTexture.type);
  17009. let glTarget;
  17010. if (dstTexture.isData3DTexture) {
  17011. textures.setTexture3D(dstTexture, 0);
  17012. glTarget = _gl.TEXTURE_3D;
  17013. } else if (dstTexture.isDataArrayTexture) {
  17014. textures.setTexture2DArray(dstTexture, 0);
  17015. glTarget = _gl.TEXTURE_2D_ARRAY;
  17016. } else {
  17017. console.warn('THREE.WebGLRenderer.copyTextureToTexture3D: only supports THREE.DataTexture3D and THREE.DataTexture2DArray.');
  17018. return;
  17019. }
  17020. _gl.pixelStorei(_gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY);
  17021. _gl.pixelStorei(_gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha);
  17022. _gl.pixelStorei(_gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment);
  17023. const unpackRowLen = _gl.getParameter(_gl.UNPACK_ROW_LENGTH);
  17024. const unpackImageHeight = _gl.getParameter(_gl.UNPACK_IMAGE_HEIGHT);
  17025. const unpackSkipPixels = _gl.getParameter(_gl.UNPACK_SKIP_PIXELS);
  17026. const unpackSkipRows = _gl.getParameter(_gl.UNPACK_SKIP_ROWS);
  17027. const unpackSkipImages = _gl.getParameter(_gl.UNPACK_SKIP_IMAGES);
  17028. const image = srcTexture.isCompressedTexture ? srcTexture.mipmaps[0] : srcTexture.image;
  17029. _gl.pixelStorei(_gl.UNPACK_ROW_LENGTH, image.width);
  17030. _gl.pixelStorei(_gl.UNPACK_IMAGE_HEIGHT, image.height);
  17031. _gl.pixelStorei(_gl.UNPACK_SKIP_PIXELS, sourceBox.min.x);
  17032. _gl.pixelStorei(_gl.UNPACK_SKIP_ROWS, sourceBox.min.y);
  17033. _gl.pixelStorei(_gl.UNPACK_SKIP_IMAGES, sourceBox.min.z);
  17034. if (srcTexture.isDataTexture || srcTexture.isData3DTexture) {
  17035. _gl.texSubImage3D(glTarget, level, position.x, position.y, position.z, width, height, depth, glFormat, glType, image.data);
  17036. } else {
  17037. if (srcTexture.isCompressedTexture) {
  17038. console.warn('THREE.WebGLRenderer.copyTextureToTexture3D: untested support for compressed srcTexture.');
  17039. _gl.compressedTexSubImage3D(glTarget, level, position.x, position.y, position.z, width, height, depth, glFormat, image.data);
  17040. } else {
  17041. _gl.texSubImage3D(glTarget, level, position.x, position.y, position.z, width, height, depth, glFormat, glType, image);
  17042. }
  17043. }
  17044. _gl.pixelStorei(_gl.UNPACK_ROW_LENGTH, unpackRowLen);
  17045. _gl.pixelStorei(_gl.UNPACK_IMAGE_HEIGHT, unpackImageHeight);
  17046. _gl.pixelStorei(_gl.UNPACK_SKIP_PIXELS, unpackSkipPixels);
  17047. _gl.pixelStorei(_gl.UNPACK_SKIP_ROWS, unpackSkipRows);
  17048. _gl.pixelStorei(_gl.UNPACK_SKIP_IMAGES, unpackSkipImages); // Generate mipmaps only when copying level 0
  17049. if (level === 0 && dstTexture.generateMipmaps) _gl.generateMipmap(glTarget);
  17050. state.unbindTexture();
  17051. };
  17052. this.initTexture = function (texture) {
  17053. if (texture.isCubeTexture) {
  17054. textures.setTextureCube(texture, 0);
  17055. } else if (texture.isData3DTexture) {
  17056. textures.setTexture3D(texture, 0);
  17057. } else if (texture.isDataArrayTexture) {
  17058. textures.setTexture2DArray(texture, 0);
  17059. } else {
  17060. textures.setTexture2D(texture, 0);
  17061. }
  17062. state.unbindTexture();
  17063. };
  17064. this.resetState = function () {
  17065. _currentActiveCubeFace = 0;
  17066. _currentActiveMipmapLevel = 0;
  17067. _currentRenderTarget = null;
  17068. state.reset();
  17069. bindingStates.reset();
  17070. };
  17071. if (typeof __THREE_DEVTOOLS__ !== 'undefined') {
  17072. __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent('observe', {
  17073. detail: this
  17074. }));
  17075. }
  17076. }
  17077. class WebGL1Renderer extends WebGLRenderer {}
  17078. WebGL1Renderer.prototype.isWebGL1Renderer = true;
  17079. class FogExp2 {
  17080. constructor(color, density = 0.00025) {
  17081. this.isFogExp2 = true;
  17082. this.name = '';
  17083. this.color = new Color(color);
  17084. this.density = density;
  17085. }
  17086. clone() {
  17087. return new FogExp2(this.color, this.density);
  17088. }
  17089. toJSON() {
  17090. return {
  17091. type: 'FogExp2',
  17092. color: this.color.getHex(),
  17093. density: this.density
  17094. };
  17095. }
  17096. }
  17097. class Fog {
  17098. constructor(color, near = 1, far = 1000) {
  17099. this.isFog = true;
  17100. this.name = '';
  17101. this.color = new Color(color);
  17102. this.near = near;
  17103. this.far = far;
  17104. }
  17105. clone() {
  17106. return new Fog(this.color, this.near, this.far);
  17107. }
  17108. toJSON() {
  17109. return {
  17110. type: 'Fog',
  17111. color: this.color.getHex(),
  17112. near: this.near,
  17113. far: this.far
  17114. };
  17115. }
  17116. }
  17117. class Scene extends Object3D {
  17118. constructor() {
  17119. super();
  17120. this.isScene = true;
  17121. this.type = 'Scene';
  17122. this.background = null;
  17123. this.environment = null;
  17124. this.fog = null;
  17125. this.overrideMaterial = null;
  17126. if (typeof __THREE_DEVTOOLS__ !== 'undefined') {
  17127. __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent('observe', {
  17128. detail: this
  17129. }));
  17130. }
  17131. }
  17132. copy(source, recursive) {
  17133. super.copy(source, recursive);
  17134. if (source.background !== null) this.background = source.background.clone();
  17135. if (source.environment !== null) this.environment = source.environment.clone();
  17136. if (source.fog !== null) this.fog = source.fog.clone();
  17137. if (source.overrideMaterial !== null) this.overrideMaterial = source.overrideMaterial.clone();
  17138. this.matrixAutoUpdate = source.matrixAutoUpdate;
  17139. return this;
  17140. }
  17141. toJSON(meta) {
  17142. const data = super.toJSON(meta);
  17143. if (this.fog !== null) data.object.fog = this.fog.toJSON();
  17144. return data;
  17145. } // @deprecated
  17146. get autoUpdate() {
  17147. console.warn('THREE.Scene: autoUpdate was renamed to matrixWorldAutoUpdate in r144.');
  17148. return this.matrixWorldAutoUpdate;
  17149. }
  17150. set autoUpdate(value) {
  17151. console.warn('THREE.Scene: autoUpdate was renamed to matrixWorldAutoUpdate in r144.');
  17152. this.matrixWorldAutoUpdate = value;
  17153. }
  17154. }
  17155. class InterleavedBuffer {
  17156. constructor(array, stride) {
  17157. this.isInterleavedBuffer = true;
  17158. this.array = array;
  17159. this.stride = stride;
  17160. this.count = array !== undefined ? array.length / stride : 0;
  17161. this.usage = StaticDrawUsage;
  17162. this.updateRange = {
  17163. offset: 0,
  17164. count: -1
  17165. };
  17166. this.version = 0;
  17167. this.uuid = generateUUID();
  17168. }
  17169. onUploadCallback() {}
  17170. set needsUpdate(value) {
  17171. if (value === true) this.version++;
  17172. }
  17173. setUsage(value) {
  17174. this.usage = value;
  17175. return this;
  17176. }
  17177. copy(source) {
  17178. this.array = new source.array.constructor(source.array);
  17179. this.count = source.count;
  17180. this.stride = source.stride;
  17181. this.usage = source.usage;
  17182. return this;
  17183. }
  17184. copyAt(index1, attribute, index2) {
  17185. index1 *= this.stride;
  17186. index2 *= attribute.stride;
  17187. for (let i = 0, l = this.stride; i < l; i++) {
  17188. this.array[index1 + i] = attribute.array[index2 + i];
  17189. }
  17190. return this;
  17191. }
  17192. set(value, offset = 0) {
  17193. this.array.set(value, offset);
  17194. return this;
  17195. }
  17196. clone(data) {
  17197. if (data.arrayBuffers === undefined) {
  17198. data.arrayBuffers = {};
  17199. }
  17200. if (this.array.buffer._uuid === undefined) {
  17201. this.array.buffer._uuid = generateUUID();
  17202. }
  17203. if (data.arrayBuffers[this.array.buffer._uuid] === undefined) {
  17204. data.arrayBuffers[this.array.buffer._uuid] = this.array.slice(0).buffer;
  17205. }
  17206. const array = new this.array.constructor(data.arrayBuffers[this.array.buffer._uuid]);
  17207. const ib = new this.constructor(array, this.stride);
  17208. ib.setUsage(this.usage);
  17209. return ib;
  17210. }
  17211. onUpload(callback) {
  17212. this.onUploadCallback = callback;
  17213. return this;
  17214. }
  17215. toJSON(data) {
  17216. if (data.arrayBuffers === undefined) {
  17217. data.arrayBuffers = {};
  17218. } // generate UUID for array buffer if necessary
  17219. if (this.array.buffer._uuid === undefined) {
  17220. this.array.buffer._uuid = generateUUID();
  17221. }
  17222. if (data.arrayBuffers[this.array.buffer._uuid] === undefined) {
  17223. data.arrayBuffers[this.array.buffer._uuid] = Array.from(new Uint32Array(this.array.buffer));
  17224. } //
  17225. return {
  17226. uuid: this.uuid,
  17227. buffer: this.array.buffer._uuid,
  17228. type: this.array.constructor.name,
  17229. stride: this.stride
  17230. };
  17231. }
  17232. }
  17233. const _vector$6 = /*@__PURE__*/new Vector3();
  17234. class InterleavedBufferAttribute {
  17235. constructor(interleavedBuffer, itemSize, offset, normalized = false) {
  17236. this.isInterleavedBufferAttribute = true;
  17237. this.name = '';
  17238. this.data = interleavedBuffer;
  17239. this.itemSize = itemSize;
  17240. this.offset = offset;
  17241. this.normalized = normalized === true;
  17242. }
  17243. get count() {
  17244. return this.data.count;
  17245. }
  17246. get array() {
  17247. return this.data.array;
  17248. }
  17249. set needsUpdate(value) {
  17250. this.data.needsUpdate = value;
  17251. }
  17252. applyMatrix4(m) {
  17253. for (let i = 0, l = this.data.count; i < l; i++) {
  17254. _vector$6.fromBufferAttribute(this, i);
  17255. _vector$6.applyMatrix4(m);
  17256. this.setXYZ(i, _vector$6.x, _vector$6.y, _vector$6.z);
  17257. }
  17258. return this;
  17259. }
  17260. applyNormalMatrix(m) {
  17261. for (let i = 0, l = this.count; i < l; i++) {
  17262. _vector$6.fromBufferAttribute(this, i);
  17263. _vector$6.applyNormalMatrix(m);
  17264. this.setXYZ(i, _vector$6.x, _vector$6.y, _vector$6.z);
  17265. }
  17266. return this;
  17267. }
  17268. transformDirection(m) {
  17269. for (let i = 0, l = this.count; i < l; i++) {
  17270. _vector$6.fromBufferAttribute(this, i);
  17271. _vector$6.transformDirection(m);
  17272. this.setXYZ(i, _vector$6.x, _vector$6.y, _vector$6.z);
  17273. }
  17274. return this;
  17275. }
  17276. setX(index, x) {
  17277. if (this.normalized) x = normalize(x, this.array);
  17278. this.data.array[index * this.data.stride + this.offset] = x;
  17279. return this;
  17280. }
  17281. setY(index, y) {
  17282. if (this.normalized) y = normalize(y, this.array);
  17283. this.data.array[index * this.data.stride + this.offset + 1] = y;
  17284. return this;
  17285. }
  17286. setZ(index, z) {
  17287. if (this.normalized) z = normalize(z, this.array);
  17288. this.data.array[index * this.data.stride + this.offset + 2] = z;
  17289. return this;
  17290. }
  17291. setW(index, w) {
  17292. if (this.normalized) w = normalize(w, this.array);
  17293. this.data.array[index * this.data.stride + this.offset + 3] = w;
  17294. return this;
  17295. }
  17296. getX(index) {
  17297. let x = this.data.array[index * this.data.stride + this.offset];
  17298. if (this.normalized) x = denormalize(x, this.array);
  17299. return x;
  17300. }
  17301. getY(index) {
  17302. let y = this.data.array[index * this.data.stride + this.offset + 1];
  17303. if (this.normalized) y = denormalize(y, this.array);
  17304. return y;
  17305. }
  17306. getZ(index) {
  17307. let z = this.data.array[index * this.data.stride + this.offset + 2];
  17308. if (this.normalized) z = denormalize(z, this.array);
  17309. return z;
  17310. }
  17311. getW(index) {
  17312. let w = this.data.array[index * this.data.stride + this.offset + 3];
  17313. if (this.normalized) w = denormalize(w, this.array);
  17314. return w;
  17315. }
  17316. setXY(index, x, y) {
  17317. index = index * this.data.stride + this.offset;
  17318. if (this.normalized) {
  17319. x = normalize(x, this.array);
  17320. y = normalize(y, this.array);
  17321. }
  17322. this.data.array[index + 0] = x;
  17323. this.data.array[index + 1] = y;
  17324. return this;
  17325. }
  17326. setXYZ(index, x, y, z) {
  17327. index = index * this.data.stride + this.offset;
  17328. if (this.normalized) {
  17329. x = normalize(x, this.array);
  17330. y = normalize(y, this.array);
  17331. z = normalize(z, this.array);
  17332. }
  17333. this.data.array[index + 0] = x;
  17334. this.data.array[index + 1] = y;
  17335. this.data.array[index + 2] = z;
  17336. return this;
  17337. }
  17338. setXYZW(index, x, y, z, w) {
  17339. index = index * this.data.stride + this.offset;
  17340. if (this.normalized) {
  17341. x = normalize(x, this.array);
  17342. y = normalize(y, this.array);
  17343. z = normalize(z, this.array);
  17344. w = normalize(w, this.array);
  17345. }
  17346. this.data.array[index + 0] = x;
  17347. this.data.array[index + 1] = y;
  17348. this.data.array[index + 2] = z;
  17349. this.data.array[index + 3] = w;
  17350. return this;
  17351. }
  17352. clone(data) {
  17353. if (data === undefined) {
  17354. console.log('THREE.InterleavedBufferAttribute.clone(): Cloning an interleaved buffer attribute will deinterleave buffer data.');
  17355. const array = [];
  17356. for (let i = 0; i < this.count; i++) {
  17357. const index = i * this.data.stride + this.offset;
  17358. for (let j = 0; j < this.itemSize; j++) {
  17359. array.push(this.data.array[index + j]);
  17360. }
  17361. }
  17362. return new BufferAttribute(new this.array.constructor(array), this.itemSize, this.normalized);
  17363. } else {
  17364. if (data.interleavedBuffers === undefined) {
  17365. data.interleavedBuffers = {};
  17366. }
  17367. if (data.interleavedBuffers[this.data.uuid] === undefined) {
  17368. data.interleavedBuffers[this.data.uuid] = this.data.clone(data);
  17369. }
  17370. return new InterleavedBufferAttribute(data.interleavedBuffers[this.data.uuid], this.itemSize, this.offset, this.normalized);
  17371. }
  17372. }
  17373. toJSON(data) {
  17374. if (data === undefined) {
  17375. console.log('THREE.InterleavedBufferAttribute.toJSON(): Serializing an interleaved buffer attribute will deinterleave buffer data.');
  17376. const array = [];
  17377. for (let i = 0; i < this.count; i++) {
  17378. const index = i * this.data.stride + this.offset;
  17379. for (let j = 0; j < this.itemSize; j++) {
  17380. array.push(this.data.array[index + j]);
  17381. }
  17382. } // deinterleave data and save it as an ordinary buffer attribute for now
  17383. return {
  17384. itemSize: this.itemSize,
  17385. type: this.array.constructor.name,
  17386. array: array,
  17387. normalized: this.normalized
  17388. };
  17389. } else {
  17390. // save as true interleaved attribtue
  17391. if (data.interleavedBuffers === undefined) {
  17392. data.interleavedBuffers = {};
  17393. }
  17394. if (data.interleavedBuffers[this.data.uuid] === undefined) {
  17395. data.interleavedBuffers[this.data.uuid] = this.data.toJSON(data);
  17396. }
  17397. return {
  17398. isInterleavedBufferAttribute: true,
  17399. itemSize: this.itemSize,
  17400. data: this.data.uuid,
  17401. offset: this.offset,
  17402. normalized: this.normalized
  17403. };
  17404. }
  17405. }
  17406. }
  17407. class SpriteMaterial extends Material {
  17408. constructor(parameters) {
  17409. super();
  17410. this.isSpriteMaterial = true;
  17411. this.type = 'SpriteMaterial';
  17412. this.color = new Color(0xffffff);
  17413. this.map = null;
  17414. this.alphaMap = null;
  17415. this.rotation = 0;
  17416. this.sizeAttenuation = true;
  17417. this.transparent = true;
  17418. this.fog = true;
  17419. this.setValues(parameters);
  17420. }
  17421. copy(source) {
  17422. super.copy(source);
  17423. this.color.copy(source.color);
  17424. this.map = source.map;
  17425. this.alphaMap = source.alphaMap;
  17426. this.rotation = source.rotation;
  17427. this.sizeAttenuation = source.sizeAttenuation;
  17428. this.fog = source.fog;
  17429. return this;
  17430. }
  17431. }
  17432. let _geometry;
  17433. const _intersectPoint = /*@__PURE__*/new Vector3();
  17434. const _worldScale = /*@__PURE__*/new Vector3();
  17435. const _mvPosition = /*@__PURE__*/new Vector3();
  17436. const _alignedPosition = /*@__PURE__*/new Vector2();
  17437. const _rotatedPosition = /*@__PURE__*/new Vector2();
  17438. const _viewWorldMatrix = /*@__PURE__*/new Matrix4();
  17439. const _vA = /*@__PURE__*/new Vector3();
  17440. const _vB = /*@__PURE__*/new Vector3();
  17441. const _vC = /*@__PURE__*/new Vector3();
  17442. const _uvA = /*@__PURE__*/new Vector2();
  17443. const _uvB = /*@__PURE__*/new Vector2();
  17444. const _uvC = /*@__PURE__*/new Vector2();
  17445. class Sprite extends Object3D {
  17446. constructor(material) {
  17447. super();
  17448. this.isSprite = true;
  17449. this.type = 'Sprite';
  17450. if (_geometry === undefined) {
  17451. _geometry = new BufferGeometry();
  17452. const float32Array = new Float32Array([-0.5, -0.5, 0, 0, 0, 0.5, -0.5, 0, 1, 0, 0.5, 0.5, 0, 1, 1, -0.5, 0.5, 0, 0, 1]);
  17453. const interleavedBuffer = new InterleavedBuffer(float32Array, 5);
  17454. _geometry.setIndex([0, 1, 2, 0, 2, 3]);
  17455. _geometry.setAttribute('position', new InterleavedBufferAttribute(interleavedBuffer, 3, 0, false));
  17456. _geometry.setAttribute('uv', new InterleavedBufferAttribute(interleavedBuffer, 2, 3, false));
  17457. }
  17458. this.geometry = _geometry;
  17459. this.material = material !== undefined ? material : new SpriteMaterial();
  17460. this.center = new Vector2(0.5, 0.5);
  17461. }
  17462. raycast(raycaster, intersects) {
  17463. if (raycaster.camera === null) {
  17464. console.error('THREE.Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.');
  17465. }
  17466. _worldScale.setFromMatrixScale(this.matrixWorld);
  17467. _viewWorldMatrix.copy(raycaster.camera.matrixWorld);
  17468. this.modelViewMatrix.multiplyMatrices(raycaster.camera.matrixWorldInverse, this.matrixWorld);
  17469. _mvPosition.setFromMatrixPosition(this.modelViewMatrix);
  17470. if (raycaster.camera.isPerspectiveCamera && this.material.sizeAttenuation === false) {
  17471. _worldScale.multiplyScalar(-_mvPosition.z);
  17472. }
  17473. const rotation = this.material.rotation;
  17474. let sin, cos;
  17475. if (rotation !== 0) {
  17476. cos = Math.cos(rotation);
  17477. sin = Math.sin(rotation);
  17478. }
  17479. const center = this.center;
  17480. transformVertex(_vA.set(-0.5, -0.5, 0), _mvPosition, center, _worldScale, sin, cos);
  17481. transformVertex(_vB.set(0.5, -0.5, 0), _mvPosition, center, _worldScale, sin, cos);
  17482. transformVertex(_vC.set(0.5, 0.5, 0), _mvPosition, center, _worldScale, sin, cos);
  17483. _uvA.set(0, 0);
  17484. _uvB.set(1, 0);
  17485. _uvC.set(1, 1); // check first triangle
  17486. let intersect = raycaster.ray.intersectTriangle(_vA, _vB, _vC, false, _intersectPoint);
  17487. if (intersect === null) {
  17488. // check second triangle
  17489. transformVertex(_vB.set(-0.5, 0.5, 0), _mvPosition, center, _worldScale, sin, cos);
  17490. _uvB.set(0, 1);
  17491. intersect = raycaster.ray.intersectTriangle(_vA, _vC, _vB, false, _intersectPoint);
  17492. if (intersect === null) {
  17493. return;
  17494. }
  17495. }
  17496. const distance = raycaster.ray.origin.distanceTo(_intersectPoint);
  17497. if (distance < raycaster.near || distance > raycaster.far) return;
  17498. intersects.push({
  17499. distance: distance,
  17500. point: _intersectPoint.clone(),
  17501. uv: Triangle.getUV(_intersectPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2()),
  17502. face: null,
  17503. object: this
  17504. });
  17505. }
  17506. copy(source, recursive) {
  17507. super.copy(source, recursive);
  17508. if (source.center !== undefined) this.center.copy(source.center);
  17509. this.material = source.material;
  17510. return this;
  17511. }
  17512. }
  17513. function transformVertex(vertexPosition, mvPosition, center, scale, sin, cos) {
  17514. // compute position in camera space
  17515. _alignedPosition.subVectors(vertexPosition, center).addScalar(0.5).multiply(scale); // to check if rotation is not zero
  17516. if (sin !== undefined) {
  17517. _rotatedPosition.x = cos * _alignedPosition.x - sin * _alignedPosition.y;
  17518. _rotatedPosition.y = sin * _alignedPosition.x + cos * _alignedPosition.y;
  17519. } else {
  17520. _rotatedPosition.copy(_alignedPosition);
  17521. }
  17522. vertexPosition.copy(mvPosition);
  17523. vertexPosition.x += _rotatedPosition.x;
  17524. vertexPosition.y += _rotatedPosition.y; // transform to world space
  17525. vertexPosition.applyMatrix4(_viewWorldMatrix);
  17526. }
  17527. const _v1$2 = /*@__PURE__*/new Vector3();
  17528. const _v2$1 = /*@__PURE__*/new Vector3();
  17529. class LOD extends Object3D {
  17530. constructor() {
  17531. super();
  17532. this._currentLevel = 0;
  17533. this.type = 'LOD';
  17534. Object.defineProperties(this, {
  17535. levels: {
  17536. enumerable: true,
  17537. value: []
  17538. },
  17539. isLOD: {
  17540. value: true
  17541. }
  17542. });
  17543. this.autoUpdate = true;
  17544. }
  17545. copy(source) {
  17546. super.copy(source, false);
  17547. const levels = source.levels;
  17548. for (let i = 0, l = levels.length; i < l; i++) {
  17549. const level = levels[i];
  17550. this.addLevel(level.object.clone(), level.distance);
  17551. }
  17552. this.autoUpdate = source.autoUpdate;
  17553. return this;
  17554. }
  17555. addLevel(object, distance = 0) {
  17556. distance = Math.abs(distance);
  17557. const levels = this.levels;
  17558. let l;
  17559. for (l = 0; l < levels.length; l++) {
  17560. if (distance < levels[l].distance) {
  17561. break;
  17562. }
  17563. }
  17564. levels.splice(l, 0, {
  17565. distance: distance,
  17566. object: object
  17567. });
  17568. this.add(object);
  17569. return this;
  17570. }
  17571. getCurrentLevel() {
  17572. return this._currentLevel;
  17573. }
  17574. getObjectForDistance(distance) {
  17575. const levels = this.levels;
  17576. if (levels.length > 0) {
  17577. let i, l;
  17578. for (i = 1, l = levels.length; i < l; i++) {
  17579. if (distance < levels[i].distance) {
  17580. break;
  17581. }
  17582. }
  17583. return levels[i - 1].object;
  17584. }
  17585. return null;
  17586. }
  17587. raycast(raycaster, intersects) {
  17588. const levels = this.levels;
  17589. if (levels.length > 0) {
  17590. _v1$2.setFromMatrixPosition(this.matrixWorld);
  17591. const distance = raycaster.ray.origin.distanceTo(_v1$2);
  17592. this.getObjectForDistance(distance).raycast(raycaster, intersects);
  17593. }
  17594. }
  17595. update(camera) {
  17596. const levels = this.levels;
  17597. if (levels.length > 1) {
  17598. _v1$2.setFromMatrixPosition(camera.matrixWorld);
  17599. _v2$1.setFromMatrixPosition(this.matrixWorld);
  17600. const distance = _v1$2.distanceTo(_v2$1) / camera.zoom;
  17601. levels[0].object.visible = true;
  17602. let i, l;
  17603. for (i = 1, l = levels.length; i < l; i++) {
  17604. if (distance >= levels[i].distance) {
  17605. levels[i - 1].object.visible = false;
  17606. levels[i].object.visible = true;
  17607. } else {
  17608. break;
  17609. }
  17610. }
  17611. this._currentLevel = i - 1;
  17612. for (; i < l; i++) {
  17613. levels[i].object.visible = false;
  17614. }
  17615. }
  17616. }
  17617. toJSON(meta) {
  17618. const data = super.toJSON(meta);
  17619. if (this.autoUpdate === false) data.object.autoUpdate = false;
  17620. data.object.levels = [];
  17621. const levels = this.levels;
  17622. for (let i = 0, l = levels.length; i < l; i++) {
  17623. const level = levels[i];
  17624. data.object.levels.push({
  17625. object: level.object.uuid,
  17626. distance: level.distance
  17627. });
  17628. }
  17629. return data;
  17630. }
  17631. }
  17632. const _basePosition = /*@__PURE__*/new Vector3();
  17633. const _skinIndex = /*@__PURE__*/new Vector4();
  17634. const _skinWeight = /*@__PURE__*/new Vector4();
  17635. const _vector$5 = /*@__PURE__*/new Vector3();
  17636. const _matrix = /*@__PURE__*/new Matrix4();
  17637. class SkinnedMesh extends Mesh {
  17638. constructor(geometry, material) {
  17639. super(geometry, material);
  17640. this.isSkinnedMesh = true;
  17641. this.type = 'SkinnedMesh';
  17642. this.bindMode = 'attached';
  17643. this.bindMatrix = new Matrix4();
  17644. this.bindMatrixInverse = new Matrix4();
  17645. }
  17646. copy(source, recursive) {
  17647. super.copy(source, recursive);
  17648. this.bindMode = source.bindMode;
  17649. this.bindMatrix.copy(source.bindMatrix);
  17650. this.bindMatrixInverse.copy(source.bindMatrixInverse);
  17651. this.skeleton = source.skeleton;
  17652. return this;
  17653. }
  17654. bind(skeleton, bindMatrix) {
  17655. this.skeleton = skeleton;
  17656. if (bindMatrix === undefined) {
  17657. this.updateMatrixWorld(true);
  17658. this.skeleton.calculateInverses();
  17659. bindMatrix = this.matrixWorld;
  17660. }
  17661. this.bindMatrix.copy(bindMatrix);
  17662. this.bindMatrixInverse.copy(bindMatrix).invert();
  17663. }
  17664. pose() {
  17665. this.skeleton.pose();
  17666. }
  17667. normalizeSkinWeights() {
  17668. const vector = new Vector4();
  17669. const skinWeight = this.geometry.attributes.skinWeight;
  17670. for (let i = 0, l = skinWeight.count; i < l; i++) {
  17671. vector.fromBufferAttribute(skinWeight, i);
  17672. const scale = 1.0 / vector.manhattanLength();
  17673. if (scale !== Infinity) {
  17674. vector.multiplyScalar(scale);
  17675. } else {
  17676. vector.set(1, 0, 0, 0); // do something reasonable
  17677. }
  17678. skinWeight.setXYZW(i, vector.x, vector.y, vector.z, vector.w);
  17679. }
  17680. }
  17681. updateMatrixWorld(force) {
  17682. super.updateMatrixWorld(force);
  17683. if (this.bindMode === 'attached') {
  17684. this.bindMatrixInverse.copy(this.matrixWorld).invert();
  17685. } else if (this.bindMode === 'detached') {
  17686. this.bindMatrixInverse.copy(this.bindMatrix).invert();
  17687. } else {
  17688. console.warn('THREE.SkinnedMesh: Unrecognized bindMode: ' + this.bindMode);
  17689. }
  17690. }
  17691. boneTransform(index, target) {
  17692. const skeleton = this.skeleton;
  17693. const geometry = this.geometry;
  17694. _skinIndex.fromBufferAttribute(geometry.attributes.skinIndex, index);
  17695. _skinWeight.fromBufferAttribute(geometry.attributes.skinWeight, index);
  17696. _basePosition.copy(target).applyMatrix4(this.bindMatrix);
  17697. target.set(0, 0, 0);
  17698. for (let i = 0; i < 4; i++) {
  17699. const weight = _skinWeight.getComponent(i);
  17700. if (weight !== 0) {
  17701. const boneIndex = _skinIndex.getComponent(i);
  17702. _matrix.multiplyMatrices(skeleton.bones[boneIndex].matrixWorld, skeleton.boneInverses[boneIndex]);
  17703. target.addScaledVector(_vector$5.copy(_basePosition).applyMatrix4(_matrix), weight);
  17704. }
  17705. }
  17706. return target.applyMatrix4(this.bindMatrixInverse);
  17707. }
  17708. }
  17709. class Bone extends Object3D {
  17710. constructor() {
  17711. super();
  17712. this.isBone = true;
  17713. this.type = 'Bone';
  17714. }
  17715. }
  17716. class DataTexture extends Texture {
  17717. constructor(data = null, width = 1, height = 1, format, type, mapping, wrapS, wrapT, magFilter = NearestFilter, minFilter = NearestFilter, anisotropy, encoding) {
  17718. super(null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding);
  17719. this.isDataTexture = true;
  17720. this.image = {
  17721. data: data,
  17722. width: width,
  17723. height: height
  17724. };
  17725. this.generateMipmaps = false;
  17726. this.flipY = false;
  17727. this.unpackAlignment = 1;
  17728. }
  17729. }
  17730. const _offsetMatrix = /*@__PURE__*/new Matrix4();
  17731. const _identityMatrix = /*@__PURE__*/new Matrix4();
  17732. class Skeleton {
  17733. constructor(bones = [], boneInverses = []) {
  17734. this.uuid = generateUUID();
  17735. this.bones = bones.slice(0);
  17736. this.boneInverses = boneInverses;
  17737. this.boneMatrices = null;
  17738. this.boneTexture = null;
  17739. this.boneTextureSize = 0;
  17740. this.frame = -1;
  17741. this.init();
  17742. }
  17743. init() {
  17744. const bones = this.bones;
  17745. const boneInverses = this.boneInverses;
  17746. this.boneMatrices = new Float32Array(bones.length * 16); // calculate inverse bone matrices if necessary
  17747. if (boneInverses.length === 0) {
  17748. this.calculateInverses();
  17749. } else {
  17750. // handle special case
  17751. if (bones.length !== boneInverses.length) {
  17752. console.warn('THREE.Skeleton: Number of inverse bone matrices does not match amount of bones.');
  17753. this.boneInverses = [];
  17754. for (let i = 0, il = this.bones.length; i < il; i++) {
  17755. this.boneInverses.push(new Matrix4());
  17756. }
  17757. }
  17758. }
  17759. }
  17760. calculateInverses() {
  17761. this.boneInverses.length = 0;
  17762. for (let i = 0, il = this.bones.length; i < il; i++) {
  17763. const inverse = new Matrix4();
  17764. if (this.bones[i]) {
  17765. inverse.copy(this.bones[i].matrixWorld).invert();
  17766. }
  17767. this.boneInverses.push(inverse);
  17768. }
  17769. }
  17770. pose() {
  17771. // recover the bind-time world matrices
  17772. for (let i = 0, il = this.bones.length; i < il; i++) {
  17773. const bone = this.bones[i];
  17774. if (bone) {
  17775. bone.matrixWorld.copy(this.boneInverses[i]).invert();
  17776. }
  17777. } // compute the local matrices, positions, rotations and scales
  17778. for (let i = 0, il = this.bones.length; i < il; i++) {
  17779. const bone = this.bones[i];
  17780. if (bone) {
  17781. if (bone.parent && bone.parent.isBone) {
  17782. bone.matrix.copy(bone.parent.matrixWorld).invert();
  17783. bone.matrix.multiply(bone.matrixWorld);
  17784. } else {
  17785. bone.matrix.copy(bone.matrixWorld);
  17786. }
  17787. bone.matrix.decompose(bone.position, bone.quaternion, bone.scale);
  17788. }
  17789. }
  17790. }
  17791. update() {
  17792. const bones = this.bones;
  17793. const boneInverses = this.boneInverses;
  17794. const boneMatrices = this.boneMatrices;
  17795. const boneTexture = this.boneTexture; // flatten bone matrices to array
  17796. for (let i = 0, il = bones.length; i < il; i++) {
  17797. // compute the offset between the current and the original transform
  17798. const matrix = bones[i] ? bones[i].matrixWorld : _identityMatrix;
  17799. _offsetMatrix.multiplyMatrices(matrix, boneInverses[i]);
  17800. _offsetMatrix.toArray(boneMatrices, i * 16);
  17801. }
  17802. if (boneTexture !== null) {
  17803. boneTexture.needsUpdate = true;
  17804. }
  17805. }
  17806. clone() {
  17807. return new Skeleton(this.bones, this.boneInverses);
  17808. }
  17809. computeBoneTexture() {
  17810. // layout (1 matrix = 4 pixels)
  17811. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  17812. // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8)
  17813. // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16)
  17814. // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32)
  17815. // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64)
  17816. let size = Math.sqrt(this.bones.length * 4); // 4 pixels needed for 1 matrix
  17817. size = ceilPowerOfTwo(size);
  17818. size = Math.max(size, 4);
  17819. const boneMatrices = new Float32Array(size * size * 4); // 4 floats per RGBA pixel
  17820. boneMatrices.set(this.boneMatrices); // copy current values
  17821. const boneTexture = new DataTexture(boneMatrices, size, size, RGBAFormat, FloatType);
  17822. boneTexture.needsUpdate = true;
  17823. this.boneMatrices = boneMatrices;
  17824. this.boneTexture = boneTexture;
  17825. this.boneTextureSize = size;
  17826. return this;
  17827. }
  17828. getBoneByName(name) {
  17829. for (let i = 0, il = this.bones.length; i < il; i++) {
  17830. const bone = this.bones[i];
  17831. if (bone.name === name) {
  17832. return bone;
  17833. }
  17834. }
  17835. return undefined;
  17836. }
  17837. dispose() {
  17838. if (this.boneTexture !== null) {
  17839. this.boneTexture.dispose();
  17840. this.boneTexture = null;
  17841. }
  17842. }
  17843. fromJSON(json, bones) {
  17844. this.uuid = json.uuid;
  17845. for (let i = 0, l = json.bones.length; i < l; i++) {
  17846. const uuid = json.bones[i];
  17847. let bone = bones[uuid];
  17848. if (bone === undefined) {
  17849. console.warn('THREE.Skeleton: No bone found with UUID:', uuid);
  17850. bone = new Bone();
  17851. }
  17852. this.bones.push(bone);
  17853. this.boneInverses.push(new Matrix4().fromArray(json.boneInverses[i]));
  17854. }
  17855. this.init();
  17856. return this;
  17857. }
  17858. toJSON() {
  17859. const data = {
  17860. metadata: {
  17861. version: 4.5,
  17862. type: 'Skeleton',
  17863. generator: 'Skeleton.toJSON'
  17864. },
  17865. bones: [],
  17866. boneInverses: []
  17867. };
  17868. data.uuid = this.uuid;
  17869. const bones = this.bones;
  17870. const boneInverses = this.boneInverses;
  17871. for (let i = 0, l = bones.length; i < l; i++) {
  17872. const bone = bones[i];
  17873. data.bones.push(bone.uuid);
  17874. const boneInverse = boneInverses[i];
  17875. data.boneInverses.push(boneInverse.toArray());
  17876. }
  17877. return data;
  17878. }
  17879. }
  17880. class InstancedBufferAttribute extends BufferAttribute {
  17881. constructor(array, itemSize, normalized, meshPerAttribute = 1) {
  17882. super(array, itemSize, normalized);
  17883. this.isInstancedBufferAttribute = true;
  17884. this.meshPerAttribute = meshPerAttribute;
  17885. }
  17886. copy(source) {
  17887. super.copy(source);
  17888. this.meshPerAttribute = source.meshPerAttribute;
  17889. return this;
  17890. }
  17891. toJSON() {
  17892. const data = super.toJSON();
  17893. data.meshPerAttribute = this.meshPerAttribute;
  17894. data.isInstancedBufferAttribute = true;
  17895. return data;
  17896. }
  17897. }
  17898. const _instanceLocalMatrix = /*@__PURE__*/new Matrix4();
  17899. const _instanceWorldMatrix = /*@__PURE__*/new Matrix4();
  17900. const _instanceIntersects = [];
  17901. const _mesh = /*@__PURE__*/new Mesh();
  17902. class InstancedMesh extends Mesh {
  17903. constructor(geometry, material, count) {
  17904. super(geometry, material);
  17905. this.isInstancedMesh = true;
  17906. this.instanceMatrix = new InstancedBufferAttribute(new Float32Array(count * 16), 16);
  17907. this.instanceColor = null;
  17908. this.count = count;
  17909. this.frustumCulled = false;
  17910. }
  17911. copy(source, recursive) {
  17912. super.copy(source, recursive);
  17913. this.instanceMatrix.copy(source.instanceMatrix);
  17914. if (source.instanceColor !== null) this.instanceColor = source.instanceColor.clone();
  17915. this.count = source.count;
  17916. return this;
  17917. }
  17918. getColorAt(index, color) {
  17919. color.fromArray(this.instanceColor.array, index * 3);
  17920. }
  17921. getMatrixAt(index, matrix) {
  17922. matrix.fromArray(this.instanceMatrix.array, index * 16);
  17923. }
  17924. raycast(raycaster, intersects) {
  17925. const matrixWorld = this.matrixWorld;
  17926. const raycastTimes = this.count;
  17927. _mesh.geometry = this.geometry;
  17928. _mesh.material = this.material;
  17929. if (_mesh.material === undefined) return;
  17930. for (let instanceId = 0; instanceId < raycastTimes; instanceId++) {
  17931. // calculate the world matrix for each instance
  17932. this.getMatrixAt(instanceId, _instanceLocalMatrix);
  17933. _instanceWorldMatrix.multiplyMatrices(matrixWorld, _instanceLocalMatrix); // the mesh represents this single instance
  17934. _mesh.matrixWorld = _instanceWorldMatrix;
  17935. _mesh.raycast(raycaster, _instanceIntersects); // process the result of raycast
  17936. for (let i = 0, l = _instanceIntersects.length; i < l; i++) {
  17937. const intersect = _instanceIntersects[i];
  17938. intersect.instanceId = instanceId;
  17939. intersect.object = this;
  17940. intersects.push(intersect);
  17941. }
  17942. _instanceIntersects.length = 0;
  17943. }
  17944. }
  17945. setColorAt(index, color) {
  17946. if (this.instanceColor === null) {
  17947. this.instanceColor = new InstancedBufferAttribute(new Float32Array(this.instanceMatrix.count * 3), 3);
  17948. }
  17949. color.toArray(this.instanceColor.array, index * 3);
  17950. }
  17951. setMatrixAt(index, matrix) {
  17952. matrix.toArray(this.instanceMatrix.array, index * 16);
  17953. }
  17954. updateMorphTargets() {}
  17955. dispose() {
  17956. this.dispatchEvent({
  17957. type: 'dispose'
  17958. });
  17959. }
  17960. }
  17961. class LineBasicMaterial extends Material {
  17962. constructor(parameters) {
  17963. super();
  17964. this.isLineBasicMaterial = true;
  17965. this.type = 'LineBasicMaterial';
  17966. this.color = new Color(0xffffff);
  17967. this.linewidth = 1;
  17968. this.linecap = 'round';
  17969. this.linejoin = 'round';
  17970. this.fog = true;
  17971. this.setValues(parameters);
  17972. }
  17973. copy(source) {
  17974. super.copy(source);
  17975. this.color.copy(source.color);
  17976. this.linewidth = source.linewidth;
  17977. this.linecap = source.linecap;
  17978. this.linejoin = source.linejoin;
  17979. this.fog = source.fog;
  17980. return this;
  17981. }
  17982. }
  17983. const _start$1 = /*@__PURE__*/new Vector3();
  17984. const _end$1 = /*@__PURE__*/new Vector3();
  17985. const _inverseMatrix$1 = /*@__PURE__*/new Matrix4();
  17986. const _ray$1 = /*@__PURE__*/new Ray();
  17987. const _sphere$1 = /*@__PURE__*/new Sphere();
  17988. class Line extends Object3D {
  17989. constructor(geometry = new BufferGeometry(), material = new LineBasicMaterial()) {
  17990. super();
  17991. this.isLine = true;
  17992. this.type = 'Line';
  17993. this.geometry = geometry;
  17994. this.material = material;
  17995. this.updateMorphTargets();
  17996. }
  17997. copy(source, recursive) {
  17998. super.copy(source, recursive);
  17999. this.material = source.material;
  18000. this.geometry = source.geometry;
  18001. return this;
  18002. }
  18003. computeLineDistances() {
  18004. const geometry = this.geometry; // we assume non-indexed geometry
  18005. if (geometry.index === null) {
  18006. const positionAttribute = geometry.attributes.position;
  18007. const lineDistances = [0];
  18008. for (let i = 1, l = positionAttribute.count; i < l; i++) {
  18009. _start$1.fromBufferAttribute(positionAttribute, i - 1);
  18010. _end$1.fromBufferAttribute(positionAttribute, i);
  18011. lineDistances[i] = lineDistances[i - 1];
  18012. lineDistances[i] += _start$1.distanceTo(_end$1);
  18013. }
  18014. geometry.setAttribute('lineDistance', new Float32BufferAttribute(lineDistances, 1));
  18015. } else {
  18016. console.warn('THREE.Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.');
  18017. }
  18018. return this;
  18019. }
  18020. raycast(raycaster, intersects) {
  18021. const geometry = this.geometry;
  18022. const matrixWorld = this.matrixWorld;
  18023. const threshold = raycaster.params.Line.threshold;
  18024. const drawRange = geometry.drawRange; // Checking boundingSphere distance to ray
  18025. if (geometry.boundingSphere === null) geometry.computeBoundingSphere();
  18026. _sphere$1.copy(geometry.boundingSphere);
  18027. _sphere$1.applyMatrix4(matrixWorld);
  18028. _sphere$1.radius += threshold;
  18029. if (raycaster.ray.intersectsSphere(_sphere$1) === false) return; //
  18030. _inverseMatrix$1.copy(matrixWorld).invert();
  18031. _ray$1.copy(raycaster.ray).applyMatrix4(_inverseMatrix$1);
  18032. const localThreshold = threshold / ((this.scale.x + this.scale.y + this.scale.z) / 3);
  18033. const localThresholdSq = localThreshold * localThreshold;
  18034. const vStart = new Vector3();
  18035. const vEnd = new Vector3();
  18036. const interSegment = new Vector3();
  18037. const interRay = new Vector3();
  18038. const step = this.isLineSegments ? 2 : 1;
  18039. const index = geometry.index;
  18040. const attributes = geometry.attributes;
  18041. const positionAttribute = attributes.position;
  18042. if (index !== null) {
  18043. const start = Math.max(0, drawRange.start);
  18044. const end = Math.min(index.count, drawRange.start + drawRange.count);
  18045. for (let i = start, l = end - 1; i < l; i += step) {
  18046. const a = index.getX(i);
  18047. const b = index.getX(i + 1);
  18048. vStart.fromBufferAttribute(positionAttribute, a);
  18049. vEnd.fromBufferAttribute(positionAttribute, b);
  18050. const distSq = _ray$1.distanceSqToSegment(vStart, vEnd, interRay, interSegment);
  18051. if (distSq > localThresholdSq) continue;
  18052. interRay.applyMatrix4(this.matrixWorld); //Move back to world space for distance calculation
  18053. const distance = raycaster.ray.origin.distanceTo(interRay);
  18054. if (distance < raycaster.near || distance > raycaster.far) continue;
  18055. intersects.push({
  18056. distance: distance,
  18057. // What do we want? intersection point on the ray or on the segment??
  18058. // point: raycaster.ray.at( distance ),
  18059. point: interSegment.clone().applyMatrix4(this.matrixWorld),
  18060. index: i,
  18061. face: null,
  18062. faceIndex: null,
  18063. object: this
  18064. });
  18065. }
  18066. } else {
  18067. const start = Math.max(0, drawRange.start);
  18068. const end = Math.min(positionAttribute.count, drawRange.start + drawRange.count);
  18069. for (let i = start, l = end - 1; i < l; i += step) {
  18070. vStart.fromBufferAttribute(positionAttribute, i);
  18071. vEnd.fromBufferAttribute(positionAttribute, i + 1);
  18072. const distSq = _ray$1.distanceSqToSegment(vStart, vEnd, interRay, interSegment);
  18073. if (distSq > localThresholdSq) continue;
  18074. interRay.applyMatrix4(this.matrixWorld); //Move back to world space for distance calculation
  18075. const distance = raycaster.ray.origin.distanceTo(interRay);
  18076. if (distance < raycaster.near || distance > raycaster.far) continue;
  18077. intersects.push({
  18078. distance: distance,
  18079. // What do we want? intersection point on the ray or on the segment??
  18080. // point: raycaster.ray.at( distance ),
  18081. point: interSegment.clone().applyMatrix4(this.matrixWorld),
  18082. index: i,
  18083. face: null,
  18084. faceIndex: null,
  18085. object: this
  18086. });
  18087. }
  18088. }
  18089. }
  18090. updateMorphTargets() {
  18091. const geometry = this.geometry;
  18092. const morphAttributes = geometry.morphAttributes;
  18093. const keys = Object.keys(morphAttributes);
  18094. if (keys.length > 0) {
  18095. const morphAttribute = morphAttributes[keys[0]];
  18096. if (morphAttribute !== undefined) {
  18097. this.morphTargetInfluences = [];
  18098. this.morphTargetDictionary = {};
  18099. for (let m = 0, ml = morphAttribute.length; m < ml; m++) {
  18100. const name = morphAttribute[m].name || String(m);
  18101. this.morphTargetInfluences.push(0);
  18102. this.morphTargetDictionary[name] = m;
  18103. }
  18104. }
  18105. }
  18106. }
  18107. }
  18108. const _start = /*@__PURE__*/new Vector3();
  18109. const _end = /*@__PURE__*/new Vector3();
  18110. class LineSegments extends Line {
  18111. constructor(geometry, material) {
  18112. super(geometry, material);
  18113. this.isLineSegments = true;
  18114. this.type = 'LineSegments';
  18115. }
  18116. computeLineDistances() {
  18117. const geometry = this.geometry; // we assume non-indexed geometry
  18118. if (geometry.index === null) {
  18119. const positionAttribute = geometry.attributes.position;
  18120. const lineDistances = [];
  18121. for (let i = 0, l = positionAttribute.count; i < l; i += 2) {
  18122. _start.fromBufferAttribute(positionAttribute, i);
  18123. _end.fromBufferAttribute(positionAttribute, i + 1);
  18124. lineDistances[i] = i === 0 ? 0 : lineDistances[i - 1];
  18125. lineDistances[i + 1] = lineDistances[i] + _start.distanceTo(_end);
  18126. }
  18127. geometry.setAttribute('lineDistance', new Float32BufferAttribute(lineDistances, 1));
  18128. } else {
  18129. console.warn('THREE.LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.');
  18130. }
  18131. return this;
  18132. }
  18133. }
  18134. class LineLoop extends Line {
  18135. constructor(geometry, material) {
  18136. super(geometry, material);
  18137. this.isLineLoop = true;
  18138. this.type = 'LineLoop';
  18139. }
  18140. }
  18141. class PointsMaterial extends Material {
  18142. constructor(parameters) {
  18143. super();
  18144. this.isPointsMaterial = true;
  18145. this.type = 'PointsMaterial';
  18146. this.color = new Color(0xffffff);
  18147. this.map = null;
  18148. this.alphaMap = null;
  18149. this.size = 1;
  18150. this.sizeAttenuation = true;
  18151. this.fog = true;
  18152. this.setValues(parameters);
  18153. }
  18154. copy(source) {
  18155. super.copy(source);
  18156. this.color.copy(source.color);
  18157. this.map = source.map;
  18158. this.alphaMap = source.alphaMap;
  18159. this.size = source.size;
  18160. this.sizeAttenuation = source.sizeAttenuation;
  18161. this.fog = source.fog;
  18162. return this;
  18163. }
  18164. }
  18165. const _inverseMatrix = /*@__PURE__*/new Matrix4();
  18166. const _ray = /*@__PURE__*/new Ray();
  18167. const _sphere = /*@__PURE__*/new Sphere();
  18168. const _position$2 = /*@__PURE__*/new Vector3();
  18169. class Points extends Object3D {
  18170. constructor(geometry = new BufferGeometry(), material = new PointsMaterial()) {
  18171. super();
  18172. this.isPoints = true;
  18173. this.type = 'Points';
  18174. this.geometry = geometry;
  18175. this.material = material;
  18176. this.updateMorphTargets();
  18177. }
  18178. copy(source, recursive) {
  18179. super.copy(source, recursive);
  18180. this.material = source.material;
  18181. this.geometry = source.geometry;
  18182. return this;
  18183. }
  18184. raycast(raycaster, intersects) {
  18185. const geometry = this.geometry;
  18186. const matrixWorld = this.matrixWorld;
  18187. const threshold = raycaster.params.Points.threshold;
  18188. const drawRange = geometry.drawRange; // Checking boundingSphere distance to ray
  18189. if (geometry.boundingSphere === null) geometry.computeBoundingSphere();
  18190. _sphere.copy(geometry.boundingSphere);
  18191. _sphere.applyMatrix4(matrixWorld);
  18192. _sphere.radius += threshold;
  18193. if (raycaster.ray.intersectsSphere(_sphere) === false) return; //
  18194. _inverseMatrix.copy(matrixWorld).invert();
  18195. _ray.copy(raycaster.ray).applyMatrix4(_inverseMatrix);
  18196. const localThreshold = threshold / ((this.scale.x + this.scale.y + this.scale.z) / 3);
  18197. const localThresholdSq = localThreshold * localThreshold;
  18198. const index = geometry.index;
  18199. const attributes = geometry.attributes;
  18200. const positionAttribute = attributes.position;
  18201. if (index !== null) {
  18202. const start = Math.max(0, drawRange.start);
  18203. const end = Math.min(index.count, drawRange.start + drawRange.count);
  18204. for (let i = start, il = end; i < il; i++) {
  18205. const a = index.getX(i);
  18206. _position$2.fromBufferAttribute(positionAttribute, a);
  18207. testPoint(_position$2, a, localThresholdSq, matrixWorld, raycaster, intersects, this);
  18208. }
  18209. } else {
  18210. const start = Math.max(0, drawRange.start);
  18211. const end = Math.min(positionAttribute.count, drawRange.start + drawRange.count);
  18212. for (let i = start, l = end; i < l; i++) {
  18213. _position$2.fromBufferAttribute(positionAttribute, i);
  18214. testPoint(_position$2, i, localThresholdSq, matrixWorld, raycaster, intersects, this);
  18215. }
  18216. }
  18217. }
  18218. updateMorphTargets() {
  18219. const geometry = this.geometry;
  18220. const morphAttributes = geometry.morphAttributes;
  18221. const keys = Object.keys(morphAttributes);
  18222. if (keys.length > 0) {
  18223. const morphAttribute = morphAttributes[keys[0]];
  18224. if (morphAttribute !== undefined) {
  18225. this.morphTargetInfluences = [];
  18226. this.morphTargetDictionary = {};
  18227. for (let m = 0, ml = morphAttribute.length; m < ml; m++) {
  18228. const name = morphAttribute[m].name || String(m);
  18229. this.morphTargetInfluences.push(0);
  18230. this.morphTargetDictionary[name] = m;
  18231. }
  18232. }
  18233. }
  18234. }
  18235. }
  18236. function testPoint(point, index, localThresholdSq, matrixWorld, raycaster, intersects, object) {
  18237. const rayPointDistanceSq = _ray.distanceSqToPoint(point);
  18238. if (rayPointDistanceSq < localThresholdSq) {
  18239. const intersectPoint = new Vector3();
  18240. _ray.closestPointToPoint(point, intersectPoint);
  18241. intersectPoint.applyMatrix4(matrixWorld);
  18242. const distance = raycaster.ray.origin.distanceTo(intersectPoint);
  18243. if (distance < raycaster.near || distance > raycaster.far) return;
  18244. intersects.push({
  18245. distance: distance,
  18246. distanceToRay: Math.sqrt(rayPointDistanceSq),
  18247. point: intersectPoint,
  18248. index: index,
  18249. face: null,
  18250. object: object
  18251. });
  18252. }
  18253. }
  18254. class VideoTexture extends Texture {
  18255. constructor(video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy) {
  18256. super(video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy);
  18257. this.isVideoTexture = true;
  18258. this.minFilter = minFilter !== undefined ? minFilter : LinearFilter;
  18259. this.magFilter = magFilter !== undefined ? magFilter : LinearFilter;
  18260. this.generateMipmaps = false;
  18261. const scope = this;
  18262. function updateVideo() {
  18263. scope.needsUpdate = true;
  18264. video.requestVideoFrameCallback(updateVideo);
  18265. }
  18266. if ('requestVideoFrameCallback' in video) {
  18267. video.requestVideoFrameCallback(updateVideo);
  18268. }
  18269. }
  18270. clone() {
  18271. return new this.constructor(this.image).copy(this);
  18272. }
  18273. update() {
  18274. const video = this.image;
  18275. const hasVideoFrameCallback = ('requestVideoFrameCallback' in video);
  18276. if (hasVideoFrameCallback === false && video.readyState >= video.HAVE_CURRENT_DATA) {
  18277. this.needsUpdate = true;
  18278. }
  18279. }
  18280. }
  18281. class FramebufferTexture extends Texture {
  18282. constructor(width, height, format) {
  18283. super({
  18284. width,
  18285. height
  18286. });
  18287. this.isFramebufferTexture = true;
  18288. this.format = format;
  18289. this.magFilter = NearestFilter;
  18290. this.minFilter = NearestFilter;
  18291. this.generateMipmaps = false;
  18292. this.needsUpdate = true;
  18293. }
  18294. }
  18295. class CompressedTexture extends Texture {
  18296. constructor(mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding) {
  18297. super(null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding);
  18298. this.isCompressedTexture = true;
  18299. this.image = {
  18300. width: width,
  18301. height: height
  18302. };
  18303. this.mipmaps = mipmaps; // no flipping for cube textures
  18304. // (also flipping doesn't work for compressed textures )
  18305. this.flipY = false; // can't generate mipmaps for compressed textures
  18306. // mips must be embedded in DDS files
  18307. this.generateMipmaps = false;
  18308. }
  18309. }
  18310. class CanvasTexture extends Texture {
  18311. constructor(canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy) {
  18312. super(canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy);
  18313. this.isCanvasTexture = true;
  18314. this.needsUpdate = true;
  18315. }
  18316. }
  18317. /**
  18318. * Extensible curve object.
  18319. *
  18320. * Some common of curve methods:
  18321. * .getPoint( t, optionalTarget ), .getTangent( t, optionalTarget )
  18322. * .getPointAt( u, optionalTarget ), .getTangentAt( u, optionalTarget )
  18323. * .getPoints(), .getSpacedPoints()
  18324. * .getLength()
  18325. * .updateArcLengths()
  18326. *
  18327. * This following curves inherit from THREE.Curve:
  18328. *
  18329. * -- 2D curves --
  18330. * THREE.ArcCurve
  18331. * THREE.CubicBezierCurve
  18332. * THREE.EllipseCurve
  18333. * THREE.LineCurve
  18334. * THREE.QuadraticBezierCurve
  18335. * THREE.SplineCurve
  18336. *
  18337. * -- 3D curves --
  18338. * THREE.CatmullRomCurve3
  18339. * THREE.CubicBezierCurve3
  18340. * THREE.LineCurve3
  18341. * THREE.QuadraticBezierCurve3
  18342. *
  18343. * A series of curves can be represented as a THREE.CurvePath.
  18344. *
  18345. **/
  18346. class Curve {
  18347. constructor() {
  18348. this.type = 'Curve';
  18349. this.arcLengthDivisions = 200;
  18350. } // Virtual base class method to overwrite and implement in subclasses
  18351. // - t [0 .. 1]
  18352. getPoint() {
  18353. console.warn('THREE.Curve: .getPoint() not implemented.');
  18354. return null;
  18355. } // Get point at relative position in curve according to arc length
  18356. // - u [0 .. 1]
  18357. getPointAt(u, optionalTarget) {
  18358. const t = this.getUtoTmapping(u);
  18359. return this.getPoint(t, optionalTarget);
  18360. } // Get sequence of points using getPoint( t )
  18361. getPoints(divisions = 5) {
  18362. const points = [];
  18363. for (let d = 0; d <= divisions; d++) {
  18364. points.push(this.getPoint(d / divisions));
  18365. }
  18366. return points;
  18367. } // Get sequence of points using getPointAt( u )
  18368. getSpacedPoints(divisions = 5) {
  18369. const points = [];
  18370. for (let d = 0; d <= divisions; d++) {
  18371. points.push(this.getPointAt(d / divisions));
  18372. }
  18373. return points;
  18374. } // Get total curve arc length
  18375. getLength() {
  18376. const lengths = this.getLengths();
  18377. return lengths[lengths.length - 1];
  18378. } // Get list of cumulative segment lengths
  18379. getLengths(divisions = this.arcLengthDivisions) {
  18380. if (this.cacheArcLengths && this.cacheArcLengths.length === divisions + 1 && !this.needsUpdate) {
  18381. return this.cacheArcLengths;
  18382. }
  18383. this.needsUpdate = false;
  18384. const cache = [];
  18385. let current,
  18386. last = this.getPoint(0);
  18387. let sum = 0;
  18388. cache.push(0);
  18389. for (let p = 1; p <= divisions; p++) {
  18390. current = this.getPoint(p / divisions);
  18391. sum += current.distanceTo(last);
  18392. cache.push(sum);
  18393. last = current;
  18394. }
  18395. this.cacheArcLengths = cache;
  18396. return cache; // { sums: cache, sum: sum }; Sum is in the last element.
  18397. }
  18398. updateArcLengths() {
  18399. this.needsUpdate = true;
  18400. this.getLengths();
  18401. } // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equidistant
  18402. getUtoTmapping(u, distance) {
  18403. const arcLengths = this.getLengths();
  18404. let i = 0;
  18405. const il = arcLengths.length;
  18406. let targetArcLength; // The targeted u distance value to get
  18407. if (distance) {
  18408. targetArcLength = distance;
  18409. } else {
  18410. targetArcLength = u * arcLengths[il - 1];
  18411. } // binary search for the index with largest value smaller than target u distance
  18412. let low = 0,
  18413. high = il - 1,
  18414. comparison;
  18415. while (low <= high) {
  18416. 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
  18417. comparison = arcLengths[i] - targetArcLength;
  18418. if (comparison < 0) {
  18419. low = i + 1;
  18420. } else if (comparison > 0) {
  18421. high = i - 1;
  18422. } else {
  18423. high = i;
  18424. break; // DONE
  18425. }
  18426. }
  18427. i = high;
  18428. if (arcLengths[i] === targetArcLength) {
  18429. return i / (il - 1);
  18430. } // we could get finer grain at lengths, or use simple interpolation between two points
  18431. const lengthBefore = arcLengths[i];
  18432. const lengthAfter = arcLengths[i + 1];
  18433. const segmentLength = lengthAfter - lengthBefore; // determine where we are between the 'before' and 'after' points
  18434. const segmentFraction = (targetArcLength - lengthBefore) / segmentLength; // add that fractional amount to t
  18435. const t = (i + segmentFraction) / (il - 1);
  18436. return t;
  18437. } // Returns a unit vector tangent at t
  18438. // In case any sub curve does not implement its tangent derivation,
  18439. // 2 points a small delta apart will be used to find its gradient
  18440. // which seems to give a reasonable approximation
  18441. getTangent(t, optionalTarget) {
  18442. const delta = 0.0001;
  18443. let t1 = t - delta;
  18444. let t2 = t + delta; // Capping in case of danger
  18445. if (t1 < 0) t1 = 0;
  18446. if (t2 > 1) t2 = 1;
  18447. const pt1 = this.getPoint(t1);
  18448. const pt2 = this.getPoint(t2);
  18449. const tangent = optionalTarget || (pt1.isVector2 ? new Vector2() : new Vector3());
  18450. tangent.copy(pt2).sub(pt1).normalize();
  18451. return tangent;
  18452. }
  18453. getTangentAt(u, optionalTarget) {
  18454. const t = this.getUtoTmapping(u);
  18455. return this.getTangent(t, optionalTarget);
  18456. }
  18457. computeFrenetFrames(segments, closed) {
  18458. // see http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  18459. const normal = new Vector3();
  18460. const tangents = [];
  18461. const normals = [];
  18462. const binormals = [];
  18463. const vec = new Vector3();
  18464. const mat = new Matrix4(); // compute the tangent vectors for each segment on the curve
  18465. for (let i = 0; i <= segments; i++) {
  18466. const u = i / segments;
  18467. tangents[i] = this.getTangentAt(u, new Vector3());
  18468. } // select an initial normal vector perpendicular to the first tangent vector,
  18469. // and in the direction of the minimum tangent xyz component
  18470. normals[0] = new Vector3();
  18471. binormals[0] = new Vector3();
  18472. let min = Number.MAX_VALUE;
  18473. const tx = Math.abs(tangents[0].x);
  18474. const ty = Math.abs(tangents[0].y);
  18475. const tz = Math.abs(tangents[0].z);
  18476. if (tx <= min) {
  18477. min = tx;
  18478. normal.set(1, 0, 0);
  18479. }
  18480. if (ty <= min) {
  18481. min = ty;
  18482. normal.set(0, 1, 0);
  18483. }
  18484. if (tz <= min) {
  18485. normal.set(0, 0, 1);
  18486. }
  18487. vec.crossVectors(tangents[0], normal).normalize();
  18488. normals[0].crossVectors(tangents[0], vec);
  18489. binormals[0].crossVectors(tangents[0], normals[0]); // compute the slowly-varying normal and binormal vectors for each segment on the curve
  18490. for (let i = 1; i <= segments; i++) {
  18491. normals[i] = normals[i - 1].clone();
  18492. binormals[i] = binormals[i - 1].clone();
  18493. vec.crossVectors(tangents[i - 1], tangents[i]);
  18494. if (vec.length() > Number.EPSILON) {
  18495. vec.normalize();
  18496. const theta = Math.acos(clamp(tangents[i - 1].dot(tangents[i]), -1, 1)); // clamp for floating pt errors
  18497. normals[i].applyMatrix4(mat.makeRotationAxis(vec, theta));
  18498. }
  18499. binormals[i].crossVectors(tangents[i], normals[i]);
  18500. } // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  18501. if (closed === true) {
  18502. let theta = Math.acos(clamp(normals[0].dot(normals[segments]), -1, 1));
  18503. theta /= segments;
  18504. if (tangents[0].dot(vec.crossVectors(normals[0], normals[segments])) > 0) {
  18505. theta = -theta;
  18506. }
  18507. for (let i = 1; i <= segments; i++) {
  18508. // twist a little...
  18509. normals[i].applyMatrix4(mat.makeRotationAxis(tangents[i], theta * i));
  18510. binormals[i].crossVectors(tangents[i], normals[i]);
  18511. }
  18512. }
  18513. return {
  18514. tangents: tangents,
  18515. normals: normals,
  18516. binormals: binormals
  18517. };
  18518. }
  18519. clone() {
  18520. return new this.constructor().copy(this);
  18521. }
  18522. copy(source) {
  18523. this.arcLengthDivisions = source.arcLengthDivisions;
  18524. return this;
  18525. }
  18526. toJSON() {
  18527. const data = {
  18528. metadata: {
  18529. version: 4.5,
  18530. type: 'Curve',
  18531. generator: 'Curve.toJSON'
  18532. }
  18533. };
  18534. data.arcLengthDivisions = this.arcLengthDivisions;
  18535. data.type = this.type;
  18536. return data;
  18537. }
  18538. fromJSON(json) {
  18539. this.arcLengthDivisions = json.arcLengthDivisions;
  18540. return this;
  18541. }
  18542. }
  18543. class EllipseCurve extends Curve {
  18544. constructor(aX = 0, aY = 0, xRadius = 1, yRadius = 1, aStartAngle = 0, aEndAngle = Math.PI * 2, aClockwise = false, aRotation = 0) {
  18545. super();
  18546. this.isEllipseCurve = true;
  18547. this.type = 'EllipseCurve';
  18548. this.aX = aX;
  18549. this.aY = aY;
  18550. this.xRadius = xRadius;
  18551. this.yRadius = yRadius;
  18552. this.aStartAngle = aStartAngle;
  18553. this.aEndAngle = aEndAngle;
  18554. this.aClockwise = aClockwise;
  18555. this.aRotation = aRotation;
  18556. }
  18557. getPoint(t, optionalTarget) {
  18558. const point = optionalTarget || new Vector2();
  18559. const twoPi = Math.PI * 2;
  18560. let deltaAngle = this.aEndAngle - this.aStartAngle;
  18561. const samePoints = Math.abs(deltaAngle) < Number.EPSILON; // ensures that deltaAngle is 0 .. 2 PI
  18562. while (deltaAngle < 0) deltaAngle += twoPi;
  18563. while (deltaAngle > twoPi) deltaAngle -= twoPi;
  18564. if (deltaAngle < Number.EPSILON) {
  18565. if (samePoints) {
  18566. deltaAngle = 0;
  18567. } else {
  18568. deltaAngle = twoPi;
  18569. }
  18570. }
  18571. if (this.aClockwise === true && !samePoints) {
  18572. if (deltaAngle === twoPi) {
  18573. deltaAngle = -twoPi;
  18574. } else {
  18575. deltaAngle = deltaAngle - twoPi;
  18576. }
  18577. }
  18578. const angle = this.aStartAngle + t * deltaAngle;
  18579. let x = this.aX + this.xRadius * Math.cos(angle);
  18580. let y = this.aY + this.yRadius * Math.sin(angle);
  18581. if (this.aRotation !== 0) {
  18582. const cos = Math.cos(this.aRotation);
  18583. const sin = Math.sin(this.aRotation);
  18584. const tx = x - this.aX;
  18585. const ty = y - this.aY; // Rotate the point about the center of the ellipse.
  18586. x = tx * cos - ty * sin + this.aX;
  18587. y = tx * sin + ty * cos + this.aY;
  18588. }
  18589. return point.set(x, y);
  18590. }
  18591. copy(source) {
  18592. super.copy(source);
  18593. this.aX = source.aX;
  18594. this.aY = source.aY;
  18595. this.xRadius = source.xRadius;
  18596. this.yRadius = source.yRadius;
  18597. this.aStartAngle = source.aStartAngle;
  18598. this.aEndAngle = source.aEndAngle;
  18599. this.aClockwise = source.aClockwise;
  18600. this.aRotation = source.aRotation;
  18601. return this;
  18602. }
  18603. toJSON() {
  18604. const data = super.toJSON();
  18605. data.aX = this.aX;
  18606. data.aY = this.aY;
  18607. data.xRadius = this.xRadius;
  18608. data.yRadius = this.yRadius;
  18609. data.aStartAngle = this.aStartAngle;
  18610. data.aEndAngle = this.aEndAngle;
  18611. data.aClockwise = this.aClockwise;
  18612. data.aRotation = this.aRotation;
  18613. return data;
  18614. }
  18615. fromJSON(json) {
  18616. super.fromJSON(json);
  18617. this.aX = json.aX;
  18618. this.aY = json.aY;
  18619. this.xRadius = json.xRadius;
  18620. this.yRadius = json.yRadius;
  18621. this.aStartAngle = json.aStartAngle;
  18622. this.aEndAngle = json.aEndAngle;
  18623. this.aClockwise = json.aClockwise;
  18624. this.aRotation = json.aRotation;
  18625. return this;
  18626. }
  18627. }
  18628. class ArcCurve extends EllipseCurve {
  18629. constructor(aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise) {
  18630. super(aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise);
  18631. this.isArcCurve = true;
  18632. this.type = 'ArcCurve';
  18633. }
  18634. }
  18635. /**
  18636. * Centripetal CatmullRom Curve - which is useful for avoiding
  18637. * cusps and self-intersections in non-uniform catmull rom curves.
  18638. * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf
  18639. *
  18640. * curve.type accepts centripetal(default), chordal and catmullrom
  18641. * curve.tension is used for catmullrom which defaults to 0.5
  18642. */
  18643. /*
  18644. Based on an optimized c++ solution in
  18645. - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/
  18646. - http://ideone.com/NoEbVM
  18647. This CubicPoly class could be used for reusing some variables and calculations,
  18648. but for three.js curve use, it could be possible inlined and flatten into a single function call
  18649. which can be placed in CurveUtils.
  18650. */
  18651. function CubicPoly() {
  18652. let c0 = 0,
  18653. c1 = 0,
  18654. c2 = 0,
  18655. c3 = 0;
  18656. /*
  18657. * Compute coefficients for a cubic polynomial
  18658. * p(s) = c0 + c1*s + c2*s^2 + c3*s^3
  18659. * such that
  18660. * p(0) = x0, p(1) = x1
  18661. * and
  18662. * p'(0) = t0, p'(1) = t1.
  18663. */
  18664. function init(x0, x1, t0, t1) {
  18665. c0 = x0;
  18666. c1 = t0;
  18667. c2 = -3 * x0 + 3 * x1 - 2 * t0 - t1;
  18668. c3 = 2 * x0 - 2 * x1 + t0 + t1;
  18669. }
  18670. return {
  18671. initCatmullRom: function (x0, x1, x2, x3, tension) {
  18672. init(x1, x2, tension * (x2 - x0), tension * (x3 - x1));
  18673. },
  18674. initNonuniformCatmullRom: function (x0, x1, x2, x3, dt0, dt1, dt2) {
  18675. // compute tangents when parameterized in [t1,t2]
  18676. let t1 = (x1 - x0) / dt0 - (x2 - x0) / (dt0 + dt1) + (x2 - x1) / dt1;
  18677. let t2 = (x2 - x1) / dt1 - (x3 - x1) / (dt1 + dt2) + (x3 - x2) / dt2; // rescale tangents for parametrization in [0,1]
  18678. t1 *= dt1;
  18679. t2 *= dt1;
  18680. init(x1, x2, t1, t2);
  18681. },
  18682. calc: function (t) {
  18683. const t2 = t * t;
  18684. const t3 = t2 * t;
  18685. return c0 + c1 * t + c2 * t2 + c3 * t3;
  18686. }
  18687. };
  18688. } //
  18689. const tmp = /*@__PURE__*/new Vector3();
  18690. const px = /*@__PURE__*/new CubicPoly();
  18691. const py = /*@__PURE__*/new CubicPoly();
  18692. const pz = /*@__PURE__*/new CubicPoly();
  18693. class CatmullRomCurve3 extends Curve {
  18694. constructor(points = [], closed = false, curveType = 'centripetal', tension = 0.5) {
  18695. super();
  18696. this.isCatmullRomCurve3 = true;
  18697. this.type = 'CatmullRomCurve3';
  18698. this.points = points;
  18699. this.closed = closed;
  18700. this.curveType = curveType;
  18701. this.tension = tension;
  18702. }
  18703. getPoint(t, optionalTarget = new Vector3()) {
  18704. const point = optionalTarget;
  18705. const points = this.points;
  18706. const l = points.length;
  18707. const p = (l - (this.closed ? 0 : 1)) * t;
  18708. let intPoint = Math.floor(p);
  18709. let weight = p - intPoint;
  18710. if (this.closed) {
  18711. intPoint += intPoint > 0 ? 0 : (Math.floor(Math.abs(intPoint) / l) + 1) * l;
  18712. } else if (weight === 0 && intPoint === l - 1) {
  18713. intPoint = l - 2;
  18714. weight = 1;
  18715. }
  18716. let p0, p3; // 4 points (p1 & p2 defined below)
  18717. if (this.closed || intPoint > 0) {
  18718. p0 = points[(intPoint - 1) % l];
  18719. } else {
  18720. // extrapolate first point
  18721. tmp.subVectors(points[0], points[1]).add(points[0]);
  18722. p0 = tmp;
  18723. }
  18724. const p1 = points[intPoint % l];
  18725. const p2 = points[(intPoint + 1) % l];
  18726. if (this.closed || intPoint + 2 < l) {
  18727. p3 = points[(intPoint + 2) % l];
  18728. } else {
  18729. // extrapolate last point
  18730. tmp.subVectors(points[l - 1], points[l - 2]).add(points[l - 1]);
  18731. p3 = tmp;
  18732. }
  18733. if (this.curveType === 'centripetal' || this.curveType === 'chordal') {
  18734. // init Centripetal / Chordal Catmull-Rom
  18735. const pow = this.curveType === 'chordal' ? 0.5 : 0.25;
  18736. let dt0 = Math.pow(p0.distanceToSquared(p1), pow);
  18737. let dt1 = Math.pow(p1.distanceToSquared(p2), pow);
  18738. let dt2 = Math.pow(p2.distanceToSquared(p3), pow); // safety check for repeated points
  18739. if (dt1 < 1e-4) dt1 = 1.0;
  18740. if (dt0 < 1e-4) dt0 = dt1;
  18741. if (dt2 < 1e-4) dt2 = dt1;
  18742. px.initNonuniformCatmullRom(p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2);
  18743. py.initNonuniformCatmullRom(p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2);
  18744. pz.initNonuniformCatmullRom(p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2);
  18745. } else if (this.curveType === 'catmullrom') {
  18746. px.initCatmullRom(p0.x, p1.x, p2.x, p3.x, this.tension);
  18747. py.initCatmullRom(p0.y, p1.y, p2.y, p3.y, this.tension);
  18748. pz.initCatmullRom(p0.z, p1.z, p2.z, p3.z, this.tension);
  18749. }
  18750. point.set(px.calc(weight), py.calc(weight), pz.calc(weight));
  18751. return point;
  18752. }
  18753. copy(source) {
  18754. super.copy(source);
  18755. this.points = [];
  18756. for (let i = 0, l = source.points.length; i < l; i++) {
  18757. const point = source.points[i];
  18758. this.points.push(point.clone());
  18759. }
  18760. this.closed = source.closed;
  18761. this.curveType = source.curveType;
  18762. this.tension = source.tension;
  18763. return this;
  18764. }
  18765. toJSON() {
  18766. const data = super.toJSON();
  18767. data.points = [];
  18768. for (let i = 0, l = this.points.length; i < l; i++) {
  18769. const point = this.points[i];
  18770. data.points.push(point.toArray());
  18771. }
  18772. data.closed = this.closed;
  18773. data.curveType = this.curveType;
  18774. data.tension = this.tension;
  18775. return data;
  18776. }
  18777. fromJSON(json) {
  18778. super.fromJSON(json);
  18779. this.points = [];
  18780. for (let i = 0, l = json.points.length; i < l; i++) {
  18781. const point = json.points[i];
  18782. this.points.push(new Vector3().fromArray(point));
  18783. }
  18784. this.closed = json.closed;
  18785. this.curveType = json.curveType;
  18786. this.tension = json.tension;
  18787. return this;
  18788. }
  18789. }
  18790. /**
  18791. * Bezier Curves formulas obtained from
  18792. * https://en.wikipedia.org/wiki/B%C3%A9zier_curve
  18793. */
  18794. function CatmullRom(t, p0, p1, p2, p3) {
  18795. const v0 = (p2 - p0) * 0.5;
  18796. const v1 = (p3 - p1) * 0.5;
  18797. const t2 = t * t;
  18798. const t3 = t * t2;
  18799. return (2 * p1 - 2 * p2 + v0 + v1) * t3 + (-3 * p1 + 3 * p2 - 2 * v0 - v1) * t2 + v0 * t + p1;
  18800. } //
  18801. function QuadraticBezierP0(t, p) {
  18802. const k = 1 - t;
  18803. return k * k * p;
  18804. }
  18805. function QuadraticBezierP1(t, p) {
  18806. return 2 * (1 - t) * t * p;
  18807. }
  18808. function QuadraticBezierP2(t, p) {
  18809. return t * t * p;
  18810. }
  18811. function QuadraticBezier(t, p0, p1, p2) {
  18812. return QuadraticBezierP0(t, p0) + QuadraticBezierP1(t, p1) + QuadraticBezierP2(t, p2);
  18813. } //
  18814. function CubicBezierP0(t, p) {
  18815. const k = 1 - t;
  18816. return k * k * k * p;
  18817. }
  18818. function CubicBezierP1(t, p) {
  18819. const k = 1 - t;
  18820. return 3 * k * k * t * p;
  18821. }
  18822. function CubicBezierP2(t, p) {
  18823. return 3 * (1 - t) * t * t * p;
  18824. }
  18825. function CubicBezierP3(t, p) {
  18826. return t * t * t * p;
  18827. }
  18828. function CubicBezier(t, p0, p1, p2, p3) {
  18829. return CubicBezierP0(t, p0) + CubicBezierP1(t, p1) + CubicBezierP2(t, p2) + CubicBezierP3(t, p3);
  18830. }
  18831. class CubicBezierCurve extends Curve {
  18832. constructor(v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2(), v3 = new Vector2()) {
  18833. super();
  18834. this.isCubicBezierCurve = true;
  18835. this.type = 'CubicBezierCurve';
  18836. this.v0 = v0;
  18837. this.v1 = v1;
  18838. this.v2 = v2;
  18839. this.v3 = v3;
  18840. }
  18841. getPoint(t, optionalTarget = new Vector2()) {
  18842. const point = optionalTarget;
  18843. const v0 = this.v0,
  18844. v1 = this.v1,
  18845. v2 = this.v2,
  18846. v3 = this.v3;
  18847. point.set(CubicBezier(t, v0.x, v1.x, v2.x, v3.x), CubicBezier(t, v0.y, v1.y, v2.y, v3.y));
  18848. return point;
  18849. }
  18850. copy(source) {
  18851. super.copy(source);
  18852. this.v0.copy(source.v0);
  18853. this.v1.copy(source.v1);
  18854. this.v2.copy(source.v2);
  18855. this.v3.copy(source.v3);
  18856. return this;
  18857. }
  18858. toJSON() {
  18859. const data = super.toJSON();
  18860. data.v0 = this.v0.toArray();
  18861. data.v1 = this.v1.toArray();
  18862. data.v2 = this.v2.toArray();
  18863. data.v3 = this.v3.toArray();
  18864. return data;
  18865. }
  18866. fromJSON(json) {
  18867. super.fromJSON(json);
  18868. this.v0.fromArray(json.v0);
  18869. this.v1.fromArray(json.v1);
  18870. this.v2.fromArray(json.v2);
  18871. this.v3.fromArray(json.v3);
  18872. return this;
  18873. }
  18874. }
  18875. class CubicBezierCurve3 extends Curve {
  18876. constructor(v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3(), v3 = new Vector3()) {
  18877. super();
  18878. this.isCubicBezierCurve3 = true;
  18879. this.type = 'CubicBezierCurve3';
  18880. this.v0 = v0;
  18881. this.v1 = v1;
  18882. this.v2 = v2;
  18883. this.v3 = v3;
  18884. }
  18885. getPoint(t, optionalTarget = new Vector3()) {
  18886. const point = optionalTarget;
  18887. const v0 = this.v0,
  18888. v1 = this.v1,
  18889. v2 = this.v2,
  18890. v3 = this.v3;
  18891. 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));
  18892. return point;
  18893. }
  18894. copy(source) {
  18895. super.copy(source);
  18896. this.v0.copy(source.v0);
  18897. this.v1.copy(source.v1);
  18898. this.v2.copy(source.v2);
  18899. this.v3.copy(source.v3);
  18900. return this;
  18901. }
  18902. toJSON() {
  18903. const data = super.toJSON();
  18904. data.v0 = this.v0.toArray();
  18905. data.v1 = this.v1.toArray();
  18906. data.v2 = this.v2.toArray();
  18907. data.v3 = this.v3.toArray();
  18908. return data;
  18909. }
  18910. fromJSON(json) {
  18911. super.fromJSON(json);
  18912. this.v0.fromArray(json.v0);
  18913. this.v1.fromArray(json.v1);
  18914. this.v2.fromArray(json.v2);
  18915. this.v3.fromArray(json.v3);
  18916. return this;
  18917. }
  18918. }
  18919. class LineCurve extends Curve {
  18920. constructor(v1 = new Vector2(), v2 = new Vector2()) {
  18921. super();
  18922. this.isLineCurve = true;
  18923. this.type = 'LineCurve';
  18924. this.v1 = v1;
  18925. this.v2 = v2;
  18926. }
  18927. getPoint(t, optionalTarget = new Vector2()) {
  18928. const point = optionalTarget;
  18929. if (t === 1) {
  18930. point.copy(this.v2);
  18931. } else {
  18932. point.copy(this.v2).sub(this.v1);
  18933. point.multiplyScalar(t).add(this.v1);
  18934. }
  18935. return point;
  18936. } // Line curve is linear, so we can overwrite default getPointAt
  18937. getPointAt(u, optionalTarget) {
  18938. return this.getPoint(u, optionalTarget);
  18939. }
  18940. getTangent(t, optionalTarget) {
  18941. const tangent = optionalTarget || new Vector2();
  18942. tangent.copy(this.v2).sub(this.v1).normalize();
  18943. return tangent;
  18944. }
  18945. copy(source) {
  18946. super.copy(source);
  18947. this.v1.copy(source.v1);
  18948. this.v2.copy(source.v2);
  18949. return this;
  18950. }
  18951. toJSON() {
  18952. const data = super.toJSON();
  18953. data.v1 = this.v1.toArray();
  18954. data.v2 = this.v2.toArray();
  18955. return data;
  18956. }
  18957. fromJSON(json) {
  18958. super.fromJSON(json);
  18959. this.v1.fromArray(json.v1);
  18960. this.v2.fromArray(json.v2);
  18961. return this;
  18962. }
  18963. }
  18964. class LineCurve3 extends Curve {
  18965. constructor(v1 = new Vector3(), v2 = new Vector3()) {
  18966. super();
  18967. this.isLineCurve3 = true;
  18968. this.type = 'LineCurve3';
  18969. this.v1 = v1;
  18970. this.v2 = v2;
  18971. }
  18972. getPoint(t, optionalTarget = new Vector3()) {
  18973. const point = optionalTarget;
  18974. if (t === 1) {
  18975. point.copy(this.v2);
  18976. } else {
  18977. point.copy(this.v2).sub(this.v1);
  18978. point.multiplyScalar(t).add(this.v1);
  18979. }
  18980. return point;
  18981. } // Line curve is linear, so we can overwrite default getPointAt
  18982. getPointAt(u, optionalTarget) {
  18983. return this.getPoint(u, optionalTarget);
  18984. }
  18985. copy(source) {
  18986. super.copy(source);
  18987. this.v1.copy(source.v1);
  18988. this.v2.copy(source.v2);
  18989. return this;
  18990. }
  18991. toJSON() {
  18992. const data = super.toJSON();
  18993. data.v1 = this.v1.toArray();
  18994. data.v2 = this.v2.toArray();
  18995. return data;
  18996. }
  18997. fromJSON(json) {
  18998. super.fromJSON(json);
  18999. this.v1.fromArray(json.v1);
  19000. this.v2.fromArray(json.v2);
  19001. return this;
  19002. }
  19003. }
  19004. class QuadraticBezierCurve extends Curve {
  19005. constructor(v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2()) {
  19006. super();
  19007. this.isQuadraticBezierCurve = true;
  19008. this.type = 'QuadraticBezierCurve';
  19009. this.v0 = v0;
  19010. this.v1 = v1;
  19011. this.v2 = v2;
  19012. }
  19013. getPoint(t, optionalTarget = new Vector2()) {
  19014. const point = optionalTarget;
  19015. const v0 = this.v0,
  19016. v1 = this.v1,
  19017. v2 = this.v2;
  19018. point.set(QuadraticBezier(t, v0.x, v1.x, v2.x), QuadraticBezier(t, v0.y, v1.y, v2.y));
  19019. return point;
  19020. }
  19021. copy(source) {
  19022. super.copy(source);
  19023. this.v0.copy(source.v0);
  19024. this.v1.copy(source.v1);
  19025. this.v2.copy(source.v2);
  19026. return this;
  19027. }
  19028. toJSON() {
  19029. const data = super.toJSON();
  19030. data.v0 = this.v0.toArray();
  19031. data.v1 = this.v1.toArray();
  19032. data.v2 = this.v2.toArray();
  19033. return data;
  19034. }
  19035. fromJSON(json) {
  19036. super.fromJSON(json);
  19037. this.v0.fromArray(json.v0);
  19038. this.v1.fromArray(json.v1);
  19039. this.v2.fromArray(json.v2);
  19040. return this;
  19041. }
  19042. }
  19043. class QuadraticBezierCurve3 extends Curve {
  19044. constructor(v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3()) {
  19045. super();
  19046. this.isQuadraticBezierCurve3 = true;
  19047. this.type = 'QuadraticBezierCurve3';
  19048. this.v0 = v0;
  19049. this.v1 = v1;
  19050. this.v2 = v2;
  19051. }
  19052. getPoint(t, optionalTarget = new Vector3()) {
  19053. const point = optionalTarget;
  19054. const v0 = this.v0,
  19055. v1 = this.v1,
  19056. v2 = this.v2;
  19057. 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));
  19058. return point;
  19059. }
  19060. copy(source) {
  19061. super.copy(source);
  19062. this.v0.copy(source.v0);
  19063. this.v1.copy(source.v1);
  19064. this.v2.copy(source.v2);
  19065. return this;
  19066. }
  19067. toJSON() {
  19068. const data = super.toJSON();
  19069. data.v0 = this.v0.toArray();
  19070. data.v1 = this.v1.toArray();
  19071. data.v2 = this.v2.toArray();
  19072. return data;
  19073. }
  19074. fromJSON(json) {
  19075. super.fromJSON(json);
  19076. this.v0.fromArray(json.v0);
  19077. this.v1.fromArray(json.v1);
  19078. this.v2.fromArray(json.v2);
  19079. return this;
  19080. }
  19081. }
  19082. class SplineCurve extends Curve {
  19083. constructor(points = []) {
  19084. super();
  19085. this.isSplineCurve = true;
  19086. this.type = 'SplineCurve';
  19087. this.points = points;
  19088. }
  19089. getPoint(t, optionalTarget = new Vector2()) {
  19090. const point = optionalTarget;
  19091. const points = this.points;
  19092. const p = (points.length - 1) * t;
  19093. const intPoint = Math.floor(p);
  19094. const weight = p - intPoint;
  19095. const p0 = points[intPoint === 0 ? intPoint : intPoint - 1];
  19096. const p1 = points[intPoint];
  19097. const p2 = points[intPoint > points.length - 2 ? points.length - 1 : intPoint + 1];
  19098. const p3 = points[intPoint > points.length - 3 ? points.length - 1 : intPoint + 2];
  19099. point.set(CatmullRom(weight, p0.x, p1.x, p2.x, p3.x), CatmullRom(weight, p0.y, p1.y, p2.y, p3.y));
  19100. return point;
  19101. }
  19102. copy(source) {
  19103. super.copy(source);
  19104. this.points = [];
  19105. for (let i = 0, l = source.points.length; i < l; i++) {
  19106. const point = source.points[i];
  19107. this.points.push(point.clone());
  19108. }
  19109. return this;
  19110. }
  19111. toJSON() {
  19112. const data = super.toJSON();
  19113. data.points = [];
  19114. for (let i = 0, l = this.points.length; i < l; i++) {
  19115. const point = this.points[i];
  19116. data.points.push(point.toArray());
  19117. }
  19118. return data;
  19119. }
  19120. fromJSON(json) {
  19121. super.fromJSON(json);
  19122. this.points = [];
  19123. for (let i = 0, l = json.points.length; i < l; i++) {
  19124. const point = json.points[i];
  19125. this.points.push(new Vector2().fromArray(point));
  19126. }
  19127. return this;
  19128. }
  19129. }
  19130. var Curves = /*#__PURE__*/Object.freeze({
  19131. __proto__: null,
  19132. ArcCurve: ArcCurve,
  19133. CatmullRomCurve3: CatmullRomCurve3,
  19134. CubicBezierCurve: CubicBezierCurve,
  19135. CubicBezierCurve3: CubicBezierCurve3,
  19136. EllipseCurve: EllipseCurve,
  19137. LineCurve: LineCurve,
  19138. LineCurve3: LineCurve3,
  19139. QuadraticBezierCurve: QuadraticBezierCurve,
  19140. QuadraticBezierCurve3: QuadraticBezierCurve3,
  19141. SplineCurve: SplineCurve
  19142. });
  19143. /**************************************************************
  19144. * Curved Path - a curve path is simply a array of connected
  19145. * curves, but retains the api of a curve
  19146. **************************************************************/
  19147. class CurvePath extends Curve {
  19148. constructor() {
  19149. super();
  19150. this.type = 'CurvePath';
  19151. this.curves = [];
  19152. this.autoClose = false; // Automatically closes the path
  19153. }
  19154. add(curve) {
  19155. this.curves.push(curve);
  19156. }
  19157. closePath() {
  19158. // Add a line curve if start and end of lines are not connected
  19159. const startPoint = this.curves[0].getPoint(0);
  19160. const endPoint = this.curves[this.curves.length - 1].getPoint(1);
  19161. if (!startPoint.equals(endPoint)) {
  19162. this.curves.push(new LineCurve(endPoint, startPoint));
  19163. }
  19164. } // To get accurate point with reference to
  19165. // entire path distance at time t,
  19166. // following has to be done:
  19167. // 1. Length of each sub path have to be known
  19168. // 2. Locate and identify type of curve
  19169. // 3. Get t for the curve
  19170. // 4. Return curve.getPointAt(t')
  19171. getPoint(t, optionalTarget) {
  19172. const d = t * this.getLength();
  19173. const curveLengths = this.getCurveLengths();
  19174. let i = 0; // To think about boundaries points.
  19175. while (i < curveLengths.length) {
  19176. if (curveLengths[i] >= d) {
  19177. const diff = curveLengths[i] - d;
  19178. const curve = this.curves[i];
  19179. const segmentLength = curve.getLength();
  19180. const u = segmentLength === 0 ? 0 : 1 - diff / segmentLength;
  19181. return curve.getPointAt(u, optionalTarget);
  19182. }
  19183. i++;
  19184. }
  19185. return null; // loop where sum != 0, sum > d , sum+1 <d
  19186. } // We cannot use the default THREE.Curve getPoint() with getLength() because in
  19187. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  19188. // getPoint() depends on getLength
  19189. getLength() {
  19190. const lens = this.getCurveLengths();
  19191. return lens[lens.length - 1];
  19192. } // cacheLengths must be recalculated.
  19193. updateArcLengths() {
  19194. this.needsUpdate = true;
  19195. this.cacheLengths = null;
  19196. this.getCurveLengths();
  19197. } // Compute lengths and cache them
  19198. // We cannot overwrite getLengths() because UtoT mapping uses it.
  19199. getCurveLengths() {
  19200. // We use cache values if curves and cache array are same length
  19201. if (this.cacheLengths && this.cacheLengths.length === this.curves.length) {
  19202. return this.cacheLengths;
  19203. } // Get length of sub-curve
  19204. // Push sums into cached array
  19205. const lengths = [];
  19206. let sums = 0;
  19207. for (let i = 0, l = this.curves.length; i < l; i++) {
  19208. sums += this.curves[i].getLength();
  19209. lengths.push(sums);
  19210. }
  19211. this.cacheLengths = lengths;
  19212. return lengths;
  19213. }
  19214. getSpacedPoints(divisions = 40) {
  19215. const points = [];
  19216. for (let i = 0; i <= divisions; i++) {
  19217. points.push(this.getPoint(i / divisions));
  19218. }
  19219. if (this.autoClose) {
  19220. points.push(points[0]);
  19221. }
  19222. return points;
  19223. }
  19224. getPoints(divisions = 12) {
  19225. const points = [];
  19226. let last;
  19227. for (let i = 0, curves = this.curves; i < curves.length; i++) {
  19228. const curve = curves[i];
  19229. const resolution = curve.isEllipseCurve ? divisions * 2 : curve.isLineCurve || curve.isLineCurve3 ? 1 : curve.isSplineCurve ? divisions * curve.points.length : divisions;
  19230. const pts = curve.getPoints(resolution);
  19231. for (let j = 0; j < pts.length; j++) {
  19232. const point = pts[j];
  19233. if (last && last.equals(point)) continue; // ensures no consecutive points are duplicates
  19234. points.push(point);
  19235. last = point;
  19236. }
  19237. }
  19238. if (this.autoClose && points.length > 1 && !points[points.length - 1].equals(points[0])) {
  19239. points.push(points[0]);
  19240. }
  19241. return points;
  19242. }
  19243. copy(source) {
  19244. super.copy(source);
  19245. this.curves = [];
  19246. for (let i = 0, l = source.curves.length; i < l; i++) {
  19247. const curve = source.curves[i];
  19248. this.curves.push(curve.clone());
  19249. }
  19250. this.autoClose = source.autoClose;
  19251. return this;
  19252. }
  19253. toJSON() {
  19254. const data = super.toJSON();
  19255. data.autoClose = this.autoClose;
  19256. data.curves = [];
  19257. for (let i = 0, l = this.curves.length; i < l; i++) {
  19258. const curve = this.curves[i];
  19259. data.curves.push(curve.toJSON());
  19260. }
  19261. return data;
  19262. }
  19263. fromJSON(json) {
  19264. super.fromJSON(json);
  19265. this.autoClose = json.autoClose;
  19266. this.curves = [];
  19267. for (let i = 0, l = json.curves.length; i < l; i++) {
  19268. const curve = json.curves[i];
  19269. this.curves.push(new Curves[curve.type]().fromJSON(curve));
  19270. }
  19271. return this;
  19272. }
  19273. }
  19274. class Path extends CurvePath {
  19275. constructor(points) {
  19276. super();
  19277. this.type = 'Path';
  19278. this.currentPoint = new Vector2();
  19279. if (points) {
  19280. this.setFromPoints(points);
  19281. }
  19282. }
  19283. setFromPoints(points) {
  19284. this.moveTo(points[0].x, points[0].y);
  19285. for (let i = 1, l = points.length; i < l; i++) {
  19286. this.lineTo(points[i].x, points[i].y);
  19287. }
  19288. return this;
  19289. }
  19290. moveTo(x, y) {
  19291. this.currentPoint.set(x, y); // TODO consider referencing vectors instead of copying?
  19292. return this;
  19293. }
  19294. lineTo(x, y) {
  19295. const curve = new LineCurve(this.currentPoint.clone(), new Vector2(x, y));
  19296. this.curves.push(curve);
  19297. this.currentPoint.set(x, y);
  19298. return this;
  19299. }
  19300. quadraticCurveTo(aCPx, aCPy, aX, aY) {
  19301. const curve = new QuadraticBezierCurve(this.currentPoint.clone(), new Vector2(aCPx, aCPy), new Vector2(aX, aY));
  19302. this.curves.push(curve);
  19303. this.currentPoint.set(aX, aY);
  19304. return this;
  19305. }
  19306. bezierCurveTo(aCP1x, aCP1y, aCP2x, aCP2y, aX, aY) {
  19307. const curve = new CubicBezierCurve(this.currentPoint.clone(), new Vector2(aCP1x, aCP1y), new Vector2(aCP2x, aCP2y), new Vector2(aX, aY));
  19308. this.curves.push(curve);
  19309. this.currentPoint.set(aX, aY);
  19310. return this;
  19311. }
  19312. splineThru(pts
  19313. /*Array of Vector*/
  19314. ) {
  19315. const npts = [this.currentPoint.clone()].concat(pts);
  19316. const curve = new SplineCurve(npts);
  19317. this.curves.push(curve);
  19318. this.currentPoint.copy(pts[pts.length - 1]);
  19319. return this;
  19320. }
  19321. arc(aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise) {
  19322. const x0 = this.currentPoint.x;
  19323. const y0 = this.currentPoint.y;
  19324. this.absarc(aX + x0, aY + y0, aRadius, aStartAngle, aEndAngle, aClockwise);
  19325. return this;
  19326. }
  19327. absarc(aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise) {
  19328. this.absellipse(aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise);
  19329. return this;
  19330. }
  19331. ellipse(aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation) {
  19332. const x0 = this.currentPoint.x;
  19333. const y0 = this.currentPoint.y;
  19334. this.absellipse(aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation);
  19335. return this;
  19336. }
  19337. absellipse(aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation) {
  19338. const curve = new EllipseCurve(aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation);
  19339. if (this.curves.length > 0) {
  19340. // if a previous curve is present, attempt to join
  19341. const firstPoint = curve.getPoint(0);
  19342. if (!firstPoint.equals(this.currentPoint)) {
  19343. this.lineTo(firstPoint.x, firstPoint.y);
  19344. }
  19345. }
  19346. this.curves.push(curve);
  19347. const lastPoint = curve.getPoint(1);
  19348. this.currentPoint.copy(lastPoint);
  19349. return this;
  19350. }
  19351. copy(source) {
  19352. super.copy(source);
  19353. this.currentPoint.copy(source.currentPoint);
  19354. return this;
  19355. }
  19356. toJSON() {
  19357. const data = super.toJSON();
  19358. data.currentPoint = this.currentPoint.toArray();
  19359. return data;
  19360. }
  19361. fromJSON(json) {
  19362. super.fromJSON(json);
  19363. this.currentPoint.fromArray(json.currentPoint);
  19364. return this;
  19365. }
  19366. }
  19367. class LatheGeometry extends BufferGeometry {
  19368. constructor(points = [new Vector2(0, -0.5), new Vector2(0.5, 0), new Vector2(0, 0.5)], segments = 12, phiStart = 0, phiLength = Math.PI * 2) {
  19369. super();
  19370. this.type = 'LatheGeometry';
  19371. this.parameters = {
  19372. points: points,
  19373. segments: segments,
  19374. phiStart: phiStart,
  19375. phiLength: phiLength
  19376. };
  19377. segments = Math.floor(segments); // clamp phiLength so it's in range of [ 0, 2PI ]
  19378. phiLength = clamp(phiLength, 0, Math.PI * 2); // buffers
  19379. const indices = [];
  19380. const vertices = [];
  19381. const uvs = [];
  19382. const initNormals = [];
  19383. const normals = []; // helper variables
  19384. const inverseSegments = 1.0 / segments;
  19385. const vertex = new Vector3();
  19386. const uv = new Vector2();
  19387. const normal = new Vector3();
  19388. const curNormal = new Vector3();
  19389. const prevNormal = new Vector3();
  19390. let dx = 0;
  19391. let dy = 0; // pre-compute normals for initial "meridian"
  19392. for (let j = 0; j <= points.length - 1; j++) {
  19393. switch (j) {
  19394. case 0:
  19395. // special handling for 1st vertex on path
  19396. dx = points[j + 1].x - points[j].x;
  19397. dy = points[j + 1].y - points[j].y;
  19398. normal.x = dy * 1.0;
  19399. normal.y = -dx;
  19400. normal.z = dy * 0.0;
  19401. prevNormal.copy(normal);
  19402. normal.normalize();
  19403. initNormals.push(normal.x, normal.y, normal.z);
  19404. break;
  19405. case points.length - 1:
  19406. // special handling for last Vertex on path
  19407. initNormals.push(prevNormal.x, prevNormal.y, prevNormal.z);
  19408. break;
  19409. default:
  19410. // default handling for all vertices in between
  19411. dx = points[j + 1].x - points[j].x;
  19412. dy = points[j + 1].y - points[j].y;
  19413. normal.x = dy * 1.0;
  19414. normal.y = -dx;
  19415. normal.z = dy * 0.0;
  19416. curNormal.copy(normal);
  19417. normal.x += prevNormal.x;
  19418. normal.y += prevNormal.y;
  19419. normal.z += prevNormal.z;
  19420. normal.normalize();
  19421. initNormals.push(normal.x, normal.y, normal.z);
  19422. prevNormal.copy(curNormal);
  19423. }
  19424. } // generate vertices, uvs and normals
  19425. for (let i = 0; i <= segments; i++) {
  19426. const phi = phiStart + i * inverseSegments * phiLength;
  19427. const sin = Math.sin(phi);
  19428. const cos = Math.cos(phi);
  19429. for (let j = 0; j <= points.length - 1; j++) {
  19430. // vertex
  19431. vertex.x = points[j].x * sin;
  19432. vertex.y = points[j].y;
  19433. vertex.z = points[j].x * cos;
  19434. vertices.push(vertex.x, vertex.y, vertex.z); // uv
  19435. uv.x = i / segments;
  19436. uv.y = j / (points.length - 1);
  19437. uvs.push(uv.x, uv.y); // normal
  19438. const x = initNormals[3 * j + 0] * sin;
  19439. const y = initNormals[3 * j + 1];
  19440. const z = initNormals[3 * j + 0] * cos;
  19441. normals.push(x, y, z);
  19442. }
  19443. } // indices
  19444. for (let i = 0; i < segments; i++) {
  19445. for (let j = 0; j < points.length - 1; j++) {
  19446. const base = j + i * points.length;
  19447. const a = base;
  19448. const b = base + points.length;
  19449. const c = base + points.length + 1;
  19450. const d = base + 1; // faces
  19451. indices.push(a, b, d);
  19452. indices.push(c, d, b);
  19453. }
  19454. } // build geometry
  19455. this.setIndex(indices);
  19456. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  19457. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  19458. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  19459. }
  19460. static fromJSON(data) {
  19461. return new LatheGeometry(data.points, data.segments, data.phiStart, data.phiLength);
  19462. }
  19463. }
  19464. class CapsuleGeometry extends LatheGeometry {
  19465. constructor(radius = 1, length = 1, capSegments = 4, radialSegments = 8) {
  19466. const path = new Path();
  19467. path.absarc(0, -length / 2, radius, Math.PI * 1.5, 0);
  19468. path.absarc(0, length / 2, radius, 0, Math.PI * 0.5);
  19469. super(path.getPoints(capSegments), radialSegments);
  19470. this.type = 'CapsuleGeometry';
  19471. this.parameters = {
  19472. radius: radius,
  19473. height: length,
  19474. capSegments: capSegments,
  19475. radialSegments: radialSegments
  19476. };
  19477. }
  19478. static fromJSON(data) {
  19479. return new CapsuleGeometry(data.radius, data.length, data.capSegments, data.radialSegments);
  19480. }
  19481. }
  19482. class CircleGeometry extends BufferGeometry {
  19483. constructor(radius = 1, segments = 8, thetaStart = 0, thetaLength = Math.PI * 2) {
  19484. super();
  19485. this.type = 'CircleGeometry';
  19486. this.parameters = {
  19487. radius: radius,
  19488. segments: segments,
  19489. thetaStart: thetaStart,
  19490. thetaLength: thetaLength
  19491. };
  19492. segments = Math.max(3, segments); // buffers
  19493. const indices = [];
  19494. const vertices = [];
  19495. const normals = [];
  19496. const uvs = []; // helper variables
  19497. const vertex = new Vector3();
  19498. const uv = new Vector2(); // center point
  19499. vertices.push(0, 0, 0);
  19500. normals.push(0, 0, 1);
  19501. uvs.push(0.5, 0.5);
  19502. for (let s = 0, i = 3; s <= segments; s++, i += 3) {
  19503. const segment = thetaStart + s / segments * thetaLength; // vertex
  19504. vertex.x = radius * Math.cos(segment);
  19505. vertex.y = radius * Math.sin(segment);
  19506. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  19507. normals.push(0, 0, 1); // uvs
  19508. uv.x = (vertices[i] / radius + 1) / 2;
  19509. uv.y = (vertices[i + 1] / radius + 1) / 2;
  19510. uvs.push(uv.x, uv.y);
  19511. } // indices
  19512. for (let i = 1; i <= segments; i++) {
  19513. indices.push(i, i + 1, 0);
  19514. } // build geometry
  19515. this.setIndex(indices);
  19516. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  19517. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  19518. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  19519. }
  19520. static fromJSON(data) {
  19521. return new CircleGeometry(data.radius, data.segments, data.thetaStart, data.thetaLength);
  19522. }
  19523. }
  19524. class CylinderGeometry extends BufferGeometry {
  19525. constructor(radiusTop = 1, radiusBottom = 1, height = 1, radialSegments = 8, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2) {
  19526. super();
  19527. this.type = 'CylinderGeometry';
  19528. this.parameters = {
  19529. radiusTop: radiusTop,
  19530. radiusBottom: radiusBottom,
  19531. height: height,
  19532. radialSegments: radialSegments,
  19533. heightSegments: heightSegments,
  19534. openEnded: openEnded,
  19535. thetaStart: thetaStart,
  19536. thetaLength: thetaLength
  19537. };
  19538. const scope = this;
  19539. radialSegments = Math.floor(radialSegments);
  19540. heightSegments = Math.floor(heightSegments); // buffers
  19541. const indices = [];
  19542. const vertices = [];
  19543. const normals = [];
  19544. const uvs = []; // helper variables
  19545. let index = 0;
  19546. const indexArray = [];
  19547. const halfHeight = height / 2;
  19548. let groupStart = 0; // generate geometry
  19549. generateTorso();
  19550. if (openEnded === false) {
  19551. if (radiusTop > 0) generateCap(true);
  19552. if (radiusBottom > 0) generateCap(false);
  19553. } // build geometry
  19554. this.setIndex(indices);
  19555. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  19556. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  19557. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  19558. function generateTorso() {
  19559. const normal = new Vector3();
  19560. const vertex = new Vector3();
  19561. let groupCount = 0; // this will be used to calculate the normal
  19562. const slope = (radiusBottom - radiusTop) / height; // generate vertices, normals and uvs
  19563. for (let y = 0; y <= heightSegments; y++) {
  19564. const indexRow = [];
  19565. const v = y / heightSegments; // calculate the radius of the current row
  19566. const radius = v * (radiusBottom - radiusTop) + radiusTop;
  19567. for (let x = 0; x <= radialSegments; x++) {
  19568. const u = x / radialSegments;
  19569. const theta = u * thetaLength + thetaStart;
  19570. const sinTheta = Math.sin(theta);
  19571. const cosTheta = Math.cos(theta); // vertex
  19572. vertex.x = radius * sinTheta;
  19573. vertex.y = -v * height + halfHeight;
  19574. vertex.z = radius * cosTheta;
  19575. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  19576. normal.set(sinTheta, slope, cosTheta).normalize();
  19577. normals.push(normal.x, normal.y, normal.z); // uv
  19578. uvs.push(u, 1 - v); // save index of vertex in respective row
  19579. indexRow.push(index++);
  19580. } // now save vertices of the row in our index array
  19581. indexArray.push(indexRow);
  19582. } // generate indices
  19583. for (let x = 0; x < radialSegments; x++) {
  19584. for (let y = 0; y < heightSegments; y++) {
  19585. // we use the index array to access the correct indices
  19586. const a = indexArray[y][x];
  19587. const b = indexArray[y + 1][x];
  19588. const c = indexArray[y + 1][x + 1];
  19589. const d = indexArray[y][x + 1]; // faces
  19590. indices.push(a, b, d);
  19591. indices.push(b, c, d); // update group counter
  19592. groupCount += 6;
  19593. }
  19594. } // add a group to the geometry. this will ensure multi material support
  19595. scope.addGroup(groupStart, groupCount, 0); // calculate new start value for groups
  19596. groupStart += groupCount;
  19597. }
  19598. function generateCap(top) {
  19599. // save the index of the first center vertex
  19600. const centerIndexStart = index;
  19601. const uv = new Vector2();
  19602. const vertex = new Vector3();
  19603. let groupCount = 0;
  19604. const radius = top === true ? radiusTop : radiusBottom;
  19605. const sign = top === true ? 1 : -1; // first we generate the center vertex data of the cap.
  19606. // because the geometry needs one set of uvs per face,
  19607. // we must generate a center vertex per face/segment
  19608. for (let x = 1; x <= radialSegments; x++) {
  19609. // vertex
  19610. vertices.push(0, halfHeight * sign, 0); // normal
  19611. normals.push(0, sign, 0); // uv
  19612. uvs.push(0.5, 0.5); // increase index
  19613. index++;
  19614. } // save the index of the last center vertex
  19615. const centerIndexEnd = index; // now we generate the surrounding vertices, normals and uvs
  19616. for (let x = 0; x <= radialSegments; x++) {
  19617. const u = x / radialSegments;
  19618. const theta = u * thetaLength + thetaStart;
  19619. const cosTheta = Math.cos(theta);
  19620. const sinTheta = Math.sin(theta); // vertex
  19621. vertex.x = radius * sinTheta;
  19622. vertex.y = halfHeight * sign;
  19623. vertex.z = radius * cosTheta;
  19624. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  19625. normals.push(0, sign, 0); // uv
  19626. uv.x = cosTheta * 0.5 + 0.5;
  19627. uv.y = sinTheta * 0.5 * sign + 0.5;
  19628. uvs.push(uv.x, uv.y); // increase index
  19629. index++;
  19630. } // generate indices
  19631. for (let x = 0; x < radialSegments; x++) {
  19632. const c = centerIndexStart + x;
  19633. const i = centerIndexEnd + x;
  19634. if (top === true) {
  19635. // face top
  19636. indices.push(i, i + 1, c);
  19637. } else {
  19638. // face bottom
  19639. indices.push(i + 1, i, c);
  19640. }
  19641. groupCount += 3;
  19642. } // add a group to the geometry. this will ensure multi material support
  19643. scope.addGroup(groupStart, groupCount, top === true ? 1 : 2); // calculate new start value for groups
  19644. groupStart += groupCount;
  19645. }
  19646. }
  19647. static fromJSON(data) {
  19648. return new CylinderGeometry(data.radiusTop, data.radiusBottom, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength);
  19649. }
  19650. }
  19651. class ConeGeometry extends CylinderGeometry {
  19652. constructor(radius = 1, height = 1, radialSegments = 8, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2) {
  19653. super(0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength);
  19654. this.type = 'ConeGeometry';
  19655. this.parameters = {
  19656. radius: radius,
  19657. height: height,
  19658. radialSegments: radialSegments,
  19659. heightSegments: heightSegments,
  19660. openEnded: openEnded,
  19661. thetaStart: thetaStart,
  19662. thetaLength: thetaLength
  19663. };
  19664. }
  19665. static fromJSON(data) {
  19666. return new ConeGeometry(data.radius, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength);
  19667. }
  19668. }
  19669. class PolyhedronGeometry extends BufferGeometry {
  19670. constructor(vertices = [], indices = [], radius = 1, detail = 0) {
  19671. super();
  19672. this.type = 'PolyhedronGeometry';
  19673. this.parameters = {
  19674. vertices: vertices,
  19675. indices: indices,
  19676. radius: radius,
  19677. detail: detail
  19678. }; // default buffer data
  19679. const vertexBuffer = [];
  19680. const uvBuffer = []; // the subdivision creates the vertex buffer data
  19681. subdivide(detail); // all vertices should lie on a conceptual sphere with a given radius
  19682. applyRadius(radius); // finally, create the uv data
  19683. generateUVs(); // build non-indexed geometry
  19684. this.setAttribute('position', new Float32BufferAttribute(vertexBuffer, 3));
  19685. this.setAttribute('normal', new Float32BufferAttribute(vertexBuffer.slice(), 3));
  19686. this.setAttribute('uv', new Float32BufferAttribute(uvBuffer, 2));
  19687. if (detail === 0) {
  19688. this.computeVertexNormals(); // flat normals
  19689. } else {
  19690. this.normalizeNormals(); // smooth normals
  19691. } // helper functions
  19692. function subdivide(detail) {
  19693. const a = new Vector3();
  19694. const b = new Vector3();
  19695. const c = new Vector3(); // iterate over all faces and apply a subdivison with the given detail value
  19696. for (let i = 0; i < indices.length; i += 3) {
  19697. // get the vertices of the face
  19698. getVertexByIndex(indices[i + 0], a);
  19699. getVertexByIndex(indices[i + 1], b);
  19700. getVertexByIndex(indices[i + 2], c); // perform subdivision
  19701. subdivideFace(a, b, c, detail);
  19702. }
  19703. }
  19704. function subdivideFace(a, b, c, detail) {
  19705. const cols = detail + 1; // we use this multidimensional array as a data structure for creating the subdivision
  19706. const v = []; // construct all of the vertices for this subdivision
  19707. for (let i = 0; i <= cols; i++) {
  19708. v[i] = [];
  19709. const aj = a.clone().lerp(c, i / cols);
  19710. const bj = b.clone().lerp(c, i / cols);
  19711. const rows = cols - i;
  19712. for (let j = 0; j <= rows; j++) {
  19713. if (j === 0 && i === cols) {
  19714. v[i][j] = aj;
  19715. } else {
  19716. v[i][j] = aj.clone().lerp(bj, j / rows);
  19717. }
  19718. }
  19719. } // construct all of the faces
  19720. for (let i = 0; i < cols; i++) {
  19721. for (let j = 0; j < 2 * (cols - i) - 1; j++) {
  19722. const k = Math.floor(j / 2);
  19723. if (j % 2 === 0) {
  19724. pushVertex(v[i][k + 1]);
  19725. pushVertex(v[i + 1][k]);
  19726. pushVertex(v[i][k]);
  19727. } else {
  19728. pushVertex(v[i][k + 1]);
  19729. pushVertex(v[i + 1][k + 1]);
  19730. pushVertex(v[i + 1][k]);
  19731. }
  19732. }
  19733. }
  19734. }
  19735. function applyRadius(radius) {
  19736. const vertex = new Vector3(); // iterate over the entire buffer and apply the radius to each vertex
  19737. for (let i = 0; i < vertexBuffer.length; i += 3) {
  19738. vertex.x = vertexBuffer[i + 0];
  19739. vertex.y = vertexBuffer[i + 1];
  19740. vertex.z = vertexBuffer[i + 2];
  19741. vertex.normalize().multiplyScalar(radius);
  19742. vertexBuffer[i + 0] = vertex.x;
  19743. vertexBuffer[i + 1] = vertex.y;
  19744. vertexBuffer[i + 2] = vertex.z;
  19745. }
  19746. }
  19747. function generateUVs() {
  19748. const vertex = new Vector3();
  19749. for (let i = 0; i < vertexBuffer.length; i += 3) {
  19750. vertex.x = vertexBuffer[i + 0];
  19751. vertex.y = vertexBuffer[i + 1];
  19752. vertex.z = vertexBuffer[i + 2];
  19753. const u = azimuth(vertex) / 2 / Math.PI + 0.5;
  19754. const v = inclination(vertex) / Math.PI + 0.5;
  19755. uvBuffer.push(u, 1 - v);
  19756. }
  19757. correctUVs();
  19758. correctSeam();
  19759. }
  19760. function correctSeam() {
  19761. // handle case when face straddles the seam, see #3269
  19762. for (let i = 0; i < uvBuffer.length; i += 6) {
  19763. // uv data of a single face
  19764. const x0 = uvBuffer[i + 0];
  19765. const x1 = uvBuffer[i + 2];
  19766. const x2 = uvBuffer[i + 4];
  19767. const max = Math.max(x0, x1, x2);
  19768. const min = Math.min(x0, x1, x2); // 0.9 is somewhat arbitrary
  19769. if (max > 0.9 && min < 0.1) {
  19770. if (x0 < 0.2) uvBuffer[i + 0] += 1;
  19771. if (x1 < 0.2) uvBuffer[i + 2] += 1;
  19772. if (x2 < 0.2) uvBuffer[i + 4] += 1;
  19773. }
  19774. }
  19775. }
  19776. function pushVertex(vertex) {
  19777. vertexBuffer.push(vertex.x, vertex.y, vertex.z);
  19778. }
  19779. function getVertexByIndex(index, vertex) {
  19780. const stride = index * 3;
  19781. vertex.x = vertices[stride + 0];
  19782. vertex.y = vertices[stride + 1];
  19783. vertex.z = vertices[stride + 2];
  19784. }
  19785. function correctUVs() {
  19786. const a = new Vector3();
  19787. const b = new Vector3();
  19788. const c = new Vector3();
  19789. const centroid = new Vector3();
  19790. const uvA = new Vector2();
  19791. const uvB = new Vector2();
  19792. const uvC = new Vector2();
  19793. for (let i = 0, j = 0; i < vertexBuffer.length; i += 9, j += 6) {
  19794. a.set(vertexBuffer[i + 0], vertexBuffer[i + 1], vertexBuffer[i + 2]);
  19795. b.set(vertexBuffer[i + 3], vertexBuffer[i + 4], vertexBuffer[i + 5]);
  19796. c.set(vertexBuffer[i + 6], vertexBuffer[i + 7], vertexBuffer[i + 8]);
  19797. uvA.set(uvBuffer[j + 0], uvBuffer[j + 1]);
  19798. uvB.set(uvBuffer[j + 2], uvBuffer[j + 3]);
  19799. uvC.set(uvBuffer[j + 4], uvBuffer[j + 5]);
  19800. centroid.copy(a).add(b).add(c).divideScalar(3);
  19801. const azi = azimuth(centroid);
  19802. correctUV(uvA, j + 0, a, azi);
  19803. correctUV(uvB, j + 2, b, azi);
  19804. correctUV(uvC, j + 4, c, azi);
  19805. }
  19806. }
  19807. function correctUV(uv, stride, vector, azimuth) {
  19808. if (azimuth < 0 && uv.x === 1) {
  19809. uvBuffer[stride] = uv.x - 1;
  19810. }
  19811. if (vector.x === 0 && vector.z === 0) {
  19812. uvBuffer[stride] = azimuth / 2 / Math.PI + 0.5;
  19813. }
  19814. } // Angle around the Y axis, counter-clockwise when looking from above.
  19815. function azimuth(vector) {
  19816. return Math.atan2(vector.z, -vector.x);
  19817. } // Angle above the XZ plane.
  19818. function inclination(vector) {
  19819. return Math.atan2(-vector.y, Math.sqrt(vector.x * vector.x + vector.z * vector.z));
  19820. }
  19821. }
  19822. static fromJSON(data) {
  19823. return new PolyhedronGeometry(data.vertices, data.indices, data.radius, data.details);
  19824. }
  19825. }
  19826. class DodecahedronGeometry extends PolyhedronGeometry {
  19827. constructor(radius = 1, detail = 0) {
  19828. const t = (1 + Math.sqrt(5)) / 2;
  19829. const r = 1 / t;
  19830. const vertices = [// (±1, ±1, ±1)
  19831. -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/φ, ±φ)
  19832. 0, -r, -t, 0, -r, t, 0, r, -t, 0, r, t, // (±1/φ, ±φ, 0)
  19833. -r, -t, 0, -r, t, 0, r, -t, 0, r, t, 0, // (±φ, 0, ±1/φ)
  19834. -t, 0, -r, t, 0, -r, -t, 0, r, t, 0, r];
  19835. const indices = [3, 11, 7, 3, 7, 15, 3, 15, 13, 7, 19, 17, 7, 17, 6, 7, 6, 15, 17, 4, 8, 17, 8, 10, 17, 10, 6, 8, 0, 16, 8, 16, 2, 8, 2, 10, 0, 12, 1, 0, 1, 18, 0, 18, 16, 6, 10, 2, 6, 2, 13, 6, 13, 15, 2, 16, 18, 2, 18, 3, 2, 3, 13, 18, 1, 9, 18, 9, 11, 18, 11, 3, 4, 14, 12, 4, 12, 0, 4, 0, 8, 11, 9, 5, 11, 5, 19, 11, 19, 7, 19, 5, 14, 19, 14, 4, 19, 4, 17, 1, 12, 14, 1, 14, 5, 1, 5, 9];
  19836. super(vertices, indices, radius, detail);
  19837. this.type = 'DodecahedronGeometry';
  19838. this.parameters = {
  19839. radius: radius,
  19840. detail: detail
  19841. };
  19842. }
  19843. static fromJSON(data) {
  19844. return new DodecahedronGeometry(data.radius, data.detail);
  19845. }
  19846. }
  19847. const _v0 = /*@__PURE__*/new Vector3();
  19848. const _v1$1 = /*@__PURE__*/new Vector3();
  19849. const _normal = /*@__PURE__*/new Vector3();
  19850. const _triangle = /*@__PURE__*/new Triangle();
  19851. class EdgesGeometry extends BufferGeometry {
  19852. constructor(geometry = null, thresholdAngle = 1) {
  19853. super();
  19854. this.type = 'EdgesGeometry';
  19855. this.parameters = {
  19856. geometry: geometry,
  19857. thresholdAngle: thresholdAngle
  19858. };
  19859. if (geometry !== null) {
  19860. const precisionPoints = 4;
  19861. const precision = Math.pow(10, precisionPoints);
  19862. const thresholdDot = Math.cos(DEG2RAD * thresholdAngle);
  19863. const indexAttr = geometry.getIndex();
  19864. const positionAttr = geometry.getAttribute('position');
  19865. const indexCount = indexAttr ? indexAttr.count : positionAttr.count;
  19866. const indexArr = [0, 0, 0];
  19867. const vertKeys = ['a', 'b', 'c'];
  19868. const hashes = new Array(3);
  19869. const edgeData = {};
  19870. const vertices = [];
  19871. for (let i = 0; i < indexCount; i += 3) {
  19872. if (indexAttr) {
  19873. indexArr[0] = indexAttr.getX(i);
  19874. indexArr[1] = indexAttr.getX(i + 1);
  19875. indexArr[2] = indexAttr.getX(i + 2);
  19876. } else {
  19877. indexArr[0] = i;
  19878. indexArr[1] = i + 1;
  19879. indexArr[2] = i + 2;
  19880. }
  19881. const {
  19882. a,
  19883. b,
  19884. c
  19885. } = _triangle;
  19886. a.fromBufferAttribute(positionAttr, indexArr[0]);
  19887. b.fromBufferAttribute(positionAttr, indexArr[1]);
  19888. c.fromBufferAttribute(positionAttr, indexArr[2]);
  19889. _triangle.getNormal(_normal); // create hashes for the edge from the vertices
  19890. hashes[0] = `${Math.round(a.x * precision)},${Math.round(a.y * precision)},${Math.round(a.z * precision)}`;
  19891. hashes[1] = `${Math.round(b.x * precision)},${Math.round(b.y * precision)},${Math.round(b.z * precision)}`;
  19892. hashes[2] = `${Math.round(c.x * precision)},${Math.round(c.y * precision)},${Math.round(c.z * precision)}`; // skip degenerate triangles
  19893. if (hashes[0] === hashes[1] || hashes[1] === hashes[2] || hashes[2] === hashes[0]) {
  19894. continue;
  19895. } // iterate over every edge
  19896. for (let j = 0; j < 3; j++) {
  19897. // get the first and next vertex making up the edge
  19898. const jNext = (j + 1) % 3;
  19899. const vecHash0 = hashes[j];
  19900. const vecHash1 = hashes[jNext];
  19901. const v0 = _triangle[vertKeys[j]];
  19902. const v1 = _triangle[vertKeys[jNext]];
  19903. const hash = `${vecHash0}_${vecHash1}`;
  19904. const reverseHash = `${vecHash1}_${vecHash0}`;
  19905. if (reverseHash in edgeData && edgeData[reverseHash]) {
  19906. // if we found a sibling edge add it into the vertex array if
  19907. // it meets the angle threshold and delete the edge from the map.
  19908. if (_normal.dot(edgeData[reverseHash].normal) <= thresholdDot) {
  19909. vertices.push(v0.x, v0.y, v0.z);
  19910. vertices.push(v1.x, v1.y, v1.z);
  19911. }
  19912. edgeData[reverseHash] = null;
  19913. } else if (!(hash in edgeData)) {
  19914. // if we've already got an edge here then skip adding a new one
  19915. edgeData[hash] = {
  19916. index0: indexArr[j],
  19917. index1: indexArr[jNext],
  19918. normal: _normal.clone()
  19919. };
  19920. }
  19921. }
  19922. } // iterate over all remaining, unmatched edges and add them to the vertex array
  19923. for (const key in edgeData) {
  19924. if (edgeData[key]) {
  19925. const {
  19926. index0,
  19927. index1
  19928. } = edgeData[key];
  19929. _v0.fromBufferAttribute(positionAttr, index0);
  19930. _v1$1.fromBufferAttribute(positionAttr, index1);
  19931. vertices.push(_v0.x, _v0.y, _v0.z);
  19932. vertices.push(_v1$1.x, _v1$1.y, _v1$1.z);
  19933. }
  19934. }
  19935. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  19936. }
  19937. }
  19938. }
  19939. class Shape extends Path {
  19940. constructor(points) {
  19941. super(points);
  19942. this.uuid = generateUUID();
  19943. this.type = 'Shape';
  19944. this.holes = [];
  19945. }
  19946. getPointsHoles(divisions) {
  19947. const holesPts = [];
  19948. for (let i = 0, l = this.holes.length; i < l; i++) {
  19949. holesPts[i] = this.holes[i].getPoints(divisions);
  19950. }
  19951. return holesPts;
  19952. } // get points of shape and holes (keypoints based on segments parameter)
  19953. extractPoints(divisions) {
  19954. return {
  19955. shape: this.getPoints(divisions),
  19956. holes: this.getPointsHoles(divisions)
  19957. };
  19958. }
  19959. copy(source) {
  19960. super.copy(source);
  19961. this.holes = [];
  19962. for (let i = 0, l = source.holes.length; i < l; i++) {
  19963. const hole = source.holes[i];
  19964. this.holes.push(hole.clone());
  19965. }
  19966. return this;
  19967. }
  19968. toJSON() {
  19969. const data = super.toJSON();
  19970. data.uuid = this.uuid;
  19971. data.holes = [];
  19972. for (let i = 0, l = this.holes.length; i < l; i++) {
  19973. const hole = this.holes[i];
  19974. data.holes.push(hole.toJSON());
  19975. }
  19976. return data;
  19977. }
  19978. fromJSON(json) {
  19979. super.fromJSON(json);
  19980. this.uuid = json.uuid;
  19981. this.holes = [];
  19982. for (let i = 0, l = json.holes.length; i < l; i++) {
  19983. const hole = json.holes[i];
  19984. this.holes.push(new Path().fromJSON(hole));
  19985. }
  19986. return this;
  19987. }
  19988. }
  19989. /**
  19990. * Port from https://github.com/mapbox/earcut (v2.2.2)
  19991. */
  19992. const Earcut = {
  19993. triangulate: function (data, holeIndices, dim = 2) {
  19994. const hasHoles = holeIndices && holeIndices.length;
  19995. const outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  19996. let outerNode = linkedList(data, 0, outerLen, dim, true);
  19997. const triangles = [];
  19998. if (!outerNode || outerNode.next === outerNode.prev) return triangles;
  19999. let minX, minY, maxX, maxY, x, y, invSize;
  20000. 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
  20001. if (data.length > 80 * dim) {
  20002. minX = maxX = data[0];
  20003. minY = maxY = data[1];
  20004. for (let i = dim; i < outerLen; i += dim) {
  20005. x = data[i];
  20006. y = data[i + 1];
  20007. if (x < minX) minX = x;
  20008. if (y < minY) minY = y;
  20009. if (x > maxX) maxX = x;
  20010. if (y > maxY) maxY = y;
  20011. } // minX, minY and invSize are later used to transform coords into integers for z-order calculation
  20012. invSize = Math.max(maxX - minX, maxY - minY);
  20013. invSize = invSize !== 0 ? 1 / invSize : 0;
  20014. }
  20015. earcutLinked(outerNode, triangles, dim, minX, minY, invSize);
  20016. return triangles;
  20017. }
  20018. }; // create a circular doubly linked list from polygon points in the specified winding order
  20019. function linkedList(data, start, end, dim, clockwise) {
  20020. let i, last;
  20021. if (clockwise === signedArea(data, start, end, dim) > 0) {
  20022. for (i = start; i < end; i += dim) last = insertNode(i, data[i], data[i + 1], last);
  20023. } else {
  20024. for (i = end - dim; i >= start; i -= dim) last = insertNode(i, data[i], data[i + 1], last);
  20025. }
  20026. if (last && equals(last, last.next)) {
  20027. removeNode(last);
  20028. last = last.next;
  20029. }
  20030. return last;
  20031. } // eliminate colinear or duplicate points
  20032. function filterPoints(start, end) {
  20033. if (!start) return start;
  20034. if (!end) end = start;
  20035. let p = start,
  20036. again;
  20037. do {
  20038. again = false;
  20039. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  20040. removeNode(p);
  20041. p = end = p.prev;
  20042. if (p === p.next) break;
  20043. again = true;
  20044. } else {
  20045. p = p.next;
  20046. }
  20047. } while (again || p !== end);
  20048. return end;
  20049. } // main ear slicing loop which triangulates a polygon (given as a linked list)
  20050. function earcutLinked(ear, triangles, dim, minX, minY, invSize, pass) {
  20051. if (!ear) return; // interlink polygon nodes in z-order
  20052. if (!pass && invSize) indexCurve(ear, minX, minY, invSize);
  20053. let stop = ear,
  20054. prev,
  20055. next; // iterate through ears, slicing them one by one
  20056. while (ear.prev !== ear.next) {
  20057. prev = ear.prev;
  20058. next = ear.next;
  20059. if (invSize ? isEarHashed(ear, minX, minY, invSize) : isEar(ear)) {
  20060. // cut off the triangle
  20061. triangles.push(prev.i / dim);
  20062. triangles.push(ear.i / dim);
  20063. triangles.push(next.i / dim);
  20064. removeNode(ear); // skipping the next vertex leads to less sliver triangles
  20065. ear = next.next;
  20066. stop = next.next;
  20067. continue;
  20068. }
  20069. ear = next; // if we looped through the whole remaining polygon and can't find any more ears
  20070. if (ear === stop) {
  20071. // try filtering points and slicing again
  20072. if (!pass) {
  20073. earcutLinked(filterPoints(ear), triangles, dim, minX, minY, invSize, 1); // if this didn't work, try curing all small self-intersections locally
  20074. } else if (pass === 1) {
  20075. ear = cureLocalIntersections(filterPoints(ear), triangles, dim);
  20076. earcutLinked(ear, triangles, dim, minX, minY, invSize, 2); // as a last resort, try splitting the remaining polygon into two
  20077. } else if (pass === 2) {
  20078. splitEarcut(ear, triangles, dim, minX, minY, invSize);
  20079. }
  20080. break;
  20081. }
  20082. }
  20083. } // check whether a polygon node forms a valid ear with adjacent nodes
  20084. function isEar(ear) {
  20085. const a = ear.prev,
  20086. b = ear,
  20087. c = ear.next;
  20088. if (area(a, b, c) >= 0) return false; // reflex, can't be an ear
  20089. // now make sure we don't have other points inside the potential ear
  20090. let p = ear.next.next;
  20091. while (p !== ear.prev) {
  20092. 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;
  20093. p = p.next;
  20094. }
  20095. return true;
  20096. }
  20097. function isEarHashed(ear, minX, minY, invSize) {
  20098. const a = ear.prev,
  20099. b = ear,
  20100. c = ear.next;
  20101. if (area(a, b, c) >= 0) return false; // reflex, can't be an ear
  20102. // triangle bbox; min & max are calculated like this for speed
  20103. const minTX = a.x < b.x ? a.x < c.x ? a.x : c.x : b.x < c.x ? b.x : c.x,
  20104. minTY = a.y < b.y ? a.y < c.y ? a.y : c.y : b.y < c.y ? b.y : c.y,
  20105. maxTX = a.x > b.x ? a.x > c.x ? a.x : c.x : b.x > c.x ? b.x : c.x,
  20106. 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;
  20107. const minZ = zOrder(minTX, minTY, minX, minY, invSize),
  20108. maxZ = zOrder(maxTX, maxTY, minX, minY, invSize);
  20109. let p = ear.prevZ,
  20110. n = ear.nextZ; // look for points inside the triangle in both directions
  20111. while (p && p.z >= minZ && n && n.z <= maxZ) {
  20112. 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;
  20113. p = p.prevZ;
  20114. 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;
  20115. n = n.nextZ;
  20116. } // look for remaining points in decreasing z-order
  20117. while (p && p.z >= minZ) {
  20118. 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;
  20119. p = p.prevZ;
  20120. } // look for remaining points in increasing z-order
  20121. while (n && n.z <= maxZ) {
  20122. 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;
  20123. n = n.nextZ;
  20124. }
  20125. return true;
  20126. } // go through all polygon nodes and cure small local self-intersections
  20127. function cureLocalIntersections(start, triangles, dim) {
  20128. let p = start;
  20129. do {
  20130. const a = p.prev,
  20131. b = p.next.next;
  20132. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  20133. triangles.push(a.i / dim);
  20134. triangles.push(p.i / dim);
  20135. triangles.push(b.i / dim); // remove two nodes involved
  20136. removeNode(p);
  20137. removeNode(p.next);
  20138. p = start = b;
  20139. }
  20140. p = p.next;
  20141. } while (p !== start);
  20142. return filterPoints(p);
  20143. } // try splitting polygon into two and triangulate them independently
  20144. function splitEarcut(start, triangles, dim, minX, minY, invSize) {
  20145. // look for a valid diagonal that divides the polygon into two
  20146. let a = start;
  20147. do {
  20148. let b = a.next.next;
  20149. while (b !== a.prev) {
  20150. if (a.i !== b.i && isValidDiagonal(a, b)) {
  20151. // split the polygon in two by the diagonal
  20152. let c = splitPolygon(a, b); // filter colinear points around the cuts
  20153. a = filterPoints(a, a.next);
  20154. c = filterPoints(c, c.next); // run earcut on each half
  20155. earcutLinked(a, triangles, dim, minX, minY, invSize);
  20156. earcutLinked(c, triangles, dim, minX, minY, invSize);
  20157. return;
  20158. }
  20159. b = b.next;
  20160. }
  20161. a = a.next;
  20162. } while (a !== start);
  20163. } // link every hole into the outer loop, producing a single-ring polygon without holes
  20164. function eliminateHoles(data, holeIndices, outerNode, dim) {
  20165. const queue = [];
  20166. let i, len, start, end, list;
  20167. for (i = 0, len = holeIndices.length; i < len; i++) {
  20168. start = holeIndices[i] * dim;
  20169. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  20170. list = linkedList(data, start, end, dim, false);
  20171. if (list === list.next) list.steiner = true;
  20172. queue.push(getLeftmost(list));
  20173. }
  20174. queue.sort(compareX); // process holes from left to right
  20175. for (i = 0; i < queue.length; i++) {
  20176. eliminateHole(queue[i], outerNode);
  20177. outerNode = filterPoints(outerNode, outerNode.next);
  20178. }
  20179. return outerNode;
  20180. }
  20181. function compareX(a, b) {
  20182. return a.x - b.x;
  20183. } // find a bridge between vertices that connects hole with an outer ring and link it
  20184. function eliminateHole(hole, outerNode) {
  20185. outerNode = findHoleBridge(hole, outerNode);
  20186. if (outerNode) {
  20187. const b = splitPolygon(outerNode, hole); // filter collinear points around the cuts
  20188. filterPoints(outerNode, outerNode.next);
  20189. filterPoints(b, b.next);
  20190. }
  20191. } // David Eberly's algorithm for finding a bridge between hole and outer polygon
  20192. function findHoleBridge(hole, outerNode) {
  20193. let p = outerNode;
  20194. const hx = hole.x;
  20195. const hy = hole.y;
  20196. let qx = -Infinity,
  20197. m; // find a segment intersected by a ray from the hole's leftmost point to the left;
  20198. // segment's endpoint with lesser x will be potential connection point
  20199. do {
  20200. if (hy <= p.y && hy >= p.next.y && p.next.y !== p.y) {
  20201. const x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  20202. if (x <= hx && x > qx) {
  20203. qx = x;
  20204. if (x === hx) {
  20205. if (hy === p.y) return p;
  20206. if (hy === p.next.y) return p.next;
  20207. }
  20208. m = p.x < p.next.x ? p : p.next;
  20209. }
  20210. }
  20211. p = p.next;
  20212. } while (p !== outerNode);
  20213. if (!m) return null;
  20214. if (hx === qx) return m; // hole touches outer segment; pick leftmost endpoint
  20215. // look for points inside the triangle of hole point, segment intersection and endpoint;
  20216. // if there are no points found, we have a valid connection;
  20217. // otherwise choose the point of the minimum angle with the ray as connection point
  20218. const stop = m,
  20219. mx = m.x,
  20220. my = m.y;
  20221. let tanMin = Infinity,
  20222. tan;
  20223. p = m;
  20224. do {
  20225. 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)) {
  20226. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  20227. if (locallyInside(p, hole) && (tan < tanMin || tan === tanMin && (p.x > m.x || p.x === m.x && sectorContainsSector(m, p)))) {
  20228. m = p;
  20229. tanMin = tan;
  20230. }
  20231. }
  20232. p = p.next;
  20233. } while (p !== stop);
  20234. return m;
  20235. } // whether sector in vertex m contains sector in vertex p in the same coordinates
  20236. function sectorContainsSector(m, p) {
  20237. return area(m.prev, m, p.prev) < 0 && area(p.next, m, m.next) < 0;
  20238. } // interlink polygon nodes in z-order
  20239. function indexCurve(start, minX, minY, invSize) {
  20240. let p = start;
  20241. do {
  20242. if (p.z === null) p.z = zOrder(p.x, p.y, minX, minY, invSize);
  20243. p.prevZ = p.prev;
  20244. p.nextZ = p.next;
  20245. p = p.next;
  20246. } while (p !== start);
  20247. p.prevZ.nextZ = null;
  20248. p.prevZ = null;
  20249. sortLinked(p);
  20250. } // Simon Tatham's linked list merge sort algorithm
  20251. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  20252. function sortLinked(list) {
  20253. let i,
  20254. p,
  20255. q,
  20256. e,
  20257. tail,
  20258. numMerges,
  20259. pSize,
  20260. qSize,
  20261. inSize = 1;
  20262. do {
  20263. p = list;
  20264. list = null;
  20265. tail = null;
  20266. numMerges = 0;
  20267. while (p) {
  20268. numMerges++;
  20269. q = p;
  20270. pSize = 0;
  20271. for (i = 0; i < inSize; i++) {
  20272. pSize++;
  20273. q = q.nextZ;
  20274. if (!q) break;
  20275. }
  20276. qSize = inSize;
  20277. while (pSize > 0 || qSize > 0 && q) {
  20278. if (pSize !== 0 && (qSize === 0 || !q || p.z <= q.z)) {
  20279. e = p;
  20280. p = p.nextZ;
  20281. pSize--;
  20282. } else {
  20283. e = q;
  20284. q = q.nextZ;
  20285. qSize--;
  20286. }
  20287. if (tail) tail.nextZ = e;else list = e;
  20288. e.prevZ = tail;
  20289. tail = e;
  20290. }
  20291. p = q;
  20292. }
  20293. tail.nextZ = null;
  20294. inSize *= 2;
  20295. } while (numMerges > 1);
  20296. return list;
  20297. } // z-order of a point given coords and inverse of the longer side of data bbox
  20298. function zOrder(x, y, minX, minY, invSize) {
  20299. // coords are transformed into non-negative 15-bit integer range
  20300. x = 32767 * (x - minX) * invSize;
  20301. y = 32767 * (y - minY) * invSize;
  20302. x = (x | x << 8) & 0x00FF00FF;
  20303. x = (x | x << 4) & 0x0F0F0F0F;
  20304. x = (x | x << 2) & 0x33333333;
  20305. x = (x | x << 1) & 0x55555555;
  20306. y = (y | y << 8) & 0x00FF00FF;
  20307. y = (y | y << 4) & 0x0F0F0F0F;
  20308. y = (y | y << 2) & 0x33333333;
  20309. y = (y | y << 1) & 0x55555555;
  20310. return x | y << 1;
  20311. } // find the leftmost node of a polygon ring
  20312. function getLeftmost(start) {
  20313. let p = start,
  20314. leftmost = start;
  20315. do {
  20316. if (p.x < leftmost.x || p.x === leftmost.x && p.y < leftmost.y) leftmost = p;
  20317. p = p.next;
  20318. } while (p !== start);
  20319. return leftmost;
  20320. } // check if a point lies within a convex triangle
  20321. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  20322. 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;
  20323. } // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  20324. function isValidDiagonal(a, b) {
  20325. return a.next.i !== b.i && a.prev.i !== b.i && !intersectsPolygon(a, b) && ( // doesn't intersect other edges
  20326. locallyInside(a, b) && locallyInside(b, a) && middleInside(a, b) && ( // locally visible
  20327. area(a.prev, a, b.prev) || area(a, b.prev, b)) || // does not create opposite-facing sectors
  20328. equals(a, b) && area(a.prev, a, a.next) > 0 && area(b.prev, b, b.next) > 0); // special zero-length case
  20329. } // signed area of a triangle
  20330. function area(p, q, r) {
  20331. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  20332. } // check if two points are equal
  20333. function equals(p1, p2) {
  20334. return p1.x === p2.x && p1.y === p2.y;
  20335. } // check if two segments intersect
  20336. function intersects(p1, q1, p2, q2) {
  20337. const o1 = sign(area(p1, q1, p2));
  20338. const o2 = sign(area(p1, q1, q2));
  20339. const o3 = sign(area(p2, q2, p1));
  20340. const o4 = sign(area(p2, q2, q1));
  20341. if (o1 !== o2 && o3 !== o4) return true; // general case
  20342. if (o1 === 0 && onSegment(p1, p2, q1)) return true; // p1, q1 and p2 are collinear and p2 lies on p1q1
  20343. if (o2 === 0 && onSegment(p1, q2, q1)) return true; // p1, q1 and q2 are collinear and q2 lies on p1q1
  20344. if (o3 === 0 && onSegment(p2, p1, q2)) return true; // p2, q2 and p1 are collinear and p1 lies on p2q2
  20345. if (o4 === 0 && onSegment(p2, q1, q2)) return true; // p2, q2 and q1 are collinear and q1 lies on p2q2
  20346. return false;
  20347. } // for collinear points p, q, r, check if point q lies on segment pr
  20348. function onSegment(p, q, r) {
  20349. return q.x <= Math.max(p.x, r.x) && q.x >= Math.min(p.x, r.x) && q.y <= Math.max(p.y, r.y) && q.y >= Math.min(p.y, r.y);
  20350. }
  20351. function sign(num) {
  20352. return num > 0 ? 1 : num < 0 ? -1 : 0;
  20353. } // check if a polygon diagonal intersects any polygon segments
  20354. function intersectsPolygon(a, b) {
  20355. let p = a;
  20356. do {
  20357. 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;
  20358. p = p.next;
  20359. } while (p !== a);
  20360. return false;
  20361. } // check if a polygon diagonal is locally inside the polygon
  20362. function locallyInside(a, b) {
  20363. 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;
  20364. } // check if the middle point of a polygon diagonal is inside the polygon
  20365. function middleInside(a, b) {
  20366. let p = a,
  20367. inside = false;
  20368. const px = (a.x + b.x) / 2,
  20369. py = (a.y + b.y) / 2;
  20370. do {
  20371. 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;
  20372. p = p.next;
  20373. } while (p !== a);
  20374. return inside;
  20375. } // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  20376. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  20377. function splitPolygon(a, b) {
  20378. const a2 = new Node(a.i, a.x, a.y),
  20379. b2 = new Node(b.i, b.x, b.y),
  20380. an = a.next,
  20381. bp = b.prev;
  20382. a.next = b;
  20383. b.prev = a;
  20384. a2.next = an;
  20385. an.prev = a2;
  20386. b2.next = a2;
  20387. a2.prev = b2;
  20388. bp.next = b2;
  20389. b2.prev = bp;
  20390. return b2;
  20391. } // create a node and optionally link it with previous one (in a circular doubly linked list)
  20392. function insertNode(i, x, y, last) {
  20393. const p = new Node(i, x, y);
  20394. if (!last) {
  20395. p.prev = p;
  20396. p.next = p;
  20397. } else {
  20398. p.next = last.next;
  20399. p.prev = last;
  20400. last.next.prev = p;
  20401. last.next = p;
  20402. }
  20403. return p;
  20404. }
  20405. function removeNode(p) {
  20406. p.next.prev = p.prev;
  20407. p.prev.next = p.next;
  20408. if (p.prevZ) p.prevZ.nextZ = p.nextZ;
  20409. if (p.nextZ) p.nextZ.prevZ = p.prevZ;
  20410. }
  20411. function Node(i, x, y) {
  20412. // vertex index in coordinates array
  20413. this.i = i; // vertex coordinates
  20414. this.x = x;
  20415. this.y = y; // previous and next vertex nodes in a polygon ring
  20416. this.prev = null;
  20417. this.next = null; // z-order curve value
  20418. this.z = null; // previous and next nodes in z-order
  20419. this.prevZ = null;
  20420. this.nextZ = null; // indicates whether this is a steiner point
  20421. this.steiner = false;
  20422. }
  20423. function signedArea(data, start, end, dim) {
  20424. let sum = 0;
  20425. for (let i = start, j = end - dim; i < end; i += dim) {
  20426. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  20427. j = i;
  20428. }
  20429. return sum;
  20430. }
  20431. class ShapeUtils {
  20432. // calculate area of the contour polygon
  20433. static area(contour) {
  20434. const n = contour.length;
  20435. let a = 0.0;
  20436. for (let p = n - 1, q = 0; q < n; p = q++) {
  20437. a += contour[p].x * contour[q].y - contour[q].x * contour[p].y;
  20438. }
  20439. return a * 0.5;
  20440. }
  20441. static isClockWise(pts) {
  20442. return ShapeUtils.area(pts) < 0;
  20443. }
  20444. static triangulateShape(contour, holes) {
  20445. const vertices = []; // flat array of vertices like [ x0,y0, x1,y1, x2,y2, ... ]
  20446. const holeIndices = []; // array of hole indices
  20447. const faces = []; // final array of vertex indices like [ [ a,b,d ], [ b,c,d ] ]
  20448. removeDupEndPts(contour);
  20449. addContour(vertices, contour); //
  20450. let holeIndex = contour.length;
  20451. holes.forEach(removeDupEndPts);
  20452. for (let i = 0; i < holes.length; i++) {
  20453. holeIndices.push(holeIndex);
  20454. holeIndex += holes[i].length;
  20455. addContour(vertices, holes[i]);
  20456. } //
  20457. const triangles = Earcut.triangulate(vertices, holeIndices); //
  20458. for (let i = 0; i < triangles.length; i += 3) {
  20459. faces.push(triangles.slice(i, i + 3));
  20460. }
  20461. return faces;
  20462. }
  20463. }
  20464. function removeDupEndPts(points) {
  20465. const l = points.length;
  20466. if (l > 2 && points[l - 1].equals(points[0])) {
  20467. points.pop();
  20468. }
  20469. }
  20470. function addContour(vertices, contour) {
  20471. for (let i = 0; i < contour.length; i++) {
  20472. vertices.push(contour[i].x);
  20473. vertices.push(contour[i].y);
  20474. }
  20475. }
  20476. /**
  20477. * Creates extruded geometry from a path shape.
  20478. *
  20479. * parameters = {
  20480. *
  20481. * curveSegments: <int>, // number of points on the curves
  20482. * steps: <int>, // number of points for z-side extrusions / used for subdividing segments of extrude spline too
  20483. * depth: <float>, // Depth to extrude the shape
  20484. *
  20485. * bevelEnabled: <bool>, // turn on bevel
  20486. * bevelThickness: <float>, // how deep into the original shape bevel goes
  20487. * bevelSize: <float>, // how far from shape outline (including bevelOffset) is bevel
  20488. * bevelOffset: <float>, // how far from shape outline does bevel start
  20489. * bevelSegments: <int>, // number of bevel layers
  20490. *
  20491. * extrudePath: <THREE.Curve> // curve to extrude shape along
  20492. *
  20493. * UVGenerator: <Object> // object that provides UV generator functions
  20494. *
  20495. * }
  20496. */
  20497. class ExtrudeGeometry extends BufferGeometry {
  20498. constructor(shapes = new Shape([new Vector2(0.5, 0.5), new Vector2(-0.5, 0.5), new Vector2(-0.5, -0.5), new Vector2(0.5, -0.5)]), options = {}) {
  20499. super();
  20500. this.type = 'ExtrudeGeometry';
  20501. this.parameters = {
  20502. shapes: shapes,
  20503. options: options
  20504. };
  20505. shapes = Array.isArray(shapes) ? shapes : [shapes];
  20506. const scope = this;
  20507. const verticesArray = [];
  20508. const uvArray = [];
  20509. for (let i = 0, l = shapes.length; i < l; i++) {
  20510. const shape = shapes[i];
  20511. addShape(shape);
  20512. } // build geometry
  20513. this.setAttribute('position', new Float32BufferAttribute(verticesArray, 3));
  20514. this.setAttribute('uv', new Float32BufferAttribute(uvArray, 2));
  20515. this.computeVertexNormals(); // functions
  20516. function addShape(shape) {
  20517. const placeholder = []; // options
  20518. const curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  20519. const steps = options.steps !== undefined ? options.steps : 1;
  20520. const depth = options.depth !== undefined ? options.depth : 1;
  20521. let bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true;
  20522. let bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 0.2;
  20523. let bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 0.1;
  20524. let bevelOffset = options.bevelOffset !== undefined ? options.bevelOffset : 0;
  20525. let bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  20526. const extrudePath = options.extrudePath;
  20527. const uvgen = options.UVGenerator !== undefined ? options.UVGenerator : WorldUVGenerator; //
  20528. let extrudePts,
  20529. extrudeByPath = false;
  20530. let splineTube, binormal, normal, position2;
  20531. if (extrudePath) {
  20532. extrudePts = extrudePath.getSpacedPoints(steps);
  20533. extrudeByPath = true;
  20534. bevelEnabled = false; // bevels not supported for path extrusion
  20535. // SETUP TNB variables
  20536. // TODO1 - have a .isClosed in spline?
  20537. splineTube = extrudePath.computeFrenetFrames(steps, false); // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  20538. binormal = new Vector3();
  20539. normal = new Vector3();
  20540. position2 = new Vector3();
  20541. } // Safeguards if bevels are not enabled
  20542. if (!bevelEnabled) {
  20543. bevelSegments = 0;
  20544. bevelThickness = 0;
  20545. bevelSize = 0;
  20546. bevelOffset = 0;
  20547. } // Variables initialization
  20548. const shapePoints = shape.extractPoints(curveSegments);
  20549. let vertices = shapePoints.shape;
  20550. const holes = shapePoints.holes;
  20551. const reverse = !ShapeUtils.isClockWise(vertices);
  20552. if (reverse) {
  20553. vertices = vertices.reverse(); // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  20554. for (let h = 0, hl = holes.length; h < hl; h++) {
  20555. const ahole = holes[h];
  20556. if (ShapeUtils.isClockWise(ahole)) {
  20557. holes[h] = ahole.reverse();
  20558. }
  20559. }
  20560. }
  20561. const faces = ShapeUtils.triangulateShape(vertices, holes);
  20562. /* Vertices */
  20563. const contour = vertices; // vertices has all points but contour has only points of circumference
  20564. for (let h = 0, hl = holes.length; h < hl; h++) {
  20565. const ahole = holes[h];
  20566. vertices = vertices.concat(ahole);
  20567. }
  20568. function scalePt2(pt, vec, size) {
  20569. if (!vec) console.error('THREE.ExtrudeGeometry: vec does not exist');
  20570. return vec.clone().multiplyScalar(size).add(pt);
  20571. }
  20572. const vlen = vertices.length,
  20573. flen = faces.length; // Find directions for point movement
  20574. function getBevelVec(inPt, inPrev, inNext) {
  20575. // computes for inPt the corresponding point inPt' on a new contour
  20576. // shifted by 1 unit (length of normalized vector) to the left
  20577. // if we walk along contour clockwise, this new contour is outside the old one
  20578. //
  20579. // inPt' is the intersection of the two lines parallel to the two
  20580. // adjacent edges of inPt at a distance of 1 unit on the left side.
  20581. let v_trans_x, v_trans_y, shrink_by; // resulting translation vector for inPt
  20582. // good reading for geometry algorithms (here: line-line intersection)
  20583. // http://geomalgorithms.com/a05-_intersect-1.html
  20584. const v_prev_x = inPt.x - inPrev.x,
  20585. v_prev_y = inPt.y - inPrev.y;
  20586. const v_next_x = inNext.x - inPt.x,
  20587. v_next_y = inNext.y - inPt.y;
  20588. const v_prev_lensq = v_prev_x * v_prev_x + v_prev_y * v_prev_y; // check for collinear edges
  20589. const collinear0 = v_prev_x * v_next_y - v_prev_y * v_next_x;
  20590. if (Math.abs(collinear0) > Number.EPSILON) {
  20591. // not collinear
  20592. // length of vectors for normalizing
  20593. const v_prev_len = Math.sqrt(v_prev_lensq);
  20594. const v_next_len = Math.sqrt(v_next_x * v_next_x + v_next_y * v_next_y); // shift adjacent points by unit vectors to the left
  20595. const ptPrevShift_x = inPrev.x - v_prev_y / v_prev_len;
  20596. const ptPrevShift_y = inPrev.y + v_prev_x / v_prev_len;
  20597. const ptNextShift_x = inNext.x - v_next_y / v_next_len;
  20598. const ptNextShift_y = inNext.y + v_next_x / v_next_len; // scaling factor for v_prev to intersection point
  20599. const sf = ((ptNextShift_x - ptPrevShift_x) * v_next_y - (ptNextShift_y - ptPrevShift_y) * v_next_x) / (v_prev_x * v_next_y - v_prev_y * v_next_x); // vector from inPt to intersection point
  20600. v_trans_x = ptPrevShift_x + v_prev_x * sf - inPt.x;
  20601. v_trans_y = ptPrevShift_y + v_prev_y * sf - inPt.y; // Don't normalize!, otherwise sharp corners become ugly
  20602. // but prevent crazy spikes
  20603. const v_trans_lensq = v_trans_x * v_trans_x + v_trans_y * v_trans_y;
  20604. if (v_trans_lensq <= 2) {
  20605. return new Vector2(v_trans_x, v_trans_y);
  20606. } else {
  20607. shrink_by = Math.sqrt(v_trans_lensq / 2);
  20608. }
  20609. } else {
  20610. // handle special case of collinear edges
  20611. let direction_eq = false; // assumes: opposite
  20612. if (v_prev_x > Number.EPSILON) {
  20613. if (v_next_x > Number.EPSILON) {
  20614. direction_eq = true;
  20615. }
  20616. } else {
  20617. if (v_prev_x < -Number.EPSILON) {
  20618. if (v_next_x < -Number.EPSILON) {
  20619. direction_eq = true;
  20620. }
  20621. } else {
  20622. if (Math.sign(v_prev_y) === Math.sign(v_next_y)) {
  20623. direction_eq = true;
  20624. }
  20625. }
  20626. }
  20627. if (direction_eq) {
  20628. // console.log("Warning: lines are a straight sequence");
  20629. v_trans_x = -v_prev_y;
  20630. v_trans_y = v_prev_x;
  20631. shrink_by = Math.sqrt(v_prev_lensq);
  20632. } else {
  20633. // console.log("Warning: lines are a straight spike");
  20634. v_trans_x = v_prev_x;
  20635. v_trans_y = v_prev_y;
  20636. shrink_by = Math.sqrt(v_prev_lensq / 2);
  20637. }
  20638. }
  20639. return new Vector2(v_trans_x / shrink_by, v_trans_y / shrink_by);
  20640. }
  20641. const contourMovements = [];
  20642. for (let i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i++, j++, k++) {
  20643. if (j === il) j = 0;
  20644. if (k === il) k = 0; // (j)---(i)---(k)
  20645. // console.log('i,j,k', i, j , k)
  20646. contourMovements[i] = getBevelVec(contour[i], contour[j], contour[k]);
  20647. }
  20648. const holesMovements = [];
  20649. let oneHoleMovements,
  20650. verticesMovements = contourMovements.concat();
  20651. for (let h = 0, hl = holes.length; h < hl; h++) {
  20652. const ahole = holes[h];
  20653. oneHoleMovements = [];
  20654. for (let i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i++, j++, k++) {
  20655. if (j === il) j = 0;
  20656. if (k === il) k = 0; // (j)---(i)---(k)
  20657. oneHoleMovements[i] = getBevelVec(ahole[i], ahole[j], ahole[k]);
  20658. }
  20659. holesMovements.push(oneHoleMovements);
  20660. verticesMovements = verticesMovements.concat(oneHoleMovements);
  20661. } // Loop bevelSegments, 1 for the front, 1 for the back
  20662. for (let b = 0; b < bevelSegments; b++) {
  20663. //for ( b = bevelSegments; b > 0; b -- ) {
  20664. const t = b / bevelSegments;
  20665. const z = bevelThickness * Math.cos(t * Math.PI / 2);
  20666. const bs = bevelSize * Math.sin(t * Math.PI / 2) + bevelOffset; // contract shape
  20667. for (let i = 0, il = contour.length; i < il; i++) {
  20668. const vert = scalePt2(contour[i], contourMovements[i], bs);
  20669. v(vert.x, vert.y, -z);
  20670. } // expand holes
  20671. for (let h = 0, hl = holes.length; h < hl; h++) {
  20672. const ahole = holes[h];
  20673. oneHoleMovements = holesMovements[h];
  20674. for (let i = 0, il = ahole.length; i < il; i++) {
  20675. const vert = scalePt2(ahole[i], oneHoleMovements[i], bs);
  20676. v(vert.x, vert.y, -z);
  20677. }
  20678. }
  20679. }
  20680. const bs = bevelSize + bevelOffset; // Back facing vertices
  20681. for (let i = 0; i < vlen; i++) {
  20682. const vert = bevelEnabled ? scalePt2(vertices[i], verticesMovements[i], bs) : vertices[i];
  20683. if (!extrudeByPath) {
  20684. v(vert.x, vert.y, 0);
  20685. } else {
  20686. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  20687. normal.copy(splineTube.normals[0]).multiplyScalar(vert.x);
  20688. binormal.copy(splineTube.binormals[0]).multiplyScalar(vert.y);
  20689. position2.copy(extrudePts[0]).add(normal).add(binormal);
  20690. v(position2.x, position2.y, position2.z);
  20691. }
  20692. } // Add stepped vertices...
  20693. // Including front facing vertices
  20694. for (let s = 1; s <= steps; s++) {
  20695. for (let i = 0; i < vlen; i++) {
  20696. const vert = bevelEnabled ? scalePt2(vertices[i], verticesMovements[i], bs) : vertices[i];
  20697. if (!extrudeByPath) {
  20698. v(vert.x, vert.y, depth / steps * s);
  20699. } else {
  20700. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  20701. normal.copy(splineTube.normals[s]).multiplyScalar(vert.x);
  20702. binormal.copy(splineTube.binormals[s]).multiplyScalar(vert.y);
  20703. position2.copy(extrudePts[s]).add(normal).add(binormal);
  20704. v(position2.x, position2.y, position2.z);
  20705. }
  20706. }
  20707. } // Add bevel segments planes
  20708. //for ( b = 1; b <= bevelSegments; b ++ ) {
  20709. for (let b = bevelSegments - 1; b >= 0; b--) {
  20710. const t = b / bevelSegments;
  20711. const z = bevelThickness * Math.cos(t * Math.PI / 2);
  20712. const bs = bevelSize * Math.sin(t * Math.PI / 2) + bevelOffset; // contract shape
  20713. for (let i = 0, il = contour.length; i < il; i++) {
  20714. const vert = scalePt2(contour[i], contourMovements[i], bs);
  20715. v(vert.x, vert.y, depth + z);
  20716. } // expand holes
  20717. for (let h = 0, hl = holes.length; h < hl; h++) {
  20718. const ahole = holes[h];
  20719. oneHoleMovements = holesMovements[h];
  20720. for (let i = 0, il = ahole.length; i < il; i++) {
  20721. const vert = scalePt2(ahole[i], oneHoleMovements[i], bs);
  20722. if (!extrudeByPath) {
  20723. v(vert.x, vert.y, depth + z);
  20724. } else {
  20725. v(vert.x, vert.y + extrudePts[steps - 1].y, extrudePts[steps - 1].x + z);
  20726. }
  20727. }
  20728. }
  20729. }
  20730. /* Faces */
  20731. // Top and bottom faces
  20732. buildLidFaces(); // Sides faces
  20733. buildSideFaces(); ///// Internal functions
  20734. function buildLidFaces() {
  20735. const start = verticesArray.length / 3;
  20736. if (bevelEnabled) {
  20737. let layer = 0; // steps + 1
  20738. let offset = vlen * layer; // Bottom faces
  20739. for (let i = 0; i < flen; i++) {
  20740. const face = faces[i];
  20741. f3(face[2] + offset, face[1] + offset, face[0] + offset);
  20742. }
  20743. layer = steps + bevelSegments * 2;
  20744. offset = vlen * layer; // Top faces
  20745. for (let i = 0; i < flen; i++) {
  20746. const face = faces[i];
  20747. f3(face[0] + offset, face[1] + offset, face[2] + offset);
  20748. }
  20749. } else {
  20750. // Bottom faces
  20751. for (let i = 0; i < flen; i++) {
  20752. const face = faces[i];
  20753. f3(face[2], face[1], face[0]);
  20754. } // Top faces
  20755. for (let i = 0; i < flen; i++) {
  20756. const face = faces[i];
  20757. f3(face[0] + vlen * steps, face[1] + vlen * steps, face[2] + vlen * steps);
  20758. }
  20759. }
  20760. scope.addGroup(start, verticesArray.length / 3 - start, 0);
  20761. } // Create faces for the z-sides of the shape
  20762. function buildSideFaces() {
  20763. const start = verticesArray.length / 3;
  20764. let layeroffset = 0;
  20765. sidewalls(contour, layeroffset);
  20766. layeroffset += contour.length;
  20767. for (let h = 0, hl = holes.length; h < hl; h++) {
  20768. const ahole = holes[h];
  20769. sidewalls(ahole, layeroffset); //, true
  20770. layeroffset += ahole.length;
  20771. }
  20772. scope.addGroup(start, verticesArray.length / 3 - start, 1);
  20773. }
  20774. function sidewalls(contour, layeroffset) {
  20775. let i = contour.length;
  20776. while (--i >= 0) {
  20777. const j = i;
  20778. let k = i - 1;
  20779. if (k < 0) k = contour.length - 1; //console.log('b', i,j, i-1, k,vertices.length);
  20780. for (let s = 0, sl = steps + bevelSegments * 2; s < sl; s++) {
  20781. const slen1 = vlen * s;
  20782. const slen2 = vlen * (s + 1);
  20783. const a = layeroffset + j + slen1,
  20784. b = layeroffset + k + slen1,
  20785. c = layeroffset + k + slen2,
  20786. d = layeroffset + j + slen2;
  20787. f4(a, b, c, d);
  20788. }
  20789. }
  20790. }
  20791. function v(x, y, z) {
  20792. placeholder.push(x);
  20793. placeholder.push(y);
  20794. placeholder.push(z);
  20795. }
  20796. function f3(a, b, c) {
  20797. addVertex(a);
  20798. addVertex(b);
  20799. addVertex(c);
  20800. const nextIndex = verticesArray.length / 3;
  20801. const uvs = uvgen.generateTopUV(scope, verticesArray, nextIndex - 3, nextIndex - 2, nextIndex - 1);
  20802. addUV(uvs[0]);
  20803. addUV(uvs[1]);
  20804. addUV(uvs[2]);
  20805. }
  20806. function f4(a, b, c, d) {
  20807. addVertex(a);
  20808. addVertex(b);
  20809. addVertex(d);
  20810. addVertex(b);
  20811. addVertex(c);
  20812. addVertex(d);
  20813. const nextIndex = verticesArray.length / 3;
  20814. const uvs = uvgen.generateSideWallUV(scope, verticesArray, nextIndex - 6, nextIndex - 3, nextIndex - 2, nextIndex - 1);
  20815. addUV(uvs[0]);
  20816. addUV(uvs[1]);
  20817. addUV(uvs[3]);
  20818. addUV(uvs[1]);
  20819. addUV(uvs[2]);
  20820. addUV(uvs[3]);
  20821. }
  20822. function addVertex(index) {
  20823. verticesArray.push(placeholder[index * 3 + 0]);
  20824. verticesArray.push(placeholder[index * 3 + 1]);
  20825. verticesArray.push(placeholder[index * 3 + 2]);
  20826. }
  20827. function addUV(vector2) {
  20828. uvArray.push(vector2.x);
  20829. uvArray.push(vector2.y);
  20830. }
  20831. }
  20832. }
  20833. toJSON() {
  20834. const data = super.toJSON();
  20835. const shapes = this.parameters.shapes;
  20836. const options = this.parameters.options;
  20837. return toJSON$1(shapes, options, data);
  20838. }
  20839. static fromJSON(data, shapes) {
  20840. const geometryShapes = [];
  20841. for (let j = 0, jl = data.shapes.length; j < jl; j++) {
  20842. const shape = shapes[data.shapes[j]];
  20843. geometryShapes.push(shape);
  20844. }
  20845. const extrudePath = data.options.extrudePath;
  20846. if (extrudePath !== undefined) {
  20847. data.options.extrudePath = new Curves[extrudePath.type]().fromJSON(extrudePath);
  20848. }
  20849. return new ExtrudeGeometry(geometryShapes, data.options);
  20850. }
  20851. }
  20852. const WorldUVGenerator = {
  20853. generateTopUV: function (geometry, vertices, indexA, indexB, indexC) {
  20854. const a_x = vertices[indexA * 3];
  20855. const a_y = vertices[indexA * 3 + 1];
  20856. const b_x = vertices[indexB * 3];
  20857. const b_y = vertices[indexB * 3 + 1];
  20858. const c_x = vertices[indexC * 3];
  20859. const c_y = vertices[indexC * 3 + 1];
  20860. return [new Vector2(a_x, a_y), new Vector2(b_x, b_y), new Vector2(c_x, c_y)];
  20861. },
  20862. generateSideWallUV: function (geometry, vertices, indexA, indexB, indexC, indexD) {
  20863. const a_x = vertices[indexA * 3];
  20864. const a_y = vertices[indexA * 3 + 1];
  20865. const a_z = vertices[indexA * 3 + 2];
  20866. const b_x = vertices[indexB * 3];
  20867. const b_y = vertices[indexB * 3 + 1];
  20868. const b_z = vertices[indexB * 3 + 2];
  20869. const c_x = vertices[indexC * 3];
  20870. const c_y = vertices[indexC * 3 + 1];
  20871. const c_z = vertices[indexC * 3 + 2];
  20872. const d_x = vertices[indexD * 3];
  20873. const d_y = vertices[indexD * 3 + 1];
  20874. const d_z = vertices[indexD * 3 + 2];
  20875. if (Math.abs(a_y - b_y) < Math.abs(a_x - b_x)) {
  20876. 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)];
  20877. } else {
  20878. 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)];
  20879. }
  20880. }
  20881. };
  20882. function toJSON$1(shapes, options, data) {
  20883. data.shapes = [];
  20884. if (Array.isArray(shapes)) {
  20885. for (let i = 0, l = shapes.length; i < l; i++) {
  20886. const shape = shapes[i];
  20887. data.shapes.push(shape.uuid);
  20888. }
  20889. } else {
  20890. data.shapes.push(shapes.uuid);
  20891. }
  20892. data.options = Object.assign({}, options);
  20893. if (options.extrudePath !== undefined) data.options.extrudePath = options.extrudePath.toJSON();
  20894. return data;
  20895. }
  20896. class IcosahedronGeometry extends PolyhedronGeometry {
  20897. constructor(radius = 1, detail = 0) {
  20898. const t = (1 + Math.sqrt(5)) / 2;
  20899. const vertices = [-1, t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, 0, -1, t, 0, 1, t, 0, -1, -t, 0, 1, -t, t, 0, -1, t, 0, 1, -t, 0, -1, -t, 0, 1];
  20900. const indices = [0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 0, 10, 11, 1, 5, 9, 5, 11, 4, 11, 10, 2, 10, 7, 6, 7, 1, 8, 3, 9, 4, 3, 4, 2, 3, 2, 6, 3, 6, 8, 3, 8, 9, 4, 9, 5, 2, 4, 11, 6, 2, 10, 8, 6, 7, 9, 8, 1];
  20901. super(vertices, indices, radius, detail);
  20902. this.type = 'IcosahedronGeometry';
  20903. this.parameters = {
  20904. radius: radius,
  20905. detail: detail
  20906. };
  20907. }
  20908. static fromJSON(data) {
  20909. return new IcosahedronGeometry(data.radius, data.detail);
  20910. }
  20911. }
  20912. class OctahedronGeometry extends PolyhedronGeometry {
  20913. constructor(radius = 1, detail = 0) {
  20914. const vertices = [1, 0, 0, -1, 0, 0, 0, 1, 0, 0, -1, 0, 0, 0, 1, 0, 0, -1];
  20915. const indices = [0, 2, 4, 0, 4, 3, 0, 3, 5, 0, 5, 2, 1, 2, 5, 1, 5, 3, 1, 3, 4, 1, 4, 2];
  20916. super(vertices, indices, radius, detail);
  20917. this.type = 'OctahedronGeometry';
  20918. this.parameters = {
  20919. radius: radius,
  20920. detail: detail
  20921. };
  20922. }
  20923. static fromJSON(data) {
  20924. return new OctahedronGeometry(data.radius, data.detail);
  20925. }
  20926. }
  20927. class RingGeometry extends BufferGeometry {
  20928. constructor(innerRadius = 0.5, outerRadius = 1, thetaSegments = 8, phiSegments = 1, thetaStart = 0, thetaLength = Math.PI * 2) {
  20929. super();
  20930. this.type = 'RingGeometry';
  20931. this.parameters = {
  20932. innerRadius: innerRadius,
  20933. outerRadius: outerRadius,
  20934. thetaSegments: thetaSegments,
  20935. phiSegments: phiSegments,
  20936. thetaStart: thetaStart,
  20937. thetaLength: thetaLength
  20938. };
  20939. thetaSegments = Math.max(3, thetaSegments);
  20940. phiSegments = Math.max(1, phiSegments); // buffers
  20941. const indices = [];
  20942. const vertices = [];
  20943. const normals = [];
  20944. const uvs = []; // some helper variables
  20945. let radius = innerRadius;
  20946. const radiusStep = (outerRadius - innerRadius) / phiSegments;
  20947. const vertex = new Vector3();
  20948. const uv = new Vector2(); // generate vertices, normals and uvs
  20949. for (let j = 0; j <= phiSegments; j++) {
  20950. for (let i = 0; i <= thetaSegments; i++) {
  20951. // values are generate from the inside of the ring to the outside
  20952. const segment = thetaStart + i / thetaSegments * thetaLength; // vertex
  20953. vertex.x = radius * Math.cos(segment);
  20954. vertex.y = radius * Math.sin(segment);
  20955. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  20956. normals.push(0, 0, 1); // uv
  20957. uv.x = (vertex.x / outerRadius + 1) / 2;
  20958. uv.y = (vertex.y / outerRadius + 1) / 2;
  20959. uvs.push(uv.x, uv.y);
  20960. } // increase the radius for next row of vertices
  20961. radius += radiusStep;
  20962. } // indices
  20963. for (let j = 0; j < phiSegments; j++) {
  20964. const thetaSegmentLevel = j * (thetaSegments + 1);
  20965. for (let i = 0; i < thetaSegments; i++) {
  20966. const segment = i + thetaSegmentLevel;
  20967. const a = segment;
  20968. const b = segment + thetaSegments + 1;
  20969. const c = segment + thetaSegments + 2;
  20970. const d = segment + 1; // faces
  20971. indices.push(a, b, d);
  20972. indices.push(b, c, d);
  20973. }
  20974. } // build geometry
  20975. this.setIndex(indices);
  20976. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  20977. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  20978. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  20979. }
  20980. static fromJSON(data) {
  20981. return new RingGeometry(data.innerRadius, data.outerRadius, data.thetaSegments, data.phiSegments, data.thetaStart, data.thetaLength);
  20982. }
  20983. }
  20984. class ShapeGeometry extends BufferGeometry {
  20985. constructor(shapes = new Shape([new Vector2(0, 0.5), new Vector2(-0.5, -0.5), new Vector2(0.5, -0.5)]), curveSegments = 12) {
  20986. super();
  20987. this.type = 'ShapeGeometry';
  20988. this.parameters = {
  20989. shapes: shapes,
  20990. curveSegments: curveSegments
  20991. }; // buffers
  20992. const indices = [];
  20993. const vertices = [];
  20994. const normals = [];
  20995. const uvs = []; // helper variables
  20996. let groupStart = 0;
  20997. let groupCount = 0; // allow single and array values for "shapes" parameter
  20998. if (Array.isArray(shapes) === false) {
  20999. addShape(shapes);
  21000. } else {
  21001. for (let i = 0; i < shapes.length; i++) {
  21002. addShape(shapes[i]);
  21003. this.addGroup(groupStart, groupCount, i); // enables MultiMaterial support
  21004. groupStart += groupCount;
  21005. groupCount = 0;
  21006. }
  21007. } // build geometry
  21008. this.setIndex(indices);
  21009. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  21010. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  21011. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2)); // helper functions
  21012. function addShape(shape) {
  21013. const indexOffset = vertices.length / 3;
  21014. const points = shape.extractPoints(curveSegments);
  21015. let shapeVertices = points.shape;
  21016. const shapeHoles = points.holes; // check direction of vertices
  21017. if (ShapeUtils.isClockWise(shapeVertices) === false) {
  21018. shapeVertices = shapeVertices.reverse();
  21019. }
  21020. for (let i = 0, l = shapeHoles.length; i < l; i++) {
  21021. const shapeHole = shapeHoles[i];
  21022. if (ShapeUtils.isClockWise(shapeHole) === true) {
  21023. shapeHoles[i] = shapeHole.reverse();
  21024. }
  21025. }
  21026. const faces = ShapeUtils.triangulateShape(shapeVertices, shapeHoles); // join vertices of inner and outer paths to a single array
  21027. for (let i = 0, l = shapeHoles.length; i < l; i++) {
  21028. const shapeHole = shapeHoles[i];
  21029. shapeVertices = shapeVertices.concat(shapeHole);
  21030. } // vertices, normals, uvs
  21031. for (let i = 0, l = shapeVertices.length; i < l; i++) {
  21032. const vertex = shapeVertices[i];
  21033. vertices.push(vertex.x, vertex.y, 0);
  21034. normals.push(0, 0, 1);
  21035. uvs.push(vertex.x, vertex.y); // world uvs
  21036. } // incides
  21037. for (let i = 0, l = faces.length; i < l; i++) {
  21038. const face = faces[i];
  21039. const a = face[0] + indexOffset;
  21040. const b = face[1] + indexOffset;
  21041. const c = face[2] + indexOffset;
  21042. indices.push(a, b, c);
  21043. groupCount += 3;
  21044. }
  21045. }
  21046. }
  21047. toJSON() {
  21048. const data = super.toJSON();
  21049. const shapes = this.parameters.shapes;
  21050. return toJSON(shapes, data);
  21051. }
  21052. static fromJSON(data, shapes) {
  21053. const geometryShapes = [];
  21054. for (let j = 0, jl = data.shapes.length; j < jl; j++) {
  21055. const shape = shapes[data.shapes[j]];
  21056. geometryShapes.push(shape);
  21057. }
  21058. return new ShapeGeometry(geometryShapes, data.curveSegments);
  21059. }
  21060. }
  21061. function toJSON(shapes, data) {
  21062. data.shapes = [];
  21063. if (Array.isArray(shapes)) {
  21064. for (let i = 0, l = shapes.length; i < l; i++) {
  21065. const shape = shapes[i];
  21066. data.shapes.push(shape.uuid);
  21067. }
  21068. } else {
  21069. data.shapes.push(shapes.uuid);
  21070. }
  21071. return data;
  21072. }
  21073. class SphereGeometry extends BufferGeometry {
  21074. constructor(radius = 1, widthSegments = 32, heightSegments = 16, phiStart = 0, phiLength = Math.PI * 2, thetaStart = 0, thetaLength = Math.PI) {
  21075. super();
  21076. this.type = 'SphereGeometry';
  21077. this.parameters = {
  21078. radius: radius,
  21079. widthSegments: widthSegments,
  21080. heightSegments: heightSegments,
  21081. phiStart: phiStart,
  21082. phiLength: phiLength,
  21083. thetaStart: thetaStart,
  21084. thetaLength: thetaLength
  21085. };
  21086. widthSegments = Math.max(3, Math.floor(widthSegments));
  21087. heightSegments = Math.max(2, Math.floor(heightSegments));
  21088. const thetaEnd = Math.min(thetaStart + thetaLength, Math.PI);
  21089. let index = 0;
  21090. const grid = [];
  21091. const vertex = new Vector3();
  21092. const normal = new Vector3(); // buffers
  21093. const indices = [];
  21094. const vertices = [];
  21095. const normals = [];
  21096. const uvs = []; // generate vertices, normals and uvs
  21097. for (let iy = 0; iy <= heightSegments; iy++) {
  21098. const verticesRow = [];
  21099. const v = iy / heightSegments; // special case for the poles
  21100. let uOffset = 0;
  21101. if (iy == 0 && thetaStart == 0) {
  21102. uOffset = 0.5 / widthSegments;
  21103. } else if (iy == heightSegments && thetaEnd == Math.PI) {
  21104. uOffset = -0.5 / widthSegments;
  21105. }
  21106. for (let ix = 0; ix <= widthSegments; ix++) {
  21107. const u = ix / widthSegments; // vertex
  21108. vertex.x = -radius * Math.cos(phiStart + u * phiLength) * Math.sin(thetaStart + v * thetaLength);
  21109. vertex.y = radius * Math.cos(thetaStart + v * thetaLength);
  21110. vertex.z = radius * Math.sin(phiStart + u * phiLength) * Math.sin(thetaStart + v * thetaLength);
  21111. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  21112. normal.copy(vertex).normalize();
  21113. normals.push(normal.x, normal.y, normal.z); // uv
  21114. uvs.push(u + uOffset, 1 - v);
  21115. verticesRow.push(index++);
  21116. }
  21117. grid.push(verticesRow);
  21118. } // indices
  21119. for (let iy = 0; iy < heightSegments; iy++) {
  21120. for (let ix = 0; ix < widthSegments; ix++) {
  21121. const a = grid[iy][ix + 1];
  21122. const b = grid[iy][ix];
  21123. const c = grid[iy + 1][ix];
  21124. const d = grid[iy + 1][ix + 1];
  21125. if (iy !== 0 || thetaStart > 0) indices.push(a, b, d);
  21126. if (iy !== heightSegments - 1 || thetaEnd < Math.PI) indices.push(b, c, d);
  21127. }
  21128. } // build geometry
  21129. this.setIndex(indices);
  21130. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  21131. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  21132. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  21133. }
  21134. static fromJSON(data) {
  21135. return new SphereGeometry(data.radius, data.widthSegments, data.heightSegments, data.phiStart, data.phiLength, data.thetaStart, data.thetaLength);
  21136. }
  21137. }
  21138. class TetrahedronGeometry extends PolyhedronGeometry {
  21139. constructor(radius = 1, detail = 0) {
  21140. const vertices = [1, 1, 1, -1, -1, 1, -1, 1, -1, 1, -1, -1];
  21141. const indices = [2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1];
  21142. super(vertices, indices, radius, detail);
  21143. this.type = 'TetrahedronGeometry';
  21144. this.parameters = {
  21145. radius: radius,
  21146. detail: detail
  21147. };
  21148. }
  21149. static fromJSON(data) {
  21150. return new TetrahedronGeometry(data.radius, data.detail);
  21151. }
  21152. }
  21153. class TorusGeometry extends BufferGeometry {
  21154. constructor(radius = 1, tube = 0.4, radialSegments = 8, tubularSegments = 6, arc = Math.PI * 2) {
  21155. super();
  21156. this.type = 'TorusGeometry';
  21157. this.parameters = {
  21158. radius: radius,
  21159. tube: tube,
  21160. radialSegments: radialSegments,
  21161. tubularSegments: tubularSegments,
  21162. arc: arc
  21163. };
  21164. radialSegments = Math.floor(radialSegments);
  21165. tubularSegments = Math.floor(tubularSegments); // buffers
  21166. const indices = [];
  21167. const vertices = [];
  21168. const normals = [];
  21169. const uvs = []; // helper variables
  21170. const center = new Vector3();
  21171. const vertex = new Vector3();
  21172. const normal = new Vector3(); // generate vertices, normals and uvs
  21173. for (let j = 0; j <= radialSegments; j++) {
  21174. for (let i = 0; i <= tubularSegments; i++) {
  21175. const u = i / tubularSegments * arc;
  21176. const v = j / radialSegments * Math.PI * 2; // vertex
  21177. vertex.x = (radius + tube * Math.cos(v)) * Math.cos(u);
  21178. vertex.y = (radius + tube * Math.cos(v)) * Math.sin(u);
  21179. vertex.z = tube * Math.sin(v);
  21180. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  21181. center.x = radius * Math.cos(u);
  21182. center.y = radius * Math.sin(u);
  21183. normal.subVectors(vertex, center).normalize();
  21184. normals.push(normal.x, normal.y, normal.z); // uv
  21185. uvs.push(i / tubularSegments);
  21186. uvs.push(j / radialSegments);
  21187. }
  21188. } // generate indices
  21189. for (let j = 1; j <= radialSegments; j++) {
  21190. for (let i = 1; i <= tubularSegments; i++) {
  21191. // indices
  21192. const a = (tubularSegments + 1) * j + i - 1;
  21193. const b = (tubularSegments + 1) * (j - 1) + i - 1;
  21194. const c = (tubularSegments + 1) * (j - 1) + i;
  21195. const d = (tubularSegments + 1) * j + i; // faces
  21196. indices.push(a, b, d);
  21197. indices.push(b, c, d);
  21198. }
  21199. } // build geometry
  21200. this.setIndex(indices);
  21201. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  21202. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  21203. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  21204. }
  21205. static fromJSON(data) {
  21206. return new TorusGeometry(data.radius, data.tube, data.radialSegments, data.tubularSegments, data.arc);
  21207. }
  21208. }
  21209. class TorusKnotGeometry extends BufferGeometry {
  21210. constructor(radius = 1, tube = 0.4, tubularSegments = 64, radialSegments = 8, p = 2, q = 3) {
  21211. super();
  21212. this.type = 'TorusKnotGeometry';
  21213. this.parameters = {
  21214. radius: radius,
  21215. tube: tube,
  21216. tubularSegments: tubularSegments,
  21217. radialSegments: radialSegments,
  21218. p: p,
  21219. q: q
  21220. };
  21221. tubularSegments = Math.floor(tubularSegments);
  21222. radialSegments = Math.floor(radialSegments); // buffers
  21223. const indices = [];
  21224. const vertices = [];
  21225. const normals = [];
  21226. const uvs = []; // helper variables
  21227. const vertex = new Vector3();
  21228. const normal = new Vector3();
  21229. const P1 = new Vector3();
  21230. const P2 = new Vector3();
  21231. const B = new Vector3();
  21232. const T = new Vector3();
  21233. const N = new Vector3(); // generate vertices, normals and uvs
  21234. for (let i = 0; i <= tubularSegments; ++i) {
  21235. // the radian "u" is used to calculate the position on the torus curve of the current tubular segment
  21236. const u = i / tubularSegments * p * Math.PI * 2; // now we calculate two points. P1 is our current position on the curve, P2 is a little farther ahead.
  21237. // these points are used to create a special "coordinate space", which is necessary to calculate the correct vertex positions
  21238. calculatePositionOnCurve(u, p, q, radius, P1);
  21239. calculatePositionOnCurve(u + 0.01, p, q, radius, P2); // calculate orthonormal basis
  21240. T.subVectors(P2, P1);
  21241. N.addVectors(P2, P1);
  21242. B.crossVectors(T, N);
  21243. N.crossVectors(B, T); // normalize B, N. T can be ignored, we don't use it
  21244. B.normalize();
  21245. N.normalize();
  21246. for (let j = 0; j <= radialSegments; ++j) {
  21247. // now calculate the vertices. they are nothing more than an extrusion of the torus curve.
  21248. // because we extrude a shape in the xy-plane, there is no need to calculate a z-value.
  21249. const v = j / radialSegments * Math.PI * 2;
  21250. const cx = -tube * Math.cos(v);
  21251. const cy = tube * Math.sin(v); // now calculate the final vertex position.
  21252. // first we orient the extrusion with our basis vectors, then we add it to the current position on the curve
  21253. vertex.x = P1.x + (cx * N.x + cy * B.x);
  21254. vertex.y = P1.y + (cx * N.y + cy * B.y);
  21255. vertex.z = P1.z + (cx * N.z + cy * B.z);
  21256. 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)
  21257. normal.subVectors(vertex, P1).normalize();
  21258. normals.push(normal.x, normal.y, normal.z); // uv
  21259. uvs.push(i / tubularSegments);
  21260. uvs.push(j / radialSegments);
  21261. }
  21262. } // generate indices
  21263. for (let j = 1; j <= tubularSegments; j++) {
  21264. for (let i = 1; i <= radialSegments; i++) {
  21265. // indices
  21266. const a = (radialSegments + 1) * (j - 1) + (i - 1);
  21267. const b = (radialSegments + 1) * j + (i - 1);
  21268. const c = (radialSegments + 1) * j + i;
  21269. const d = (radialSegments + 1) * (j - 1) + i; // faces
  21270. indices.push(a, b, d);
  21271. indices.push(b, c, d);
  21272. }
  21273. } // build geometry
  21274. this.setIndex(indices);
  21275. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  21276. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  21277. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2)); // this function calculates the current position on the torus curve
  21278. function calculatePositionOnCurve(u, p, q, radius, position) {
  21279. const cu = Math.cos(u);
  21280. const su = Math.sin(u);
  21281. const quOverP = q / p * u;
  21282. const cs = Math.cos(quOverP);
  21283. position.x = radius * (2 + cs) * 0.5 * cu;
  21284. position.y = radius * (2 + cs) * su * 0.5;
  21285. position.z = radius * Math.sin(quOverP) * 0.5;
  21286. }
  21287. }
  21288. static fromJSON(data) {
  21289. return new TorusKnotGeometry(data.radius, data.tube, data.tubularSegments, data.radialSegments, data.p, data.q);
  21290. }
  21291. }
  21292. class TubeGeometry extends BufferGeometry {
  21293. constructor(path = new QuadraticBezierCurve3(new Vector3(-1, -1, 0), new Vector3(-1, 1, 0), new Vector3(1, 1, 0)), tubularSegments = 64, radius = 1, radialSegments = 8, closed = false) {
  21294. super();
  21295. this.type = 'TubeGeometry';
  21296. this.parameters = {
  21297. path: path,
  21298. tubularSegments: tubularSegments,
  21299. radius: radius,
  21300. radialSegments: radialSegments,
  21301. closed: closed
  21302. };
  21303. const frames = path.computeFrenetFrames(tubularSegments, closed); // expose internals
  21304. this.tangents = frames.tangents;
  21305. this.normals = frames.normals;
  21306. this.binormals = frames.binormals; // helper variables
  21307. const vertex = new Vector3();
  21308. const normal = new Vector3();
  21309. const uv = new Vector2();
  21310. let P = new Vector3(); // buffer
  21311. const vertices = [];
  21312. const normals = [];
  21313. const uvs = [];
  21314. const indices = []; // create buffer data
  21315. generateBufferData(); // build geometry
  21316. this.setIndex(indices);
  21317. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  21318. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  21319. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2)); // functions
  21320. function generateBufferData() {
  21321. for (let i = 0; i < tubularSegments; i++) {
  21322. generateSegment(i);
  21323. } // if the geometry is not closed, generate the last row of vertices and normals
  21324. // at the regular position on the given path
  21325. //
  21326. // if the geometry is closed, duplicate the first row of vertices and normals (uvs will differ)
  21327. generateSegment(closed === false ? tubularSegments : 0); // uvs are generated in a separate function.
  21328. // this makes it easy compute correct values for closed geometries
  21329. generateUVs(); // finally create faces
  21330. generateIndices();
  21331. }
  21332. function generateSegment(i) {
  21333. // we use getPointAt to sample evenly distributed points from the given path
  21334. P = path.getPointAt(i / tubularSegments, P); // retrieve corresponding normal and binormal
  21335. const N = frames.normals[i];
  21336. const B = frames.binormals[i]; // generate normals and vertices for the current segment
  21337. for (let j = 0; j <= radialSegments; j++) {
  21338. const v = j / radialSegments * Math.PI * 2;
  21339. const sin = Math.sin(v);
  21340. const cos = -Math.cos(v); // normal
  21341. normal.x = cos * N.x + sin * B.x;
  21342. normal.y = cos * N.y + sin * B.y;
  21343. normal.z = cos * N.z + sin * B.z;
  21344. normal.normalize();
  21345. normals.push(normal.x, normal.y, normal.z); // vertex
  21346. vertex.x = P.x + radius * normal.x;
  21347. vertex.y = P.y + radius * normal.y;
  21348. vertex.z = P.z + radius * normal.z;
  21349. vertices.push(vertex.x, vertex.y, vertex.z);
  21350. }
  21351. }
  21352. function generateIndices() {
  21353. for (let j = 1; j <= tubularSegments; j++) {
  21354. for (let i = 1; i <= radialSegments; i++) {
  21355. const a = (radialSegments + 1) * (j - 1) + (i - 1);
  21356. const b = (radialSegments + 1) * j + (i - 1);
  21357. const c = (radialSegments + 1) * j + i;
  21358. const d = (radialSegments + 1) * (j - 1) + i; // faces
  21359. indices.push(a, b, d);
  21360. indices.push(b, c, d);
  21361. }
  21362. }
  21363. }
  21364. function generateUVs() {
  21365. for (let i = 0; i <= tubularSegments; i++) {
  21366. for (let j = 0; j <= radialSegments; j++) {
  21367. uv.x = i / tubularSegments;
  21368. uv.y = j / radialSegments;
  21369. uvs.push(uv.x, uv.y);
  21370. }
  21371. }
  21372. }
  21373. }
  21374. toJSON() {
  21375. const data = super.toJSON();
  21376. data.path = this.parameters.path.toJSON();
  21377. return data;
  21378. }
  21379. static fromJSON(data) {
  21380. // This only works for built-in curves (e.g. CatmullRomCurve3).
  21381. // User defined curves or instances of CurvePath will not be deserialized.
  21382. return new TubeGeometry(new Curves[data.path.type]().fromJSON(data.path), data.tubularSegments, data.radius, data.radialSegments, data.closed);
  21383. }
  21384. }
  21385. class WireframeGeometry extends BufferGeometry {
  21386. constructor(geometry = null) {
  21387. super();
  21388. this.type = 'WireframeGeometry';
  21389. this.parameters = {
  21390. geometry: geometry
  21391. };
  21392. if (geometry !== null) {
  21393. // buffer
  21394. const vertices = [];
  21395. const edges = new Set(); // helper variables
  21396. const start = new Vector3();
  21397. const end = new Vector3();
  21398. if (geometry.index !== null) {
  21399. // indexed BufferGeometry
  21400. const position = geometry.attributes.position;
  21401. const indices = geometry.index;
  21402. let groups = geometry.groups;
  21403. if (groups.length === 0) {
  21404. groups = [{
  21405. start: 0,
  21406. count: indices.count,
  21407. materialIndex: 0
  21408. }];
  21409. } // create a data structure that contains all edges without duplicates
  21410. for (let o = 0, ol = groups.length; o < ol; ++o) {
  21411. const group = groups[o];
  21412. const groupStart = group.start;
  21413. const groupCount = group.count;
  21414. for (let i = groupStart, l = groupStart + groupCount; i < l; i += 3) {
  21415. for (let j = 0; j < 3; j++) {
  21416. const index1 = indices.getX(i + j);
  21417. const index2 = indices.getX(i + (j + 1) % 3);
  21418. start.fromBufferAttribute(position, index1);
  21419. end.fromBufferAttribute(position, index2);
  21420. if (isUniqueEdge(start, end, edges) === true) {
  21421. vertices.push(start.x, start.y, start.z);
  21422. vertices.push(end.x, end.y, end.z);
  21423. }
  21424. }
  21425. }
  21426. }
  21427. } else {
  21428. // non-indexed BufferGeometry
  21429. const position = geometry.attributes.position;
  21430. for (let i = 0, l = position.count / 3; i < l; i++) {
  21431. for (let j = 0; j < 3; j++) {
  21432. // three edges per triangle, an edge is represented as (index1, index2)
  21433. // e.g. the first triangle has the following edges: (0,1),(1,2),(2,0)
  21434. const index1 = 3 * i + j;
  21435. const index2 = 3 * i + (j + 1) % 3;
  21436. start.fromBufferAttribute(position, index1);
  21437. end.fromBufferAttribute(position, index2);
  21438. if (isUniqueEdge(start, end, edges) === true) {
  21439. vertices.push(start.x, start.y, start.z);
  21440. vertices.push(end.x, end.y, end.z);
  21441. }
  21442. }
  21443. }
  21444. } // build geometry
  21445. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  21446. }
  21447. }
  21448. }
  21449. function isUniqueEdge(start, end, edges) {
  21450. const hash1 = `${start.x},${start.y},${start.z}-${end.x},${end.y},${end.z}`;
  21451. const hash2 = `${end.x},${end.y},${end.z}-${start.x},${start.y},${start.z}`; // coincident edge
  21452. if (edges.has(hash1) === true || edges.has(hash2) === true) {
  21453. return false;
  21454. } else {
  21455. edges.add(hash1);
  21456. edges.add(hash2);
  21457. return true;
  21458. }
  21459. }
  21460. var Geometries = /*#__PURE__*/Object.freeze({
  21461. __proto__: null,
  21462. BoxGeometry: BoxGeometry,
  21463. CapsuleGeometry: CapsuleGeometry,
  21464. CircleGeometry: CircleGeometry,
  21465. ConeGeometry: ConeGeometry,
  21466. CylinderGeometry: CylinderGeometry,
  21467. DodecahedronGeometry: DodecahedronGeometry,
  21468. EdgesGeometry: EdgesGeometry,
  21469. ExtrudeGeometry: ExtrudeGeometry,
  21470. IcosahedronGeometry: IcosahedronGeometry,
  21471. LatheGeometry: LatheGeometry,
  21472. OctahedronGeometry: OctahedronGeometry,
  21473. PlaneGeometry: PlaneGeometry,
  21474. PolyhedronGeometry: PolyhedronGeometry,
  21475. RingGeometry: RingGeometry,
  21476. ShapeGeometry: ShapeGeometry,
  21477. SphereGeometry: SphereGeometry,
  21478. TetrahedronGeometry: TetrahedronGeometry,
  21479. TorusGeometry: TorusGeometry,
  21480. TorusKnotGeometry: TorusKnotGeometry,
  21481. TubeGeometry: TubeGeometry,
  21482. WireframeGeometry: WireframeGeometry
  21483. });
  21484. class ShadowMaterial extends Material {
  21485. constructor(parameters) {
  21486. super();
  21487. this.isShadowMaterial = true;
  21488. this.type = 'ShadowMaterial';
  21489. this.color = new Color(0x000000);
  21490. this.transparent = true;
  21491. this.fog = true;
  21492. this.setValues(parameters);
  21493. }
  21494. copy(source) {
  21495. super.copy(source);
  21496. this.color.copy(source.color);
  21497. this.fog = source.fog;
  21498. return this;
  21499. }
  21500. }
  21501. class RawShaderMaterial extends ShaderMaterial {
  21502. constructor(parameters) {
  21503. super(parameters);
  21504. this.isRawShaderMaterial = true;
  21505. this.type = 'RawShaderMaterial';
  21506. }
  21507. }
  21508. class MeshStandardMaterial extends Material {
  21509. constructor(parameters) {
  21510. super();
  21511. this.isMeshStandardMaterial = true;
  21512. this.defines = {
  21513. 'STANDARD': ''
  21514. };
  21515. this.type = 'MeshStandardMaterial';
  21516. this.color = new Color(0xffffff); // diffuse
  21517. this.roughness = 1.0;
  21518. this.metalness = 0.0;
  21519. this.map = null;
  21520. this.lightMap = null;
  21521. this.lightMapIntensity = 1.0;
  21522. this.aoMap = null;
  21523. this.aoMapIntensity = 1.0;
  21524. this.emissive = new Color(0x000000);
  21525. this.emissiveIntensity = 1.0;
  21526. this.emissiveMap = null;
  21527. this.bumpMap = null;
  21528. this.bumpScale = 1;
  21529. this.normalMap = null;
  21530. this.normalMapType = TangentSpaceNormalMap;
  21531. this.normalScale = new Vector2(1, 1);
  21532. this.displacementMap = null;
  21533. this.displacementScale = 1;
  21534. this.displacementBias = 0;
  21535. this.roughnessMap = null;
  21536. this.metalnessMap = null;
  21537. this.alphaMap = null;
  21538. this.envMap = null;
  21539. this.envMapIntensity = 1.0;
  21540. this.wireframe = false;
  21541. this.wireframeLinewidth = 1;
  21542. this.wireframeLinecap = 'round';
  21543. this.wireframeLinejoin = 'round';
  21544. this.flatShading = false;
  21545. this.fog = true;
  21546. this.setValues(parameters);
  21547. }
  21548. copy(source) {
  21549. super.copy(source);
  21550. this.defines = {
  21551. 'STANDARD': ''
  21552. };
  21553. this.color.copy(source.color);
  21554. this.roughness = source.roughness;
  21555. this.metalness = source.metalness;
  21556. this.map = source.map;
  21557. this.lightMap = source.lightMap;
  21558. this.lightMapIntensity = source.lightMapIntensity;
  21559. this.aoMap = source.aoMap;
  21560. this.aoMapIntensity = source.aoMapIntensity;
  21561. this.emissive.copy(source.emissive);
  21562. this.emissiveMap = source.emissiveMap;
  21563. this.emissiveIntensity = source.emissiveIntensity;
  21564. this.bumpMap = source.bumpMap;
  21565. this.bumpScale = source.bumpScale;
  21566. this.normalMap = source.normalMap;
  21567. this.normalMapType = source.normalMapType;
  21568. this.normalScale.copy(source.normalScale);
  21569. this.displacementMap = source.displacementMap;
  21570. this.displacementScale = source.displacementScale;
  21571. this.displacementBias = source.displacementBias;
  21572. this.roughnessMap = source.roughnessMap;
  21573. this.metalnessMap = source.metalnessMap;
  21574. this.alphaMap = source.alphaMap;
  21575. this.envMap = source.envMap;
  21576. this.envMapIntensity = source.envMapIntensity;
  21577. this.wireframe = source.wireframe;
  21578. this.wireframeLinewidth = source.wireframeLinewidth;
  21579. this.wireframeLinecap = source.wireframeLinecap;
  21580. this.wireframeLinejoin = source.wireframeLinejoin;
  21581. this.flatShading = source.flatShading;
  21582. this.fog = source.fog;
  21583. return this;
  21584. }
  21585. }
  21586. class MeshPhysicalMaterial extends MeshStandardMaterial {
  21587. constructor(parameters) {
  21588. super();
  21589. this.isMeshPhysicalMaterial = true;
  21590. this.defines = {
  21591. 'STANDARD': '',
  21592. 'PHYSICAL': ''
  21593. };
  21594. this.type = 'MeshPhysicalMaterial';
  21595. this.clearcoatMap = null;
  21596. this.clearcoatRoughness = 0.0;
  21597. this.clearcoatRoughnessMap = null;
  21598. this.clearcoatNormalScale = new Vector2(1, 1);
  21599. this.clearcoatNormalMap = null;
  21600. this.ior = 1.5;
  21601. Object.defineProperty(this, 'reflectivity', {
  21602. get: function () {
  21603. return clamp(2.5 * (this.ior - 1) / (this.ior + 1), 0, 1);
  21604. },
  21605. set: function (reflectivity) {
  21606. this.ior = (1 + 0.4 * reflectivity) / (1 - 0.4 * reflectivity);
  21607. }
  21608. });
  21609. this.iridescenceMap = null;
  21610. this.iridescenceIOR = 1.3;
  21611. this.iridescenceThicknessRange = [100, 400];
  21612. this.iridescenceThicknessMap = null;
  21613. this.sheenColor = new Color(0x000000);
  21614. this.sheenColorMap = null;
  21615. this.sheenRoughness = 1.0;
  21616. this.sheenRoughnessMap = null;
  21617. this.transmissionMap = null;
  21618. this.thickness = 0;
  21619. this.thicknessMap = null;
  21620. this.attenuationDistance = Infinity;
  21621. this.attenuationColor = new Color(1, 1, 1);
  21622. this.specularIntensity = 1.0;
  21623. this.specularIntensityMap = null;
  21624. this.specularColor = new Color(1, 1, 1);
  21625. this.specularColorMap = null;
  21626. this._sheen = 0.0;
  21627. this._clearcoat = 0;
  21628. this._iridescence = 0;
  21629. this._transmission = 0;
  21630. this.setValues(parameters);
  21631. }
  21632. get sheen() {
  21633. return this._sheen;
  21634. }
  21635. set sheen(value) {
  21636. if (this._sheen > 0 !== value > 0) {
  21637. this.version++;
  21638. }
  21639. this._sheen = value;
  21640. }
  21641. get clearcoat() {
  21642. return this._clearcoat;
  21643. }
  21644. set clearcoat(value) {
  21645. if (this._clearcoat > 0 !== value > 0) {
  21646. this.version++;
  21647. }
  21648. this._clearcoat = value;
  21649. }
  21650. get iridescence() {
  21651. return this._iridescence;
  21652. }
  21653. set iridescence(value) {
  21654. if (this._iridescence > 0 !== value > 0) {
  21655. this.version++;
  21656. }
  21657. this._iridescence = value;
  21658. }
  21659. get transmission() {
  21660. return this._transmission;
  21661. }
  21662. set transmission(value) {
  21663. if (this._transmission > 0 !== value > 0) {
  21664. this.version++;
  21665. }
  21666. this._transmission = value;
  21667. }
  21668. copy(source) {
  21669. super.copy(source);
  21670. this.defines = {
  21671. 'STANDARD': '',
  21672. 'PHYSICAL': ''
  21673. };
  21674. this.clearcoat = source.clearcoat;
  21675. this.clearcoatMap = source.clearcoatMap;
  21676. this.clearcoatRoughness = source.clearcoatRoughness;
  21677. this.clearcoatRoughnessMap = source.clearcoatRoughnessMap;
  21678. this.clearcoatNormalMap = source.clearcoatNormalMap;
  21679. this.clearcoatNormalScale.copy(source.clearcoatNormalScale);
  21680. this.ior = source.ior;
  21681. this.iridescence = source.iridescence;
  21682. this.iridescenceMap = source.iridescenceMap;
  21683. this.iridescenceIOR = source.iridescenceIOR;
  21684. this.iridescenceThicknessRange = [...source.iridescenceThicknessRange];
  21685. this.iridescenceThicknessMap = source.iridescenceThicknessMap;
  21686. this.sheen = source.sheen;
  21687. this.sheenColor.copy(source.sheenColor);
  21688. this.sheenColorMap = source.sheenColorMap;
  21689. this.sheenRoughness = source.sheenRoughness;
  21690. this.sheenRoughnessMap = source.sheenRoughnessMap;
  21691. this.transmission = source.transmission;
  21692. this.transmissionMap = source.transmissionMap;
  21693. this.thickness = source.thickness;
  21694. this.thicknessMap = source.thicknessMap;
  21695. this.attenuationDistance = source.attenuationDistance;
  21696. this.attenuationColor.copy(source.attenuationColor);
  21697. this.specularIntensity = source.specularIntensity;
  21698. this.specularIntensityMap = source.specularIntensityMap;
  21699. this.specularColor.copy(source.specularColor);
  21700. this.specularColorMap = source.specularColorMap;
  21701. return this;
  21702. }
  21703. }
  21704. class MeshPhongMaterial extends Material {
  21705. constructor(parameters) {
  21706. super();
  21707. this.isMeshPhongMaterial = true;
  21708. this.type = 'MeshPhongMaterial';
  21709. this.color = new Color(0xffffff); // diffuse
  21710. this.specular = new Color(0x111111);
  21711. this.shininess = 30;
  21712. this.map = null;
  21713. this.lightMap = null;
  21714. this.lightMapIntensity = 1.0;
  21715. this.aoMap = null;
  21716. this.aoMapIntensity = 1.0;
  21717. this.emissive = new Color(0x000000);
  21718. this.emissiveIntensity = 1.0;
  21719. this.emissiveMap = null;
  21720. this.bumpMap = null;
  21721. this.bumpScale = 1;
  21722. this.normalMap = null;
  21723. this.normalMapType = TangentSpaceNormalMap;
  21724. this.normalScale = new Vector2(1, 1);
  21725. this.displacementMap = null;
  21726. this.displacementScale = 1;
  21727. this.displacementBias = 0;
  21728. this.specularMap = null;
  21729. this.alphaMap = null;
  21730. this.envMap = null;
  21731. this.combine = MultiplyOperation;
  21732. this.reflectivity = 1;
  21733. this.refractionRatio = 0.98;
  21734. this.wireframe = false;
  21735. this.wireframeLinewidth = 1;
  21736. this.wireframeLinecap = 'round';
  21737. this.wireframeLinejoin = 'round';
  21738. this.flatShading = false;
  21739. this.fog = true;
  21740. this.setValues(parameters);
  21741. }
  21742. copy(source) {
  21743. super.copy(source);
  21744. this.color.copy(source.color);
  21745. this.specular.copy(source.specular);
  21746. this.shininess = source.shininess;
  21747. this.map = source.map;
  21748. this.lightMap = source.lightMap;
  21749. this.lightMapIntensity = source.lightMapIntensity;
  21750. this.aoMap = source.aoMap;
  21751. this.aoMapIntensity = source.aoMapIntensity;
  21752. this.emissive.copy(source.emissive);
  21753. this.emissiveMap = source.emissiveMap;
  21754. this.emissiveIntensity = source.emissiveIntensity;
  21755. this.bumpMap = source.bumpMap;
  21756. this.bumpScale = source.bumpScale;
  21757. this.normalMap = source.normalMap;
  21758. this.normalMapType = source.normalMapType;
  21759. this.normalScale.copy(source.normalScale);
  21760. this.displacementMap = source.displacementMap;
  21761. this.displacementScale = source.displacementScale;
  21762. this.displacementBias = source.displacementBias;
  21763. this.specularMap = source.specularMap;
  21764. this.alphaMap = source.alphaMap;
  21765. this.envMap = source.envMap;
  21766. this.combine = source.combine;
  21767. this.reflectivity = source.reflectivity;
  21768. this.refractionRatio = source.refractionRatio;
  21769. this.wireframe = source.wireframe;
  21770. this.wireframeLinewidth = source.wireframeLinewidth;
  21771. this.wireframeLinecap = source.wireframeLinecap;
  21772. this.wireframeLinejoin = source.wireframeLinejoin;
  21773. this.flatShading = source.flatShading;
  21774. this.fog = source.fog;
  21775. return this;
  21776. }
  21777. }
  21778. class MeshToonMaterial extends Material {
  21779. constructor(parameters) {
  21780. super();
  21781. this.isMeshToonMaterial = true;
  21782. this.defines = {
  21783. 'TOON': ''
  21784. };
  21785. this.type = 'MeshToonMaterial';
  21786. this.color = new Color(0xffffff);
  21787. this.map = null;
  21788. this.gradientMap = null;
  21789. this.lightMap = null;
  21790. this.lightMapIntensity = 1.0;
  21791. this.aoMap = null;
  21792. this.aoMapIntensity = 1.0;
  21793. this.emissive = new Color(0x000000);
  21794. this.emissiveIntensity = 1.0;
  21795. this.emissiveMap = null;
  21796. this.bumpMap = null;
  21797. this.bumpScale = 1;
  21798. this.normalMap = null;
  21799. this.normalMapType = TangentSpaceNormalMap;
  21800. this.normalScale = new Vector2(1, 1);
  21801. this.displacementMap = null;
  21802. this.displacementScale = 1;
  21803. this.displacementBias = 0;
  21804. this.alphaMap = null;
  21805. this.wireframe = false;
  21806. this.wireframeLinewidth = 1;
  21807. this.wireframeLinecap = 'round';
  21808. this.wireframeLinejoin = 'round';
  21809. this.fog = true;
  21810. this.setValues(parameters);
  21811. }
  21812. copy(source) {
  21813. super.copy(source);
  21814. this.color.copy(source.color);
  21815. this.map = source.map;
  21816. this.gradientMap = source.gradientMap;
  21817. this.lightMap = source.lightMap;
  21818. this.lightMapIntensity = source.lightMapIntensity;
  21819. this.aoMap = source.aoMap;
  21820. this.aoMapIntensity = source.aoMapIntensity;
  21821. this.emissive.copy(source.emissive);
  21822. this.emissiveMap = source.emissiveMap;
  21823. this.emissiveIntensity = source.emissiveIntensity;
  21824. this.bumpMap = source.bumpMap;
  21825. this.bumpScale = source.bumpScale;
  21826. this.normalMap = source.normalMap;
  21827. this.normalMapType = source.normalMapType;
  21828. this.normalScale.copy(source.normalScale);
  21829. this.displacementMap = source.displacementMap;
  21830. this.displacementScale = source.displacementScale;
  21831. this.displacementBias = source.displacementBias;
  21832. this.alphaMap = source.alphaMap;
  21833. this.wireframe = source.wireframe;
  21834. this.wireframeLinewidth = source.wireframeLinewidth;
  21835. this.wireframeLinecap = source.wireframeLinecap;
  21836. this.wireframeLinejoin = source.wireframeLinejoin;
  21837. this.fog = source.fog;
  21838. return this;
  21839. }
  21840. }
  21841. class MeshNormalMaterial extends Material {
  21842. constructor(parameters) {
  21843. super();
  21844. this.isMeshNormalMaterial = true;
  21845. this.type = 'MeshNormalMaterial';
  21846. this.bumpMap = null;
  21847. this.bumpScale = 1;
  21848. this.normalMap = null;
  21849. this.normalMapType = TangentSpaceNormalMap;
  21850. this.normalScale = new Vector2(1, 1);
  21851. this.displacementMap = null;
  21852. this.displacementScale = 1;
  21853. this.displacementBias = 0;
  21854. this.wireframe = false;
  21855. this.wireframeLinewidth = 1;
  21856. this.flatShading = false;
  21857. this.setValues(parameters);
  21858. }
  21859. copy(source) {
  21860. super.copy(source);
  21861. this.bumpMap = source.bumpMap;
  21862. this.bumpScale = source.bumpScale;
  21863. this.normalMap = source.normalMap;
  21864. this.normalMapType = source.normalMapType;
  21865. this.normalScale.copy(source.normalScale);
  21866. this.displacementMap = source.displacementMap;
  21867. this.displacementScale = source.displacementScale;
  21868. this.displacementBias = source.displacementBias;
  21869. this.wireframe = source.wireframe;
  21870. this.wireframeLinewidth = source.wireframeLinewidth;
  21871. this.flatShading = source.flatShading;
  21872. return this;
  21873. }
  21874. }
  21875. class MeshLambertMaterial extends Material {
  21876. constructor(parameters) {
  21877. super();
  21878. this.isMeshLambertMaterial = true;
  21879. this.type = 'MeshLambertMaterial';
  21880. this.color = new Color(0xffffff); // diffuse
  21881. this.map = null;
  21882. this.lightMap = null;
  21883. this.lightMapIntensity = 1.0;
  21884. this.aoMap = null;
  21885. this.aoMapIntensity = 1.0;
  21886. this.emissive = new Color(0x000000);
  21887. this.emissiveIntensity = 1.0;
  21888. this.emissiveMap = null;
  21889. this.bumpMap = null;
  21890. this.bumpScale = 1;
  21891. this.normalMap = null;
  21892. this.normalMapType = TangentSpaceNormalMap;
  21893. this.normalScale = new Vector2(1, 1);
  21894. this.displacementMap = null;
  21895. this.displacementScale = 1;
  21896. this.displacementBias = 0;
  21897. this.specularMap = null;
  21898. this.alphaMap = null;
  21899. this.envMap = null;
  21900. this.combine = MultiplyOperation;
  21901. this.reflectivity = 1;
  21902. this.refractionRatio = 0.98;
  21903. this.wireframe = false;
  21904. this.wireframeLinewidth = 1;
  21905. this.wireframeLinecap = 'round';
  21906. this.wireframeLinejoin = 'round';
  21907. this.flatShading = false;
  21908. this.fog = true;
  21909. this.setValues(parameters);
  21910. }
  21911. copy(source) {
  21912. super.copy(source);
  21913. this.color.copy(source.color);
  21914. this.map = source.map;
  21915. this.lightMap = source.lightMap;
  21916. this.lightMapIntensity = source.lightMapIntensity;
  21917. this.aoMap = source.aoMap;
  21918. this.aoMapIntensity = source.aoMapIntensity;
  21919. this.emissive.copy(source.emissive);
  21920. this.emissiveMap = source.emissiveMap;
  21921. this.emissiveIntensity = source.emissiveIntensity;
  21922. this.bumpMap = source.bumpMap;
  21923. this.bumpScale = source.bumpScale;
  21924. this.normalMap = source.normalMap;
  21925. this.normalMapType = source.normalMapType;
  21926. this.normalScale.copy(source.normalScale);
  21927. this.displacementMap = source.displacementMap;
  21928. this.displacementScale = source.displacementScale;
  21929. this.displacementBias = source.displacementBias;
  21930. this.specularMap = source.specularMap;
  21931. this.alphaMap = source.alphaMap;
  21932. this.envMap = source.envMap;
  21933. this.combine = source.combine;
  21934. this.reflectivity = source.reflectivity;
  21935. this.refractionRatio = source.refractionRatio;
  21936. this.wireframe = source.wireframe;
  21937. this.wireframeLinewidth = source.wireframeLinewidth;
  21938. this.wireframeLinecap = source.wireframeLinecap;
  21939. this.wireframeLinejoin = source.wireframeLinejoin;
  21940. this.flatShading = source.flatShading;
  21941. this.fog = source.fog;
  21942. return this;
  21943. }
  21944. }
  21945. class MeshMatcapMaterial extends Material {
  21946. constructor(parameters) {
  21947. super();
  21948. this.isMeshMatcapMaterial = true;
  21949. this.defines = {
  21950. 'MATCAP': ''
  21951. };
  21952. this.type = 'MeshMatcapMaterial';
  21953. this.color = new Color(0xffffff); // diffuse
  21954. this.matcap = null;
  21955. this.map = null;
  21956. this.bumpMap = null;
  21957. this.bumpScale = 1;
  21958. this.normalMap = null;
  21959. this.normalMapType = TangentSpaceNormalMap;
  21960. this.normalScale = new Vector2(1, 1);
  21961. this.displacementMap = null;
  21962. this.displacementScale = 1;
  21963. this.displacementBias = 0;
  21964. this.alphaMap = null;
  21965. this.flatShading = false;
  21966. this.fog = true;
  21967. this.setValues(parameters);
  21968. }
  21969. copy(source) {
  21970. super.copy(source);
  21971. this.defines = {
  21972. 'MATCAP': ''
  21973. };
  21974. this.color.copy(source.color);
  21975. this.matcap = source.matcap;
  21976. this.map = source.map;
  21977. this.bumpMap = source.bumpMap;
  21978. this.bumpScale = source.bumpScale;
  21979. this.normalMap = source.normalMap;
  21980. this.normalMapType = source.normalMapType;
  21981. this.normalScale.copy(source.normalScale);
  21982. this.displacementMap = source.displacementMap;
  21983. this.displacementScale = source.displacementScale;
  21984. this.displacementBias = source.displacementBias;
  21985. this.alphaMap = source.alphaMap;
  21986. this.flatShading = source.flatShading;
  21987. this.fog = source.fog;
  21988. return this;
  21989. }
  21990. }
  21991. class LineDashedMaterial extends LineBasicMaterial {
  21992. constructor(parameters) {
  21993. super();
  21994. this.isLineDashedMaterial = true;
  21995. this.type = 'LineDashedMaterial';
  21996. this.scale = 1;
  21997. this.dashSize = 3;
  21998. this.gapSize = 1;
  21999. this.setValues(parameters);
  22000. }
  22001. copy(source) {
  22002. super.copy(source);
  22003. this.scale = source.scale;
  22004. this.dashSize = source.dashSize;
  22005. this.gapSize = source.gapSize;
  22006. return this;
  22007. }
  22008. }
  22009. function arraySlice(array, from, to) {
  22010. if (isTypedArray(array)) {
  22011. // in ios9 array.subarray(from, undefined) will return empty array
  22012. // but array.subarray(from) or array.subarray(from, len) is correct
  22013. return new array.constructor(array.subarray(from, to !== undefined ? to : array.length));
  22014. }
  22015. return array.slice(from, to);
  22016. } // converts an array to a specific type
  22017. function convertArray(array, type, forceClone) {
  22018. if (!array || // let 'undefined' and 'null' pass
  22019. !forceClone && array.constructor === type) return array;
  22020. if (typeof type.BYTES_PER_ELEMENT === 'number') {
  22021. return new type(array); // create typed array
  22022. }
  22023. return Array.prototype.slice.call(array); // create Array
  22024. }
  22025. function isTypedArray(object) {
  22026. return ArrayBuffer.isView(object) && !(object instanceof DataView);
  22027. } // returns an array by which times and values can be sorted
  22028. function getKeyframeOrder(times) {
  22029. function compareTime(i, j) {
  22030. return times[i] - times[j];
  22031. }
  22032. const n = times.length;
  22033. const result = new Array(n);
  22034. for (let i = 0; i !== n; ++i) result[i] = i;
  22035. result.sort(compareTime);
  22036. return result;
  22037. } // uses the array previously returned by 'getKeyframeOrder' to sort data
  22038. function sortedArray(values, stride, order) {
  22039. const nValues = values.length;
  22040. const result = new values.constructor(nValues);
  22041. for (let i = 0, dstOffset = 0; dstOffset !== nValues; ++i) {
  22042. const srcOffset = order[i] * stride;
  22043. for (let j = 0; j !== stride; ++j) {
  22044. result[dstOffset++] = values[srcOffset + j];
  22045. }
  22046. }
  22047. return result;
  22048. } // function for parsing AOS keyframe formats
  22049. function flattenJSON(jsonKeys, times, values, valuePropertyName) {
  22050. let i = 1,
  22051. key = jsonKeys[0];
  22052. while (key !== undefined && key[valuePropertyName] === undefined) {
  22053. key = jsonKeys[i++];
  22054. }
  22055. if (key === undefined) return; // no data
  22056. let value = key[valuePropertyName];
  22057. if (value === undefined) return; // no data
  22058. if (Array.isArray(value)) {
  22059. do {
  22060. value = key[valuePropertyName];
  22061. if (value !== undefined) {
  22062. times.push(key.time);
  22063. values.push.apply(values, value); // push all elements
  22064. }
  22065. key = jsonKeys[i++];
  22066. } while (key !== undefined);
  22067. } else if (value.toArray !== undefined) {
  22068. // ...assume THREE.Math-ish
  22069. do {
  22070. value = key[valuePropertyName];
  22071. if (value !== undefined) {
  22072. times.push(key.time);
  22073. value.toArray(values, values.length);
  22074. }
  22075. key = jsonKeys[i++];
  22076. } while (key !== undefined);
  22077. } else {
  22078. // otherwise push as-is
  22079. do {
  22080. value = key[valuePropertyName];
  22081. if (value !== undefined) {
  22082. times.push(key.time);
  22083. values.push(value);
  22084. }
  22085. key = jsonKeys[i++];
  22086. } while (key !== undefined);
  22087. }
  22088. }
  22089. function subclip(sourceClip, name, startFrame, endFrame, fps = 30) {
  22090. const clip = sourceClip.clone();
  22091. clip.name = name;
  22092. const tracks = [];
  22093. for (let i = 0; i < clip.tracks.length; ++i) {
  22094. const track = clip.tracks[i];
  22095. const valueSize = track.getValueSize();
  22096. const times = [];
  22097. const values = [];
  22098. for (let j = 0; j < track.times.length; ++j) {
  22099. const frame = track.times[j] * fps;
  22100. if (frame < startFrame || frame >= endFrame) continue;
  22101. times.push(track.times[j]);
  22102. for (let k = 0; k < valueSize; ++k) {
  22103. values.push(track.values[j * valueSize + k]);
  22104. }
  22105. }
  22106. if (times.length === 0) continue;
  22107. track.times = convertArray(times, track.times.constructor);
  22108. track.values = convertArray(values, track.values.constructor);
  22109. tracks.push(track);
  22110. }
  22111. clip.tracks = tracks; // find minimum .times value across all tracks in the trimmed clip
  22112. let minStartTime = Infinity;
  22113. for (let i = 0; i < clip.tracks.length; ++i) {
  22114. if (minStartTime > clip.tracks[i].times[0]) {
  22115. minStartTime = clip.tracks[i].times[0];
  22116. }
  22117. } // shift all tracks such that clip begins at t=0
  22118. for (let i = 0; i < clip.tracks.length; ++i) {
  22119. clip.tracks[i].shift(-1 * minStartTime);
  22120. }
  22121. clip.resetDuration();
  22122. return clip;
  22123. }
  22124. function makeClipAdditive(targetClip, referenceFrame = 0, referenceClip = targetClip, fps = 30) {
  22125. if (fps <= 0) fps = 30;
  22126. const numTracks = referenceClip.tracks.length;
  22127. const referenceTime = referenceFrame / fps; // Make each track's values relative to the values at the reference frame
  22128. for (let i = 0; i < numTracks; ++i) {
  22129. const referenceTrack = referenceClip.tracks[i];
  22130. const referenceTrackType = referenceTrack.ValueTypeName; // Skip this track if it's non-numeric
  22131. if (referenceTrackType === 'bool' || referenceTrackType === 'string') continue; // Find the track in the target clip whose name and type matches the reference track
  22132. const targetTrack = targetClip.tracks.find(function (track) {
  22133. return track.name === referenceTrack.name && track.ValueTypeName === referenceTrackType;
  22134. });
  22135. if (targetTrack === undefined) continue;
  22136. let referenceOffset = 0;
  22137. const referenceValueSize = referenceTrack.getValueSize();
  22138. if (referenceTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline) {
  22139. referenceOffset = referenceValueSize / 3;
  22140. }
  22141. let targetOffset = 0;
  22142. const targetValueSize = targetTrack.getValueSize();
  22143. if (targetTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline) {
  22144. targetOffset = targetValueSize / 3;
  22145. }
  22146. const lastIndex = referenceTrack.times.length - 1;
  22147. let referenceValue; // Find the value to subtract out of the track
  22148. if (referenceTime <= referenceTrack.times[0]) {
  22149. // Reference frame is earlier than the first keyframe, so just use the first keyframe
  22150. const startIndex = referenceOffset;
  22151. const endIndex = referenceValueSize - referenceOffset;
  22152. referenceValue = arraySlice(referenceTrack.values, startIndex, endIndex);
  22153. } else if (referenceTime >= referenceTrack.times[lastIndex]) {
  22154. // Reference frame is after the last keyframe, so just use the last keyframe
  22155. const startIndex = lastIndex * referenceValueSize + referenceOffset;
  22156. const endIndex = startIndex + referenceValueSize - referenceOffset;
  22157. referenceValue = arraySlice(referenceTrack.values, startIndex, endIndex);
  22158. } else {
  22159. // Interpolate to the reference value
  22160. const interpolant = referenceTrack.createInterpolant();
  22161. const startIndex = referenceOffset;
  22162. const endIndex = referenceValueSize - referenceOffset;
  22163. interpolant.evaluate(referenceTime);
  22164. referenceValue = arraySlice(interpolant.resultBuffer, startIndex, endIndex);
  22165. } // Conjugate the quaternion
  22166. if (referenceTrackType === 'quaternion') {
  22167. const referenceQuat = new Quaternion().fromArray(referenceValue).normalize().conjugate();
  22168. referenceQuat.toArray(referenceValue);
  22169. } // Subtract the reference value from all of the track values
  22170. const numTimes = targetTrack.times.length;
  22171. for (let j = 0; j < numTimes; ++j) {
  22172. const valueStart = j * targetValueSize + targetOffset;
  22173. if (referenceTrackType === 'quaternion') {
  22174. // Multiply the conjugate for quaternion track types
  22175. Quaternion.multiplyQuaternionsFlat(targetTrack.values, valueStart, referenceValue, 0, targetTrack.values, valueStart);
  22176. } else {
  22177. const valueEnd = targetValueSize - targetOffset * 2; // Subtract each value for all other numeric track types
  22178. for (let k = 0; k < valueEnd; ++k) {
  22179. targetTrack.values[valueStart + k] -= referenceValue[k];
  22180. }
  22181. }
  22182. }
  22183. }
  22184. targetClip.blendMode = AdditiveAnimationBlendMode;
  22185. return targetClip;
  22186. }
  22187. var AnimationUtils = /*#__PURE__*/Object.freeze({
  22188. __proto__: null,
  22189. arraySlice: arraySlice,
  22190. convertArray: convertArray,
  22191. isTypedArray: isTypedArray,
  22192. getKeyframeOrder: getKeyframeOrder,
  22193. sortedArray: sortedArray,
  22194. flattenJSON: flattenJSON,
  22195. subclip: subclip,
  22196. makeClipAdditive: makeClipAdditive
  22197. });
  22198. /**
  22199. * Abstract base class of interpolants over parametric samples.
  22200. *
  22201. * The parameter domain is one dimensional, typically the time or a path
  22202. * along a curve defined by the data.
  22203. *
  22204. * The sample values can have any dimensionality and derived classes may
  22205. * apply special interpretations to the data.
  22206. *
  22207. * This class provides the interval seek in a Template Method, deferring
  22208. * the actual interpolation to derived classes.
  22209. *
  22210. * Time complexity is O(1) for linear access crossing at most two points
  22211. * and O(log N) for random access, where N is the number of positions.
  22212. *
  22213. * References:
  22214. *
  22215. * http://www.oodesign.com/template-method-pattern.html
  22216. *
  22217. */
  22218. class Interpolant {
  22219. constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  22220. this.parameterPositions = parameterPositions;
  22221. this._cachedIndex = 0;
  22222. this.resultBuffer = resultBuffer !== undefined ? resultBuffer : new sampleValues.constructor(sampleSize);
  22223. this.sampleValues = sampleValues;
  22224. this.valueSize = sampleSize;
  22225. this.settings = null;
  22226. this.DefaultSettings_ = {};
  22227. }
  22228. evaluate(t) {
  22229. const pp = this.parameterPositions;
  22230. let i1 = this._cachedIndex,
  22231. t1 = pp[i1],
  22232. t0 = pp[i1 - 1];
  22233. validate_interval: {
  22234. seek: {
  22235. let right;
  22236. linear_scan: {
  22237. //- See http://jsperf.com/comparison-to-undefined/3
  22238. //- slower code:
  22239. //-
  22240. //- if ( t >= t1 || t1 === undefined ) {
  22241. forward_scan: if (!(t < t1)) {
  22242. for (let giveUpAt = i1 + 2;;) {
  22243. if (t1 === undefined) {
  22244. if (t < t0) break forward_scan; // after end
  22245. i1 = pp.length;
  22246. this._cachedIndex = i1;
  22247. return this.copySampleValue_(i1 - 1);
  22248. }
  22249. if (i1 === giveUpAt) break; // this loop
  22250. t0 = t1;
  22251. t1 = pp[++i1];
  22252. if (t < t1) {
  22253. // we have arrived at the sought interval
  22254. break seek;
  22255. }
  22256. } // prepare binary search on the right side of the index
  22257. right = pp.length;
  22258. break linear_scan;
  22259. } //- slower code:
  22260. //- if ( t < t0 || t0 === undefined ) {
  22261. if (!(t >= t0)) {
  22262. // looping?
  22263. const t1global = pp[1];
  22264. if (t < t1global) {
  22265. i1 = 2; // + 1, using the scan for the details
  22266. t0 = t1global;
  22267. } // linear reverse scan
  22268. for (let giveUpAt = i1 - 2;;) {
  22269. if (t0 === undefined) {
  22270. // before start
  22271. this._cachedIndex = 0;
  22272. return this.copySampleValue_(0);
  22273. }
  22274. if (i1 === giveUpAt) break; // this loop
  22275. t1 = t0;
  22276. t0 = pp[--i1 - 1];
  22277. if (t >= t0) {
  22278. // we have arrived at the sought interval
  22279. break seek;
  22280. }
  22281. } // prepare binary search on the left side of the index
  22282. right = i1;
  22283. i1 = 0;
  22284. break linear_scan;
  22285. } // the interval is valid
  22286. break validate_interval;
  22287. } // linear scan
  22288. // binary search
  22289. while (i1 < right) {
  22290. const mid = i1 + right >>> 1;
  22291. if (t < pp[mid]) {
  22292. right = mid;
  22293. } else {
  22294. i1 = mid + 1;
  22295. }
  22296. }
  22297. t1 = pp[i1];
  22298. t0 = pp[i1 - 1]; // check boundary cases, again
  22299. if (t0 === undefined) {
  22300. this._cachedIndex = 0;
  22301. return this.copySampleValue_(0);
  22302. }
  22303. if (t1 === undefined) {
  22304. i1 = pp.length;
  22305. this._cachedIndex = i1;
  22306. return this.copySampleValue_(i1 - 1);
  22307. }
  22308. } // seek
  22309. this._cachedIndex = i1;
  22310. this.intervalChanged_(i1, t0, t1);
  22311. } // validate_interval
  22312. return this.interpolate_(i1, t0, t, t1);
  22313. }
  22314. getSettings_() {
  22315. return this.settings || this.DefaultSettings_;
  22316. }
  22317. copySampleValue_(index) {
  22318. // copies a sample value to the result buffer
  22319. const result = this.resultBuffer,
  22320. values = this.sampleValues,
  22321. stride = this.valueSize,
  22322. offset = index * stride;
  22323. for (let i = 0; i !== stride; ++i) {
  22324. result[i] = values[offset + i];
  22325. }
  22326. return result;
  22327. } // Template methods for derived classes:
  22328. interpolate_() {
  22329. throw new Error('call to abstract method'); // implementations shall return this.resultBuffer
  22330. }
  22331. intervalChanged_() {// empty
  22332. }
  22333. }
  22334. /**
  22335. * Fast and simple cubic spline interpolant.
  22336. *
  22337. * It was derived from a Hermitian construction setting the first derivative
  22338. * at each sample position to the linear slope between neighboring positions
  22339. * over their parameter interval.
  22340. */
  22341. class CubicInterpolant extends Interpolant {
  22342. constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  22343. super(parameterPositions, sampleValues, sampleSize, resultBuffer);
  22344. this._weightPrev = -0;
  22345. this._offsetPrev = -0;
  22346. this._weightNext = -0;
  22347. this._offsetNext = -0;
  22348. this.DefaultSettings_ = {
  22349. endingStart: ZeroCurvatureEnding,
  22350. endingEnd: ZeroCurvatureEnding
  22351. };
  22352. }
  22353. intervalChanged_(i1, t0, t1) {
  22354. const pp = this.parameterPositions;
  22355. let iPrev = i1 - 2,
  22356. iNext = i1 + 1,
  22357. tPrev = pp[iPrev],
  22358. tNext = pp[iNext];
  22359. if (tPrev === undefined) {
  22360. switch (this.getSettings_().endingStart) {
  22361. case ZeroSlopeEnding:
  22362. // f'(t0) = 0
  22363. iPrev = i1;
  22364. tPrev = 2 * t0 - t1;
  22365. break;
  22366. case WrapAroundEnding:
  22367. // use the other end of the curve
  22368. iPrev = pp.length - 2;
  22369. tPrev = t0 + pp[iPrev] - pp[iPrev + 1];
  22370. break;
  22371. default:
  22372. // ZeroCurvatureEnding
  22373. // f''(t0) = 0 a.k.a. Natural Spline
  22374. iPrev = i1;
  22375. tPrev = t1;
  22376. }
  22377. }
  22378. if (tNext === undefined) {
  22379. switch (this.getSettings_().endingEnd) {
  22380. case ZeroSlopeEnding:
  22381. // f'(tN) = 0
  22382. iNext = i1;
  22383. tNext = 2 * t1 - t0;
  22384. break;
  22385. case WrapAroundEnding:
  22386. // use the other end of the curve
  22387. iNext = 1;
  22388. tNext = t1 + pp[1] - pp[0];
  22389. break;
  22390. default:
  22391. // ZeroCurvatureEnding
  22392. // f''(tN) = 0, a.k.a. Natural Spline
  22393. iNext = i1 - 1;
  22394. tNext = t0;
  22395. }
  22396. }
  22397. const halfDt = (t1 - t0) * 0.5,
  22398. stride = this.valueSize;
  22399. this._weightPrev = halfDt / (t0 - tPrev);
  22400. this._weightNext = halfDt / (tNext - t1);
  22401. this._offsetPrev = iPrev * stride;
  22402. this._offsetNext = iNext * stride;
  22403. }
  22404. interpolate_(i1, t0, t, t1) {
  22405. const result = this.resultBuffer,
  22406. values = this.sampleValues,
  22407. stride = this.valueSize,
  22408. o1 = i1 * stride,
  22409. o0 = o1 - stride,
  22410. oP = this._offsetPrev,
  22411. oN = this._offsetNext,
  22412. wP = this._weightPrev,
  22413. wN = this._weightNext,
  22414. p = (t - t0) / (t1 - t0),
  22415. pp = p * p,
  22416. ppp = pp * p; // evaluate polynomials
  22417. const sP = -wP * ppp + 2 * wP * pp - wP * p;
  22418. const s0 = (1 + wP) * ppp + (-1.5 - 2 * wP) * pp + (-0.5 + wP) * p + 1;
  22419. const s1 = (-1 - wN) * ppp + (1.5 + wN) * pp + 0.5 * p;
  22420. const sN = wN * ppp - wN * pp; // combine data linearly
  22421. for (let i = 0; i !== stride; ++i) {
  22422. result[i] = sP * values[oP + i] + s0 * values[o0 + i] + s1 * values[o1 + i] + sN * values[oN + i];
  22423. }
  22424. return result;
  22425. }
  22426. }
  22427. class LinearInterpolant extends Interpolant {
  22428. constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  22429. super(parameterPositions, sampleValues, sampleSize, resultBuffer);
  22430. }
  22431. interpolate_(i1, t0, t, t1) {
  22432. const result = this.resultBuffer,
  22433. values = this.sampleValues,
  22434. stride = this.valueSize,
  22435. offset1 = i1 * stride,
  22436. offset0 = offset1 - stride,
  22437. weight1 = (t - t0) / (t1 - t0),
  22438. weight0 = 1 - weight1;
  22439. for (let i = 0; i !== stride; ++i) {
  22440. result[i] = values[offset0 + i] * weight0 + values[offset1 + i] * weight1;
  22441. }
  22442. return result;
  22443. }
  22444. }
  22445. /**
  22446. *
  22447. * Interpolant that evaluates to the sample value at the position preceding
  22448. * the parameter.
  22449. */
  22450. class DiscreteInterpolant extends Interpolant {
  22451. constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  22452. super(parameterPositions, sampleValues, sampleSize, resultBuffer);
  22453. }
  22454. interpolate_(i1
  22455. /*, t0, t, t1 */
  22456. ) {
  22457. return this.copySampleValue_(i1 - 1);
  22458. }
  22459. }
  22460. class KeyframeTrack {
  22461. constructor(name, times, values, interpolation) {
  22462. if (name === undefined) throw new Error('THREE.KeyframeTrack: track name is undefined');
  22463. if (times === undefined || times.length === 0) throw new Error('THREE.KeyframeTrack: no keyframes in track named ' + name);
  22464. this.name = name;
  22465. this.times = convertArray(times, this.TimeBufferType);
  22466. this.values = convertArray(values, this.ValueBufferType);
  22467. this.setInterpolation(interpolation || this.DefaultInterpolation);
  22468. } // Serialization (in static context, because of constructor invocation
  22469. // and automatic invocation of .toJSON):
  22470. static toJSON(track) {
  22471. const trackType = track.constructor;
  22472. let json; // derived classes can define a static toJSON method
  22473. if (trackType.toJSON !== this.toJSON) {
  22474. json = trackType.toJSON(track);
  22475. } else {
  22476. // by default, we assume the data can be serialized as-is
  22477. json = {
  22478. 'name': track.name,
  22479. 'times': convertArray(track.times, Array),
  22480. 'values': convertArray(track.values, Array)
  22481. };
  22482. const interpolation = track.getInterpolation();
  22483. if (interpolation !== track.DefaultInterpolation) {
  22484. json.interpolation = interpolation;
  22485. }
  22486. }
  22487. json.type = track.ValueTypeName; // mandatory
  22488. return json;
  22489. }
  22490. InterpolantFactoryMethodDiscrete(result) {
  22491. return new DiscreteInterpolant(this.times, this.values, this.getValueSize(), result);
  22492. }
  22493. InterpolantFactoryMethodLinear(result) {
  22494. return new LinearInterpolant(this.times, this.values, this.getValueSize(), result);
  22495. }
  22496. InterpolantFactoryMethodSmooth(result) {
  22497. return new CubicInterpolant(this.times, this.values, this.getValueSize(), result);
  22498. }
  22499. setInterpolation(interpolation) {
  22500. let factoryMethod;
  22501. switch (interpolation) {
  22502. case InterpolateDiscrete:
  22503. factoryMethod = this.InterpolantFactoryMethodDiscrete;
  22504. break;
  22505. case InterpolateLinear:
  22506. factoryMethod = this.InterpolantFactoryMethodLinear;
  22507. break;
  22508. case InterpolateSmooth:
  22509. factoryMethod = this.InterpolantFactoryMethodSmooth;
  22510. break;
  22511. }
  22512. if (factoryMethod === undefined) {
  22513. const message = 'unsupported interpolation for ' + this.ValueTypeName + ' keyframe track named ' + this.name;
  22514. if (this.createInterpolant === undefined) {
  22515. // fall back to default, unless the default itself is messed up
  22516. if (interpolation !== this.DefaultInterpolation) {
  22517. this.setInterpolation(this.DefaultInterpolation);
  22518. } else {
  22519. throw new Error(message); // fatal, in this case
  22520. }
  22521. }
  22522. console.warn('THREE.KeyframeTrack:', message);
  22523. return this;
  22524. }
  22525. this.createInterpolant = factoryMethod;
  22526. return this;
  22527. }
  22528. getInterpolation() {
  22529. switch (this.createInterpolant) {
  22530. case this.InterpolantFactoryMethodDiscrete:
  22531. return InterpolateDiscrete;
  22532. case this.InterpolantFactoryMethodLinear:
  22533. return InterpolateLinear;
  22534. case this.InterpolantFactoryMethodSmooth:
  22535. return InterpolateSmooth;
  22536. }
  22537. }
  22538. getValueSize() {
  22539. return this.values.length / this.times.length;
  22540. } // move all keyframes either forwards or backwards in time
  22541. shift(timeOffset) {
  22542. if (timeOffset !== 0.0) {
  22543. const times = this.times;
  22544. for (let i = 0, n = times.length; i !== n; ++i) {
  22545. times[i] += timeOffset;
  22546. }
  22547. }
  22548. return this;
  22549. } // scale all keyframe times by a factor (useful for frame <-> seconds conversions)
  22550. scale(timeScale) {
  22551. if (timeScale !== 1.0) {
  22552. const times = this.times;
  22553. for (let i = 0, n = times.length; i !== n; ++i) {
  22554. times[i] *= timeScale;
  22555. }
  22556. }
  22557. return this;
  22558. } // removes keyframes before and after animation without changing any values within the range [startTime, endTime].
  22559. // IMPORTANT: We do not shift around keys to the start of the track time, because for interpolated keys this will change their values
  22560. trim(startTime, endTime) {
  22561. const times = this.times,
  22562. nKeys = times.length;
  22563. let from = 0,
  22564. to = nKeys - 1;
  22565. while (from !== nKeys && times[from] < startTime) {
  22566. ++from;
  22567. }
  22568. while (to !== -1 && times[to] > endTime) {
  22569. --to;
  22570. }
  22571. ++to; // inclusive -> exclusive bound
  22572. if (from !== 0 || to !== nKeys) {
  22573. // empty tracks are forbidden, so keep at least one keyframe
  22574. if (from >= to) {
  22575. to = Math.max(to, 1);
  22576. from = to - 1;
  22577. }
  22578. const stride = this.getValueSize();
  22579. this.times = arraySlice(times, from, to);
  22580. this.values = arraySlice(this.values, from * stride, to * stride);
  22581. }
  22582. return this;
  22583. } // ensure we do not get a GarbageInGarbageOut situation, make sure tracks are at least minimally viable
  22584. validate() {
  22585. let valid = true;
  22586. const valueSize = this.getValueSize();
  22587. if (valueSize - Math.floor(valueSize) !== 0) {
  22588. console.error('THREE.KeyframeTrack: Invalid value size in track.', this);
  22589. valid = false;
  22590. }
  22591. const times = this.times,
  22592. values = this.values,
  22593. nKeys = times.length;
  22594. if (nKeys === 0) {
  22595. console.error('THREE.KeyframeTrack: Track is empty.', this);
  22596. valid = false;
  22597. }
  22598. let prevTime = null;
  22599. for (let i = 0; i !== nKeys; i++) {
  22600. const currTime = times[i];
  22601. if (typeof currTime === 'number' && isNaN(currTime)) {
  22602. console.error('THREE.KeyframeTrack: Time is not a valid number.', this, i, currTime);
  22603. valid = false;
  22604. break;
  22605. }
  22606. if (prevTime !== null && prevTime > currTime) {
  22607. console.error('THREE.KeyframeTrack: Out of order keys.', this, i, currTime, prevTime);
  22608. valid = false;
  22609. break;
  22610. }
  22611. prevTime = currTime;
  22612. }
  22613. if (values !== undefined) {
  22614. if (isTypedArray(values)) {
  22615. for (let i = 0, n = values.length; i !== n; ++i) {
  22616. const value = values[i];
  22617. if (isNaN(value)) {
  22618. console.error('THREE.KeyframeTrack: Value is not a valid number.', this, i, value);
  22619. valid = false;
  22620. break;
  22621. }
  22622. }
  22623. }
  22624. }
  22625. return valid;
  22626. } // removes equivalent sequential keys as common in morph target sequences
  22627. // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0)
  22628. optimize() {
  22629. // times or values may be shared with other tracks, so overwriting is unsafe
  22630. const times = arraySlice(this.times),
  22631. values = arraySlice(this.values),
  22632. stride = this.getValueSize(),
  22633. smoothInterpolation = this.getInterpolation() === InterpolateSmooth,
  22634. lastIndex = times.length - 1;
  22635. let writeIndex = 1;
  22636. for (let i = 1; i < lastIndex; ++i) {
  22637. let keep = false;
  22638. const time = times[i];
  22639. const timeNext = times[i + 1]; // remove adjacent keyframes scheduled at the same time
  22640. if (time !== timeNext && (i !== 1 || time !== times[0])) {
  22641. if (!smoothInterpolation) {
  22642. // remove unnecessary keyframes same as their neighbors
  22643. const offset = i * stride,
  22644. offsetP = offset - stride,
  22645. offsetN = offset + stride;
  22646. for (let j = 0; j !== stride; ++j) {
  22647. const value = values[offset + j];
  22648. if (value !== values[offsetP + j] || value !== values[offsetN + j]) {
  22649. keep = true;
  22650. break;
  22651. }
  22652. }
  22653. } else {
  22654. keep = true;
  22655. }
  22656. } // in-place compaction
  22657. if (keep) {
  22658. if (i !== writeIndex) {
  22659. times[writeIndex] = times[i];
  22660. const readOffset = i * stride,
  22661. writeOffset = writeIndex * stride;
  22662. for (let j = 0; j !== stride; ++j) {
  22663. values[writeOffset + j] = values[readOffset + j];
  22664. }
  22665. }
  22666. ++writeIndex;
  22667. }
  22668. } // flush last keyframe (compaction looks ahead)
  22669. if (lastIndex > 0) {
  22670. times[writeIndex] = times[lastIndex];
  22671. for (let readOffset = lastIndex * stride, writeOffset = writeIndex * stride, j = 0; j !== stride; ++j) {
  22672. values[writeOffset + j] = values[readOffset + j];
  22673. }
  22674. ++writeIndex;
  22675. }
  22676. if (writeIndex !== times.length) {
  22677. this.times = arraySlice(times, 0, writeIndex);
  22678. this.values = arraySlice(values, 0, writeIndex * stride);
  22679. } else {
  22680. this.times = times;
  22681. this.values = values;
  22682. }
  22683. return this;
  22684. }
  22685. clone() {
  22686. const times = arraySlice(this.times, 0);
  22687. const values = arraySlice(this.values, 0);
  22688. const TypedKeyframeTrack = this.constructor;
  22689. const track = new TypedKeyframeTrack(this.name, times, values); // Interpolant argument to constructor is not saved, so copy the factory method directly.
  22690. track.createInterpolant = this.createInterpolant;
  22691. return track;
  22692. }
  22693. }
  22694. KeyframeTrack.prototype.TimeBufferType = Float32Array;
  22695. KeyframeTrack.prototype.ValueBufferType = Float32Array;
  22696. KeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear;
  22697. /**
  22698. * A Track of Boolean keyframe values.
  22699. */
  22700. class BooleanKeyframeTrack extends KeyframeTrack {}
  22701. BooleanKeyframeTrack.prototype.ValueTypeName = 'bool';
  22702. BooleanKeyframeTrack.prototype.ValueBufferType = Array;
  22703. BooleanKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  22704. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  22705. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined; // Note: Actually this track could have a optimized / compressed
  22706. /**
  22707. * A Track of keyframe values that represent color.
  22708. */
  22709. class ColorKeyframeTrack extends KeyframeTrack {}
  22710. ColorKeyframeTrack.prototype.ValueTypeName = 'color'; // ValueBufferType is inherited
  22711. /**
  22712. * A Track of numeric keyframe values.
  22713. */
  22714. class NumberKeyframeTrack extends KeyframeTrack {}
  22715. NumberKeyframeTrack.prototype.ValueTypeName = 'number'; // ValueBufferType is inherited
  22716. /**
  22717. * Spherical linear unit quaternion interpolant.
  22718. */
  22719. class QuaternionLinearInterpolant extends Interpolant {
  22720. constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  22721. super(parameterPositions, sampleValues, sampleSize, resultBuffer);
  22722. }
  22723. interpolate_(i1, t0, t, t1) {
  22724. const result = this.resultBuffer,
  22725. values = this.sampleValues,
  22726. stride = this.valueSize,
  22727. alpha = (t - t0) / (t1 - t0);
  22728. let offset = i1 * stride;
  22729. for (let end = offset + stride; offset !== end; offset += 4) {
  22730. Quaternion.slerpFlat(result, 0, values, offset - stride, values, offset, alpha);
  22731. }
  22732. return result;
  22733. }
  22734. }
  22735. /**
  22736. * A Track of quaternion keyframe values.
  22737. */
  22738. class QuaternionKeyframeTrack extends KeyframeTrack {
  22739. InterpolantFactoryMethodLinear(result) {
  22740. return new QuaternionLinearInterpolant(this.times, this.values, this.getValueSize(), result);
  22741. }
  22742. }
  22743. QuaternionKeyframeTrack.prototype.ValueTypeName = 'quaternion'; // ValueBufferType is inherited
  22744. QuaternionKeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear;
  22745. QuaternionKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  22746. /**
  22747. * A Track that interpolates Strings
  22748. */
  22749. class StringKeyframeTrack extends KeyframeTrack {}
  22750. StringKeyframeTrack.prototype.ValueTypeName = 'string';
  22751. StringKeyframeTrack.prototype.ValueBufferType = Array;
  22752. StringKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  22753. StringKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  22754. StringKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  22755. /**
  22756. * A Track of vectored keyframe values.
  22757. */
  22758. class VectorKeyframeTrack extends KeyframeTrack {}
  22759. VectorKeyframeTrack.prototype.ValueTypeName = 'vector'; // ValueBufferType is inherited
  22760. class AnimationClip {
  22761. constructor(name, duration = -1, tracks, blendMode = NormalAnimationBlendMode) {
  22762. this.name = name;
  22763. this.tracks = tracks;
  22764. this.duration = duration;
  22765. this.blendMode = blendMode;
  22766. this.uuid = generateUUID(); // this means it should figure out its duration by scanning the tracks
  22767. if (this.duration < 0) {
  22768. this.resetDuration();
  22769. }
  22770. }
  22771. static parse(json) {
  22772. const tracks = [],
  22773. jsonTracks = json.tracks,
  22774. frameTime = 1.0 / (json.fps || 1.0);
  22775. for (let i = 0, n = jsonTracks.length; i !== n; ++i) {
  22776. tracks.push(parseKeyframeTrack(jsonTracks[i]).scale(frameTime));
  22777. }
  22778. const clip = new this(json.name, json.duration, tracks, json.blendMode);
  22779. clip.uuid = json.uuid;
  22780. return clip;
  22781. }
  22782. static toJSON(clip) {
  22783. const tracks = [],
  22784. clipTracks = clip.tracks;
  22785. const json = {
  22786. 'name': clip.name,
  22787. 'duration': clip.duration,
  22788. 'tracks': tracks,
  22789. 'uuid': clip.uuid,
  22790. 'blendMode': clip.blendMode
  22791. };
  22792. for (let i = 0, n = clipTracks.length; i !== n; ++i) {
  22793. tracks.push(KeyframeTrack.toJSON(clipTracks[i]));
  22794. }
  22795. return json;
  22796. }
  22797. static CreateFromMorphTargetSequence(name, morphTargetSequence, fps, noLoop) {
  22798. const numMorphTargets = morphTargetSequence.length;
  22799. const tracks = [];
  22800. for (let i = 0; i < numMorphTargets; i++) {
  22801. let times = [];
  22802. let values = [];
  22803. times.push((i + numMorphTargets - 1) % numMorphTargets, i, (i + 1) % numMorphTargets);
  22804. values.push(0, 1, 0);
  22805. const order = getKeyframeOrder(times);
  22806. times = sortedArray(times, 1, order);
  22807. values = sortedArray(values, 1, order); // if there is a key at the first frame, duplicate it as the
  22808. // last frame as well for perfect loop.
  22809. if (!noLoop && times[0] === 0) {
  22810. times.push(numMorphTargets);
  22811. values.push(values[0]);
  22812. }
  22813. tracks.push(new NumberKeyframeTrack('.morphTargetInfluences[' + morphTargetSequence[i].name + ']', times, values).scale(1.0 / fps));
  22814. }
  22815. return new this(name, -1, tracks);
  22816. }
  22817. static findByName(objectOrClipArray, name) {
  22818. let clipArray = objectOrClipArray;
  22819. if (!Array.isArray(objectOrClipArray)) {
  22820. const o = objectOrClipArray;
  22821. clipArray = o.geometry && o.geometry.animations || o.animations;
  22822. }
  22823. for (let i = 0; i < clipArray.length; i++) {
  22824. if (clipArray[i].name === name) {
  22825. return clipArray[i];
  22826. }
  22827. }
  22828. return null;
  22829. }
  22830. static CreateClipsFromMorphTargetSequences(morphTargets, fps, noLoop) {
  22831. const animationToMorphTargets = {}; // tested with https://regex101.com/ on trick sequences
  22832. // such flamingo_flyA_003, flamingo_run1_003, crdeath0059
  22833. const pattern = /^([\w-]*?)([\d]+)$/; // sort morph target names into animation groups based
  22834. // patterns like Walk_001, Walk_002, Run_001, Run_002
  22835. for (let i = 0, il = morphTargets.length; i < il; i++) {
  22836. const morphTarget = morphTargets[i];
  22837. const parts = morphTarget.name.match(pattern);
  22838. if (parts && parts.length > 1) {
  22839. const name = parts[1];
  22840. let animationMorphTargets = animationToMorphTargets[name];
  22841. if (!animationMorphTargets) {
  22842. animationToMorphTargets[name] = animationMorphTargets = [];
  22843. }
  22844. animationMorphTargets.push(morphTarget);
  22845. }
  22846. }
  22847. const clips = [];
  22848. for (const name in animationToMorphTargets) {
  22849. clips.push(this.CreateFromMorphTargetSequence(name, animationToMorphTargets[name], fps, noLoop));
  22850. }
  22851. return clips;
  22852. } // parse the animation.hierarchy format
  22853. static parseAnimation(animation, bones) {
  22854. if (!animation) {
  22855. console.error('THREE.AnimationClip: No animation in JSONLoader data.');
  22856. return null;
  22857. }
  22858. const addNonemptyTrack = function (trackType, trackName, animationKeys, propertyName, destTracks) {
  22859. // only return track if there are actually keys.
  22860. if (animationKeys.length !== 0) {
  22861. const times = [];
  22862. const values = [];
  22863. flattenJSON(animationKeys, times, values, propertyName); // empty keys are filtered out, so check again
  22864. if (times.length !== 0) {
  22865. destTracks.push(new trackType(trackName, times, values));
  22866. }
  22867. }
  22868. };
  22869. const tracks = [];
  22870. const clipName = animation.name || 'default';
  22871. const fps = animation.fps || 30;
  22872. const blendMode = animation.blendMode; // automatic length determination in AnimationClip.
  22873. let duration = animation.length || -1;
  22874. const hierarchyTracks = animation.hierarchy || [];
  22875. for (let h = 0; h < hierarchyTracks.length; h++) {
  22876. const animationKeys = hierarchyTracks[h].keys; // skip empty tracks
  22877. if (!animationKeys || animationKeys.length === 0) continue; // process morph targets
  22878. if (animationKeys[0].morphTargets) {
  22879. // figure out all morph targets used in this track
  22880. const morphTargetNames = {};
  22881. let k;
  22882. for (k = 0; k < animationKeys.length; k++) {
  22883. if (animationKeys[k].morphTargets) {
  22884. for (let m = 0; m < animationKeys[k].morphTargets.length; m++) {
  22885. morphTargetNames[animationKeys[k].morphTargets[m]] = -1;
  22886. }
  22887. }
  22888. } // create a track for each morph target with all zero
  22889. // morphTargetInfluences except for the keys in which
  22890. // the morphTarget is named.
  22891. for (const morphTargetName in morphTargetNames) {
  22892. const times = [];
  22893. const values = [];
  22894. for (let m = 0; m !== animationKeys[k].morphTargets.length; ++m) {
  22895. const animationKey = animationKeys[k];
  22896. times.push(animationKey.time);
  22897. values.push(animationKey.morphTarget === morphTargetName ? 1 : 0);
  22898. }
  22899. tracks.push(new NumberKeyframeTrack('.morphTargetInfluence[' + morphTargetName + ']', times, values));
  22900. }
  22901. duration = morphTargetNames.length * fps;
  22902. } else {
  22903. // ...assume skeletal animation
  22904. const boneName = '.bones[' + bones[h].name + ']';
  22905. addNonemptyTrack(VectorKeyframeTrack, boneName + '.position', animationKeys, 'pos', tracks);
  22906. addNonemptyTrack(QuaternionKeyframeTrack, boneName + '.quaternion', animationKeys, 'rot', tracks);
  22907. addNonemptyTrack(VectorKeyframeTrack, boneName + '.scale', animationKeys, 'scl', tracks);
  22908. }
  22909. }
  22910. if (tracks.length === 0) {
  22911. return null;
  22912. }
  22913. const clip = new this(clipName, duration, tracks, blendMode);
  22914. return clip;
  22915. }
  22916. resetDuration() {
  22917. const tracks = this.tracks;
  22918. let duration = 0;
  22919. for (let i = 0, n = tracks.length; i !== n; ++i) {
  22920. const track = this.tracks[i];
  22921. duration = Math.max(duration, track.times[track.times.length - 1]);
  22922. }
  22923. this.duration = duration;
  22924. return this;
  22925. }
  22926. trim() {
  22927. for (let i = 0; i < this.tracks.length; i++) {
  22928. this.tracks[i].trim(0, this.duration);
  22929. }
  22930. return this;
  22931. }
  22932. validate() {
  22933. let valid = true;
  22934. for (let i = 0; i < this.tracks.length; i++) {
  22935. valid = valid && this.tracks[i].validate();
  22936. }
  22937. return valid;
  22938. }
  22939. optimize() {
  22940. for (let i = 0; i < this.tracks.length; i++) {
  22941. this.tracks[i].optimize();
  22942. }
  22943. return this;
  22944. }
  22945. clone() {
  22946. const tracks = [];
  22947. for (let i = 0; i < this.tracks.length; i++) {
  22948. tracks.push(this.tracks[i].clone());
  22949. }
  22950. return new this.constructor(this.name, this.duration, tracks, this.blendMode);
  22951. }
  22952. toJSON() {
  22953. return this.constructor.toJSON(this);
  22954. }
  22955. }
  22956. function getTrackTypeForValueTypeName(typeName) {
  22957. switch (typeName.toLowerCase()) {
  22958. case 'scalar':
  22959. case 'double':
  22960. case 'float':
  22961. case 'number':
  22962. case 'integer':
  22963. return NumberKeyframeTrack;
  22964. case 'vector':
  22965. case 'vector2':
  22966. case 'vector3':
  22967. case 'vector4':
  22968. return VectorKeyframeTrack;
  22969. case 'color':
  22970. return ColorKeyframeTrack;
  22971. case 'quaternion':
  22972. return QuaternionKeyframeTrack;
  22973. case 'bool':
  22974. case 'boolean':
  22975. return BooleanKeyframeTrack;
  22976. case 'string':
  22977. return StringKeyframeTrack;
  22978. }
  22979. throw new Error('THREE.KeyframeTrack: Unsupported typeName: ' + typeName);
  22980. }
  22981. function parseKeyframeTrack(json) {
  22982. if (json.type === undefined) {
  22983. throw new Error('THREE.KeyframeTrack: track type undefined, can not parse');
  22984. }
  22985. const trackType = getTrackTypeForValueTypeName(json.type);
  22986. if (json.times === undefined) {
  22987. const times = [],
  22988. values = [];
  22989. flattenJSON(json.keys, times, values, 'value');
  22990. json.times = times;
  22991. json.values = values;
  22992. } // derived classes can define a static parse method
  22993. if (trackType.parse !== undefined) {
  22994. return trackType.parse(json);
  22995. } else {
  22996. // by default, we assume a constructor compatible with the base
  22997. return new trackType(json.name, json.times, json.values, json.interpolation);
  22998. }
  22999. }
  23000. const Cache = {
  23001. enabled: false,
  23002. files: {},
  23003. add: function (key, file) {
  23004. if (this.enabled === false) return; // console.log( 'THREE.Cache', 'Adding key:', key );
  23005. this.files[key] = file;
  23006. },
  23007. get: function (key) {
  23008. if (this.enabled === false) return; // console.log( 'THREE.Cache', 'Checking key:', key );
  23009. return this.files[key];
  23010. },
  23011. remove: function (key) {
  23012. delete this.files[key];
  23013. },
  23014. clear: function () {
  23015. this.files = {};
  23016. }
  23017. };
  23018. class LoadingManager {
  23019. constructor(onLoad, onProgress, onError) {
  23020. const scope = this;
  23021. let isLoading = false;
  23022. let itemsLoaded = 0;
  23023. let itemsTotal = 0;
  23024. let urlModifier = undefined;
  23025. const handlers = []; // Refer to #5689 for the reason why we don't set .onStart
  23026. // in the constructor
  23027. this.onStart = undefined;
  23028. this.onLoad = onLoad;
  23029. this.onProgress = onProgress;
  23030. this.onError = onError;
  23031. this.itemStart = function (url) {
  23032. itemsTotal++;
  23033. if (isLoading === false) {
  23034. if (scope.onStart !== undefined) {
  23035. scope.onStart(url, itemsLoaded, itemsTotal);
  23036. }
  23037. }
  23038. isLoading = true;
  23039. };
  23040. this.itemEnd = function (url) {
  23041. itemsLoaded++;
  23042. if (scope.onProgress !== undefined) {
  23043. scope.onProgress(url, itemsLoaded, itemsTotal);
  23044. }
  23045. if (itemsLoaded === itemsTotal) {
  23046. isLoading = false;
  23047. if (scope.onLoad !== undefined) {
  23048. scope.onLoad();
  23049. }
  23050. }
  23051. };
  23052. this.itemError = function (url) {
  23053. if (scope.onError !== undefined) {
  23054. scope.onError(url);
  23055. }
  23056. };
  23057. this.resolveURL = function (url) {
  23058. if (urlModifier) {
  23059. return urlModifier(url);
  23060. }
  23061. return url;
  23062. };
  23063. this.setURLModifier = function (transform) {
  23064. urlModifier = transform;
  23065. return this;
  23066. };
  23067. this.addHandler = function (regex, loader) {
  23068. handlers.push(regex, loader);
  23069. return this;
  23070. };
  23071. this.removeHandler = function (regex) {
  23072. const index = handlers.indexOf(regex);
  23073. if (index !== -1) {
  23074. handlers.splice(index, 2);
  23075. }
  23076. return this;
  23077. };
  23078. this.getHandler = function (file) {
  23079. for (let i = 0, l = handlers.length; i < l; i += 2) {
  23080. const regex = handlers[i];
  23081. const loader = handlers[i + 1];
  23082. if (regex.global) regex.lastIndex = 0; // see #17920
  23083. if (regex.test(file)) {
  23084. return loader;
  23085. }
  23086. }
  23087. return null;
  23088. };
  23089. }
  23090. }
  23091. const DefaultLoadingManager = /*@__PURE__*/new LoadingManager();
  23092. class Loader {
  23093. constructor(manager) {
  23094. this.manager = manager !== undefined ? manager : DefaultLoadingManager;
  23095. this.crossOrigin = 'anonymous';
  23096. this.withCredentials = false;
  23097. this.path = '';
  23098. this.resourcePath = '';
  23099. this.requestHeader = {};
  23100. }
  23101. load() {}
  23102. loadAsync(url, onProgress) {
  23103. const scope = this;
  23104. return new Promise(function (resolve, reject) {
  23105. scope.load(url, resolve, onProgress, reject);
  23106. });
  23107. }
  23108. parse() {}
  23109. setCrossOrigin(crossOrigin) {
  23110. this.crossOrigin = crossOrigin;
  23111. return this;
  23112. }
  23113. setWithCredentials(value) {
  23114. this.withCredentials = value;
  23115. return this;
  23116. }
  23117. setPath(path) {
  23118. this.path = path;
  23119. return this;
  23120. }
  23121. setResourcePath(resourcePath) {
  23122. this.resourcePath = resourcePath;
  23123. return this;
  23124. }
  23125. setRequestHeader(requestHeader) {
  23126. this.requestHeader = requestHeader;
  23127. return this;
  23128. }
  23129. }
  23130. const loading = {};
  23131. class HttpError extends Error {
  23132. constructor(message, response) {
  23133. super(message);
  23134. this.response = response;
  23135. }
  23136. }
  23137. class FileLoader extends Loader {
  23138. constructor(manager) {
  23139. super(manager);
  23140. }
  23141. load(url, onLoad, onProgress, onError) {
  23142. if (url === undefined) url = '';
  23143. if (this.path !== undefined) url = this.path + url;
  23144. url = this.manager.resolveURL(url);
  23145. const cached = Cache.get(url);
  23146. if (cached !== undefined) {
  23147. this.manager.itemStart(url);
  23148. setTimeout(() => {
  23149. if (onLoad) onLoad(cached);
  23150. this.manager.itemEnd(url);
  23151. }, 0);
  23152. return cached;
  23153. } // Check if request is duplicate
  23154. if (loading[url] !== undefined) {
  23155. loading[url].push({
  23156. onLoad: onLoad,
  23157. onProgress: onProgress,
  23158. onError: onError
  23159. });
  23160. return;
  23161. } // Initialise array for duplicate requests
  23162. loading[url] = [];
  23163. loading[url].push({
  23164. onLoad: onLoad,
  23165. onProgress: onProgress,
  23166. onError: onError
  23167. }); // create request
  23168. const req = new Request(url, {
  23169. headers: new Headers(this.requestHeader),
  23170. credentials: this.withCredentials ? 'include' : 'same-origin' // An abort controller could be added within a future PR
  23171. }); // record states ( avoid data race )
  23172. const mimeType = this.mimeType;
  23173. const responseType = this.responseType; // start the fetch
  23174. fetch(req).then(response => {
  23175. if (response.status === 200 || response.status === 0) {
  23176. // Some browsers return HTTP Status 0 when using non-http protocol
  23177. // e.g. 'file://' or 'data://'. Handle as success.
  23178. if (response.status === 0) {
  23179. console.warn('THREE.FileLoader: HTTP Status 0 received.');
  23180. } // Workaround: Checking if response.body === undefined for Alipay browser #23548
  23181. if (typeof ReadableStream === 'undefined' || response.body === undefined || response.body.getReader === undefined) {
  23182. return response;
  23183. }
  23184. const callbacks = loading[url];
  23185. const reader = response.body.getReader();
  23186. const contentLength = response.headers.get('Content-Length');
  23187. const total = contentLength ? parseInt(contentLength) : 0;
  23188. const lengthComputable = total !== 0;
  23189. let loaded = 0; // periodically read data into the new stream tracking while download progress
  23190. const stream = new ReadableStream({
  23191. start(controller) {
  23192. readData();
  23193. function readData() {
  23194. reader.read().then(({
  23195. done,
  23196. value
  23197. }) => {
  23198. if (done) {
  23199. controller.close();
  23200. } else {
  23201. loaded += value.byteLength;
  23202. const event = new ProgressEvent('progress', {
  23203. lengthComputable,
  23204. loaded,
  23205. total
  23206. });
  23207. for (let i = 0, il = callbacks.length; i < il; i++) {
  23208. const callback = callbacks[i];
  23209. if (callback.onProgress) callback.onProgress(event);
  23210. }
  23211. controller.enqueue(value);
  23212. readData();
  23213. }
  23214. });
  23215. }
  23216. }
  23217. });
  23218. return new Response(stream);
  23219. } else {
  23220. throw new HttpError(`fetch for "${response.url}" responded with ${response.status}: ${response.statusText}`, response);
  23221. }
  23222. }).then(response => {
  23223. switch (responseType) {
  23224. case 'arraybuffer':
  23225. return response.arrayBuffer();
  23226. case 'blob':
  23227. return response.blob();
  23228. case 'document':
  23229. return response.text().then(text => {
  23230. const parser = new DOMParser();
  23231. return parser.parseFromString(text, mimeType);
  23232. });
  23233. case 'json':
  23234. return response.json();
  23235. default:
  23236. if (mimeType === undefined) {
  23237. return response.text();
  23238. } else {
  23239. // sniff encoding
  23240. const re = /charset="?([^;"\s]*)"?/i;
  23241. const exec = re.exec(mimeType);
  23242. const label = exec && exec[1] ? exec[1].toLowerCase() : undefined;
  23243. const decoder = new TextDecoder(label);
  23244. return response.arrayBuffer().then(ab => decoder.decode(ab));
  23245. }
  23246. }
  23247. }).then(data => {
  23248. // Add to cache only on HTTP success, so that we do not cache
  23249. // error response bodies as proper responses to requests.
  23250. Cache.add(url, data);
  23251. const callbacks = loading[url];
  23252. delete loading[url];
  23253. for (let i = 0, il = callbacks.length; i < il; i++) {
  23254. const callback = callbacks[i];
  23255. if (callback.onLoad) callback.onLoad(data);
  23256. }
  23257. }).catch(err => {
  23258. // Abort errors and other errors are handled the same
  23259. const callbacks = loading[url];
  23260. if (callbacks === undefined) {
  23261. // When onLoad was called and url was deleted in `loading`
  23262. this.manager.itemError(url);
  23263. throw err;
  23264. }
  23265. delete loading[url];
  23266. for (let i = 0, il = callbacks.length; i < il; i++) {
  23267. const callback = callbacks[i];
  23268. if (callback.onError) callback.onError(err);
  23269. }
  23270. this.manager.itemError(url);
  23271. }).finally(() => {
  23272. this.manager.itemEnd(url);
  23273. });
  23274. this.manager.itemStart(url);
  23275. }
  23276. setResponseType(value) {
  23277. this.responseType = value;
  23278. return this;
  23279. }
  23280. setMimeType(value) {
  23281. this.mimeType = value;
  23282. return this;
  23283. }
  23284. }
  23285. class AnimationLoader extends Loader {
  23286. constructor(manager) {
  23287. super(manager);
  23288. }
  23289. load(url, onLoad, onProgress, onError) {
  23290. const scope = this;
  23291. const loader = new FileLoader(this.manager);
  23292. loader.setPath(this.path);
  23293. loader.setRequestHeader(this.requestHeader);
  23294. loader.setWithCredentials(this.withCredentials);
  23295. loader.load(url, function (text) {
  23296. try {
  23297. onLoad(scope.parse(JSON.parse(text)));
  23298. } catch (e) {
  23299. if (onError) {
  23300. onError(e);
  23301. } else {
  23302. console.error(e);
  23303. }
  23304. scope.manager.itemError(url);
  23305. }
  23306. }, onProgress, onError);
  23307. }
  23308. parse(json) {
  23309. const animations = [];
  23310. for (let i = 0; i < json.length; i++) {
  23311. const clip = AnimationClip.parse(json[i]);
  23312. animations.push(clip);
  23313. }
  23314. return animations;
  23315. }
  23316. }
  23317. /**
  23318. * Abstract Base class to block based textures loader (dds, pvr, ...)
  23319. *
  23320. * Sub classes have to implement the parse() method which will be used in load().
  23321. */
  23322. class CompressedTextureLoader extends Loader {
  23323. constructor(manager) {
  23324. super(manager);
  23325. }
  23326. load(url, onLoad, onProgress, onError) {
  23327. const scope = this;
  23328. const images = [];
  23329. const texture = new CompressedTexture();
  23330. const loader = new FileLoader(this.manager);
  23331. loader.setPath(this.path);
  23332. loader.setResponseType('arraybuffer');
  23333. loader.setRequestHeader(this.requestHeader);
  23334. loader.setWithCredentials(scope.withCredentials);
  23335. let loaded = 0;
  23336. function loadTexture(i) {
  23337. loader.load(url[i], function (buffer) {
  23338. const texDatas = scope.parse(buffer, true);
  23339. images[i] = {
  23340. width: texDatas.width,
  23341. height: texDatas.height,
  23342. format: texDatas.format,
  23343. mipmaps: texDatas.mipmaps
  23344. };
  23345. loaded += 1;
  23346. if (loaded === 6) {
  23347. if (texDatas.mipmapCount === 1) texture.minFilter = LinearFilter;
  23348. texture.image = images;
  23349. texture.format = texDatas.format;
  23350. texture.needsUpdate = true;
  23351. if (onLoad) onLoad(texture);
  23352. }
  23353. }, onProgress, onError);
  23354. }
  23355. if (Array.isArray(url)) {
  23356. for (let i = 0, il = url.length; i < il; ++i) {
  23357. loadTexture(i);
  23358. }
  23359. } else {
  23360. // compressed cubemap texture stored in a single DDS file
  23361. loader.load(url, function (buffer) {
  23362. const texDatas = scope.parse(buffer, true);
  23363. if (texDatas.isCubemap) {
  23364. const faces = texDatas.mipmaps.length / texDatas.mipmapCount;
  23365. for (let f = 0; f < faces; f++) {
  23366. images[f] = {
  23367. mipmaps: []
  23368. };
  23369. for (let i = 0; i < texDatas.mipmapCount; i++) {
  23370. images[f].mipmaps.push(texDatas.mipmaps[f * texDatas.mipmapCount + i]);
  23371. images[f].format = texDatas.format;
  23372. images[f].width = texDatas.width;
  23373. images[f].height = texDatas.height;
  23374. }
  23375. }
  23376. texture.image = images;
  23377. } else {
  23378. texture.image.width = texDatas.width;
  23379. texture.image.height = texDatas.height;
  23380. texture.mipmaps = texDatas.mipmaps;
  23381. }
  23382. if (texDatas.mipmapCount === 1) {
  23383. texture.minFilter = LinearFilter;
  23384. }
  23385. texture.format = texDatas.format;
  23386. texture.needsUpdate = true;
  23387. if (onLoad) onLoad(texture);
  23388. }, onProgress, onError);
  23389. }
  23390. return texture;
  23391. }
  23392. }
  23393. class ImageLoader extends Loader {
  23394. constructor(manager) {
  23395. super(manager);
  23396. }
  23397. load(url, onLoad, onProgress, onError) {
  23398. if (this.path !== undefined) url = this.path + url;
  23399. url = this.manager.resolveURL(url);
  23400. const scope = this;
  23401. const cached = Cache.get(url);
  23402. if (cached !== undefined) {
  23403. scope.manager.itemStart(url);
  23404. setTimeout(function () {
  23405. if (onLoad) onLoad(cached);
  23406. scope.manager.itemEnd(url);
  23407. }, 0);
  23408. return cached;
  23409. }
  23410. const image = createElementNS('img');
  23411. function onImageLoad() {
  23412. removeEventListeners();
  23413. Cache.add(url, this);
  23414. if (onLoad) onLoad(this);
  23415. scope.manager.itemEnd(url);
  23416. }
  23417. function onImageError(event) {
  23418. removeEventListeners();
  23419. if (onError) onError(event);
  23420. scope.manager.itemError(url);
  23421. scope.manager.itemEnd(url);
  23422. }
  23423. function removeEventListeners() {
  23424. image.removeEventListener('load', onImageLoad, false);
  23425. image.removeEventListener('error', onImageError, false);
  23426. }
  23427. image.addEventListener('load', onImageLoad, false);
  23428. image.addEventListener('error', onImageError, false);
  23429. if (url.slice(0, 5) !== 'data:') {
  23430. if (this.crossOrigin !== undefined) image.crossOrigin = this.crossOrigin;
  23431. }
  23432. scope.manager.itemStart(url);
  23433. image.src = url;
  23434. return image;
  23435. }
  23436. }
  23437. class CubeTextureLoader extends Loader {
  23438. constructor(manager) {
  23439. super(manager);
  23440. }
  23441. load(urls, onLoad, onProgress, onError) {
  23442. const texture = new CubeTexture();
  23443. const loader = new ImageLoader(this.manager);
  23444. loader.setCrossOrigin(this.crossOrigin);
  23445. loader.setPath(this.path);
  23446. let loaded = 0;
  23447. function loadTexture(i) {
  23448. loader.load(urls[i], function (image) {
  23449. texture.images[i] = image;
  23450. loaded++;
  23451. if (loaded === 6) {
  23452. texture.needsUpdate = true;
  23453. if (onLoad) onLoad(texture);
  23454. }
  23455. }, undefined, onError);
  23456. }
  23457. for (let i = 0; i < urls.length; ++i) {
  23458. loadTexture(i);
  23459. }
  23460. return texture;
  23461. }
  23462. }
  23463. /**
  23464. * Abstract Base class to load generic binary textures formats (rgbe, hdr, ...)
  23465. *
  23466. * Sub classes have to implement the parse() method which will be used in load().
  23467. */
  23468. class DataTextureLoader extends Loader {
  23469. constructor(manager) {
  23470. super(manager);
  23471. }
  23472. load(url, onLoad, onProgress, onError) {
  23473. const scope = this;
  23474. const texture = new DataTexture();
  23475. const loader = new FileLoader(this.manager);
  23476. loader.setResponseType('arraybuffer');
  23477. loader.setRequestHeader(this.requestHeader);
  23478. loader.setPath(this.path);
  23479. loader.setWithCredentials(scope.withCredentials);
  23480. loader.load(url, function (buffer) {
  23481. const texData = scope.parse(buffer);
  23482. if (!texData) return;
  23483. if (texData.image !== undefined) {
  23484. texture.image = texData.image;
  23485. } else if (texData.data !== undefined) {
  23486. texture.image.width = texData.width;
  23487. texture.image.height = texData.height;
  23488. texture.image.data = texData.data;
  23489. }
  23490. texture.wrapS = texData.wrapS !== undefined ? texData.wrapS : ClampToEdgeWrapping;
  23491. texture.wrapT = texData.wrapT !== undefined ? texData.wrapT : ClampToEdgeWrapping;
  23492. texture.magFilter = texData.magFilter !== undefined ? texData.magFilter : LinearFilter;
  23493. texture.minFilter = texData.minFilter !== undefined ? texData.minFilter : LinearFilter;
  23494. texture.anisotropy = texData.anisotropy !== undefined ? texData.anisotropy : 1;
  23495. if (texData.encoding !== undefined) {
  23496. texture.encoding = texData.encoding;
  23497. }
  23498. if (texData.flipY !== undefined) {
  23499. texture.flipY = texData.flipY;
  23500. }
  23501. if (texData.format !== undefined) {
  23502. texture.format = texData.format;
  23503. }
  23504. if (texData.type !== undefined) {
  23505. texture.type = texData.type;
  23506. }
  23507. if (texData.mipmaps !== undefined) {
  23508. texture.mipmaps = texData.mipmaps;
  23509. texture.minFilter = LinearMipmapLinearFilter; // presumably...
  23510. }
  23511. if (texData.mipmapCount === 1) {
  23512. texture.minFilter = LinearFilter;
  23513. }
  23514. if (texData.generateMipmaps !== undefined) {
  23515. texture.generateMipmaps = texData.generateMipmaps;
  23516. }
  23517. texture.needsUpdate = true;
  23518. if (onLoad) onLoad(texture, texData);
  23519. }, onProgress, onError);
  23520. return texture;
  23521. }
  23522. }
  23523. class TextureLoader extends Loader {
  23524. constructor(manager) {
  23525. super(manager);
  23526. }
  23527. load(url, onLoad, onProgress, onError) {
  23528. const texture = new Texture();
  23529. const loader = new ImageLoader(this.manager);
  23530. loader.setCrossOrigin(this.crossOrigin);
  23531. loader.setPath(this.path);
  23532. loader.load(url, function (image) {
  23533. texture.image = image;
  23534. texture.needsUpdate = true;
  23535. if (onLoad !== undefined) {
  23536. onLoad(texture);
  23537. }
  23538. }, onProgress, onError);
  23539. return texture;
  23540. }
  23541. }
  23542. class Light extends Object3D {
  23543. constructor(color, intensity = 1) {
  23544. super();
  23545. this.isLight = true;
  23546. this.type = 'Light';
  23547. this.color = new Color(color);
  23548. this.intensity = intensity;
  23549. }
  23550. dispose() {// Empty here in base class; some subclasses override.
  23551. }
  23552. copy(source, recursive) {
  23553. super.copy(source, recursive);
  23554. this.color.copy(source.color);
  23555. this.intensity = source.intensity;
  23556. return this;
  23557. }
  23558. toJSON(meta) {
  23559. const data = super.toJSON(meta);
  23560. data.object.color = this.color.getHex();
  23561. data.object.intensity = this.intensity;
  23562. if (this.groundColor !== undefined) data.object.groundColor = this.groundColor.getHex();
  23563. if (this.distance !== undefined) data.object.distance = this.distance;
  23564. if (this.angle !== undefined) data.object.angle = this.angle;
  23565. if (this.decay !== undefined) data.object.decay = this.decay;
  23566. if (this.penumbra !== undefined) data.object.penumbra = this.penumbra;
  23567. if (this.shadow !== undefined) data.object.shadow = this.shadow.toJSON();
  23568. return data;
  23569. }
  23570. }
  23571. class HemisphereLight extends Light {
  23572. constructor(skyColor, groundColor, intensity) {
  23573. super(skyColor, intensity);
  23574. this.isHemisphereLight = true;
  23575. this.type = 'HemisphereLight';
  23576. this.position.copy(Object3D.DefaultUp);
  23577. this.updateMatrix();
  23578. this.groundColor = new Color(groundColor);
  23579. }
  23580. copy(source, recursive) {
  23581. super.copy(source, recursive);
  23582. this.groundColor.copy(source.groundColor);
  23583. return this;
  23584. }
  23585. }
  23586. const _projScreenMatrix$1 = /*@__PURE__*/new Matrix4();
  23587. const _lightPositionWorld$1 = /*@__PURE__*/new Vector3();
  23588. const _lookTarget$1 = /*@__PURE__*/new Vector3();
  23589. class LightShadow {
  23590. constructor(camera) {
  23591. this.camera = camera;
  23592. this.bias = 0;
  23593. this.normalBias = 0;
  23594. this.radius = 1;
  23595. this.blurSamples = 8;
  23596. this.mapSize = new Vector2(512, 512);
  23597. this.map = null;
  23598. this.mapPass = null;
  23599. this.matrix = new Matrix4();
  23600. this.autoUpdate = true;
  23601. this.needsUpdate = false;
  23602. this._frustum = new Frustum();
  23603. this._frameExtents = new Vector2(1, 1);
  23604. this._viewportCount = 1;
  23605. this._viewports = [new Vector4(0, 0, 1, 1)];
  23606. }
  23607. getViewportCount() {
  23608. return this._viewportCount;
  23609. }
  23610. getFrustum() {
  23611. return this._frustum;
  23612. }
  23613. updateMatrices(light) {
  23614. const shadowCamera = this.camera;
  23615. const shadowMatrix = this.matrix;
  23616. _lightPositionWorld$1.setFromMatrixPosition(light.matrixWorld);
  23617. shadowCamera.position.copy(_lightPositionWorld$1);
  23618. _lookTarget$1.setFromMatrixPosition(light.target.matrixWorld);
  23619. shadowCamera.lookAt(_lookTarget$1);
  23620. shadowCamera.updateMatrixWorld();
  23621. _projScreenMatrix$1.multiplyMatrices(shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse);
  23622. this._frustum.setFromProjectionMatrix(_projScreenMatrix$1);
  23623. 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);
  23624. shadowMatrix.multiply(_projScreenMatrix$1);
  23625. }
  23626. getViewport(viewportIndex) {
  23627. return this._viewports[viewportIndex];
  23628. }
  23629. getFrameExtents() {
  23630. return this._frameExtents;
  23631. }
  23632. dispose() {
  23633. if (this.map) {
  23634. this.map.dispose();
  23635. }
  23636. if (this.mapPass) {
  23637. this.mapPass.dispose();
  23638. }
  23639. }
  23640. copy(source) {
  23641. this.camera = source.camera.clone();
  23642. this.bias = source.bias;
  23643. this.radius = source.radius;
  23644. this.mapSize.copy(source.mapSize);
  23645. return this;
  23646. }
  23647. clone() {
  23648. return new this.constructor().copy(this);
  23649. }
  23650. toJSON() {
  23651. const object = {};
  23652. if (this.bias !== 0) object.bias = this.bias;
  23653. if (this.normalBias !== 0) object.normalBias = this.normalBias;
  23654. if (this.radius !== 1) object.radius = this.radius;
  23655. if (this.mapSize.x !== 512 || this.mapSize.y !== 512) object.mapSize = this.mapSize.toArray();
  23656. object.camera = this.camera.toJSON(false).object;
  23657. delete object.camera.matrix;
  23658. return object;
  23659. }
  23660. }
  23661. class SpotLightShadow extends LightShadow {
  23662. constructor() {
  23663. super(new PerspectiveCamera(50, 1, 0.5, 500));
  23664. this.isSpotLightShadow = true;
  23665. this.focus = 1;
  23666. }
  23667. updateMatrices(light) {
  23668. const camera = this.camera;
  23669. const fov = RAD2DEG * 2 * light.angle * this.focus;
  23670. const aspect = this.mapSize.width / this.mapSize.height;
  23671. const far = light.distance || camera.far;
  23672. if (fov !== camera.fov || aspect !== camera.aspect || far !== camera.far) {
  23673. camera.fov = fov;
  23674. camera.aspect = aspect;
  23675. camera.far = far;
  23676. camera.updateProjectionMatrix();
  23677. }
  23678. super.updateMatrices(light);
  23679. }
  23680. copy(source) {
  23681. super.copy(source);
  23682. this.focus = source.focus;
  23683. return this;
  23684. }
  23685. }
  23686. class SpotLight extends Light {
  23687. constructor(color, intensity, distance = 0, angle = Math.PI / 3, penumbra = 0, decay = 1) {
  23688. super(color, intensity);
  23689. this.isSpotLight = true;
  23690. this.type = 'SpotLight';
  23691. this.position.copy(Object3D.DefaultUp);
  23692. this.updateMatrix();
  23693. this.target = new Object3D();
  23694. this.distance = distance;
  23695. this.angle = angle;
  23696. this.penumbra = penumbra;
  23697. this.decay = decay; // for physically correct lights, should be 2.
  23698. this.map = null;
  23699. this.shadow = new SpotLightShadow();
  23700. }
  23701. get power() {
  23702. // compute the light's luminous power (in lumens) from its intensity (in candela)
  23703. // by convention for a spotlight, luminous power (lm) = π * luminous intensity (cd)
  23704. return this.intensity * Math.PI;
  23705. }
  23706. set power(power) {
  23707. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  23708. this.intensity = power / Math.PI;
  23709. }
  23710. dispose() {
  23711. this.shadow.dispose();
  23712. }
  23713. copy(source, recursive) {
  23714. super.copy(source, recursive);
  23715. this.distance = source.distance;
  23716. this.angle = source.angle;
  23717. this.penumbra = source.penumbra;
  23718. this.decay = source.decay;
  23719. this.target = source.target.clone();
  23720. this.shadow = source.shadow.clone();
  23721. return this;
  23722. }
  23723. }
  23724. const _projScreenMatrix = /*@__PURE__*/new Matrix4();
  23725. const _lightPositionWorld = /*@__PURE__*/new Vector3();
  23726. const _lookTarget = /*@__PURE__*/new Vector3();
  23727. class PointLightShadow extends LightShadow {
  23728. constructor() {
  23729. super(new PerspectiveCamera(90, 1, 0.5, 500));
  23730. this.isPointLightShadow = true;
  23731. this._frameExtents = new Vector2(4, 2);
  23732. this._viewportCount = 6;
  23733. this._viewports = [// These viewports map a cube-map onto a 2D texture with the
  23734. // following orientation:
  23735. //
  23736. // xzXZ
  23737. // y Y
  23738. //
  23739. // X - Positive x direction
  23740. // x - Negative x direction
  23741. // Y - Positive y direction
  23742. // y - Negative y direction
  23743. // Z - Positive z direction
  23744. // z - Negative z direction
  23745. // positive X
  23746. new Vector4(2, 1, 1, 1), // negative X
  23747. new Vector4(0, 1, 1, 1), // positive Z
  23748. new Vector4(3, 1, 1, 1), // negative Z
  23749. new Vector4(1, 1, 1, 1), // positive Y
  23750. new Vector4(3, 0, 1, 1), // negative Y
  23751. new Vector4(1, 0, 1, 1)];
  23752. 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)];
  23753. 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)];
  23754. }
  23755. updateMatrices(light, viewportIndex = 0) {
  23756. const camera = this.camera;
  23757. const shadowMatrix = this.matrix;
  23758. const far = light.distance || camera.far;
  23759. if (far !== camera.far) {
  23760. camera.far = far;
  23761. camera.updateProjectionMatrix();
  23762. }
  23763. _lightPositionWorld.setFromMatrixPosition(light.matrixWorld);
  23764. camera.position.copy(_lightPositionWorld);
  23765. _lookTarget.copy(camera.position);
  23766. _lookTarget.add(this._cubeDirections[viewportIndex]);
  23767. camera.up.copy(this._cubeUps[viewportIndex]);
  23768. camera.lookAt(_lookTarget);
  23769. camera.updateMatrixWorld();
  23770. shadowMatrix.makeTranslation(-_lightPositionWorld.x, -_lightPositionWorld.y, -_lightPositionWorld.z);
  23771. _projScreenMatrix.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse);
  23772. this._frustum.setFromProjectionMatrix(_projScreenMatrix);
  23773. }
  23774. }
  23775. class PointLight extends Light {
  23776. constructor(color, intensity, distance = 0, decay = 1) {
  23777. super(color, intensity);
  23778. this.isPointLight = true;
  23779. this.type = 'PointLight';
  23780. this.distance = distance;
  23781. this.decay = decay; // for physically correct lights, should be 2.
  23782. this.shadow = new PointLightShadow();
  23783. }
  23784. get power() {
  23785. // compute the light's luminous power (in lumens) from its intensity (in candela)
  23786. // for an isotropic light source, luminous power (lm) = 4 π luminous intensity (cd)
  23787. return this.intensity * 4 * Math.PI;
  23788. }
  23789. set power(power) {
  23790. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  23791. this.intensity = power / (4 * Math.PI);
  23792. }
  23793. dispose() {
  23794. this.shadow.dispose();
  23795. }
  23796. copy(source, recursive) {
  23797. super.copy(source, recursive);
  23798. this.distance = source.distance;
  23799. this.decay = source.decay;
  23800. this.shadow = source.shadow.clone();
  23801. return this;
  23802. }
  23803. }
  23804. class DirectionalLightShadow extends LightShadow {
  23805. constructor() {
  23806. super(new OrthographicCamera(-5, 5, 5, -5, 0.5, 500));
  23807. this.isDirectionalLightShadow = true;
  23808. }
  23809. }
  23810. class DirectionalLight extends Light {
  23811. constructor(color, intensity) {
  23812. super(color, intensity);
  23813. this.isDirectionalLight = true;
  23814. this.type = 'DirectionalLight';
  23815. this.position.copy(Object3D.DefaultUp);
  23816. this.updateMatrix();
  23817. this.target = new Object3D();
  23818. this.shadow = new DirectionalLightShadow();
  23819. }
  23820. dispose() {
  23821. this.shadow.dispose();
  23822. }
  23823. copy(source) {
  23824. super.copy(source);
  23825. this.target = source.target.clone();
  23826. this.shadow = source.shadow.clone();
  23827. return this;
  23828. }
  23829. }
  23830. class AmbientLight extends Light {
  23831. constructor(color, intensity) {
  23832. super(color, intensity);
  23833. this.isAmbientLight = true;
  23834. this.type = 'AmbientLight';
  23835. }
  23836. }
  23837. class RectAreaLight extends Light {
  23838. constructor(color, intensity, width = 10, height = 10) {
  23839. super(color, intensity);
  23840. this.isRectAreaLight = true;
  23841. this.type = 'RectAreaLight';
  23842. this.width = width;
  23843. this.height = height;
  23844. }
  23845. get power() {
  23846. // compute the light's luminous power (in lumens) from its intensity (in nits)
  23847. return this.intensity * this.width * this.height * Math.PI;
  23848. }
  23849. set power(power) {
  23850. // set the light's intensity (in nits) from the desired luminous power (in lumens)
  23851. this.intensity = power / (this.width * this.height * Math.PI);
  23852. }
  23853. copy(source) {
  23854. super.copy(source);
  23855. this.width = source.width;
  23856. this.height = source.height;
  23857. return this;
  23858. }
  23859. toJSON(meta) {
  23860. const data = super.toJSON(meta);
  23861. data.object.width = this.width;
  23862. data.object.height = this.height;
  23863. return data;
  23864. }
  23865. }
  23866. /**
  23867. * Primary reference:
  23868. * https://graphics.stanford.edu/papers/envmap/envmap.pdf
  23869. *
  23870. * Secondary reference:
  23871. * https://www.ppsloan.org/publications/StupidSH36.pdf
  23872. */
  23873. // 3-band SH defined by 9 coefficients
  23874. class SphericalHarmonics3 {
  23875. constructor() {
  23876. this.isSphericalHarmonics3 = true;
  23877. this.coefficients = [];
  23878. for (let i = 0; i < 9; i++) {
  23879. this.coefficients.push(new Vector3());
  23880. }
  23881. }
  23882. set(coefficients) {
  23883. for (let i = 0; i < 9; i++) {
  23884. this.coefficients[i].copy(coefficients[i]);
  23885. }
  23886. return this;
  23887. }
  23888. zero() {
  23889. for (let i = 0; i < 9; i++) {
  23890. this.coefficients[i].set(0, 0, 0);
  23891. }
  23892. return this;
  23893. } // get the radiance in the direction of the normal
  23894. // target is a Vector3
  23895. getAt(normal, target) {
  23896. // normal is assumed to be unit length
  23897. const x = normal.x,
  23898. y = normal.y,
  23899. z = normal.z;
  23900. const coeff = this.coefficients; // band 0
  23901. target.copy(coeff[0]).multiplyScalar(0.282095); // band 1
  23902. target.addScaledVector(coeff[1], 0.488603 * y);
  23903. target.addScaledVector(coeff[2], 0.488603 * z);
  23904. target.addScaledVector(coeff[3], 0.488603 * x); // band 2
  23905. target.addScaledVector(coeff[4], 1.092548 * (x * y));
  23906. target.addScaledVector(coeff[5], 1.092548 * (y * z));
  23907. target.addScaledVector(coeff[6], 0.315392 * (3.0 * z * z - 1.0));
  23908. target.addScaledVector(coeff[7], 1.092548 * (x * z));
  23909. target.addScaledVector(coeff[8], 0.546274 * (x * x - y * y));
  23910. return target;
  23911. } // get the irradiance (radiance convolved with cosine lobe) in the direction of the normal
  23912. // target is a Vector3
  23913. // https://graphics.stanford.edu/papers/envmap/envmap.pdf
  23914. getIrradianceAt(normal, target) {
  23915. // normal is assumed to be unit length
  23916. const x = normal.x,
  23917. y = normal.y,
  23918. z = normal.z;
  23919. const coeff = this.coefficients; // band 0
  23920. target.copy(coeff[0]).multiplyScalar(0.886227); // π * 0.282095
  23921. // band 1
  23922. target.addScaledVector(coeff[1], 2.0 * 0.511664 * y); // ( 2 * π / 3 ) * 0.488603
  23923. target.addScaledVector(coeff[2], 2.0 * 0.511664 * z);
  23924. target.addScaledVector(coeff[3], 2.0 * 0.511664 * x); // band 2
  23925. target.addScaledVector(coeff[4], 2.0 * 0.429043 * x * y); // ( π / 4 ) * 1.092548
  23926. target.addScaledVector(coeff[5], 2.0 * 0.429043 * y * z);
  23927. target.addScaledVector(coeff[6], 0.743125 * z * z - 0.247708); // ( π / 4 ) * 0.315392 * 3
  23928. target.addScaledVector(coeff[7], 2.0 * 0.429043 * x * z);
  23929. target.addScaledVector(coeff[8], 0.429043 * (x * x - y * y)); // ( π / 4 ) * 0.546274
  23930. return target;
  23931. }
  23932. add(sh) {
  23933. for (let i = 0; i < 9; i++) {
  23934. this.coefficients[i].add(sh.coefficients[i]);
  23935. }
  23936. return this;
  23937. }
  23938. addScaledSH(sh, s) {
  23939. for (let i = 0; i < 9; i++) {
  23940. this.coefficients[i].addScaledVector(sh.coefficients[i], s);
  23941. }
  23942. return this;
  23943. }
  23944. scale(s) {
  23945. for (let i = 0; i < 9; i++) {
  23946. this.coefficients[i].multiplyScalar(s);
  23947. }
  23948. return this;
  23949. }
  23950. lerp(sh, alpha) {
  23951. for (let i = 0; i < 9; i++) {
  23952. this.coefficients[i].lerp(sh.coefficients[i], alpha);
  23953. }
  23954. return this;
  23955. }
  23956. equals(sh) {
  23957. for (let i = 0; i < 9; i++) {
  23958. if (!this.coefficients[i].equals(sh.coefficients[i])) {
  23959. return false;
  23960. }
  23961. }
  23962. return true;
  23963. }
  23964. copy(sh) {
  23965. return this.set(sh.coefficients);
  23966. }
  23967. clone() {
  23968. return new this.constructor().copy(this);
  23969. }
  23970. fromArray(array, offset = 0) {
  23971. const coefficients = this.coefficients;
  23972. for (let i = 0; i < 9; i++) {
  23973. coefficients[i].fromArray(array, offset + i * 3);
  23974. }
  23975. return this;
  23976. }
  23977. toArray(array = [], offset = 0) {
  23978. const coefficients = this.coefficients;
  23979. for (let i = 0; i < 9; i++) {
  23980. coefficients[i].toArray(array, offset + i * 3);
  23981. }
  23982. return array;
  23983. } // evaluate the basis functions
  23984. // shBasis is an Array[ 9 ]
  23985. static getBasisAt(normal, shBasis) {
  23986. // normal is assumed to be unit length
  23987. const x = normal.x,
  23988. y = normal.y,
  23989. z = normal.z; // band 0
  23990. shBasis[0] = 0.282095; // band 1
  23991. shBasis[1] = 0.488603 * y;
  23992. shBasis[2] = 0.488603 * z;
  23993. shBasis[3] = 0.488603 * x; // band 2
  23994. shBasis[4] = 1.092548 * x * y;
  23995. shBasis[5] = 1.092548 * y * z;
  23996. shBasis[6] = 0.315392 * (3 * z * z - 1);
  23997. shBasis[7] = 1.092548 * x * z;
  23998. shBasis[8] = 0.546274 * (x * x - y * y);
  23999. }
  24000. }
  24001. class LightProbe extends Light {
  24002. constructor(sh = new SphericalHarmonics3(), intensity = 1) {
  24003. super(undefined, intensity);
  24004. this.isLightProbe = true;
  24005. this.sh = sh;
  24006. }
  24007. copy(source) {
  24008. super.copy(source);
  24009. this.sh.copy(source.sh);
  24010. return this;
  24011. }
  24012. fromJSON(json) {
  24013. this.intensity = json.intensity; // TODO: Move this bit to Light.fromJSON();
  24014. this.sh.fromArray(json.sh);
  24015. return this;
  24016. }
  24017. toJSON(meta) {
  24018. const data = super.toJSON(meta);
  24019. data.object.sh = this.sh.toArray();
  24020. return data;
  24021. }
  24022. }
  24023. class MaterialLoader extends Loader {
  24024. constructor(manager) {
  24025. super(manager);
  24026. this.textures = {};
  24027. }
  24028. load(url, onLoad, onProgress, onError) {
  24029. const scope = this;
  24030. const loader = new FileLoader(scope.manager);
  24031. loader.setPath(scope.path);
  24032. loader.setRequestHeader(scope.requestHeader);
  24033. loader.setWithCredentials(scope.withCredentials);
  24034. loader.load(url, function (text) {
  24035. try {
  24036. onLoad(scope.parse(JSON.parse(text)));
  24037. } catch (e) {
  24038. if (onError) {
  24039. onError(e);
  24040. } else {
  24041. console.error(e);
  24042. }
  24043. scope.manager.itemError(url);
  24044. }
  24045. }, onProgress, onError);
  24046. }
  24047. parse(json) {
  24048. const textures = this.textures;
  24049. function getTexture(name) {
  24050. if (textures[name] === undefined) {
  24051. console.warn('THREE.MaterialLoader: Undefined texture', name);
  24052. }
  24053. return textures[name];
  24054. }
  24055. const material = MaterialLoader.createMaterialFromType(json.type);
  24056. if (json.uuid !== undefined) material.uuid = json.uuid;
  24057. if (json.name !== undefined) material.name = json.name;
  24058. if (json.color !== undefined && material.color !== undefined) material.color.setHex(json.color);
  24059. if (json.roughness !== undefined) material.roughness = json.roughness;
  24060. if (json.metalness !== undefined) material.metalness = json.metalness;
  24061. if (json.sheen !== undefined) material.sheen = json.sheen;
  24062. if (json.sheenColor !== undefined) material.sheenColor = new Color().setHex(json.sheenColor);
  24063. if (json.sheenRoughness !== undefined) material.sheenRoughness = json.sheenRoughness;
  24064. if (json.emissive !== undefined && material.emissive !== undefined) material.emissive.setHex(json.emissive);
  24065. if (json.specular !== undefined && material.specular !== undefined) material.specular.setHex(json.specular);
  24066. if (json.specularIntensity !== undefined) material.specularIntensity = json.specularIntensity;
  24067. if (json.specularColor !== undefined && material.specularColor !== undefined) material.specularColor.setHex(json.specularColor);
  24068. if (json.shininess !== undefined) material.shininess = json.shininess;
  24069. if (json.clearcoat !== undefined) material.clearcoat = json.clearcoat;
  24070. if (json.clearcoatRoughness !== undefined) material.clearcoatRoughness = json.clearcoatRoughness;
  24071. if (json.iridescence !== undefined) material.iridescence = json.iridescence;
  24072. if (json.iridescenceIOR !== undefined) material.iridescenceIOR = json.iridescenceIOR;
  24073. if (json.iridescenceThicknessRange !== undefined) material.iridescenceThicknessRange = json.iridescenceThicknessRange;
  24074. if (json.transmission !== undefined) material.transmission = json.transmission;
  24075. if (json.thickness !== undefined) material.thickness = json.thickness;
  24076. if (json.attenuationDistance !== undefined) material.attenuationDistance = json.attenuationDistance;
  24077. if (json.attenuationColor !== undefined && material.attenuationColor !== undefined) material.attenuationColor.setHex(json.attenuationColor);
  24078. if (json.fog !== undefined) material.fog = json.fog;
  24079. if (json.flatShading !== undefined) material.flatShading = json.flatShading;
  24080. if (json.blending !== undefined) material.blending = json.blending;
  24081. if (json.combine !== undefined) material.combine = json.combine;
  24082. if (json.side !== undefined) material.side = json.side;
  24083. if (json.shadowSide !== undefined) material.shadowSide = json.shadowSide;
  24084. if (json.opacity !== undefined) material.opacity = json.opacity;
  24085. if (json.transparent !== undefined) material.transparent = json.transparent;
  24086. if (json.alphaTest !== undefined) material.alphaTest = json.alphaTest;
  24087. if (json.depthTest !== undefined) material.depthTest = json.depthTest;
  24088. if (json.depthWrite !== undefined) material.depthWrite = json.depthWrite;
  24089. if (json.colorWrite !== undefined) material.colorWrite = json.colorWrite;
  24090. if (json.stencilWrite !== undefined) material.stencilWrite = json.stencilWrite;
  24091. if (json.stencilWriteMask !== undefined) material.stencilWriteMask = json.stencilWriteMask;
  24092. if (json.stencilFunc !== undefined) material.stencilFunc = json.stencilFunc;
  24093. if (json.stencilRef !== undefined) material.stencilRef = json.stencilRef;
  24094. if (json.stencilFuncMask !== undefined) material.stencilFuncMask = json.stencilFuncMask;
  24095. if (json.stencilFail !== undefined) material.stencilFail = json.stencilFail;
  24096. if (json.stencilZFail !== undefined) material.stencilZFail = json.stencilZFail;
  24097. if (json.stencilZPass !== undefined) material.stencilZPass = json.stencilZPass;
  24098. if (json.wireframe !== undefined) material.wireframe = json.wireframe;
  24099. if (json.wireframeLinewidth !== undefined) material.wireframeLinewidth = json.wireframeLinewidth;
  24100. if (json.wireframeLinecap !== undefined) material.wireframeLinecap = json.wireframeLinecap;
  24101. if (json.wireframeLinejoin !== undefined) material.wireframeLinejoin = json.wireframeLinejoin;
  24102. if (json.rotation !== undefined) material.rotation = json.rotation;
  24103. if (json.linewidth !== 1) material.linewidth = json.linewidth;
  24104. if (json.dashSize !== undefined) material.dashSize = json.dashSize;
  24105. if (json.gapSize !== undefined) material.gapSize = json.gapSize;
  24106. if (json.scale !== undefined) material.scale = json.scale;
  24107. if (json.polygonOffset !== undefined) material.polygonOffset = json.polygonOffset;
  24108. if (json.polygonOffsetFactor !== undefined) material.polygonOffsetFactor = json.polygonOffsetFactor;
  24109. if (json.polygonOffsetUnits !== undefined) material.polygonOffsetUnits = json.polygonOffsetUnits;
  24110. if (json.dithering !== undefined) material.dithering = json.dithering;
  24111. if (json.alphaToCoverage !== undefined) material.alphaToCoverage = json.alphaToCoverage;
  24112. if (json.premultipliedAlpha !== undefined) material.premultipliedAlpha = json.premultipliedAlpha;
  24113. if (json.visible !== undefined) material.visible = json.visible;
  24114. if (json.toneMapped !== undefined) material.toneMapped = json.toneMapped;
  24115. if (json.userData !== undefined) material.userData = json.userData;
  24116. if (json.vertexColors !== undefined) {
  24117. if (typeof json.vertexColors === 'number') {
  24118. material.vertexColors = json.vertexColors > 0 ? true : false;
  24119. } else {
  24120. material.vertexColors = json.vertexColors;
  24121. }
  24122. } // Shader Material
  24123. if (json.uniforms !== undefined) {
  24124. for (const name in json.uniforms) {
  24125. const uniform = json.uniforms[name];
  24126. material.uniforms[name] = {};
  24127. switch (uniform.type) {
  24128. case 't':
  24129. material.uniforms[name].value = getTexture(uniform.value);
  24130. break;
  24131. case 'c':
  24132. material.uniforms[name].value = new Color().setHex(uniform.value);
  24133. break;
  24134. case 'v2':
  24135. material.uniforms[name].value = new Vector2().fromArray(uniform.value);
  24136. break;
  24137. case 'v3':
  24138. material.uniforms[name].value = new Vector3().fromArray(uniform.value);
  24139. break;
  24140. case 'v4':
  24141. material.uniforms[name].value = new Vector4().fromArray(uniform.value);
  24142. break;
  24143. case 'm3':
  24144. material.uniforms[name].value = new Matrix3().fromArray(uniform.value);
  24145. break;
  24146. case 'm4':
  24147. material.uniforms[name].value = new Matrix4().fromArray(uniform.value);
  24148. break;
  24149. default:
  24150. material.uniforms[name].value = uniform.value;
  24151. }
  24152. }
  24153. }
  24154. if (json.defines !== undefined) material.defines = json.defines;
  24155. if (json.vertexShader !== undefined) material.vertexShader = json.vertexShader;
  24156. if (json.fragmentShader !== undefined) material.fragmentShader = json.fragmentShader;
  24157. if (json.glslVersion !== undefined) material.glslVersion = json.glslVersion;
  24158. if (json.extensions !== undefined) {
  24159. for (const key in json.extensions) {
  24160. material.extensions[key] = json.extensions[key];
  24161. }
  24162. } // for PointsMaterial
  24163. if (json.size !== undefined) material.size = json.size;
  24164. if (json.sizeAttenuation !== undefined) material.sizeAttenuation = json.sizeAttenuation; // maps
  24165. if (json.map !== undefined) material.map = getTexture(json.map);
  24166. if (json.matcap !== undefined) material.matcap = getTexture(json.matcap);
  24167. if (json.alphaMap !== undefined) material.alphaMap = getTexture(json.alphaMap);
  24168. if (json.bumpMap !== undefined) material.bumpMap = getTexture(json.bumpMap);
  24169. if (json.bumpScale !== undefined) material.bumpScale = json.bumpScale;
  24170. if (json.normalMap !== undefined) material.normalMap = getTexture(json.normalMap);
  24171. if (json.normalMapType !== undefined) material.normalMapType = json.normalMapType;
  24172. if (json.normalScale !== undefined) {
  24173. let normalScale = json.normalScale;
  24174. if (Array.isArray(normalScale) === false) {
  24175. // Blender exporter used to export a scalar. See #7459
  24176. normalScale = [normalScale, normalScale];
  24177. }
  24178. material.normalScale = new Vector2().fromArray(normalScale);
  24179. }
  24180. if (json.displacementMap !== undefined) material.displacementMap = getTexture(json.displacementMap);
  24181. if (json.displacementScale !== undefined) material.displacementScale = json.displacementScale;
  24182. if (json.displacementBias !== undefined) material.displacementBias = json.displacementBias;
  24183. if (json.roughnessMap !== undefined) material.roughnessMap = getTexture(json.roughnessMap);
  24184. if (json.metalnessMap !== undefined) material.metalnessMap = getTexture(json.metalnessMap);
  24185. if (json.emissiveMap !== undefined) material.emissiveMap = getTexture(json.emissiveMap);
  24186. if (json.emissiveIntensity !== undefined) material.emissiveIntensity = json.emissiveIntensity;
  24187. if (json.specularMap !== undefined) material.specularMap = getTexture(json.specularMap);
  24188. if (json.specularIntensityMap !== undefined) material.specularIntensityMap = getTexture(json.specularIntensityMap);
  24189. if (json.specularColorMap !== undefined) material.specularColorMap = getTexture(json.specularColorMap);
  24190. if (json.envMap !== undefined) material.envMap = getTexture(json.envMap);
  24191. if (json.envMapIntensity !== undefined) material.envMapIntensity = json.envMapIntensity;
  24192. if (json.reflectivity !== undefined) material.reflectivity = json.reflectivity;
  24193. if (json.refractionRatio !== undefined) material.refractionRatio = json.refractionRatio;
  24194. if (json.lightMap !== undefined) material.lightMap = getTexture(json.lightMap);
  24195. if (json.lightMapIntensity !== undefined) material.lightMapIntensity = json.lightMapIntensity;
  24196. if (json.aoMap !== undefined) material.aoMap = getTexture(json.aoMap);
  24197. if (json.aoMapIntensity !== undefined) material.aoMapIntensity = json.aoMapIntensity;
  24198. if (json.gradientMap !== undefined) material.gradientMap = getTexture(json.gradientMap);
  24199. if (json.clearcoatMap !== undefined) material.clearcoatMap = getTexture(json.clearcoatMap);
  24200. if (json.clearcoatRoughnessMap !== undefined) material.clearcoatRoughnessMap = getTexture(json.clearcoatRoughnessMap);
  24201. if (json.clearcoatNormalMap !== undefined) material.clearcoatNormalMap = getTexture(json.clearcoatNormalMap);
  24202. if (json.clearcoatNormalScale !== undefined) material.clearcoatNormalScale = new Vector2().fromArray(json.clearcoatNormalScale);
  24203. if (json.iridescenceMap !== undefined) material.iridescenceMap = getTexture(json.iridescenceMap);
  24204. if (json.iridescenceThicknessMap !== undefined) material.iridescenceThicknessMap = getTexture(json.iridescenceThicknessMap);
  24205. if (json.transmissionMap !== undefined) material.transmissionMap = getTexture(json.transmissionMap);
  24206. if (json.thicknessMap !== undefined) material.thicknessMap = getTexture(json.thicknessMap);
  24207. if (json.sheenColorMap !== undefined) material.sheenColorMap = getTexture(json.sheenColorMap);
  24208. if (json.sheenRoughnessMap !== undefined) material.sheenRoughnessMap = getTexture(json.sheenRoughnessMap);
  24209. return material;
  24210. }
  24211. setTextures(value) {
  24212. this.textures = value;
  24213. return this;
  24214. }
  24215. static createMaterialFromType(type) {
  24216. const materialLib = {
  24217. ShadowMaterial,
  24218. SpriteMaterial,
  24219. RawShaderMaterial,
  24220. ShaderMaterial,
  24221. PointsMaterial,
  24222. MeshPhysicalMaterial,
  24223. MeshStandardMaterial,
  24224. MeshPhongMaterial,
  24225. MeshToonMaterial,
  24226. MeshNormalMaterial,
  24227. MeshLambertMaterial,
  24228. MeshDepthMaterial,
  24229. MeshDistanceMaterial,
  24230. MeshBasicMaterial,
  24231. MeshMatcapMaterial,
  24232. LineDashedMaterial,
  24233. LineBasicMaterial,
  24234. Material
  24235. };
  24236. return new materialLib[type]();
  24237. }
  24238. }
  24239. class LoaderUtils {
  24240. static decodeText(array) {
  24241. if (typeof TextDecoder !== 'undefined') {
  24242. return new TextDecoder().decode(array);
  24243. } // Avoid the String.fromCharCode.apply(null, array) shortcut, which
  24244. // throws a "maximum call stack size exceeded" error for large arrays.
  24245. let s = '';
  24246. for (let i = 0, il = array.length; i < il; i++) {
  24247. // Implicitly assumes little-endian.
  24248. s += String.fromCharCode(array[i]);
  24249. }
  24250. try {
  24251. // merges multi-byte utf-8 characters.
  24252. return decodeURIComponent(escape(s));
  24253. } catch (e) {
  24254. // see #16358
  24255. return s;
  24256. }
  24257. }
  24258. static extractUrlBase(url) {
  24259. const index = url.lastIndexOf('/');
  24260. if (index === -1) return './';
  24261. return url.slice(0, index + 1);
  24262. }
  24263. static resolveURL(url, path) {
  24264. // Invalid URL
  24265. if (typeof url !== 'string' || url === '') return ''; // Host Relative URL
  24266. if (/^https?:\/\//i.test(path) && /^\//.test(url)) {
  24267. path = path.replace(/(^https?:\/\/[^\/]+).*/i, '$1');
  24268. } // Absolute URL http://,https://,//
  24269. if (/^(https?:)?\/\//i.test(url)) return url; // Data URI
  24270. if (/^data:.*,.*$/i.test(url)) return url; // Blob URL
  24271. if (/^blob:.*$/i.test(url)) return url; // Relative URL
  24272. return path + url;
  24273. }
  24274. }
  24275. class InstancedBufferGeometry extends BufferGeometry {
  24276. constructor() {
  24277. super();
  24278. this.isInstancedBufferGeometry = true;
  24279. this.type = 'InstancedBufferGeometry';
  24280. this.instanceCount = Infinity;
  24281. }
  24282. copy(source) {
  24283. super.copy(source);
  24284. this.instanceCount = source.instanceCount;
  24285. return this;
  24286. }
  24287. clone() {
  24288. return new this.constructor().copy(this);
  24289. }
  24290. toJSON() {
  24291. const data = super.toJSON(this);
  24292. data.instanceCount = this.instanceCount;
  24293. data.isInstancedBufferGeometry = true;
  24294. return data;
  24295. }
  24296. }
  24297. class BufferGeometryLoader extends Loader {
  24298. constructor(manager) {
  24299. super(manager);
  24300. }
  24301. load(url, onLoad, onProgress, onError) {
  24302. const scope = this;
  24303. const loader = new FileLoader(scope.manager);
  24304. loader.setPath(scope.path);
  24305. loader.setRequestHeader(scope.requestHeader);
  24306. loader.setWithCredentials(scope.withCredentials);
  24307. loader.load(url, function (text) {
  24308. try {
  24309. onLoad(scope.parse(JSON.parse(text)));
  24310. } catch (e) {
  24311. if (onError) {
  24312. onError(e);
  24313. } else {
  24314. console.error(e);
  24315. }
  24316. scope.manager.itemError(url);
  24317. }
  24318. }, onProgress, onError);
  24319. }
  24320. parse(json) {
  24321. const interleavedBufferMap = {};
  24322. const arrayBufferMap = {};
  24323. function getInterleavedBuffer(json, uuid) {
  24324. if (interleavedBufferMap[uuid] !== undefined) return interleavedBufferMap[uuid];
  24325. const interleavedBuffers = json.interleavedBuffers;
  24326. const interleavedBuffer = interleavedBuffers[uuid];
  24327. const buffer = getArrayBuffer(json, interleavedBuffer.buffer);
  24328. const array = getTypedArray(interleavedBuffer.type, buffer);
  24329. const ib = new InterleavedBuffer(array, interleavedBuffer.stride);
  24330. ib.uuid = interleavedBuffer.uuid;
  24331. interleavedBufferMap[uuid] = ib;
  24332. return ib;
  24333. }
  24334. function getArrayBuffer(json, uuid) {
  24335. if (arrayBufferMap[uuid] !== undefined) return arrayBufferMap[uuid];
  24336. const arrayBuffers = json.arrayBuffers;
  24337. const arrayBuffer = arrayBuffers[uuid];
  24338. const ab = new Uint32Array(arrayBuffer).buffer;
  24339. arrayBufferMap[uuid] = ab;
  24340. return ab;
  24341. }
  24342. const geometry = json.isInstancedBufferGeometry ? new InstancedBufferGeometry() : new BufferGeometry();
  24343. const index = json.data.index;
  24344. if (index !== undefined) {
  24345. const typedArray = getTypedArray(index.type, index.array);
  24346. geometry.setIndex(new BufferAttribute(typedArray, 1));
  24347. }
  24348. const attributes = json.data.attributes;
  24349. for (const key in attributes) {
  24350. const attribute = attributes[key];
  24351. let bufferAttribute;
  24352. if (attribute.isInterleavedBufferAttribute) {
  24353. const interleavedBuffer = getInterleavedBuffer(json.data, attribute.data);
  24354. bufferAttribute = new InterleavedBufferAttribute(interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized);
  24355. } else {
  24356. const typedArray = getTypedArray(attribute.type, attribute.array);
  24357. const bufferAttributeConstr = attribute.isInstancedBufferAttribute ? InstancedBufferAttribute : BufferAttribute;
  24358. bufferAttribute = new bufferAttributeConstr(typedArray, attribute.itemSize, attribute.normalized);
  24359. }
  24360. if (attribute.name !== undefined) bufferAttribute.name = attribute.name;
  24361. if (attribute.usage !== undefined) bufferAttribute.setUsage(attribute.usage);
  24362. if (attribute.updateRange !== undefined) {
  24363. bufferAttribute.updateRange.offset = attribute.updateRange.offset;
  24364. bufferAttribute.updateRange.count = attribute.updateRange.count;
  24365. }
  24366. geometry.setAttribute(key, bufferAttribute);
  24367. }
  24368. const morphAttributes = json.data.morphAttributes;
  24369. if (morphAttributes) {
  24370. for (const key in morphAttributes) {
  24371. const attributeArray = morphAttributes[key];
  24372. const array = [];
  24373. for (let i = 0, il = attributeArray.length; i < il; i++) {
  24374. const attribute = attributeArray[i];
  24375. let bufferAttribute;
  24376. if (attribute.isInterleavedBufferAttribute) {
  24377. const interleavedBuffer = getInterleavedBuffer(json.data, attribute.data);
  24378. bufferAttribute = new InterleavedBufferAttribute(interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized);
  24379. } else {
  24380. const typedArray = getTypedArray(attribute.type, attribute.array);
  24381. bufferAttribute = new BufferAttribute(typedArray, attribute.itemSize, attribute.normalized);
  24382. }
  24383. if (attribute.name !== undefined) bufferAttribute.name = attribute.name;
  24384. array.push(bufferAttribute);
  24385. }
  24386. geometry.morphAttributes[key] = array;
  24387. }
  24388. }
  24389. const morphTargetsRelative = json.data.morphTargetsRelative;
  24390. if (morphTargetsRelative) {
  24391. geometry.morphTargetsRelative = true;
  24392. }
  24393. const groups = json.data.groups || json.data.drawcalls || json.data.offsets;
  24394. if (groups !== undefined) {
  24395. for (let i = 0, n = groups.length; i !== n; ++i) {
  24396. const group = groups[i];
  24397. geometry.addGroup(group.start, group.count, group.materialIndex);
  24398. }
  24399. }
  24400. const boundingSphere = json.data.boundingSphere;
  24401. if (boundingSphere !== undefined) {
  24402. const center = new Vector3();
  24403. if (boundingSphere.center !== undefined) {
  24404. center.fromArray(boundingSphere.center);
  24405. }
  24406. geometry.boundingSphere = new Sphere(center, boundingSphere.radius);
  24407. }
  24408. if (json.name) geometry.name = json.name;
  24409. if (json.userData) geometry.userData = json.userData;
  24410. return geometry;
  24411. }
  24412. }
  24413. class ObjectLoader extends Loader {
  24414. constructor(manager) {
  24415. super(manager);
  24416. }
  24417. load(url, onLoad, onProgress, onError) {
  24418. const scope = this;
  24419. const path = this.path === '' ? LoaderUtils.extractUrlBase(url) : this.path;
  24420. this.resourcePath = this.resourcePath || path;
  24421. const loader = new FileLoader(this.manager);
  24422. loader.setPath(this.path);
  24423. loader.setRequestHeader(this.requestHeader);
  24424. loader.setWithCredentials(this.withCredentials);
  24425. loader.load(url, function (text) {
  24426. let json = null;
  24427. try {
  24428. json = JSON.parse(text);
  24429. } catch (error) {
  24430. if (onError !== undefined) onError(error);
  24431. console.error('THREE:ObjectLoader: Can\'t parse ' + url + '.', error.message);
  24432. return;
  24433. }
  24434. const metadata = json.metadata;
  24435. if (metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry') {
  24436. console.error('THREE.ObjectLoader: Can\'t load ' + url);
  24437. return;
  24438. }
  24439. scope.parse(json, onLoad);
  24440. }, onProgress, onError);
  24441. }
  24442. async loadAsync(url, onProgress) {
  24443. const scope = this;
  24444. const path = this.path === '' ? LoaderUtils.extractUrlBase(url) : this.path;
  24445. this.resourcePath = this.resourcePath || path;
  24446. const loader = new FileLoader(this.manager);
  24447. loader.setPath(this.path);
  24448. loader.setRequestHeader(this.requestHeader);
  24449. loader.setWithCredentials(this.withCredentials);
  24450. const text = await loader.loadAsync(url, onProgress);
  24451. const json = JSON.parse(text);
  24452. const metadata = json.metadata;
  24453. if (metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry') {
  24454. throw new Error('THREE.ObjectLoader: Can\'t load ' + url);
  24455. }
  24456. return await scope.parseAsync(json);
  24457. }
  24458. parse(json, onLoad) {
  24459. const animations = this.parseAnimations(json.animations);
  24460. const shapes = this.parseShapes(json.shapes);
  24461. const geometries = this.parseGeometries(json.geometries, shapes);
  24462. const images = this.parseImages(json.images, function () {
  24463. if (onLoad !== undefined) onLoad(object);
  24464. });
  24465. const textures = this.parseTextures(json.textures, images);
  24466. const materials = this.parseMaterials(json.materials, textures);
  24467. const object = this.parseObject(json.object, geometries, materials, textures, animations);
  24468. const skeletons = this.parseSkeletons(json.skeletons, object);
  24469. this.bindSkeletons(object, skeletons); //
  24470. if (onLoad !== undefined) {
  24471. let hasImages = false;
  24472. for (const uuid in images) {
  24473. if (images[uuid].data instanceof HTMLImageElement) {
  24474. hasImages = true;
  24475. break;
  24476. }
  24477. }
  24478. if (hasImages === false) onLoad(object);
  24479. }
  24480. return object;
  24481. }
  24482. async parseAsync(json) {
  24483. const animations = this.parseAnimations(json.animations);
  24484. const shapes = this.parseShapes(json.shapes);
  24485. const geometries = this.parseGeometries(json.geometries, shapes);
  24486. const images = await this.parseImagesAsync(json.images);
  24487. const textures = this.parseTextures(json.textures, images);
  24488. const materials = this.parseMaterials(json.materials, textures);
  24489. const object = this.parseObject(json.object, geometries, materials, textures, animations);
  24490. const skeletons = this.parseSkeletons(json.skeletons, object);
  24491. this.bindSkeletons(object, skeletons);
  24492. return object;
  24493. }
  24494. parseShapes(json) {
  24495. const shapes = {};
  24496. if (json !== undefined) {
  24497. for (let i = 0, l = json.length; i < l; i++) {
  24498. const shape = new Shape().fromJSON(json[i]);
  24499. shapes[shape.uuid] = shape;
  24500. }
  24501. }
  24502. return shapes;
  24503. }
  24504. parseSkeletons(json, object) {
  24505. const skeletons = {};
  24506. const bones = {}; // generate bone lookup table
  24507. object.traverse(function (child) {
  24508. if (child.isBone) bones[child.uuid] = child;
  24509. }); // create skeletons
  24510. if (json !== undefined) {
  24511. for (let i = 0, l = json.length; i < l; i++) {
  24512. const skeleton = new Skeleton().fromJSON(json[i], bones);
  24513. skeletons[skeleton.uuid] = skeleton;
  24514. }
  24515. }
  24516. return skeletons;
  24517. }
  24518. parseGeometries(json, shapes) {
  24519. const geometries = {};
  24520. if (json !== undefined) {
  24521. const bufferGeometryLoader = new BufferGeometryLoader();
  24522. for (let i = 0, l = json.length; i < l; i++) {
  24523. let geometry;
  24524. const data = json[i];
  24525. switch (data.type) {
  24526. case 'BufferGeometry':
  24527. case 'InstancedBufferGeometry':
  24528. geometry = bufferGeometryLoader.parse(data);
  24529. break;
  24530. default:
  24531. if (data.type in Geometries) {
  24532. geometry = Geometries[data.type].fromJSON(data, shapes);
  24533. } else {
  24534. console.warn(`THREE.ObjectLoader: Unsupported geometry type "${data.type}"`);
  24535. }
  24536. }
  24537. geometry.uuid = data.uuid;
  24538. if (data.name !== undefined) geometry.name = data.name;
  24539. if (geometry.isBufferGeometry === true && data.userData !== undefined) geometry.userData = data.userData;
  24540. geometries[data.uuid] = geometry;
  24541. }
  24542. }
  24543. return geometries;
  24544. }
  24545. parseMaterials(json, textures) {
  24546. const cache = {}; // MultiMaterial
  24547. const materials = {};
  24548. if (json !== undefined) {
  24549. const loader = new MaterialLoader();
  24550. loader.setTextures(textures);
  24551. for (let i = 0, l = json.length; i < l; i++) {
  24552. const data = json[i];
  24553. if (cache[data.uuid] === undefined) {
  24554. cache[data.uuid] = loader.parse(data);
  24555. }
  24556. materials[data.uuid] = cache[data.uuid];
  24557. }
  24558. }
  24559. return materials;
  24560. }
  24561. parseAnimations(json) {
  24562. const animations = {};
  24563. if (json !== undefined) {
  24564. for (let i = 0; i < json.length; i++) {
  24565. const data = json[i];
  24566. const clip = AnimationClip.parse(data);
  24567. animations[clip.uuid] = clip;
  24568. }
  24569. }
  24570. return animations;
  24571. }
  24572. parseImages(json, onLoad) {
  24573. const scope = this;
  24574. const images = {};
  24575. let loader;
  24576. function loadImage(url) {
  24577. scope.manager.itemStart(url);
  24578. return loader.load(url, function () {
  24579. scope.manager.itemEnd(url);
  24580. }, undefined, function () {
  24581. scope.manager.itemError(url);
  24582. scope.manager.itemEnd(url);
  24583. });
  24584. }
  24585. function deserializeImage(image) {
  24586. if (typeof image === 'string') {
  24587. const url = image;
  24588. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test(url) ? url : scope.resourcePath + url;
  24589. return loadImage(path);
  24590. } else {
  24591. if (image.data) {
  24592. return {
  24593. data: getTypedArray(image.type, image.data),
  24594. width: image.width,
  24595. height: image.height
  24596. };
  24597. } else {
  24598. return null;
  24599. }
  24600. }
  24601. }
  24602. if (json !== undefined && json.length > 0) {
  24603. const manager = new LoadingManager(onLoad);
  24604. loader = new ImageLoader(manager);
  24605. loader.setCrossOrigin(this.crossOrigin);
  24606. for (let i = 0, il = json.length; i < il; i++) {
  24607. const image = json[i];
  24608. const url = image.url;
  24609. if (Array.isArray(url)) {
  24610. // load array of images e.g CubeTexture
  24611. const imageArray = [];
  24612. for (let j = 0, jl = url.length; j < jl; j++) {
  24613. const currentUrl = url[j];
  24614. const deserializedImage = deserializeImage(currentUrl);
  24615. if (deserializedImage !== null) {
  24616. if (deserializedImage instanceof HTMLImageElement) {
  24617. imageArray.push(deserializedImage);
  24618. } else {
  24619. // special case: handle array of data textures for cube textures
  24620. imageArray.push(new DataTexture(deserializedImage.data, deserializedImage.width, deserializedImage.height));
  24621. }
  24622. }
  24623. }
  24624. images[image.uuid] = new Source(imageArray);
  24625. } else {
  24626. // load single image
  24627. const deserializedImage = deserializeImage(image.url);
  24628. images[image.uuid] = new Source(deserializedImage);
  24629. }
  24630. }
  24631. }
  24632. return images;
  24633. }
  24634. async parseImagesAsync(json) {
  24635. const scope = this;
  24636. const images = {};
  24637. let loader;
  24638. async function deserializeImage(image) {
  24639. if (typeof image === 'string') {
  24640. const url = image;
  24641. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test(url) ? url : scope.resourcePath + url;
  24642. return await loader.loadAsync(path);
  24643. } else {
  24644. if (image.data) {
  24645. return {
  24646. data: getTypedArray(image.type, image.data),
  24647. width: image.width,
  24648. height: image.height
  24649. };
  24650. } else {
  24651. return null;
  24652. }
  24653. }
  24654. }
  24655. if (json !== undefined && json.length > 0) {
  24656. loader = new ImageLoader(this.manager);
  24657. loader.setCrossOrigin(this.crossOrigin);
  24658. for (let i = 0, il = json.length; i < il; i++) {
  24659. const image = json[i];
  24660. const url = image.url;
  24661. if (Array.isArray(url)) {
  24662. // load array of images e.g CubeTexture
  24663. const imageArray = [];
  24664. for (let j = 0, jl = url.length; j < jl; j++) {
  24665. const currentUrl = url[j];
  24666. const deserializedImage = await deserializeImage(currentUrl);
  24667. if (deserializedImage !== null) {
  24668. if (deserializedImage instanceof HTMLImageElement) {
  24669. imageArray.push(deserializedImage);
  24670. } else {
  24671. // special case: handle array of data textures for cube textures
  24672. imageArray.push(new DataTexture(deserializedImage.data, deserializedImage.width, deserializedImage.height));
  24673. }
  24674. }
  24675. }
  24676. images[image.uuid] = new Source(imageArray);
  24677. } else {
  24678. // load single image
  24679. const deserializedImage = await deserializeImage(image.url);
  24680. images[image.uuid] = new Source(deserializedImage);
  24681. }
  24682. }
  24683. }
  24684. return images;
  24685. }
  24686. parseTextures(json, images) {
  24687. function parseConstant(value, type) {
  24688. if (typeof value === 'number') return value;
  24689. console.warn('THREE.ObjectLoader.parseTexture: Constant should be in numeric form.', value);
  24690. return type[value];
  24691. }
  24692. const textures = {};
  24693. if (json !== undefined) {
  24694. for (let i = 0, l = json.length; i < l; i++) {
  24695. const data = json[i];
  24696. if (data.image === undefined) {
  24697. console.warn('THREE.ObjectLoader: No "image" specified for', data.uuid);
  24698. }
  24699. if (images[data.image] === undefined) {
  24700. console.warn('THREE.ObjectLoader: Undefined image', data.image);
  24701. }
  24702. const source = images[data.image];
  24703. const image = source.data;
  24704. let texture;
  24705. if (Array.isArray(image)) {
  24706. texture = new CubeTexture();
  24707. if (image.length === 6) texture.needsUpdate = true;
  24708. } else {
  24709. if (image && image.data) {
  24710. texture = new DataTexture();
  24711. } else {
  24712. texture = new Texture();
  24713. }
  24714. if (image) texture.needsUpdate = true; // textures can have undefined image data
  24715. }
  24716. texture.source = source;
  24717. texture.uuid = data.uuid;
  24718. if (data.name !== undefined) texture.name = data.name;
  24719. if (data.mapping !== undefined) texture.mapping = parseConstant(data.mapping, TEXTURE_MAPPING);
  24720. if (data.offset !== undefined) texture.offset.fromArray(data.offset);
  24721. if (data.repeat !== undefined) texture.repeat.fromArray(data.repeat);
  24722. if (data.center !== undefined) texture.center.fromArray(data.center);
  24723. if (data.rotation !== undefined) texture.rotation = data.rotation;
  24724. if (data.wrap !== undefined) {
  24725. texture.wrapS = parseConstant(data.wrap[0], TEXTURE_WRAPPING);
  24726. texture.wrapT = parseConstant(data.wrap[1], TEXTURE_WRAPPING);
  24727. }
  24728. if (data.format !== undefined) texture.format = data.format;
  24729. if (data.type !== undefined) texture.type = data.type;
  24730. if (data.encoding !== undefined) texture.encoding = data.encoding;
  24731. if (data.minFilter !== undefined) texture.minFilter = parseConstant(data.minFilter, TEXTURE_FILTER);
  24732. if (data.magFilter !== undefined) texture.magFilter = parseConstant(data.magFilter, TEXTURE_FILTER);
  24733. if (data.anisotropy !== undefined) texture.anisotropy = data.anisotropy;
  24734. if (data.flipY !== undefined) texture.flipY = data.flipY;
  24735. if (data.premultiplyAlpha !== undefined) texture.premultiplyAlpha = data.premultiplyAlpha;
  24736. if (data.unpackAlignment !== undefined) texture.unpackAlignment = data.unpackAlignment;
  24737. if (data.userData !== undefined) texture.userData = data.userData;
  24738. textures[data.uuid] = texture;
  24739. }
  24740. }
  24741. return textures;
  24742. }
  24743. parseObject(data, geometries, materials, textures, animations) {
  24744. let object;
  24745. function getGeometry(name) {
  24746. if (geometries[name] === undefined) {
  24747. console.warn('THREE.ObjectLoader: Undefined geometry', name);
  24748. }
  24749. return geometries[name];
  24750. }
  24751. function getMaterial(name) {
  24752. if (name === undefined) return undefined;
  24753. if (Array.isArray(name)) {
  24754. const array = [];
  24755. for (let i = 0, l = name.length; i < l; i++) {
  24756. const uuid = name[i];
  24757. if (materials[uuid] === undefined) {
  24758. console.warn('THREE.ObjectLoader: Undefined material', uuid);
  24759. }
  24760. array.push(materials[uuid]);
  24761. }
  24762. return array;
  24763. }
  24764. if (materials[name] === undefined) {
  24765. console.warn('THREE.ObjectLoader: Undefined material', name);
  24766. }
  24767. return materials[name];
  24768. }
  24769. function getTexture(uuid) {
  24770. if (textures[uuid] === undefined) {
  24771. console.warn('THREE.ObjectLoader: Undefined texture', uuid);
  24772. }
  24773. return textures[uuid];
  24774. }
  24775. let geometry, material;
  24776. switch (data.type) {
  24777. case 'Scene':
  24778. object = new Scene();
  24779. if (data.background !== undefined) {
  24780. if (Number.isInteger(data.background)) {
  24781. object.background = new Color(data.background);
  24782. } else {
  24783. object.background = getTexture(data.background);
  24784. }
  24785. }
  24786. if (data.environment !== undefined) {
  24787. object.environment = getTexture(data.environment);
  24788. }
  24789. if (data.fog !== undefined) {
  24790. if (data.fog.type === 'Fog') {
  24791. object.fog = new Fog(data.fog.color, data.fog.near, data.fog.far);
  24792. } else if (data.fog.type === 'FogExp2') {
  24793. object.fog = new FogExp2(data.fog.color, data.fog.density);
  24794. }
  24795. }
  24796. break;
  24797. case 'PerspectiveCamera':
  24798. object = new PerspectiveCamera(data.fov, data.aspect, data.near, data.far);
  24799. if (data.focus !== undefined) object.focus = data.focus;
  24800. if (data.zoom !== undefined) object.zoom = data.zoom;
  24801. if (data.filmGauge !== undefined) object.filmGauge = data.filmGauge;
  24802. if (data.filmOffset !== undefined) object.filmOffset = data.filmOffset;
  24803. if (data.view !== undefined) object.view = Object.assign({}, data.view);
  24804. break;
  24805. case 'OrthographicCamera':
  24806. object = new OrthographicCamera(data.left, data.right, data.top, data.bottom, data.near, data.far);
  24807. if (data.zoom !== undefined) object.zoom = data.zoom;
  24808. if (data.view !== undefined) object.view = Object.assign({}, data.view);
  24809. break;
  24810. case 'AmbientLight':
  24811. object = new AmbientLight(data.color, data.intensity);
  24812. break;
  24813. case 'DirectionalLight':
  24814. object = new DirectionalLight(data.color, data.intensity);
  24815. break;
  24816. case 'PointLight':
  24817. object = new PointLight(data.color, data.intensity, data.distance, data.decay);
  24818. break;
  24819. case 'RectAreaLight':
  24820. object = new RectAreaLight(data.color, data.intensity, data.width, data.height);
  24821. break;
  24822. case 'SpotLight':
  24823. object = new SpotLight(data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay);
  24824. break;
  24825. case 'HemisphereLight':
  24826. object = new HemisphereLight(data.color, data.groundColor, data.intensity);
  24827. break;
  24828. case 'LightProbe':
  24829. object = new LightProbe().fromJSON(data);
  24830. break;
  24831. case 'SkinnedMesh':
  24832. geometry = getGeometry(data.geometry);
  24833. material = getMaterial(data.material);
  24834. object = new SkinnedMesh(geometry, material);
  24835. if (data.bindMode !== undefined) object.bindMode = data.bindMode;
  24836. if (data.bindMatrix !== undefined) object.bindMatrix.fromArray(data.bindMatrix);
  24837. if (data.skeleton !== undefined) object.skeleton = data.skeleton;
  24838. break;
  24839. case 'Mesh':
  24840. geometry = getGeometry(data.geometry);
  24841. material = getMaterial(data.material);
  24842. object = new Mesh(geometry, material);
  24843. break;
  24844. case 'InstancedMesh':
  24845. geometry = getGeometry(data.geometry);
  24846. material = getMaterial(data.material);
  24847. const count = data.count;
  24848. const instanceMatrix = data.instanceMatrix;
  24849. const instanceColor = data.instanceColor;
  24850. object = new InstancedMesh(geometry, material, count);
  24851. object.instanceMatrix = new InstancedBufferAttribute(new Float32Array(instanceMatrix.array), 16);
  24852. if (instanceColor !== undefined) object.instanceColor = new InstancedBufferAttribute(new Float32Array(instanceColor.array), instanceColor.itemSize);
  24853. break;
  24854. case 'LOD':
  24855. object = new LOD();
  24856. break;
  24857. case 'Line':
  24858. object = new Line(getGeometry(data.geometry), getMaterial(data.material));
  24859. break;
  24860. case 'LineLoop':
  24861. object = new LineLoop(getGeometry(data.geometry), getMaterial(data.material));
  24862. break;
  24863. case 'LineSegments':
  24864. object = new LineSegments(getGeometry(data.geometry), getMaterial(data.material));
  24865. break;
  24866. case 'PointCloud':
  24867. case 'Points':
  24868. object = new Points(getGeometry(data.geometry), getMaterial(data.material));
  24869. break;
  24870. case 'Sprite':
  24871. object = new Sprite(getMaterial(data.material));
  24872. break;
  24873. case 'Group':
  24874. object = new Group();
  24875. break;
  24876. case 'Bone':
  24877. object = new Bone();
  24878. break;
  24879. default:
  24880. object = new Object3D();
  24881. }
  24882. object.uuid = data.uuid;
  24883. if (data.name !== undefined) object.name = data.name;
  24884. if (data.matrix !== undefined) {
  24885. object.matrix.fromArray(data.matrix);
  24886. if (data.matrixAutoUpdate !== undefined) object.matrixAutoUpdate = data.matrixAutoUpdate;
  24887. if (object.matrixAutoUpdate) object.matrix.decompose(object.position, object.quaternion, object.scale);
  24888. } else {
  24889. if (data.position !== undefined) object.position.fromArray(data.position);
  24890. if (data.rotation !== undefined) object.rotation.fromArray(data.rotation);
  24891. if (data.quaternion !== undefined) object.quaternion.fromArray(data.quaternion);
  24892. if (data.scale !== undefined) object.scale.fromArray(data.scale);
  24893. }
  24894. if (data.castShadow !== undefined) object.castShadow = data.castShadow;
  24895. if (data.receiveShadow !== undefined) object.receiveShadow = data.receiveShadow;
  24896. if (data.shadow) {
  24897. if (data.shadow.bias !== undefined) object.shadow.bias = data.shadow.bias;
  24898. if (data.shadow.normalBias !== undefined) object.shadow.normalBias = data.shadow.normalBias;
  24899. if (data.shadow.radius !== undefined) object.shadow.radius = data.shadow.radius;
  24900. if (data.shadow.mapSize !== undefined) object.shadow.mapSize.fromArray(data.shadow.mapSize);
  24901. if (data.shadow.camera !== undefined) object.shadow.camera = this.parseObject(data.shadow.camera);
  24902. }
  24903. if (data.visible !== undefined) object.visible = data.visible;
  24904. if (data.frustumCulled !== undefined) object.frustumCulled = data.frustumCulled;
  24905. if (data.renderOrder !== undefined) object.renderOrder = data.renderOrder;
  24906. if (data.userData !== undefined) object.userData = data.userData;
  24907. if (data.layers !== undefined) object.layers.mask = data.layers;
  24908. if (data.children !== undefined) {
  24909. const children = data.children;
  24910. for (let i = 0; i < children.length; i++) {
  24911. object.add(this.parseObject(children[i], geometries, materials, textures, animations));
  24912. }
  24913. }
  24914. if (data.animations !== undefined) {
  24915. const objectAnimations = data.animations;
  24916. for (let i = 0; i < objectAnimations.length; i++) {
  24917. const uuid = objectAnimations[i];
  24918. object.animations.push(animations[uuid]);
  24919. }
  24920. }
  24921. if (data.type === 'LOD') {
  24922. if (data.autoUpdate !== undefined) object.autoUpdate = data.autoUpdate;
  24923. const levels = data.levels;
  24924. for (let l = 0; l < levels.length; l++) {
  24925. const level = levels[l];
  24926. const child = object.getObjectByProperty('uuid', level.object);
  24927. if (child !== undefined) {
  24928. object.addLevel(child, level.distance);
  24929. }
  24930. }
  24931. }
  24932. return object;
  24933. }
  24934. bindSkeletons(object, skeletons) {
  24935. if (Object.keys(skeletons).length === 0) return;
  24936. object.traverse(function (child) {
  24937. if (child.isSkinnedMesh === true && child.skeleton !== undefined) {
  24938. const skeleton = skeletons[child.skeleton];
  24939. if (skeleton === undefined) {
  24940. console.warn('THREE.ObjectLoader: No skeleton found with UUID:', child.skeleton);
  24941. } else {
  24942. child.bind(skeleton, child.bindMatrix);
  24943. }
  24944. }
  24945. });
  24946. }
  24947. }
  24948. const TEXTURE_MAPPING = {
  24949. UVMapping: UVMapping,
  24950. CubeReflectionMapping: CubeReflectionMapping,
  24951. CubeRefractionMapping: CubeRefractionMapping,
  24952. EquirectangularReflectionMapping: EquirectangularReflectionMapping,
  24953. EquirectangularRefractionMapping: EquirectangularRefractionMapping,
  24954. CubeUVReflectionMapping: CubeUVReflectionMapping
  24955. };
  24956. const TEXTURE_WRAPPING = {
  24957. RepeatWrapping: RepeatWrapping,
  24958. ClampToEdgeWrapping: ClampToEdgeWrapping,
  24959. MirroredRepeatWrapping: MirroredRepeatWrapping
  24960. };
  24961. const TEXTURE_FILTER = {
  24962. NearestFilter: NearestFilter,
  24963. NearestMipmapNearestFilter: NearestMipmapNearestFilter,
  24964. NearestMipmapLinearFilter: NearestMipmapLinearFilter,
  24965. LinearFilter: LinearFilter,
  24966. LinearMipmapNearestFilter: LinearMipmapNearestFilter,
  24967. LinearMipmapLinearFilter: LinearMipmapLinearFilter
  24968. };
  24969. class ImageBitmapLoader extends Loader {
  24970. constructor(manager) {
  24971. super(manager);
  24972. this.isImageBitmapLoader = true;
  24973. if (typeof createImageBitmap === 'undefined') {
  24974. console.warn('THREE.ImageBitmapLoader: createImageBitmap() not supported.');
  24975. }
  24976. if (typeof fetch === 'undefined') {
  24977. console.warn('THREE.ImageBitmapLoader: fetch() not supported.');
  24978. }
  24979. this.options = {
  24980. premultiplyAlpha: 'none'
  24981. };
  24982. }
  24983. setOptions(options) {
  24984. this.options = options;
  24985. return this;
  24986. }
  24987. load(url, onLoad, onProgress, onError) {
  24988. if (url === undefined) url = '';
  24989. if (this.path !== undefined) url = this.path + url;
  24990. url = this.manager.resolveURL(url);
  24991. const scope = this;
  24992. const cached = Cache.get(url);
  24993. if (cached !== undefined) {
  24994. scope.manager.itemStart(url);
  24995. setTimeout(function () {
  24996. if (onLoad) onLoad(cached);
  24997. scope.manager.itemEnd(url);
  24998. }, 0);
  24999. return cached;
  25000. }
  25001. const fetchOptions = {};
  25002. fetchOptions.credentials = this.crossOrigin === 'anonymous' ? 'same-origin' : 'include';
  25003. fetchOptions.headers = this.requestHeader;
  25004. fetch(url, fetchOptions).then(function (res) {
  25005. return res.blob();
  25006. }).then(function (blob) {
  25007. return createImageBitmap(blob, Object.assign(scope.options, {
  25008. colorSpaceConversion: 'none'
  25009. }));
  25010. }).then(function (imageBitmap) {
  25011. Cache.add(url, imageBitmap);
  25012. if (onLoad) onLoad(imageBitmap);
  25013. scope.manager.itemEnd(url);
  25014. }).catch(function (e) {
  25015. if (onError) onError(e);
  25016. scope.manager.itemError(url);
  25017. scope.manager.itemEnd(url);
  25018. });
  25019. scope.manager.itemStart(url);
  25020. }
  25021. }
  25022. let _context;
  25023. const AudioContext = {
  25024. getContext: function () {
  25025. if (_context === undefined) {
  25026. _context = new (window.AudioContext || window.webkitAudioContext)();
  25027. }
  25028. return _context;
  25029. },
  25030. setContext: function (value) {
  25031. _context = value;
  25032. }
  25033. };
  25034. class AudioLoader extends Loader {
  25035. constructor(manager) {
  25036. super(manager);
  25037. }
  25038. load(url, onLoad, onProgress, onError) {
  25039. const scope = this;
  25040. const loader = new FileLoader(this.manager);
  25041. loader.setResponseType('arraybuffer');
  25042. loader.setPath(this.path);
  25043. loader.setRequestHeader(this.requestHeader);
  25044. loader.setWithCredentials(this.withCredentials);
  25045. loader.load(url, function (buffer) {
  25046. try {
  25047. // Create a copy of the buffer. The `decodeAudioData` method
  25048. // detaches the buffer when complete, preventing reuse.
  25049. const bufferCopy = buffer.slice(0);
  25050. const context = AudioContext.getContext();
  25051. context.decodeAudioData(bufferCopy, function (audioBuffer) {
  25052. onLoad(audioBuffer);
  25053. });
  25054. } catch (e) {
  25055. if (onError) {
  25056. onError(e);
  25057. } else {
  25058. console.error(e);
  25059. }
  25060. scope.manager.itemError(url);
  25061. }
  25062. }, onProgress, onError);
  25063. }
  25064. }
  25065. class HemisphereLightProbe extends LightProbe {
  25066. constructor(skyColor, groundColor, intensity = 1) {
  25067. super(undefined, intensity);
  25068. this.isHemisphereLightProbe = true;
  25069. const color1 = new Color().set(skyColor);
  25070. const color2 = new Color().set(groundColor);
  25071. const sky = new Vector3(color1.r, color1.g, color1.b);
  25072. const ground = new Vector3(color2.r, color2.g, color2.b); // without extra factor of PI in the shader, should = 1 / Math.sqrt( Math.PI );
  25073. const c0 = Math.sqrt(Math.PI);
  25074. const c1 = c0 * Math.sqrt(0.75);
  25075. this.sh.coefficients[0].copy(sky).add(ground).multiplyScalar(c0);
  25076. this.sh.coefficients[1].copy(sky).sub(ground).multiplyScalar(c1);
  25077. }
  25078. }
  25079. class AmbientLightProbe extends LightProbe {
  25080. constructor(color, intensity = 1) {
  25081. super(undefined, intensity);
  25082. this.isAmbientLightProbe = true;
  25083. const color1 = new Color().set(color); // without extra factor of PI in the shader, would be 2 / Math.sqrt( Math.PI );
  25084. this.sh.coefficients[0].set(color1.r, color1.g, color1.b).multiplyScalar(2 * Math.sqrt(Math.PI));
  25085. }
  25086. }
  25087. const _eyeRight = /*@__PURE__*/new Matrix4();
  25088. const _eyeLeft = /*@__PURE__*/new Matrix4();
  25089. const _projectionMatrix = /*@__PURE__*/new Matrix4();
  25090. class StereoCamera {
  25091. constructor() {
  25092. this.type = 'StereoCamera';
  25093. this.aspect = 1;
  25094. this.eyeSep = 0.064;
  25095. this.cameraL = new PerspectiveCamera();
  25096. this.cameraL.layers.enable(1);
  25097. this.cameraL.matrixAutoUpdate = false;
  25098. this.cameraR = new PerspectiveCamera();
  25099. this.cameraR.layers.enable(2);
  25100. this.cameraR.matrixAutoUpdate = false;
  25101. this._cache = {
  25102. focus: null,
  25103. fov: null,
  25104. aspect: null,
  25105. near: null,
  25106. far: null,
  25107. zoom: null,
  25108. eyeSep: null
  25109. };
  25110. }
  25111. update(camera) {
  25112. const cache = this._cache;
  25113. const needsUpdate = cache.focus !== camera.focus || cache.fov !== camera.fov || cache.aspect !== camera.aspect * this.aspect || cache.near !== camera.near || cache.far !== camera.far || cache.zoom !== camera.zoom || cache.eyeSep !== this.eyeSep;
  25114. if (needsUpdate) {
  25115. cache.focus = camera.focus;
  25116. cache.fov = camera.fov;
  25117. cache.aspect = camera.aspect * this.aspect;
  25118. cache.near = camera.near;
  25119. cache.far = camera.far;
  25120. cache.zoom = camera.zoom;
  25121. cache.eyeSep = this.eyeSep; // Off-axis stereoscopic effect based on
  25122. // http://paulbourke.net/stereographics/stereorender/
  25123. _projectionMatrix.copy(camera.projectionMatrix);
  25124. const eyeSepHalf = cache.eyeSep / 2;
  25125. const eyeSepOnProjection = eyeSepHalf * cache.near / cache.focus;
  25126. const ymax = cache.near * Math.tan(DEG2RAD * cache.fov * 0.5) / cache.zoom;
  25127. let xmin, xmax; // translate xOffset
  25128. _eyeLeft.elements[12] = -eyeSepHalf;
  25129. _eyeRight.elements[12] = eyeSepHalf; // for left eye
  25130. xmin = -ymax * cache.aspect + eyeSepOnProjection;
  25131. xmax = ymax * cache.aspect + eyeSepOnProjection;
  25132. _projectionMatrix.elements[0] = 2 * cache.near / (xmax - xmin);
  25133. _projectionMatrix.elements[8] = (xmax + xmin) / (xmax - xmin);
  25134. this.cameraL.projectionMatrix.copy(_projectionMatrix); // for right eye
  25135. xmin = -ymax * cache.aspect - eyeSepOnProjection;
  25136. xmax = ymax * cache.aspect - eyeSepOnProjection;
  25137. _projectionMatrix.elements[0] = 2 * cache.near / (xmax - xmin);
  25138. _projectionMatrix.elements[8] = (xmax + xmin) / (xmax - xmin);
  25139. this.cameraR.projectionMatrix.copy(_projectionMatrix);
  25140. }
  25141. this.cameraL.matrixWorld.copy(camera.matrixWorld).multiply(_eyeLeft);
  25142. this.cameraR.matrixWorld.copy(camera.matrixWorld).multiply(_eyeRight);
  25143. }
  25144. }
  25145. class Clock {
  25146. constructor(autoStart = true) {
  25147. this.autoStart = autoStart;
  25148. this.startTime = 0;
  25149. this.oldTime = 0;
  25150. this.elapsedTime = 0;
  25151. this.running = false;
  25152. }
  25153. start() {
  25154. this.startTime = now();
  25155. this.oldTime = this.startTime;
  25156. this.elapsedTime = 0;
  25157. this.running = true;
  25158. }
  25159. stop() {
  25160. this.getElapsedTime();
  25161. this.running = false;
  25162. this.autoStart = false;
  25163. }
  25164. getElapsedTime() {
  25165. this.getDelta();
  25166. return this.elapsedTime;
  25167. }
  25168. getDelta() {
  25169. let diff = 0;
  25170. if (this.autoStart && !this.running) {
  25171. this.start();
  25172. return 0;
  25173. }
  25174. if (this.running) {
  25175. const newTime = now();
  25176. diff = (newTime - this.oldTime) / 1000;
  25177. this.oldTime = newTime;
  25178. this.elapsedTime += diff;
  25179. }
  25180. return diff;
  25181. }
  25182. }
  25183. function now() {
  25184. return (typeof performance === 'undefined' ? Date : performance).now(); // see #10732
  25185. }
  25186. const _position$1 = /*@__PURE__*/new Vector3();
  25187. const _quaternion$1 = /*@__PURE__*/new Quaternion();
  25188. const _scale$1 = /*@__PURE__*/new Vector3();
  25189. const _orientation$1 = /*@__PURE__*/new Vector3();
  25190. class AudioListener extends Object3D {
  25191. constructor() {
  25192. super();
  25193. this.type = 'AudioListener';
  25194. this.context = AudioContext.getContext();
  25195. this.gain = this.context.createGain();
  25196. this.gain.connect(this.context.destination);
  25197. this.filter = null;
  25198. this.timeDelta = 0; // private
  25199. this._clock = new Clock();
  25200. }
  25201. getInput() {
  25202. return this.gain;
  25203. }
  25204. removeFilter() {
  25205. if (this.filter !== null) {
  25206. this.gain.disconnect(this.filter);
  25207. this.filter.disconnect(this.context.destination);
  25208. this.gain.connect(this.context.destination);
  25209. this.filter = null;
  25210. }
  25211. return this;
  25212. }
  25213. getFilter() {
  25214. return this.filter;
  25215. }
  25216. setFilter(value) {
  25217. if (this.filter !== null) {
  25218. this.gain.disconnect(this.filter);
  25219. this.filter.disconnect(this.context.destination);
  25220. } else {
  25221. this.gain.disconnect(this.context.destination);
  25222. }
  25223. this.filter = value;
  25224. this.gain.connect(this.filter);
  25225. this.filter.connect(this.context.destination);
  25226. return this;
  25227. }
  25228. getMasterVolume() {
  25229. return this.gain.gain.value;
  25230. }
  25231. setMasterVolume(value) {
  25232. this.gain.gain.setTargetAtTime(value, this.context.currentTime, 0.01);
  25233. return this;
  25234. }
  25235. updateMatrixWorld(force) {
  25236. super.updateMatrixWorld(force);
  25237. const listener = this.context.listener;
  25238. const up = this.up;
  25239. this.timeDelta = this._clock.getDelta();
  25240. this.matrixWorld.decompose(_position$1, _quaternion$1, _scale$1);
  25241. _orientation$1.set(0, 0, -1).applyQuaternion(_quaternion$1);
  25242. if (listener.positionX) {
  25243. // code path for Chrome (see #14393)
  25244. const endTime = this.context.currentTime + this.timeDelta;
  25245. listener.positionX.linearRampToValueAtTime(_position$1.x, endTime);
  25246. listener.positionY.linearRampToValueAtTime(_position$1.y, endTime);
  25247. listener.positionZ.linearRampToValueAtTime(_position$1.z, endTime);
  25248. listener.forwardX.linearRampToValueAtTime(_orientation$1.x, endTime);
  25249. listener.forwardY.linearRampToValueAtTime(_orientation$1.y, endTime);
  25250. listener.forwardZ.linearRampToValueAtTime(_orientation$1.z, endTime);
  25251. listener.upX.linearRampToValueAtTime(up.x, endTime);
  25252. listener.upY.linearRampToValueAtTime(up.y, endTime);
  25253. listener.upZ.linearRampToValueAtTime(up.z, endTime);
  25254. } else {
  25255. listener.setPosition(_position$1.x, _position$1.y, _position$1.z);
  25256. listener.setOrientation(_orientation$1.x, _orientation$1.y, _orientation$1.z, up.x, up.y, up.z);
  25257. }
  25258. }
  25259. }
  25260. class Audio extends Object3D {
  25261. constructor(listener) {
  25262. super();
  25263. this.type = 'Audio';
  25264. this.listener = listener;
  25265. this.context = listener.context;
  25266. this.gain = this.context.createGain();
  25267. this.gain.connect(listener.getInput());
  25268. this.autoplay = false;
  25269. this.buffer = null;
  25270. this.detune = 0;
  25271. this.loop = false;
  25272. this.loopStart = 0;
  25273. this.loopEnd = 0;
  25274. this.offset = 0;
  25275. this.duration = undefined;
  25276. this.playbackRate = 1;
  25277. this.isPlaying = false;
  25278. this.hasPlaybackControl = true;
  25279. this.source = null;
  25280. this.sourceType = 'empty';
  25281. this._startedAt = 0;
  25282. this._progress = 0;
  25283. this._connected = false;
  25284. this.filters = [];
  25285. }
  25286. getOutput() {
  25287. return this.gain;
  25288. }
  25289. setNodeSource(audioNode) {
  25290. this.hasPlaybackControl = false;
  25291. this.sourceType = 'audioNode';
  25292. this.source = audioNode;
  25293. this.connect();
  25294. return this;
  25295. }
  25296. setMediaElementSource(mediaElement) {
  25297. this.hasPlaybackControl = false;
  25298. this.sourceType = 'mediaNode';
  25299. this.source = this.context.createMediaElementSource(mediaElement);
  25300. this.connect();
  25301. return this;
  25302. }
  25303. setMediaStreamSource(mediaStream) {
  25304. this.hasPlaybackControl = false;
  25305. this.sourceType = 'mediaStreamNode';
  25306. this.source = this.context.createMediaStreamSource(mediaStream);
  25307. this.connect();
  25308. return this;
  25309. }
  25310. setBuffer(audioBuffer) {
  25311. this.buffer = audioBuffer;
  25312. this.sourceType = 'buffer';
  25313. if (this.autoplay) this.play();
  25314. return this;
  25315. }
  25316. play(delay = 0) {
  25317. if (this.isPlaying === true) {
  25318. console.warn('THREE.Audio: Audio is already playing.');
  25319. return;
  25320. }
  25321. if (this.hasPlaybackControl === false) {
  25322. console.warn('THREE.Audio: this Audio has no playback control.');
  25323. return;
  25324. }
  25325. this._startedAt = this.context.currentTime + delay;
  25326. const source = this.context.createBufferSource();
  25327. source.buffer = this.buffer;
  25328. source.loop = this.loop;
  25329. source.loopStart = this.loopStart;
  25330. source.loopEnd = this.loopEnd;
  25331. source.onended = this.onEnded.bind(this);
  25332. source.start(this._startedAt, this._progress + this.offset, this.duration);
  25333. this.isPlaying = true;
  25334. this.source = source;
  25335. this.setDetune(this.detune);
  25336. this.setPlaybackRate(this.playbackRate);
  25337. return this.connect();
  25338. }
  25339. pause() {
  25340. if (this.hasPlaybackControl === false) {
  25341. console.warn('THREE.Audio: this Audio has no playback control.');
  25342. return;
  25343. }
  25344. if (this.isPlaying === true) {
  25345. // update current progress
  25346. this._progress += Math.max(this.context.currentTime - this._startedAt, 0) * this.playbackRate;
  25347. if (this.loop === true) {
  25348. // ensure _progress does not exceed duration with looped audios
  25349. this._progress = this._progress % (this.duration || this.buffer.duration);
  25350. }
  25351. this.source.stop();
  25352. this.source.onended = null;
  25353. this.isPlaying = false;
  25354. }
  25355. return this;
  25356. }
  25357. stop() {
  25358. if (this.hasPlaybackControl === false) {
  25359. console.warn('THREE.Audio: this Audio has no playback control.');
  25360. return;
  25361. }
  25362. this._progress = 0;
  25363. this.source.stop();
  25364. this.source.onended = null;
  25365. this.isPlaying = false;
  25366. return this;
  25367. }
  25368. connect() {
  25369. if (this.filters.length > 0) {
  25370. this.source.connect(this.filters[0]);
  25371. for (let i = 1, l = this.filters.length; i < l; i++) {
  25372. this.filters[i - 1].connect(this.filters[i]);
  25373. }
  25374. this.filters[this.filters.length - 1].connect(this.getOutput());
  25375. } else {
  25376. this.source.connect(this.getOutput());
  25377. }
  25378. this._connected = true;
  25379. return this;
  25380. }
  25381. disconnect() {
  25382. if (this.filters.length > 0) {
  25383. this.source.disconnect(this.filters[0]);
  25384. for (let i = 1, l = this.filters.length; i < l; i++) {
  25385. this.filters[i - 1].disconnect(this.filters[i]);
  25386. }
  25387. this.filters[this.filters.length - 1].disconnect(this.getOutput());
  25388. } else {
  25389. this.source.disconnect(this.getOutput());
  25390. }
  25391. this._connected = false;
  25392. return this;
  25393. }
  25394. getFilters() {
  25395. return this.filters;
  25396. }
  25397. setFilters(value) {
  25398. if (!value) value = [];
  25399. if (this._connected === true) {
  25400. this.disconnect();
  25401. this.filters = value.slice();
  25402. this.connect();
  25403. } else {
  25404. this.filters = value.slice();
  25405. }
  25406. return this;
  25407. }
  25408. setDetune(value) {
  25409. this.detune = value;
  25410. if (this.source.detune === undefined) return; // only set detune when available
  25411. if (this.isPlaying === true) {
  25412. this.source.detune.setTargetAtTime(this.detune, this.context.currentTime, 0.01);
  25413. }
  25414. return this;
  25415. }
  25416. getDetune() {
  25417. return this.detune;
  25418. }
  25419. getFilter() {
  25420. return this.getFilters()[0];
  25421. }
  25422. setFilter(filter) {
  25423. return this.setFilters(filter ? [filter] : []);
  25424. }
  25425. setPlaybackRate(value) {
  25426. if (this.hasPlaybackControl === false) {
  25427. console.warn('THREE.Audio: this Audio has no playback control.');
  25428. return;
  25429. }
  25430. this.playbackRate = value;
  25431. if (this.isPlaying === true) {
  25432. this.source.playbackRate.setTargetAtTime(this.playbackRate, this.context.currentTime, 0.01);
  25433. }
  25434. return this;
  25435. }
  25436. getPlaybackRate() {
  25437. return this.playbackRate;
  25438. }
  25439. onEnded() {
  25440. this.isPlaying = false;
  25441. }
  25442. getLoop() {
  25443. if (this.hasPlaybackControl === false) {
  25444. console.warn('THREE.Audio: this Audio has no playback control.');
  25445. return false;
  25446. }
  25447. return this.loop;
  25448. }
  25449. setLoop(value) {
  25450. if (this.hasPlaybackControl === false) {
  25451. console.warn('THREE.Audio: this Audio has no playback control.');
  25452. return;
  25453. }
  25454. this.loop = value;
  25455. if (this.isPlaying === true) {
  25456. this.source.loop = this.loop;
  25457. }
  25458. return this;
  25459. }
  25460. setLoopStart(value) {
  25461. this.loopStart = value;
  25462. return this;
  25463. }
  25464. setLoopEnd(value) {
  25465. this.loopEnd = value;
  25466. return this;
  25467. }
  25468. getVolume() {
  25469. return this.gain.gain.value;
  25470. }
  25471. setVolume(value) {
  25472. this.gain.gain.setTargetAtTime(value, this.context.currentTime, 0.01);
  25473. return this;
  25474. }
  25475. }
  25476. const _position = /*@__PURE__*/new Vector3();
  25477. const _quaternion = /*@__PURE__*/new Quaternion();
  25478. const _scale = /*@__PURE__*/new Vector3();
  25479. const _orientation = /*@__PURE__*/new Vector3();
  25480. class PositionalAudio extends Audio {
  25481. constructor(listener) {
  25482. super(listener);
  25483. this.panner = this.context.createPanner();
  25484. this.panner.panningModel = 'HRTF';
  25485. this.panner.connect(this.gain);
  25486. }
  25487. disconnect() {
  25488. super.disconnect();
  25489. this.panner.disconnect(this.gain);
  25490. }
  25491. getOutput() {
  25492. return this.panner;
  25493. }
  25494. getRefDistance() {
  25495. return this.panner.refDistance;
  25496. }
  25497. setRefDistance(value) {
  25498. this.panner.refDistance = value;
  25499. return this;
  25500. }
  25501. getRolloffFactor() {
  25502. return this.panner.rolloffFactor;
  25503. }
  25504. setRolloffFactor(value) {
  25505. this.panner.rolloffFactor = value;
  25506. return this;
  25507. }
  25508. getDistanceModel() {
  25509. return this.panner.distanceModel;
  25510. }
  25511. setDistanceModel(value) {
  25512. this.panner.distanceModel = value;
  25513. return this;
  25514. }
  25515. getMaxDistance() {
  25516. return this.panner.maxDistance;
  25517. }
  25518. setMaxDistance(value) {
  25519. this.panner.maxDistance = value;
  25520. return this;
  25521. }
  25522. setDirectionalCone(coneInnerAngle, coneOuterAngle, coneOuterGain) {
  25523. this.panner.coneInnerAngle = coneInnerAngle;
  25524. this.panner.coneOuterAngle = coneOuterAngle;
  25525. this.panner.coneOuterGain = coneOuterGain;
  25526. return this;
  25527. }
  25528. updateMatrixWorld(force) {
  25529. super.updateMatrixWorld(force);
  25530. if (this.hasPlaybackControl === true && this.isPlaying === false) return;
  25531. this.matrixWorld.decompose(_position, _quaternion, _scale);
  25532. _orientation.set(0, 0, 1).applyQuaternion(_quaternion);
  25533. const panner = this.panner;
  25534. if (panner.positionX) {
  25535. // code path for Chrome and Firefox (see #14393)
  25536. const endTime = this.context.currentTime + this.listener.timeDelta;
  25537. panner.positionX.linearRampToValueAtTime(_position.x, endTime);
  25538. panner.positionY.linearRampToValueAtTime(_position.y, endTime);
  25539. panner.positionZ.linearRampToValueAtTime(_position.z, endTime);
  25540. panner.orientationX.linearRampToValueAtTime(_orientation.x, endTime);
  25541. panner.orientationY.linearRampToValueAtTime(_orientation.y, endTime);
  25542. panner.orientationZ.linearRampToValueAtTime(_orientation.z, endTime);
  25543. } else {
  25544. panner.setPosition(_position.x, _position.y, _position.z);
  25545. panner.setOrientation(_orientation.x, _orientation.y, _orientation.z);
  25546. }
  25547. }
  25548. }
  25549. class AudioAnalyser {
  25550. constructor(audio, fftSize = 2048) {
  25551. this.analyser = audio.context.createAnalyser();
  25552. this.analyser.fftSize = fftSize;
  25553. this.data = new Uint8Array(this.analyser.frequencyBinCount);
  25554. audio.getOutput().connect(this.analyser);
  25555. }
  25556. getFrequencyData() {
  25557. this.analyser.getByteFrequencyData(this.data);
  25558. return this.data;
  25559. }
  25560. getAverageFrequency() {
  25561. let value = 0;
  25562. const data = this.getFrequencyData();
  25563. for (let i = 0; i < data.length; i++) {
  25564. value += data[i];
  25565. }
  25566. return value / data.length;
  25567. }
  25568. }
  25569. class PropertyMixer {
  25570. constructor(binding, typeName, valueSize) {
  25571. this.binding = binding;
  25572. this.valueSize = valueSize;
  25573. let mixFunction, mixFunctionAdditive, setIdentity; // buffer layout: [ incoming | accu0 | accu1 | orig | addAccu | (optional work) ]
  25574. //
  25575. // interpolators can use .buffer as their .result
  25576. // the data then goes to 'incoming'
  25577. //
  25578. // 'accu0' and 'accu1' are used frame-interleaved for
  25579. // the cumulative result and are compared to detect
  25580. // changes
  25581. //
  25582. // 'orig' stores the original state of the property
  25583. //
  25584. // 'add' is used for additive cumulative results
  25585. //
  25586. // 'work' is optional and is only present for quaternion types. It is used
  25587. // to store intermediate quaternion multiplication results
  25588. switch (typeName) {
  25589. case 'quaternion':
  25590. mixFunction = this._slerp;
  25591. mixFunctionAdditive = this._slerpAdditive;
  25592. setIdentity = this._setAdditiveIdentityQuaternion;
  25593. this.buffer = new Float64Array(valueSize * 6);
  25594. this._workIndex = 5;
  25595. break;
  25596. case 'string':
  25597. case 'bool':
  25598. mixFunction = this._select; // Use the regular mix function and for additive on these types,
  25599. // additive is not relevant for non-numeric types
  25600. mixFunctionAdditive = this._select;
  25601. setIdentity = this._setAdditiveIdentityOther;
  25602. this.buffer = new Array(valueSize * 5);
  25603. break;
  25604. default:
  25605. mixFunction = this._lerp;
  25606. mixFunctionAdditive = this._lerpAdditive;
  25607. setIdentity = this._setAdditiveIdentityNumeric;
  25608. this.buffer = new Float64Array(valueSize * 5);
  25609. }
  25610. this._mixBufferRegion = mixFunction;
  25611. this._mixBufferRegionAdditive = mixFunctionAdditive;
  25612. this._setIdentity = setIdentity;
  25613. this._origIndex = 3;
  25614. this._addIndex = 4;
  25615. this.cumulativeWeight = 0;
  25616. this.cumulativeWeightAdditive = 0;
  25617. this.useCount = 0;
  25618. this.referenceCount = 0;
  25619. } // accumulate data in the 'incoming' region into 'accu<i>'
  25620. accumulate(accuIndex, weight) {
  25621. // note: happily accumulating nothing when weight = 0, the caller knows
  25622. // the weight and shouldn't have made the call in the first place
  25623. const buffer = this.buffer,
  25624. stride = this.valueSize,
  25625. offset = accuIndex * stride + stride;
  25626. let currentWeight = this.cumulativeWeight;
  25627. if (currentWeight === 0) {
  25628. // accuN := incoming * weight
  25629. for (let i = 0; i !== stride; ++i) {
  25630. buffer[offset + i] = buffer[i];
  25631. }
  25632. currentWeight = weight;
  25633. } else {
  25634. // accuN := accuN + incoming * weight
  25635. currentWeight += weight;
  25636. const mix = weight / currentWeight;
  25637. this._mixBufferRegion(buffer, offset, 0, mix, stride);
  25638. }
  25639. this.cumulativeWeight = currentWeight;
  25640. } // accumulate data in the 'incoming' region into 'add'
  25641. accumulateAdditive(weight) {
  25642. const buffer = this.buffer,
  25643. stride = this.valueSize,
  25644. offset = stride * this._addIndex;
  25645. if (this.cumulativeWeightAdditive === 0) {
  25646. // add = identity
  25647. this._setIdentity();
  25648. } // add := add + incoming * weight
  25649. this._mixBufferRegionAdditive(buffer, offset, 0, weight, stride);
  25650. this.cumulativeWeightAdditive += weight;
  25651. } // apply the state of 'accu<i>' to the binding when accus differ
  25652. apply(accuIndex) {
  25653. const stride = this.valueSize,
  25654. buffer = this.buffer,
  25655. offset = accuIndex * stride + stride,
  25656. weight = this.cumulativeWeight,
  25657. weightAdditive = this.cumulativeWeightAdditive,
  25658. binding = this.binding;
  25659. this.cumulativeWeight = 0;
  25660. this.cumulativeWeightAdditive = 0;
  25661. if (weight < 1) {
  25662. // accuN := accuN + original * ( 1 - cumulativeWeight )
  25663. const originalValueOffset = stride * this._origIndex;
  25664. this._mixBufferRegion(buffer, offset, originalValueOffset, 1 - weight, stride);
  25665. }
  25666. if (weightAdditive > 0) {
  25667. // accuN := accuN + additive accuN
  25668. this._mixBufferRegionAdditive(buffer, offset, this._addIndex * stride, 1, stride);
  25669. }
  25670. for (let i = stride, e = stride + stride; i !== e; ++i) {
  25671. if (buffer[i] !== buffer[i + stride]) {
  25672. // value has changed -> update scene graph
  25673. binding.setValue(buffer, offset);
  25674. break;
  25675. }
  25676. }
  25677. } // remember the state of the bound property and copy it to both accus
  25678. saveOriginalState() {
  25679. const binding = this.binding;
  25680. const buffer = this.buffer,
  25681. stride = this.valueSize,
  25682. originalValueOffset = stride * this._origIndex;
  25683. binding.getValue(buffer, originalValueOffset); // accu[0..1] := orig -- initially detect changes against the original
  25684. for (let i = stride, e = originalValueOffset; i !== e; ++i) {
  25685. buffer[i] = buffer[originalValueOffset + i % stride];
  25686. } // Add to identity for additive
  25687. this._setIdentity();
  25688. this.cumulativeWeight = 0;
  25689. this.cumulativeWeightAdditive = 0;
  25690. } // apply the state previously taken via 'saveOriginalState' to the binding
  25691. restoreOriginalState() {
  25692. const originalValueOffset = this.valueSize * 3;
  25693. this.binding.setValue(this.buffer, originalValueOffset);
  25694. }
  25695. _setAdditiveIdentityNumeric() {
  25696. const startIndex = this._addIndex * this.valueSize;
  25697. const endIndex = startIndex + this.valueSize;
  25698. for (let i = startIndex; i < endIndex; i++) {
  25699. this.buffer[i] = 0;
  25700. }
  25701. }
  25702. _setAdditiveIdentityQuaternion() {
  25703. this._setAdditiveIdentityNumeric();
  25704. this.buffer[this._addIndex * this.valueSize + 3] = 1;
  25705. }
  25706. _setAdditiveIdentityOther() {
  25707. const startIndex = this._origIndex * this.valueSize;
  25708. const targetIndex = this._addIndex * this.valueSize;
  25709. for (let i = 0; i < this.valueSize; i++) {
  25710. this.buffer[targetIndex + i] = this.buffer[startIndex + i];
  25711. }
  25712. } // mix functions
  25713. _select(buffer, dstOffset, srcOffset, t, stride) {
  25714. if (t >= 0.5) {
  25715. for (let i = 0; i !== stride; ++i) {
  25716. buffer[dstOffset + i] = buffer[srcOffset + i];
  25717. }
  25718. }
  25719. }
  25720. _slerp(buffer, dstOffset, srcOffset, t) {
  25721. Quaternion.slerpFlat(buffer, dstOffset, buffer, dstOffset, buffer, srcOffset, t);
  25722. }
  25723. _slerpAdditive(buffer, dstOffset, srcOffset, t, stride) {
  25724. const workOffset = this._workIndex * stride; // Store result in intermediate buffer offset
  25725. Quaternion.multiplyQuaternionsFlat(buffer, workOffset, buffer, dstOffset, buffer, srcOffset); // Slerp to the intermediate result
  25726. Quaternion.slerpFlat(buffer, dstOffset, buffer, dstOffset, buffer, workOffset, t);
  25727. }
  25728. _lerp(buffer, dstOffset, srcOffset, t, stride) {
  25729. const s = 1 - t;
  25730. for (let i = 0; i !== stride; ++i) {
  25731. const j = dstOffset + i;
  25732. buffer[j] = buffer[j] * s + buffer[srcOffset + i] * t;
  25733. }
  25734. }
  25735. _lerpAdditive(buffer, dstOffset, srcOffset, t, stride) {
  25736. for (let i = 0; i !== stride; ++i) {
  25737. const j = dstOffset + i;
  25738. buffer[j] = buffer[j] + buffer[srcOffset + i] * t;
  25739. }
  25740. }
  25741. }
  25742. // Characters [].:/ are reserved for track binding syntax.
  25743. const _RESERVED_CHARS_RE = '\\[\\]\\.:\\/';
  25744. const _reservedRe = new RegExp('[' + _RESERVED_CHARS_RE + ']', 'g'); // Attempts to allow node names from any language. ES5's `\w` regexp matches
  25745. // only latin characters, and the unicode \p{L} is not yet supported. So
  25746. // instead, we exclude reserved characters and match everything else.
  25747. const _wordChar = '[^' + _RESERVED_CHARS_RE + ']';
  25748. const _wordCharOrDot = '[^' + _RESERVED_CHARS_RE.replace('\\.', '') + ']'; // Parent directories, delimited by '/' or ':'. Currently unused, but must
  25749. // be matched to parse the rest of the track name.
  25750. const _directoryRe = /*@__PURE__*/ /((?:WC+[\/:])*)/.source.replace('WC', _wordChar); // Target node. May contain word characters (a-zA-Z0-9_) and '.' or '-'.
  25751. const _nodeRe = /*@__PURE__*/ /(WCOD+)?/.source.replace('WCOD', _wordCharOrDot); // Object on target node, and accessor. May not contain reserved
  25752. // characters. Accessor may contain any character except closing bracket.
  25753. const _objectRe = /*@__PURE__*/ /(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace('WC', _wordChar); // Property and accessor. May not contain reserved characters. Accessor may
  25754. // contain any non-bracket characters.
  25755. const _propertyRe = /*@__PURE__*/ /\.(WC+)(?:\[(.+)\])?/.source.replace('WC', _wordChar);
  25756. const _trackRe = new RegExp('' + '^' + _directoryRe + _nodeRe + _objectRe + _propertyRe + '$');
  25757. const _supportedObjectNames = ['material', 'materials', 'bones', 'map'];
  25758. class Composite {
  25759. constructor(targetGroup, path, optionalParsedPath) {
  25760. const parsedPath = optionalParsedPath || PropertyBinding.parseTrackName(path);
  25761. this._targetGroup = targetGroup;
  25762. this._bindings = targetGroup.subscribe_(path, parsedPath);
  25763. }
  25764. getValue(array, offset) {
  25765. this.bind(); // bind all binding
  25766. const firstValidIndex = this._targetGroup.nCachedObjects_,
  25767. binding = this._bindings[firstValidIndex]; // and only call .getValue on the first
  25768. if (binding !== undefined) binding.getValue(array, offset);
  25769. }
  25770. setValue(array, offset) {
  25771. const bindings = this._bindings;
  25772. for (let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++i) {
  25773. bindings[i].setValue(array, offset);
  25774. }
  25775. }
  25776. bind() {
  25777. const bindings = this._bindings;
  25778. for (let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++i) {
  25779. bindings[i].bind();
  25780. }
  25781. }
  25782. unbind() {
  25783. const bindings = this._bindings;
  25784. for (let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++i) {
  25785. bindings[i].unbind();
  25786. }
  25787. }
  25788. } // Note: This class uses a State pattern on a per-method basis:
  25789. // 'bind' sets 'this.getValue' / 'setValue' and shadows the
  25790. // prototype version of these methods with one that represents
  25791. // the bound state. When the property is not found, the methods
  25792. // become no-ops.
  25793. class PropertyBinding {
  25794. constructor(rootNode, path, parsedPath) {
  25795. this.path = path;
  25796. this.parsedPath = parsedPath || PropertyBinding.parseTrackName(path);
  25797. this.node = PropertyBinding.findNode(rootNode, this.parsedPath.nodeName) || rootNode;
  25798. this.rootNode = rootNode; // initial state of these methods that calls 'bind'
  25799. this.getValue = this._getValue_unbound;
  25800. this.setValue = this._setValue_unbound;
  25801. }
  25802. static create(root, path, parsedPath) {
  25803. if (!(root && root.isAnimationObjectGroup)) {
  25804. return new PropertyBinding(root, path, parsedPath);
  25805. } else {
  25806. return new PropertyBinding.Composite(root, path, parsedPath);
  25807. }
  25808. }
  25809. /**
  25810. * Replaces spaces with underscores and removes unsupported characters from
  25811. * node names, to ensure compatibility with parseTrackName().
  25812. *
  25813. * @param {string} name Node name to be sanitized.
  25814. * @return {string}
  25815. */
  25816. static sanitizeNodeName(name) {
  25817. return name.replace(/\s/g, '_').replace(_reservedRe, '');
  25818. }
  25819. static parseTrackName(trackName) {
  25820. const matches = _trackRe.exec(trackName);
  25821. if (matches === null) {
  25822. throw new Error('PropertyBinding: Cannot parse trackName: ' + trackName);
  25823. }
  25824. const results = {
  25825. // directoryName: matches[ 1 ], // (tschw) currently unused
  25826. nodeName: matches[2],
  25827. objectName: matches[3],
  25828. objectIndex: matches[4],
  25829. propertyName: matches[5],
  25830. // required
  25831. propertyIndex: matches[6]
  25832. };
  25833. const lastDot = results.nodeName && results.nodeName.lastIndexOf('.');
  25834. if (lastDot !== undefined && lastDot !== -1) {
  25835. const objectName = results.nodeName.substring(lastDot + 1); // Object names must be checked against an allowlist. Otherwise, there
  25836. // is no way to parse 'foo.bar.baz': 'baz' must be a property, but
  25837. // 'bar' could be the objectName, or part of a nodeName (which can
  25838. // include '.' characters).
  25839. if (_supportedObjectNames.indexOf(objectName) !== -1) {
  25840. results.nodeName = results.nodeName.substring(0, lastDot);
  25841. results.objectName = objectName;
  25842. }
  25843. }
  25844. if (results.propertyName === null || results.propertyName.length === 0) {
  25845. throw new Error('PropertyBinding: can not parse propertyName from trackName: ' + trackName);
  25846. }
  25847. return results;
  25848. }
  25849. static findNode(root, nodeName) {
  25850. if (nodeName === undefined || nodeName === '' || nodeName === '.' || nodeName === -1 || nodeName === root.name || nodeName === root.uuid) {
  25851. return root;
  25852. } // search into skeleton bones.
  25853. if (root.skeleton) {
  25854. const bone = root.skeleton.getBoneByName(nodeName);
  25855. if (bone !== undefined) {
  25856. return bone;
  25857. }
  25858. } // search into node subtree.
  25859. if (root.children) {
  25860. const searchNodeSubtree = function (children) {
  25861. for (let i = 0; i < children.length; i++) {
  25862. const childNode = children[i];
  25863. if (childNode.name === nodeName || childNode.uuid === nodeName) {
  25864. return childNode;
  25865. }
  25866. const result = searchNodeSubtree(childNode.children);
  25867. if (result) return result;
  25868. }
  25869. return null;
  25870. };
  25871. const subTreeNode = searchNodeSubtree(root.children);
  25872. if (subTreeNode) {
  25873. return subTreeNode;
  25874. }
  25875. }
  25876. return null;
  25877. } // these are used to "bind" a nonexistent property
  25878. _getValue_unavailable() {}
  25879. _setValue_unavailable() {} // Getters
  25880. _getValue_direct(buffer, offset) {
  25881. buffer[offset] = this.targetObject[this.propertyName];
  25882. }
  25883. _getValue_array(buffer, offset) {
  25884. const source = this.resolvedProperty;
  25885. for (let i = 0, n = source.length; i !== n; ++i) {
  25886. buffer[offset++] = source[i];
  25887. }
  25888. }
  25889. _getValue_arrayElement(buffer, offset) {
  25890. buffer[offset] = this.resolvedProperty[this.propertyIndex];
  25891. }
  25892. _getValue_toArray(buffer, offset) {
  25893. this.resolvedProperty.toArray(buffer, offset);
  25894. } // Direct
  25895. _setValue_direct(buffer, offset) {
  25896. this.targetObject[this.propertyName] = buffer[offset];
  25897. }
  25898. _setValue_direct_setNeedsUpdate(buffer, offset) {
  25899. this.targetObject[this.propertyName] = buffer[offset];
  25900. this.targetObject.needsUpdate = true;
  25901. }
  25902. _setValue_direct_setMatrixWorldNeedsUpdate(buffer, offset) {
  25903. this.targetObject[this.propertyName] = buffer[offset];
  25904. this.targetObject.matrixWorldNeedsUpdate = true;
  25905. } // EntireArray
  25906. _setValue_array(buffer, offset) {
  25907. const dest = this.resolvedProperty;
  25908. for (let i = 0, n = dest.length; i !== n; ++i) {
  25909. dest[i] = buffer[offset++];
  25910. }
  25911. }
  25912. _setValue_array_setNeedsUpdate(buffer, offset) {
  25913. const dest = this.resolvedProperty;
  25914. for (let i = 0, n = dest.length; i !== n; ++i) {
  25915. dest[i] = buffer[offset++];
  25916. }
  25917. this.targetObject.needsUpdate = true;
  25918. }
  25919. _setValue_array_setMatrixWorldNeedsUpdate(buffer, offset) {
  25920. const dest = this.resolvedProperty;
  25921. for (let i = 0, n = dest.length; i !== n; ++i) {
  25922. dest[i] = buffer[offset++];
  25923. }
  25924. this.targetObject.matrixWorldNeedsUpdate = true;
  25925. } // ArrayElement
  25926. _setValue_arrayElement(buffer, offset) {
  25927. this.resolvedProperty[this.propertyIndex] = buffer[offset];
  25928. }
  25929. _setValue_arrayElement_setNeedsUpdate(buffer, offset) {
  25930. this.resolvedProperty[this.propertyIndex] = buffer[offset];
  25931. this.targetObject.needsUpdate = true;
  25932. }
  25933. _setValue_arrayElement_setMatrixWorldNeedsUpdate(buffer, offset) {
  25934. this.resolvedProperty[this.propertyIndex] = buffer[offset];
  25935. this.targetObject.matrixWorldNeedsUpdate = true;
  25936. } // HasToFromArray
  25937. _setValue_fromArray(buffer, offset) {
  25938. this.resolvedProperty.fromArray(buffer, offset);
  25939. }
  25940. _setValue_fromArray_setNeedsUpdate(buffer, offset) {
  25941. this.resolvedProperty.fromArray(buffer, offset);
  25942. this.targetObject.needsUpdate = true;
  25943. }
  25944. _setValue_fromArray_setMatrixWorldNeedsUpdate(buffer, offset) {
  25945. this.resolvedProperty.fromArray(buffer, offset);
  25946. this.targetObject.matrixWorldNeedsUpdate = true;
  25947. }
  25948. _getValue_unbound(targetArray, offset) {
  25949. this.bind();
  25950. this.getValue(targetArray, offset);
  25951. }
  25952. _setValue_unbound(sourceArray, offset) {
  25953. this.bind();
  25954. this.setValue(sourceArray, offset);
  25955. } // create getter / setter pair for a property in the scene graph
  25956. bind() {
  25957. let targetObject = this.node;
  25958. const parsedPath = this.parsedPath;
  25959. const objectName = parsedPath.objectName;
  25960. const propertyName = parsedPath.propertyName;
  25961. let propertyIndex = parsedPath.propertyIndex;
  25962. if (!targetObject) {
  25963. targetObject = PropertyBinding.findNode(this.rootNode, parsedPath.nodeName) || this.rootNode;
  25964. this.node = targetObject;
  25965. } // set fail state so we can just 'return' on error
  25966. this.getValue = this._getValue_unavailable;
  25967. this.setValue = this._setValue_unavailable; // ensure there is a value node
  25968. if (!targetObject) {
  25969. console.error('THREE.PropertyBinding: Trying to update node for track: ' + this.path + ' but it wasn\'t found.');
  25970. return;
  25971. }
  25972. if (objectName) {
  25973. let objectIndex = parsedPath.objectIndex; // special cases were we need to reach deeper into the hierarchy to get the face materials....
  25974. switch (objectName) {
  25975. case 'materials':
  25976. if (!targetObject.material) {
  25977. console.error('THREE.PropertyBinding: Can not bind to material as node does not have a material.', this);
  25978. return;
  25979. }
  25980. if (!targetObject.material.materials) {
  25981. console.error('THREE.PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.', this);
  25982. return;
  25983. }
  25984. targetObject = targetObject.material.materials;
  25985. break;
  25986. case 'bones':
  25987. if (!targetObject.skeleton) {
  25988. console.error('THREE.PropertyBinding: Can not bind to bones as node does not have a skeleton.', this);
  25989. return;
  25990. } // potential future optimization: skip this if propertyIndex is already an integer
  25991. // and convert the integer string to a true integer.
  25992. targetObject = targetObject.skeleton.bones; // support resolving morphTarget names into indices.
  25993. for (let i = 0; i < targetObject.length; i++) {
  25994. if (targetObject[i].name === objectIndex) {
  25995. objectIndex = i;
  25996. break;
  25997. }
  25998. }
  25999. break;
  26000. case 'map':
  26001. if ('map' in targetObject) {
  26002. targetObject = targetObject.map;
  26003. break;
  26004. }
  26005. if (!targetObject.material) {
  26006. console.error('THREE.PropertyBinding: Can not bind to material as node does not have a material.', this);
  26007. return;
  26008. }
  26009. if (!targetObject.material.map) {
  26010. console.error('THREE.PropertyBinding: Can not bind to material.map as node.material does not have a map.', this);
  26011. return;
  26012. }
  26013. targetObject = targetObject.material.map;
  26014. break;
  26015. default:
  26016. if (targetObject[objectName] === undefined) {
  26017. console.error('THREE.PropertyBinding: Can not bind to objectName of node undefined.', this);
  26018. return;
  26019. }
  26020. targetObject = targetObject[objectName];
  26021. }
  26022. if (objectIndex !== undefined) {
  26023. if (targetObject[objectIndex] === undefined) {
  26024. console.error('THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.', this, targetObject);
  26025. return;
  26026. }
  26027. targetObject = targetObject[objectIndex];
  26028. }
  26029. } // resolve property
  26030. const nodeProperty = targetObject[propertyName];
  26031. if (nodeProperty === undefined) {
  26032. const nodeName = parsedPath.nodeName;
  26033. console.error('THREE.PropertyBinding: Trying to update property for track: ' + nodeName + '.' + propertyName + ' but it wasn\'t found.', targetObject);
  26034. return;
  26035. } // determine versioning scheme
  26036. let versioning = this.Versioning.None;
  26037. this.targetObject = targetObject;
  26038. if (targetObject.needsUpdate !== undefined) {
  26039. // material
  26040. versioning = this.Versioning.NeedsUpdate;
  26041. } else if (targetObject.matrixWorldNeedsUpdate !== undefined) {
  26042. // node transform
  26043. versioning = this.Versioning.MatrixWorldNeedsUpdate;
  26044. } // determine how the property gets bound
  26045. let bindingType = this.BindingType.Direct;
  26046. if (propertyIndex !== undefined) {
  26047. // access a sub element of the property array (only primitives are supported right now)
  26048. if (propertyName === 'morphTargetInfluences') {
  26049. // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer.
  26050. // support resolving morphTarget names into indices.
  26051. if (!targetObject.geometry) {
  26052. console.error('THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.', this);
  26053. return;
  26054. }
  26055. if (!targetObject.geometry.morphAttributes) {
  26056. console.error('THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.', this);
  26057. return;
  26058. }
  26059. if (targetObject.morphTargetDictionary[propertyIndex] !== undefined) {
  26060. propertyIndex = targetObject.morphTargetDictionary[propertyIndex];
  26061. }
  26062. }
  26063. bindingType = this.BindingType.ArrayElement;
  26064. this.resolvedProperty = nodeProperty;
  26065. this.propertyIndex = propertyIndex;
  26066. } else if (nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined) {
  26067. // must use copy for Object3D.Euler/Quaternion
  26068. bindingType = this.BindingType.HasFromToArray;
  26069. this.resolvedProperty = nodeProperty;
  26070. } else if (Array.isArray(nodeProperty)) {
  26071. bindingType = this.BindingType.EntireArray;
  26072. this.resolvedProperty = nodeProperty;
  26073. } else {
  26074. this.propertyName = propertyName;
  26075. } // select getter / setter
  26076. this.getValue = this.GetterByBindingType[bindingType];
  26077. this.setValue = this.SetterByBindingTypeAndVersioning[bindingType][versioning];
  26078. }
  26079. unbind() {
  26080. this.node = null; // back to the prototype version of getValue / setValue
  26081. // note: avoiding to mutate the shape of 'this' via 'delete'
  26082. this.getValue = this._getValue_unbound;
  26083. this.setValue = this._setValue_unbound;
  26084. }
  26085. }
  26086. PropertyBinding.Composite = Composite;
  26087. PropertyBinding.prototype.BindingType = {
  26088. Direct: 0,
  26089. EntireArray: 1,
  26090. ArrayElement: 2,
  26091. HasFromToArray: 3
  26092. };
  26093. PropertyBinding.prototype.Versioning = {
  26094. None: 0,
  26095. NeedsUpdate: 1,
  26096. MatrixWorldNeedsUpdate: 2
  26097. };
  26098. PropertyBinding.prototype.GetterByBindingType = [PropertyBinding.prototype._getValue_direct, PropertyBinding.prototype._getValue_array, PropertyBinding.prototype._getValue_arrayElement, PropertyBinding.prototype._getValue_toArray];
  26099. PropertyBinding.prototype.SetterByBindingTypeAndVersioning = [[// Direct
  26100. PropertyBinding.prototype._setValue_direct, PropertyBinding.prototype._setValue_direct_setNeedsUpdate, PropertyBinding.prototype._setValue_direct_setMatrixWorldNeedsUpdate], [// EntireArray
  26101. PropertyBinding.prototype._setValue_array, PropertyBinding.prototype._setValue_array_setNeedsUpdate, PropertyBinding.prototype._setValue_array_setMatrixWorldNeedsUpdate], [// ArrayElement
  26102. PropertyBinding.prototype._setValue_arrayElement, PropertyBinding.prototype._setValue_arrayElement_setNeedsUpdate, PropertyBinding.prototype._setValue_arrayElement_setMatrixWorldNeedsUpdate], [// HasToFromArray
  26103. PropertyBinding.prototype._setValue_fromArray, PropertyBinding.prototype._setValue_fromArray_setNeedsUpdate, PropertyBinding.prototype._setValue_fromArray_setMatrixWorldNeedsUpdate]];
  26104. /**
  26105. *
  26106. * A group of objects that receives a shared animation state.
  26107. *
  26108. * Usage:
  26109. *
  26110. * - Add objects you would otherwise pass as 'root' to the
  26111. * constructor or the .clipAction method of AnimationMixer.
  26112. *
  26113. * - Instead pass this object as 'root'.
  26114. *
  26115. * - You can also add and remove objects later when the mixer
  26116. * is running.
  26117. *
  26118. * Note:
  26119. *
  26120. * Objects of this class appear as one object to the mixer,
  26121. * so cache control of the individual objects must be done
  26122. * on the group.
  26123. *
  26124. * Limitation:
  26125. *
  26126. * - The animated properties must be compatible among the
  26127. * all objects in the group.
  26128. *
  26129. * - A single property can either be controlled through a
  26130. * target group or directly, but not both.
  26131. */
  26132. class AnimationObjectGroup {
  26133. constructor() {
  26134. this.isAnimationObjectGroup = true;
  26135. this.uuid = generateUUID(); // cached objects followed by the active ones
  26136. this._objects = Array.prototype.slice.call(arguments);
  26137. this.nCachedObjects_ = 0; // threshold
  26138. // note: read by PropertyBinding.Composite
  26139. const indices = {};
  26140. this._indicesByUUID = indices; // for bookkeeping
  26141. for (let i = 0, n = arguments.length; i !== n; ++i) {
  26142. indices[arguments[i].uuid] = i;
  26143. }
  26144. this._paths = []; // inside: string
  26145. this._parsedPaths = []; // inside: { we don't care, here }
  26146. this._bindings = []; // inside: Array< PropertyBinding >
  26147. this._bindingsIndicesByPath = {}; // inside: indices in these arrays
  26148. const scope = this;
  26149. this.stats = {
  26150. objects: {
  26151. get total() {
  26152. return scope._objects.length;
  26153. },
  26154. get inUse() {
  26155. return this.total - scope.nCachedObjects_;
  26156. }
  26157. },
  26158. get bindingsPerObject() {
  26159. return scope._bindings.length;
  26160. }
  26161. };
  26162. }
  26163. add() {
  26164. const objects = this._objects,
  26165. indicesByUUID = this._indicesByUUID,
  26166. paths = this._paths,
  26167. parsedPaths = this._parsedPaths,
  26168. bindings = this._bindings,
  26169. nBindings = bindings.length;
  26170. let knownObject = undefined,
  26171. nObjects = objects.length,
  26172. nCachedObjects = this.nCachedObjects_;
  26173. for (let i = 0, n = arguments.length; i !== n; ++i) {
  26174. const object = arguments[i],
  26175. uuid = object.uuid;
  26176. let index = indicesByUUID[uuid];
  26177. if (index === undefined) {
  26178. // unknown object -> add it to the ACTIVE region
  26179. index = nObjects++;
  26180. indicesByUUID[uuid] = index;
  26181. objects.push(object); // accounting is done, now do the same for all bindings
  26182. for (let j = 0, m = nBindings; j !== m; ++j) {
  26183. bindings[j].push(new PropertyBinding(object, paths[j], parsedPaths[j]));
  26184. }
  26185. } else if (index < nCachedObjects) {
  26186. knownObject = objects[index]; // move existing object to the ACTIVE region
  26187. const firstActiveIndex = --nCachedObjects,
  26188. lastCachedObject = objects[firstActiveIndex];
  26189. indicesByUUID[lastCachedObject.uuid] = index;
  26190. objects[index] = lastCachedObject;
  26191. indicesByUUID[uuid] = firstActiveIndex;
  26192. objects[firstActiveIndex] = object; // accounting is done, now do the same for all bindings
  26193. for (let j = 0, m = nBindings; j !== m; ++j) {
  26194. const bindingsForPath = bindings[j],
  26195. lastCached = bindingsForPath[firstActiveIndex];
  26196. let binding = bindingsForPath[index];
  26197. bindingsForPath[index] = lastCached;
  26198. if (binding === undefined) {
  26199. // since we do not bother to create new bindings
  26200. // for objects that are cached, the binding may
  26201. // or may not exist
  26202. binding = new PropertyBinding(object, paths[j], parsedPaths[j]);
  26203. }
  26204. bindingsForPath[firstActiveIndex] = binding;
  26205. }
  26206. } else if (objects[index] !== knownObject) {
  26207. console.error('THREE.AnimationObjectGroup: Different objects with the same UUID ' + 'detected. Clean the caches or recreate your infrastructure when reloading scenes.');
  26208. } // else the object is already where we want it to be
  26209. } // for arguments
  26210. this.nCachedObjects_ = nCachedObjects;
  26211. }
  26212. remove() {
  26213. const objects = this._objects,
  26214. indicesByUUID = this._indicesByUUID,
  26215. bindings = this._bindings,
  26216. nBindings = bindings.length;
  26217. let nCachedObjects = this.nCachedObjects_;
  26218. for (let i = 0, n = arguments.length; i !== n; ++i) {
  26219. const object = arguments[i],
  26220. uuid = object.uuid,
  26221. index = indicesByUUID[uuid];
  26222. if (index !== undefined && index >= nCachedObjects) {
  26223. // move existing object into the CACHED region
  26224. const lastCachedIndex = nCachedObjects++,
  26225. firstActiveObject = objects[lastCachedIndex];
  26226. indicesByUUID[firstActiveObject.uuid] = index;
  26227. objects[index] = firstActiveObject;
  26228. indicesByUUID[uuid] = lastCachedIndex;
  26229. objects[lastCachedIndex] = object; // accounting is done, now do the same for all bindings
  26230. for (let j = 0, m = nBindings; j !== m; ++j) {
  26231. const bindingsForPath = bindings[j],
  26232. firstActive = bindingsForPath[lastCachedIndex],
  26233. binding = bindingsForPath[index];
  26234. bindingsForPath[index] = firstActive;
  26235. bindingsForPath[lastCachedIndex] = binding;
  26236. }
  26237. }
  26238. } // for arguments
  26239. this.nCachedObjects_ = nCachedObjects;
  26240. } // remove & forget
  26241. uncache() {
  26242. const objects = this._objects,
  26243. indicesByUUID = this._indicesByUUID,
  26244. bindings = this._bindings,
  26245. nBindings = bindings.length;
  26246. let nCachedObjects = this.nCachedObjects_,
  26247. nObjects = objects.length;
  26248. for (let i = 0, n = arguments.length; i !== n; ++i) {
  26249. const object = arguments[i],
  26250. uuid = object.uuid,
  26251. index = indicesByUUID[uuid];
  26252. if (index !== undefined) {
  26253. delete indicesByUUID[uuid];
  26254. if (index < nCachedObjects) {
  26255. // object is cached, shrink the CACHED region
  26256. const firstActiveIndex = --nCachedObjects,
  26257. lastCachedObject = objects[firstActiveIndex],
  26258. lastIndex = --nObjects,
  26259. lastObject = objects[lastIndex]; // last cached object takes this object's place
  26260. indicesByUUID[lastCachedObject.uuid] = index;
  26261. objects[index] = lastCachedObject; // last object goes to the activated slot and pop
  26262. indicesByUUID[lastObject.uuid] = firstActiveIndex;
  26263. objects[firstActiveIndex] = lastObject;
  26264. objects.pop(); // accounting is done, now do the same for all bindings
  26265. for (let j = 0, m = nBindings; j !== m; ++j) {
  26266. const bindingsForPath = bindings[j],
  26267. lastCached = bindingsForPath[firstActiveIndex],
  26268. last = bindingsForPath[lastIndex];
  26269. bindingsForPath[index] = lastCached;
  26270. bindingsForPath[firstActiveIndex] = last;
  26271. bindingsForPath.pop();
  26272. }
  26273. } else {
  26274. // object is active, just swap with the last and pop
  26275. const lastIndex = --nObjects,
  26276. lastObject = objects[lastIndex];
  26277. if (lastIndex > 0) {
  26278. indicesByUUID[lastObject.uuid] = index;
  26279. }
  26280. objects[index] = lastObject;
  26281. objects.pop(); // accounting is done, now do the same for all bindings
  26282. for (let j = 0, m = nBindings; j !== m; ++j) {
  26283. const bindingsForPath = bindings[j];
  26284. bindingsForPath[index] = bindingsForPath[lastIndex];
  26285. bindingsForPath.pop();
  26286. }
  26287. } // cached or active
  26288. } // if object is known
  26289. } // for arguments
  26290. this.nCachedObjects_ = nCachedObjects;
  26291. } // Internal interface used by befriended PropertyBinding.Composite:
  26292. subscribe_(path, parsedPath) {
  26293. // returns an array of bindings for the given path that is changed
  26294. // according to the contained objects in the group
  26295. const indicesByPath = this._bindingsIndicesByPath;
  26296. let index = indicesByPath[path];
  26297. const bindings = this._bindings;
  26298. if (index !== undefined) return bindings[index];
  26299. const paths = this._paths,
  26300. parsedPaths = this._parsedPaths,
  26301. objects = this._objects,
  26302. nObjects = objects.length,
  26303. nCachedObjects = this.nCachedObjects_,
  26304. bindingsForPath = new Array(nObjects);
  26305. index = bindings.length;
  26306. indicesByPath[path] = index;
  26307. paths.push(path);
  26308. parsedPaths.push(parsedPath);
  26309. bindings.push(bindingsForPath);
  26310. for (let i = nCachedObjects, n = objects.length; i !== n; ++i) {
  26311. const object = objects[i];
  26312. bindingsForPath[i] = new PropertyBinding(object, path, parsedPath);
  26313. }
  26314. return bindingsForPath;
  26315. }
  26316. unsubscribe_(path) {
  26317. // tells the group to forget about a property path and no longer
  26318. // update the array previously obtained with 'subscribe_'
  26319. const indicesByPath = this._bindingsIndicesByPath,
  26320. index = indicesByPath[path];
  26321. if (index !== undefined) {
  26322. const paths = this._paths,
  26323. parsedPaths = this._parsedPaths,
  26324. bindings = this._bindings,
  26325. lastBindingsIndex = bindings.length - 1,
  26326. lastBindings = bindings[lastBindingsIndex],
  26327. lastBindingsPath = path[lastBindingsIndex];
  26328. indicesByPath[lastBindingsPath] = index;
  26329. bindings[index] = lastBindings;
  26330. bindings.pop();
  26331. parsedPaths[index] = parsedPaths[lastBindingsIndex];
  26332. parsedPaths.pop();
  26333. paths[index] = paths[lastBindingsIndex];
  26334. paths.pop();
  26335. }
  26336. }
  26337. }
  26338. class AnimationAction {
  26339. constructor(mixer, clip, localRoot = null, blendMode = clip.blendMode) {
  26340. this._mixer = mixer;
  26341. this._clip = clip;
  26342. this._localRoot = localRoot;
  26343. this.blendMode = blendMode;
  26344. const tracks = clip.tracks,
  26345. nTracks = tracks.length,
  26346. interpolants = new Array(nTracks);
  26347. const interpolantSettings = {
  26348. endingStart: ZeroCurvatureEnding,
  26349. endingEnd: ZeroCurvatureEnding
  26350. };
  26351. for (let i = 0; i !== nTracks; ++i) {
  26352. const interpolant = tracks[i].createInterpolant(null);
  26353. interpolants[i] = interpolant;
  26354. interpolant.settings = interpolantSettings;
  26355. }
  26356. this._interpolantSettings = interpolantSettings;
  26357. this._interpolants = interpolants; // bound by the mixer
  26358. // inside: PropertyMixer (managed by the mixer)
  26359. this._propertyBindings = new Array(nTracks);
  26360. this._cacheIndex = null; // for the memory manager
  26361. this._byClipCacheIndex = null; // for the memory manager
  26362. this._timeScaleInterpolant = null;
  26363. this._weightInterpolant = null;
  26364. this.loop = LoopRepeat;
  26365. this._loopCount = -1; // global mixer time when the action is to be started
  26366. // it's set back to 'null' upon start of the action
  26367. this._startTime = null; // scaled local time of the action
  26368. // gets clamped or wrapped to 0..clip.duration according to loop
  26369. this.time = 0;
  26370. this.timeScale = 1;
  26371. this._effectiveTimeScale = 1;
  26372. this.weight = 1;
  26373. this._effectiveWeight = 1;
  26374. this.repetitions = Infinity; // no. of repetitions when looping
  26375. this.paused = false; // true -> zero effective time scale
  26376. this.enabled = true; // false -> zero effective weight
  26377. this.clampWhenFinished = false; // keep feeding the last frame?
  26378. this.zeroSlopeAtStart = true; // for smooth interpolation w/o separate
  26379. this.zeroSlopeAtEnd = true; // clips for start, loop and end
  26380. } // State & Scheduling
  26381. play() {
  26382. this._mixer._activateAction(this);
  26383. return this;
  26384. }
  26385. stop() {
  26386. this._mixer._deactivateAction(this);
  26387. return this.reset();
  26388. }
  26389. reset() {
  26390. this.paused = false;
  26391. this.enabled = true;
  26392. this.time = 0; // restart clip
  26393. this._loopCount = -1; // forget previous loops
  26394. this._startTime = null; // forget scheduling
  26395. return this.stopFading().stopWarping();
  26396. }
  26397. isRunning() {
  26398. return this.enabled && !this.paused && this.timeScale !== 0 && this._startTime === null && this._mixer._isActiveAction(this);
  26399. } // return true when play has been called
  26400. isScheduled() {
  26401. return this._mixer._isActiveAction(this);
  26402. }
  26403. startAt(time) {
  26404. this._startTime = time;
  26405. return this;
  26406. }
  26407. setLoop(mode, repetitions) {
  26408. this.loop = mode;
  26409. this.repetitions = repetitions;
  26410. return this;
  26411. } // Weight
  26412. // set the weight stopping any scheduled fading
  26413. // although .enabled = false yields an effective weight of zero, this
  26414. // method does *not* change .enabled, because it would be confusing
  26415. setEffectiveWeight(weight) {
  26416. this.weight = weight; // note: same logic as when updated at runtime
  26417. this._effectiveWeight = this.enabled ? weight : 0;
  26418. return this.stopFading();
  26419. } // return the weight considering fading and .enabled
  26420. getEffectiveWeight() {
  26421. return this._effectiveWeight;
  26422. }
  26423. fadeIn(duration) {
  26424. return this._scheduleFading(duration, 0, 1);
  26425. }
  26426. fadeOut(duration) {
  26427. return this._scheduleFading(duration, 1, 0);
  26428. }
  26429. crossFadeFrom(fadeOutAction, duration, warp) {
  26430. fadeOutAction.fadeOut(duration);
  26431. this.fadeIn(duration);
  26432. if (warp) {
  26433. const fadeInDuration = this._clip.duration,
  26434. fadeOutDuration = fadeOutAction._clip.duration,
  26435. startEndRatio = fadeOutDuration / fadeInDuration,
  26436. endStartRatio = fadeInDuration / fadeOutDuration;
  26437. fadeOutAction.warp(1.0, startEndRatio, duration);
  26438. this.warp(endStartRatio, 1.0, duration);
  26439. }
  26440. return this;
  26441. }
  26442. crossFadeTo(fadeInAction, duration, warp) {
  26443. return fadeInAction.crossFadeFrom(this, duration, warp);
  26444. }
  26445. stopFading() {
  26446. const weightInterpolant = this._weightInterpolant;
  26447. if (weightInterpolant !== null) {
  26448. this._weightInterpolant = null;
  26449. this._mixer._takeBackControlInterpolant(weightInterpolant);
  26450. }
  26451. return this;
  26452. } // Time Scale Control
  26453. // set the time scale stopping any scheduled warping
  26454. // although .paused = true yields an effective time scale of zero, this
  26455. // method does *not* change .paused, because it would be confusing
  26456. setEffectiveTimeScale(timeScale) {
  26457. this.timeScale = timeScale;
  26458. this._effectiveTimeScale = this.paused ? 0 : timeScale;
  26459. return this.stopWarping();
  26460. } // return the time scale considering warping and .paused
  26461. getEffectiveTimeScale() {
  26462. return this._effectiveTimeScale;
  26463. }
  26464. setDuration(duration) {
  26465. this.timeScale = this._clip.duration / duration;
  26466. return this.stopWarping();
  26467. }
  26468. syncWith(action) {
  26469. this.time = action.time;
  26470. this.timeScale = action.timeScale;
  26471. return this.stopWarping();
  26472. }
  26473. halt(duration) {
  26474. return this.warp(this._effectiveTimeScale, 0, duration);
  26475. }
  26476. warp(startTimeScale, endTimeScale, duration) {
  26477. const mixer = this._mixer,
  26478. now = mixer.time,
  26479. timeScale = this.timeScale;
  26480. let interpolant = this._timeScaleInterpolant;
  26481. if (interpolant === null) {
  26482. interpolant = mixer._lendControlInterpolant();
  26483. this._timeScaleInterpolant = interpolant;
  26484. }
  26485. const times = interpolant.parameterPositions,
  26486. values = interpolant.sampleValues;
  26487. times[0] = now;
  26488. times[1] = now + duration;
  26489. values[0] = startTimeScale / timeScale;
  26490. values[1] = endTimeScale / timeScale;
  26491. return this;
  26492. }
  26493. stopWarping() {
  26494. const timeScaleInterpolant = this._timeScaleInterpolant;
  26495. if (timeScaleInterpolant !== null) {
  26496. this._timeScaleInterpolant = null;
  26497. this._mixer._takeBackControlInterpolant(timeScaleInterpolant);
  26498. }
  26499. return this;
  26500. } // Object Accessors
  26501. getMixer() {
  26502. return this._mixer;
  26503. }
  26504. getClip() {
  26505. return this._clip;
  26506. }
  26507. getRoot() {
  26508. return this._localRoot || this._mixer._root;
  26509. } // Interna
  26510. _update(time, deltaTime, timeDirection, accuIndex) {
  26511. // called by the mixer
  26512. if (!this.enabled) {
  26513. // call ._updateWeight() to update ._effectiveWeight
  26514. this._updateWeight(time);
  26515. return;
  26516. }
  26517. const startTime = this._startTime;
  26518. if (startTime !== null) {
  26519. // check for scheduled start of action
  26520. const timeRunning = (time - startTime) * timeDirection;
  26521. if (timeRunning < 0 || timeDirection === 0) {
  26522. deltaTime = 0;
  26523. } else {
  26524. this._startTime = null; // unschedule
  26525. deltaTime = timeDirection * timeRunning;
  26526. }
  26527. } // apply time scale and advance time
  26528. deltaTime *= this._updateTimeScale(time);
  26529. const clipTime = this._updateTime(deltaTime); // note: _updateTime may disable the action resulting in
  26530. // an effective weight of 0
  26531. const weight = this._updateWeight(time);
  26532. if (weight > 0) {
  26533. const interpolants = this._interpolants;
  26534. const propertyMixers = this._propertyBindings;
  26535. switch (this.blendMode) {
  26536. case AdditiveAnimationBlendMode:
  26537. for (let j = 0, m = interpolants.length; j !== m; ++j) {
  26538. interpolants[j].evaluate(clipTime);
  26539. propertyMixers[j].accumulateAdditive(weight);
  26540. }
  26541. break;
  26542. case NormalAnimationBlendMode:
  26543. default:
  26544. for (let j = 0, m = interpolants.length; j !== m; ++j) {
  26545. interpolants[j].evaluate(clipTime);
  26546. propertyMixers[j].accumulate(accuIndex, weight);
  26547. }
  26548. }
  26549. }
  26550. }
  26551. _updateWeight(time) {
  26552. let weight = 0;
  26553. if (this.enabled) {
  26554. weight = this.weight;
  26555. const interpolant = this._weightInterpolant;
  26556. if (interpolant !== null) {
  26557. const interpolantValue = interpolant.evaluate(time)[0];
  26558. weight *= interpolantValue;
  26559. if (time > interpolant.parameterPositions[1]) {
  26560. this.stopFading();
  26561. if (interpolantValue === 0) {
  26562. // faded out, disable
  26563. this.enabled = false;
  26564. }
  26565. }
  26566. }
  26567. }
  26568. this._effectiveWeight = weight;
  26569. return weight;
  26570. }
  26571. _updateTimeScale(time) {
  26572. let timeScale = 0;
  26573. if (!this.paused) {
  26574. timeScale = this.timeScale;
  26575. const interpolant = this._timeScaleInterpolant;
  26576. if (interpolant !== null) {
  26577. const interpolantValue = interpolant.evaluate(time)[0];
  26578. timeScale *= interpolantValue;
  26579. if (time > interpolant.parameterPositions[1]) {
  26580. this.stopWarping();
  26581. if (timeScale === 0) {
  26582. // motion has halted, pause
  26583. this.paused = true;
  26584. } else {
  26585. // warp done - apply final time scale
  26586. this.timeScale = timeScale;
  26587. }
  26588. }
  26589. }
  26590. }
  26591. this._effectiveTimeScale = timeScale;
  26592. return timeScale;
  26593. }
  26594. _updateTime(deltaTime) {
  26595. const duration = this._clip.duration;
  26596. const loop = this.loop;
  26597. let time = this.time + deltaTime;
  26598. let loopCount = this._loopCount;
  26599. const pingPong = loop === LoopPingPong;
  26600. if (deltaTime === 0) {
  26601. if (loopCount === -1) return time;
  26602. return pingPong && (loopCount & 1) === 1 ? duration - time : time;
  26603. }
  26604. if (loop === LoopOnce) {
  26605. if (loopCount === -1) {
  26606. // just started
  26607. this._loopCount = 0;
  26608. this._setEndings(true, true, false);
  26609. }
  26610. handle_stop: {
  26611. if (time >= duration) {
  26612. time = duration;
  26613. } else if (time < 0) {
  26614. time = 0;
  26615. } else {
  26616. this.time = time;
  26617. break handle_stop;
  26618. }
  26619. if (this.clampWhenFinished) this.paused = true;else this.enabled = false;
  26620. this.time = time;
  26621. this._mixer.dispatchEvent({
  26622. type: 'finished',
  26623. action: this,
  26624. direction: deltaTime < 0 ? -1 : 1
  26625. });
  26626. }
  26627. } else {
  26628. // repetitive Repeat or PingPong
  26629. if (loopCount === -1) {
  26630. // just started
  26631. if (deltaTime >= 0) {
  26632. loopCount = 0;
  26633. this._setEndings(true, this.repetitions === 0, pingPong);
  26634. } else {
  26635. // when looping in reverse direction, the initial
  26636. // transition through zero counts as a repetition,
  26637. // so leave loopCount at -1
  26638. this._setEndings(this.repetitions === 0, true, pingPong);
  26639. }
  26640. }
  26641. if (time >= duration || time < 0) {
  26642. // wrap around
  26643. const loopDelta = Math.floor(time / duration); // signed
  26644. time -= duration * loopDelta;
  26645. loopCount += Math.abs(loopDelta);
  26646. const pending = this.repetitions - loopCount;
  26647. if (pending <= 0) {
  26648. // have to stop (switch state, clamp time, fire event)
  26649. if (this.clampWhenFinished) this.paused = true;else this.enabled = false;
  26650. time = deltaTime > 0 ? duration : 0;
  26651. this.time = time;
  26652. this._mixer.dispatchEvent({
  26653. type: 'finished',
  26654. action: this,
  26655. direction: deltaTime > 0 ? 1 : -1
  26656. });
  26657. } else {
  26658. // keep running
  26659. if (pending === 1) {
  26660. // entering the last round
  26661. const atStart = deltaTime < 0;
  26662. this._setEndings(atStart, !atStart, pingPong);
  26663. } else {
  26664. this._setEndings(false, false, pingPong);
  26665. }
  26666. this._loopCount = loopCount;
  26667. this.time = time;
  26668. this._mixer.dispatchEvent({
  26669. type: 'loop',
  26670. action: this,
  26671. loopDelta: loopDelta
  26672. });
  26673. }
  26674. } else {
  26675. this.time = time;
  26676. }
  26677. if (pingPong && (loopCount & 1) === 1) {
  26678. // invert time for the "pong round"
  26679. return duration - time;
  26680. }
  26681. }
  26682. return time;
  26683. }
  26684. _setEndings(atStart, atEnd, pingPong) {
  26685. const settings = this._interpolantSettings;
  26686. if (pingPong) {
  26687. settings.endingStart = ZeroSlopeEnding;
  26688. settings.endingEnd = ZeroSlopeEnding;
  26689. } else {
  26690. // assuming for LoopOnce atStart == atEnd == true
  26691. if (atStart) {
  26692. settings.endingStart = this.zeroSlopeAtStart ? ZeroSlopeEnding : ZeroCurvatureEnding;
  26693. } else {
  26694. settings.endingStart = WrapAroundEnding;
  26695. }
  26696. if (atEnd) {
  26697. settings.endingEnd = this.zeroSlopeAtEnd ? ZeroSlopeEnding : ZeroCurvatureEnding;
  26698. } else {
  26699. settings.endingEnd = WrapAroundEnding;
  26700. }
  26701. }
  26702. }
  26703. _scheduleFading(duration, weightNow, weightThen) {
  26704. const mixer = this._mixer,
  26705. now = mixer.time;
  26706. let interpolant = this._weightInterpolant;
  26707. if (interpolant === null) {
  26708. interpolant = mixer._lendControlInterpolant();
  26709. this._weightInterpolant = interpolant;
  26710. }
  26711. const times = interpolant.parameterPositions,
  26712. values = interpolant.sampleValues;
  26713. times[0] = now;
  26714. values[0] = weightNow;
  26715. times[1] = now + duration;
  26716. values[1] = weightThen;
  26717. return this;
  26718. }
  26719. }
  26720. const _controlInterpolantsResultBuffer = new Float32Array(1);
  26721. class AnimationMixer extends EventDispatcher {
  26722. constructor(root) {
  26723. super();
  26724. this._root = root;
  26725. this._initMemoryManager();
  26726. this._accuIndex = 0;
  26727. this.time = 0;
  26728. this.timeScale = 1.0;
  26729. }
  26730. _bindAction(action, prototypeAction) {
  26731. const root = action._localRoot || this._root,
  26732. tracks = action._clip.tracks,
  26733. nTracks = tracks.length,
  26734. bindings = action._propertyBindings,
  26735. interpolants = action._interpolants,
  26736. rootUuid = root.uuid,
  26737. bindingsByRoot = this._bindingsByRootAndName;
  26738. let bindingsByName = bindingsByRoot[rootUuid];
  26739. if (bindingsByName === undefined) {
  26740. bindingsByName = {};
  26741. bindingsByRoot[rootUuid] = bindingsByName;
  26742. }
  26743. for (let i = 0; i !== nTracks; ++i) {
  26744. const track = tracks[i],
  26745. trackName = track.name;
  26746. let binding = bindingsByName[trackName];
  26747. if (binding !== undefined) {
  26748. ++binding.referenceCount;
  26749. bindings[i] = binding;
  26750. } else {
  26751. binding = bindings[i];
  26752. if (binding !== undefined) {
  26753. // existing binding, make sure the cache knows
  26754. if (binding._cacheIndex === null) {
  26755. ++binding.referenceCount;
  26756. this._addInactiveBinding(binding, rootUuid, trackName);
  26757. }
  26758. continue;
  26759. }
  26760. const path = prototypeAction && prototypeAction._propertyBindings[i].binding.parsedPath;
  26761. binding = new PropertyMixer(PropertyBinding.create(root, trackName, path), track.ValueTypeName, track.getValueSize());
  26762. ++binding.referenceCount;
  26763. this._addInactiveBinding(binding, rootUuid, trackName);
  26764. bindings[i] = binding;
  26765. }
  26766. interpolants[i].resultBuffer = binding.buffer;
  26767. }
  26768. }
  26769. _activateAction(action) {
  26770. if (!this._isActiveAction(action)) {
  26771. if (action._cacheIndex === null) {
  26772. // this action has been forgotten by the cache, but the user
  26773. // appears to be still using it -> rebind
  26774. const rootUuid = (action._localRoot || this._root).uuid,
  26775. clipUuid = action._clip.uuid,
  26776. actionsForClip = this._actionsByClip[clipUuid];
  26777. this._bindAction(action, actionsForClip && actionsForClip.knownActions[0]);
  26778. this._addInactiveAction(action, clipUuid, rootUuid);
  26779. }
  26780. const bindings = action._propertyBindings; // increment reference counts / sort out state
  26781. for (let i = 0, n = bindings.length; i !== n; ++i) {
  26782. const binding = bindings[i];
  26783. if (binding.useCount++ === 0) {
  26784. this._lendBinding(binding);
  26785. binding.saveOriginalState();
  26786. }
  26787. }
  26788. this._lendAction(action);
  26789. }
  26790. }
  26791. _deactivateAction(action) {
  26792. if (this._isActiveAction(action)) {
  26793. const bindings = action._propertyBindings; // decrement reference counts / sort out state
  26794. for (let i = 0, n = bindings.length; i !== n; ++i) {
  26795. const binding = bindings[i];
  26796. if (--binding.useCount === 0) {
  26797. binding.restoreOriginalState();
  26798. this._takeBackBinding(binding);
  26799. }
  26800. }
  26801. this._takeBackAction(action);
  26802. }
  26803. } // Memory manager
  26804. _initMemoryManager() {
  26805. this._actions = []; // 'nActiveActions' followed by inactive ones
  26806. this._nActiveActions = 0;
  26807. this._actionsByClip = {}; // inside:
  26808. // {
  26809. // knownActions: Array< AnimationAction > - used as prototypes
  26810. // actionByRoot: AnimationAction - lookup
  26811. // }
  26812. this._bindings = []; // 'nActiveBindings' followed by inactive ones
  26813. this._nActiveBindings = 0;
  26814. this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer >
  26815. this._controlInterpolants = []; // same game as above
  26816. this._nActiveControlInterpolants = 0;
  26817. const scope = this;
  26818. this.stats = {
  26819. actions: {
  26820. get total() {
  26821. return scope._actions.length;
  26822. },
  26823. get inUse() {
  26824. return scope._nActiveActions;
  26825. }
  26826. },
  26827. bindings: {
  26828. get total() {
  26829. return scope._bindings.length;
  26830. },
  26831. get inUse() {
  26832. return scope._nActiveBindings;
  26833. }
  26834. },
  26835. controlInterpolants: {
  26836. get total() {
  26837. return scope._controlInterpolants.length;
  26838. },
  26839. get inUse() {
  26840. return scope._nActiveControlInterpolants;
  26841. }
  26842. }
  26843. };
  26844. } // Memory management for AnimationAction objects
  26845. _isActiveAction(action) {
  26846. const index = action._cacheIndex;
  26847. return index !== null && index < this._nActiveActions;
  26848. }
  26849. _addInactiveAction(action, clipUuid, rootUuid) {
  26850. const actions = this._actions,
  26851. actionsByClip = this._actionsByClip;
  26852. let actionsForClip = actionsByClip[clipUuid];
  26853. if (actionsForClip === undefined) {
  26854. actionsForClip = {
  26855. knownActions: [action],
  26856. actionByRoot: {}
  26857. };
  26858. action._byClipCacheIndex = 0;
  26859. actionsByClip[clipUuid] = actionsForClip;
  26860. } else {
  26861. const knownActions = actionsForClip.knownActions;
  26862. action._byClipCacheIndex = knownActions.length;
  26863. knownActions.push(action);
  26864. }
  26865. action._cacheIndex = actions.length;
  26866. actions.push(action);
  26867. actionsForClip.actionByRoot[rootUuid] = action;
  26868. }
  26869. _removeInactiveAction(action) {
  26870. const actions = this._actions,
  26871. lastInactiveAction = actions[actions.length - 1],
  26872. cacheIndex = action._cacheIndex;
  26873. lastInactiveAction._cacheIndex = cacheIndex;
  26874. actions[cacheIndex] = lastInactiveAction;
  26875. actions.pop();
  26876. action._cacheIndex = null;
  26877. const clipUuid = action._clip.uuid,
  26878. actionsByClip = this._actionsByClip,
  26879. actionsForClip = actionsByClip[clipUuid],
  26880. knownActionsForClip = actionsForClip.knownActions,
  26881. lastKnownAction = knownActionsForClip[knownActionsForClip.length - 1],
  26882. byClipCacheIndex = action._byClipCacheIndex;
  26883. lastKnownAction._byClipCacheIndex = byClipCacheIndex;
  26884. knownActionsForClip[byClipCacheIndex] = lastKnownAction;
  26885. knownActionsForClip.pop();
  26886. action._byClipCacheIndex = null;
  26887. const actionByRoot = actionsForClip.actionByRoot,
  26888. rootUuid = (action._localRoot || this._root).uuid;
  26889. delete actionByRoot[rootUuid];
  26890. if (knownActionsForClip.length === 0) {
  26891. delete actionsByClip[clipUuid];
  26892. }
  26893. this._removeInactiveBindingsForAction(action);
  26894. }
  26895. _removeInactiveBindingsForAction(action) {
  26896. const bindings = action._propertyBindings;
  26897. for (let i = 0, n = bindings.length; i !== n; ++i) {
  26898. const binding = bindings[i];
  26899. if (--binding.referenceCount === 0) {
  26900. this._removeInactiveBinding(binding);
  26901. }
  26902. }
  26903. }
  26904. _lendAction(action) {
  26905. // [ active actions | inactive actions ]
  26906. // [ active actions >| inactive actions ]
  26907. // s a
  26908. // <-swap->
  26909. // a s
  26910. const actions = this._actions,
  26911. prevIndex = action._cacheIndex,
  26912. lastActiveIndex = this._nActiveActions++,
  26913. firstInactiveAction = actions[lastActiveIndex];
  26914. action._cacheIndex = lastActiveIndex;
  26915. actions[lastActiveIndex] = action;
  26916. firstInactiveAction._cacheIndex = prevIndex;
  26917. actions[prevIndex] = firstInactiveAction;
  26918. }
  26919. _takeBackAction(action) {
  26920. // [ active actions | inactive actions ]
  26921. // [ active actions |< inactive actions ]
  26922. // a s
  26923. // <-swap->
  26924. // s a
  26925. const actions = this._actions,
  26926. prevIndex = action._cacheIndex,
  26927. firstInactiveIndex = --this._nActiveActions,
  26928. lastActiveAction = actions[firstInactiveIndex];
  26929. action._cacheIndex = firstInactiveIndex;
  26930. actions[firstInactiveIndex] = action;
  26931. lastActiveAction._cacheIndex = prevIndex;
  26932. actions[prevIndex] = lastActiveAction;
  26933. } // Memory management for PropertyMixer objects
  26934. _addInactiveBinding(binding, rootUuid, trackName) {
  26935. const bindingsByRoot = this._bindingsByRootAndName,
  26936. bindings = this._bindings;
  26937. let bindingByName = bindingsByRoot[rootUuid];
  26938. if (bindingByName === undefined) {
  26939. bindingByName = {};
  26940. bindingsByRoot[rootUuid] = bindingByName;
  26941. }
  26942. bindingByName[trackName] = binding;
  26943. binding._cacheIndex = bindings.length;
  26944. bindings.push(binding);
  26945. }
  26946. _removeInactiveBinding(binding) {
  26947. const bindings = this._bindings,
  26948. propBinding = binding.binding,
  26949. rootUuid = propBinding.rootNode.uuid,
  26950. trackName = propBinding.path,
  26951. bindingsByRoot = this._bindingsByRootAndName,
  26952. bindingByName = bindingsByRoot[rootUuid],
  26953. lastInactiveBinding = bindings[bindings.length - 1],
  26954. cacheIndex = binding._cacheIndex;
  26955. lastInactiveBinding._cacheIndex = cacheIndex;
  26956. bindings[cacheIndex] = lastInactiveBinding;
  26957. bindings.pop();
  26958. delete bindingByName[trackName];
  26959. if (Object.keys(bindingByName).length === 0) {
  26960. delete bindingsByRoot[rootUuid];
  26961. }
  26962. }
  26963. _lendBinding(binding) {
  26964. const bindings = this._bindings,
  26965. prevIndex = binding._cacheIndex,
  26966. lastActiveIndex = this._nActiveBindings++,
  26967. firstInactiveBinding = bindings[lastActiveIndex];
  26968. binding._cacheIndex = lastActiveIndex;
  26969. bindings[lastActiveIndex] = binding;
  26970. firstInactiveBinding._cacheIndex = prevIndex;
  26971. bindings[prevIndex] = firstInactiveBinding;
  26972. }
  26973. _takeBackBinding(binding) {
  26974. const bindings = this._bindings,
  26975. prevIndex = binding._cacheIndex,
  26976. firstInactiveIndex = --this._nActiveBindings,
  26977. lastActiveBinding = bindings[firstInactiveIndex];
  26978. binding._cacheIndex = firstInactiveIndex;
  26979. bindings[firstInactiveIndex] = binding;
  26980. lastActiveBinding._cacheIndex = prevIndex;
  26981. bindings[prevIndex] = lastActiveBinding;
  26982. } // Memory management of Interpolants for weight and time scale
  26983. _lendControlInterpolant() {
  26984. const interpolants = this._controlInterpolants,
  26985. lastActiveIndex = this._nActiveControlInterpolants++;
  26986. let interpolant = interpolants[lastActiveIndex];
  26987. if (interpolant === undefined) {
  26988. interpolant = new LinearInterpolant(new Float32Array(2), new Float32Array(2), 1, _controlInterpolantsResultBuffer);
  26989. interpolant.__cacheIndex = lastActiveIndex;
  26990. interpolants[lastActiveIndex] = interpolant;
  26991. }
  26992. return interpolant;
  26993. }
  26994. _takeBackControlInterpolant(interpolant) {
  26995. const interpolants = this._controlInterpolants,
  26996. prevIndex = interpolant.__cacheIndex,
  26997. firstInactiveIndex = --this._nActiveControlInterpolants,
  26998. lastActiveInterpolant = interpolants[firstInactiveIndex];
  26999. interpolant.__cacheIndex = firstInactiveIndex;
  27000. interpolants[firstInactiveIndex] = interpolant;
  27001. lastActiveInterpolant.__cacheIndex = prevIndex;
  27002. interpolants[prevIndex] = lastActiveInterpolant;
  27003. } // return an action for a clip optionally using a custom root target
  27004. // object (this method allocates a lot of dynamic memory in case a
  27005. // previously unknown clip/root combination is specified)
  27006. clipAction(clip, optionalRoot, blendMode) {
  27007. const root = optionalRoot || this._root,
  27008. rootUuid = root.uuid;
  27009. let clipObject = typeof clip === 'string' ? AnimationClip.findByName(root, clip) : clip;
  27010. const clipUuid = clipObject !== null ? clipObject.uuid : clip;
  27011. const actionsForClip = this._actionsByClip[clipUuid];
  27012. let prototypeAction = null;
  27013. if (blendMode === undefined) {
  27014. if (clipObject !== null) {
  27015. blendMode = clipObject.blendMode;
  27016. } else {
  27017. blendMode = NormalAnimationBlendMode;
  27018. }
  27019. }
  27020. if (actionsForClip !== undefined) {
  27021. const existingAction = actionsForClip.actionByRoot[rootUuid];
  27022. if (existingAction !== undefined && existingAction.blendMode === blendMode) {
  27023. return existingAction;
  27024. } // we know the clip, so we don't have to parse all
  27025. // the bindings again but can just copy
  27026. prototypeAction = actionsForClip.knownActions[0]; // also, take the clip from the prototype action
  27027. if (clipObject === null) clipObject = prototypeAction._clip;
  27028. } // clip must be known when specified via string
  27029. if (clipObject === null) return null; // allocate all resources required to run it
  27030. const newAction = new AnimationAction(this, clipObject, optionalRoot, blendMode);
  27031. this._bindAction(newAction, prototypeAction); // and make the action known to the memory manager
  27032. this._addInactiveAction(newAction, clipUuid, rootUuid);
  27033. return newAction;
  27034. } // get an existing action
  27035. existingAction(clip, optionalRoot) {
  27036. const root = optionalRoot || this._root,
  27037. rootUuid = root.uuid,
  27038. clipObject = typeof clip === 'string' ? AnimationClip.findByName(root, clip) : clip,
  27039. clipUuid = clipObject ? clipObject.uuid : clip,
  27040. actionsForClip = this._actionsByClip[clipUuid];
  27041. if (actionsForClip !== undefined) {
  27042. return actionsForClip.actionByRoot[rootUuid] || null;
  27043. }
  27044. return null;
  27045. } // deactivates all previously scheduled actions
  27046. stopAllAction() {
  27047. const actions = this._actions,
  27048. nActions = this._nActiveActions;
  27049. for (let i = nActions - 1; i >= 0; --i) {
  27050. actions[i].stop();
  27051. }
  27052. return this;
  27053. } // advance the time and update apply the animation
  27054. update(deltaTime) {
  27055. deltaTime *= this.timeScale;
  27056. const actions = this._actions,
  27057. nActions = this._nActiveActions,
  27058. time = this.time += deltaTime,
  27059. timeDirection = Math.sign(deltaTime),
  27060. accuIndex = this._accuIndex ^= 1; // run active actions
  27061. for (let i = 0; i !== nActions; ++i) {
  27062. const action = actions[i];
  27063. action._update(time, deltaTime, timeDirection, accuIndex);
  27064. } // update scene graph
  27065. const bindings = this._bindings,
  27066. nBindings = this._nActiveBindings;
  27067. for (let i = 0; i !== nBindings; ++i) {
  27068. bindings[i].apply(accuIndex);
  27069. }
  27070. return this;
  27071. } // Allows you to seek to a specific time in an animation.
  27072. setTime(timeInSeconds) {
  27073. this.time = 0; // Zero out time attribute for AnimationMixer object;
  27074. for (let i = 0; i < this._actions.length; i++) {
  27075. this._actions[i].time = 0; // Zero out time attribute for all associated AnimationAction objects.
  27076. }
  27077. return this.update(timeInSeconds); // Update used to set exact time. Returns "this" AnimationMixer object.
  27078. } // return this mixer's root target object
  27079. getRoot() {
  27080. return this._root;
  27081. } // free all resources specific to a particular clip
  27082. uncacheClip(clip) {
  27083. const actions = this._actions,
  27084. clipUuid = clip.uuid,
  27085. actionsByClip = this._actionsByClip,
  27086. actionsForClip = actionsByClip[clipUuid];
  27087. if (actionsForClip !== undefined) {
  27088. // note: just calling _removeInactiveAction would mess up the
  27089. // iteration state and also require updating the state we can
  27090. // just throw away
  27091. const actionsToRemove = actionsForClip.knownActions;
  27092. for (let i = 0, n = actionsToRemove.length; i !== n; ++i) {
  27093. const action = actionsToRemove[i];
  27094. this._deactivateAction(action);
  27095. const cacheIndex = action._cacheIndex,
  27096. lastInactiveAction = actions[actions.length - 1];
  27097. action._cacheIndex = null;
  27098. action._byClipCacheIndex = null;
  27099. lastInactiveAction._cacheIndex = cacheIndex;
  27100. actions[cacheIndex] = lastInactiveAction;
  27101. actions.pop();
  27102. this._removeInactiveBindingsForAction(action);
  27103. }
  27104. delete actionsByClip[clipUuid];
  27105. }
  27106. } // free all resources specific to a particular root target object
  27107. uncacheRoot(root) {
  27108. const rootUuid = root.uuid,
  27109. actionsByClip = this._actionsByClip;
  27110. for (const clipUuid in actionsByClip) {
  27111. const actionByRoot = actionsByClip[clipUuid].actionByRoot,
  27112. action = actionByRoot[rootUuid];
  27113. if (action !== undefined) {
  27114. this._deactivateAction(action);
  27115. this._removeInactiveAction(action);
  27116. }
  27117. }
  27118. const bindingsByRoot = this._bindingsByRootAndName,
  27119. bindingByName = bindingsByRoot[rootUuid];
  27120. if (bindingByName !== undefined) {
  27121. for (const trackName in bindingByName) {
  27122. const binding = bindingByName[trackName];
  27123. binding.restoreOriginalState();
  27124. this._removeInactiveBinding(binding);
  27125. }
  27126. }
  27127. } // remove a targeted clip from the cache
  27128. uncacheAction(clip, optionalRoot) {
  27129. const action = this.existingAction(clip, optionalRoot);
  27130. if (action !== null) {
  27131. this._deactivateAction(action);
  27132. this._removeInactiveAction(action);
  27133. }
  27134. }
  27135. }
  27136. class Uniform {
  27137. constructor(value) {
  27138. this.value = value;
  27139. }
  27140. clone() {
  27141. return new Uniform(this.value.clone === undefined ? this.value : this.value.clone());
  27142. }
  27143. }
  27144. let id = 0;
  27145. class UniformsGroup extends EventDispatcher {
  27146. constructor() {
  27147. super();
  27148. this.isUniformsGroup = true;
  27149. Object.defineProperty(this, 'id', {
  27150. value: id++
  27151. });
  27152. this.name = '';
  27153. this.usage = StaticDrawUsage;
  27154. this.uniforms = [];
  27155. }
  27156. add(uniform) {
  27157. this.uniforms.push(uniform);
  27158. return this;
  27159. }
  27160. remove(uniform) {
  27161. const index = this.uniforms.indexOf(uniform);
  27162. if (index !== -1) this.uniforms.splice(index, 1);
  27163. return this;
  27164. }
  27165. setName(name) {
  27166. this.name = name;
  27167. return this;
  27168. }
  27169. setUsage(value) {
  27170. this.usage = value;
  27171. return this;
  27172. }
  27173. dispose() {
  27174. this.dispatchEvent({
  27175. type: 'dispose'
  27176. });
  27177. return this;
  27178. }
  27179. copy(source) {
  27180. this.name = source.name;
  27181. this.usage = source.usage;
  27182. const uniformsSource = source.uniforms;
  27183. this.uniforms.length = 0;
  27184. for (let i = 0, l = uniformsSource.length; i < l; i++) {
  27185. this.uniforms.push(uniformsSource[i].clone());
  27186. }
  27187. return this;
  27188. }
  27189. clone() {
  27190. return new this.constructor().copy(this);
  27191. }
  27192. }
  27193. class InstancedInterleavedBuffer extends InterleavedBuffer {
  27194. constructor(array, stride, meshPerAttribute = 1) {
  27195. super(array, stride);
  27196. this.isInstancedInterleavedBuffer = true;
  27197. this.meshPerAttribute = meshPerAttribute;
  27198. }
  27199. copy(source) {
  27200. super.copy(source);
  27201. this.meshPerAttribute = source.meshPerAttribute;
  27202. return this;
  27203. }
  27204. clone(data) {
  27205. const ib = super.clone(data);
  27206. ib.meshPerAttribute = this.meshPerAttribute;
  27207. return ib;
  27208. }
  27209. toJSON(data) {
  27210. const json = super.toJSON(data);
  27211. json.isInstancedInterleavedBuffer = true;
  27212. json.meshPerAttribute = this.meshPerAttribute;
  27213. return json;
  27214. }
  27215. }
  27216. class GLBufferAttribute {
  27217. constructor(buffer, type, itemSize, elementSize, count) {
  27218. this.isGLBufferAttribute = true;
  27219. this.buffer = buffer;
  27220. this.type = type;
  27221. this.itemSize = itemSize;
  27222. this.elementSize = elementSize;
  27223. this.count = count;
  27224. this.version = 0;
  27225. }
  27226. set needsUpdate(value) {
  27227. if (value === true) this.version++;
  27228. }
  27229. setBuffer(buffer) {
  27230. this.buffer = buffer;
  27231. return this;
  27232. }
  27233. setType(type, elementSize) {
  27234. this.type = type;
  27235. this.elementSize = elementSize;
  27236. return this;
  27237. }
  27238. setItemSize(itemSize) {
  27239. this.itemSize = itemSize;
  27240. return this;
  27241. }
  27242. setCount(count) {
  27243. this.count = count;
  27244. return this;
  27245. }
  27246. }
  27247. class Raycaster {
  27248. constructor(origin, direction, near = 0, far = Infinity) {
  27249. this.ray = new Ray(origin, direction); // direction is assumed to be normalized (for accurate distance calculations)
  27250. this.near = near;
  27251. this.far = far;
  27252. this.camera = null;
  27253. this.layers = new Layers();
  27254. this.params = {
  27255. Mesh: {},
  27256. Line: {
  27257. threshold: 1
  27258. },
  27259. LOD: {},
  27260. Points: {
  27261. threshold: 1
  27262. },
  27263. Sprite: {}
  27264. };
  27265. }
  27266. set(origin, direction) {
  27267. // direction is assumed to be normalized (for accurate distance calculations)
  27268. this.ray.set(origin, direction);
  27269. }
  27270. setFromCamera(coords, camera) {
  27271. if (camera.isPerspectiveCamera) {
  27272. this.ray.origin.setFromMatrixPosition(camera.matrixWorld);
  27273. this.ray.direction.set(coords.x, coords.y, 0.5).unproject(camera).sub(this.ray.origin).normalize();
  27274. this.camera = camera;
  27275. } else if (camera.isOrthographicCamera) {
  27276. this.ray.origin.set(coords.x, coords.y, (camera.near + camera.far) / (camera.near - camera.far)).unproject(camera); // set origin in plane of camera
  27277. this.ray.direction.set(0, 0, -1).transformDirection(camera.matrixWorld);
  27278. this.camera = camera;
  27279. } else {
  27280. console.error('THREE.Raycaster: Unsupported camera type: ' + camera.type);
  27281. }
  27282. }
  27283. intersectObject(object, recursive = true, intersects = []) {
  27284. intersectObject(object, this, intersects, recursive);
  27285. intersects.sort(ascSort);
  27286. return intersects;
  27287. }
  27288. intersectObjects(objects, recursive = true, intersects = []) {
  27289. for (let i = 0, l = objects.length; i < l; i++) {
  27290. intersectObject(objects[i], this, intersects, recursive);
  27291. }
  27292. intersects.sort(ascSort);
  27293. return intersects;
  27294. }
  27295. }
  27296. function ascSort(a, b) {
  27297. return a.distance - b.distance;
  27298. }
  27299. function intersectObject(object, raycaster, intersects, recursive) {
  27300. if (object.layers.test(raycaster.layers)) {
  27301. object.raycast(raycaster, intersects);
  27302. }
  27303. if (recursive === true) {
  27304. const children = object.children;
  27305. for (let i = 0, l = children.length; i < l; i++) {
  27306. intersectObject(children[i], raycaster, intersects, true);
  27307. }
  27308. }
  27309. }
  27310. /**
  27311. * Ref: https://en.wikipedia.org/wiki/Spherical_coordinate_system
  27312. *
  27313. * The polar angle (phi) is measured from the positive y-axis. The positive y-axis is up.
  27314. * The azimuthal angle (theta) is measured from the positive z-axis.
  27315. */
  27316. class Spherical {
  27317. constructor(radius = 1, phi = 0, theta = 0) {
  27318. this.radius = radius;
  27319. this.phi = phi; // polar angle
  27320. this.theta = theta; // azimuthal angle
  27321. return this;
  27322. }
  27323. set(radius, phi, theta) {
  27324. this.radius = radius;
  27325. this.phi = phi;
  27326. this.theta = theta;
  27327. return this;
  27328. }
  27329. copy(other) {
  27330. this.radius = other.radius;
  27331. this.phi = other.phi;
  27332. this.theta = other.theta;
  27333. return this;
  27334. } // restrict phi to be between EPS and PI-EPS
  27335. makeSafe() {
  27336. const EPS = 0.000001;
  27337. this.phi = Math.max(EPS, Math.min(Math.PI - EPS, this.phi));
  27338. return this;
  27339. }
  27340. setFromVector3(v) {
  27341. return this.setFromCartesianCoords(v.x, v.y, v.z);
  27342. }
  27343. setFromCartesianCoords(x, y, z) {
  27344. this.radius = Math.sqrt(x * x + y * y + z * z);
  27345. if (this.radius === 0) {
  27346. this.theta = 0;
  27347. this.phi = 0;
  27348. } else {
  27349. this.theta = Math.atan2(x, z);
  27350. this.phi = Math.acos(clamp(y / this.radius, -1, 1));
  27351. }
  27352. return this;
  27353. }
  27354. clone() {
  27355. return new this.constructor().copy(this);
  27356. }
  27357. }
  27358. /**
  27359. * Ref: https://en.wikipedia.org/wiki/Cylindrical_coordinate_system
  27360. */
  27361. class Cylindrical {
  27362. constructor(radius = 1, theta = 0, y = 0) {
  27363. this.radius = radius; // distance from the origin to a point in the x-z plane
  27364. this.theta = theta; // counterclockwise angle in the x-z plane measured in radians from the positive z-axis
  27365. this.y = y; // height above the x-z plane
  27366. return this;
  27367. }
  27368. set(radius, theta, y) {
  27369. this.radius = radius;
  27370. this.theta = theta;
  27371. this.y = y;
  27372. return this;
  27373. }
  27374. copy(other) {
  27375. this.radius = other.radius;
  27376. this.theta = other.theta;
  27377. this.y = other.y;
  27378. return this;
  27379. }
  27380. setFromVector3(v) {
  27381. return this.setFromCartesianCoords(v.x, v.y, v.z);
  27382. }
  27383. setFromCartesianCoords(x, y, z) {
  27384. this.radius = Math.sqrt(x * x + z * z);
  27385. this.theta = Math.atan2(x, z);
  27386. this.y = y;
  27387. return this;
  27388. }
  27389. clone() {
  27390. return new this.constructor().copy(this);
  27391. }
  27392. }
  27393. const _vector$4 = /*@__PURE__*/new Vector2();
  27394. class Box2 {
  27395. constructor(min = new Vector2(+Infinity, +Infinity), max = new Vector2(-Infinity, -Infinity)) {
  27396. this.isBox2 = true;
  27397. this.min = min;
  27398. this.max = max;
  27399. }
  27400. set(min, max) {
  27401. this.min.copy(min);
  27402. this.max.copy(max);
  27403. return this;
  27404. }
  27405. setFromPoints(points) {
  27406. this.makeEmpty();
  27407. for (let i = 0, il = points.length; i < il; i++) {
  27408. this.expandByPoint(points[i]);
  27409. }
  27410. return this;
  27411. }
  27412. setFromCenterAndSize(center, size) {
  27413. const halfSize = _vector$4.copy(size).multiplyScalar(0.5);
  27414. this.min.copy(center).sub(halfSize);
  27415. this.max.copy(center).add(halfSize);
  27416. return this;
  27417. }
  27418. clone() {
  27419. return new this.constructor().copy(this);
  27420. }
  27421. copy(box) {
  27422. this.min.copy(box.min);
  27423. this.max.copy(box.max);
  27424. return this;
  27425. }
  27426. makeEmpty() {
  27427. this.min.x = this.min.y = +Infinity;
  27428. this.max.x = this.max.y = -Infinity;
  27429. return this;
  27430. }
  27431. isEmpty() {
  27432. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  27433. return this.max.x < this.min.x || this.max.y < this.min.y;
  27434. }
  27435. getCenter(target) {
  27436. return this.isEmpty() ? target.set(0, 0) : target.addVectors(this.min, this.max).multiplyScalar(0.5);
  27437. }
  27438. getSize(target) {
  27439. return this.isEmpty() ? target.set(0, 0) : target.subVectors(this.max, this.min);
  27440. }
  27441. expandByPoint(point) {
  27442. this.min.min(point);
  27443. this.max.max(point);
  27444. return this;
  27445. }
  27446. expandByVector(vector) {
  27447. this.min.sub(vector);
  27448. this.max.add(vector);
  27449. return this;
  27450. }
  27451. expandByScalar(scalar) {
  27452. this.min.addScalar(-scalar);
  27453. this.max.addScalar(scalar);
  27454. return this;
  27455. }
  27456. containsPoint(point) {
  27457. return point.x < this.min.x || point.x > this.max.x || point.y < this.min.y || point.y > this.max.y ? false : true;
  27458. }
  27459. containsBox(box) {
  27460. 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;
  27461. }
  27462. getParameter(point, target) {
  27463. // This can potentially have a divide by zero if the box
  27464. // has a size dimension of 0.
  27465. 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));
  27466. }
  27467. intersectsBox(box) {
  27468. // using 4 splitting planes to rule out intersections
  27469. 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;
  27470. }
  27471. clampPoint(point, target) {
  27472. return target.copy(point).clamp(this.min, this.max);
  27473. }
  27474. distanceToPoint(point) {
  27475. const clampedPoint = _vector$4.copy(point).clamp(this.min, this.max);
  27476. return clampedPoint.sub(point).length();
  27477. }
  27478. intersect(box) {
  27479. this.min.max(box.min);
  27480. this.max.min(box.max);
  27481. return this;
  27482. }
  27483. union(box) {
  27484. this.min.min(box.min);
  27485. this.max.max(box.max);
  27486. return this;
  27487. }
  27488. translate(offset) {
  27489. this.min.add(offset);
  27490. this.max.add(offset);
  27491. return this;
  27492. }
  27493. equals(box) {
  27494. return box.min.equals(this.min) && box.max.equals(this.max);
  27495. }
  27496. }
  27497. const _startP = /*@__PURE__*/new Vector3();
  27498. const _startEnd = /*@__PURE__*/new Vector3();
  27499. class Line3 {
  27500. constructor(start = new Vector3(), end = new Vector3()) {
  27501. this.start = start;
  27502. this.end = end;
  27503. }
  27504. set(start, end) {
  27505. this.start.copy(start);
  27506. this.end.copy(end);
  27507. return this;
  27508. }
  27509. copy(line) {
  27510. this.start.copy(line.start);
  27511. this.end.copy(line.end);
  27512. return this;
  27513. }
  27514. getCenter(target) {
  27515. return target.addVectors(this.start, this.end).multiplyScalar(0.5);
  27516. }
  27517. delta(target) {
  27518. return target.subVectors(this.end, this.start);
  27519. }
  27520. distanceSq() {
  27521. return this.start.distanceToSquared(this.end);
  27522. }
  27523. distance() {
  27524. return this.start.distanceTo(this.end);
  27525. }
  27526. at(t, target) {
  27527. return this.delta(target).multiplyScalar(t).add(this.start);
  27528. }
  27529. closestPointToPointParameter(point, clampToLine) {
  27530. _startP.subVectors(point, this.start);
  27531. _startEnd.subVectors(this.end, this.start);
  27532. const startEnd2 = _startEnd.dot(_startEnd);
  27533. const startEnd_startP = _startEnd.dot(_startP);
  27534. let t = startEnd_startP / startEnd2;
  27535. if (clampToLine) {
  27536. t = clamp(t, 0, 1);
  27537. }
  27538. return t;
  27539. }
  27540. closestPointToPoint(point, clampToLine, target) {
  27541. const t = this.closestPointToPointParameter(point, clampToLine);
  27542. return this.delta(target).multiplyScalar(t).add(this.start);
  27543. }
  27544. applyMatrix4(matrix) {
  27545. this.start.applyMatrix4(matrix);
  27546. this.end.applyMatrix4(matrix);
  27547. return this;
  27548. }
  27549. equals(line) {
  27550. return line.start.equals(this.start) && line.end.equals(this.end);
  27551. }
  27552. clone() {
  27553. return new this.constructor().copy(this);
  27554. }
  27555. }
  27556. const _vector$3 = /*@__PURE__*/new Vector3();
  27557. class SpotLightHelper extends Object3D {
  27558. constructor(light, color) {
  27559. super();
  27560. this.light = light;
  27561. this.light.updateMatrixWorld();
  27562. this.matrix = light.matrixWorld;
  27563. this.matrixAutoUpdate = false;
  27564. this.color = color;
  27565. const geometry = new BufferGeometry();
  27566. const positions = [0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, -1, 0, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, -1, 1];
  27567. for (let i = 0, j = 1, l = 32; i < l; i++, j++) {
  27568. const p1 = i / l * Math.PI * 2;
  27569. const p2 = j / l * Math.PI * 2;
  27570. positions.push(Math.cos(p1), Math.sin(p1), 1, Math.cos(p2), Math.sin(p2), 1);
  27571. }
  27572. geometry.setAttribute('position', new Float32BufferAttribute(positions, 3));
  27573. const material = new LineBasicMaterial({
  27574. fog: false,
  27575. toneMapped: false
  27576. });
  27577. this.cone = new LineSegments(geometry, material);
  27578. this.add(this.cone);
  27579. this.update();
  27580. }
  27581. dispose() {
  27582. this.cone.geometry.dispose();
  27583. this.cone.material.dispose();
  27584. }
  27585. update() {
  27586. this.light.updateMatrixWorld();
  27587. const coneLength = this.light.distance ? this.light.distance : 1000;
  27588. const coneWidth = coneLength * Math.tan(this.light.angle);
  27589. this.cone.scale.set(coneWidth, coneWidth, coneLength);
  27590. _vector$3.setFromMatrixPosition(this.light.target.matrixWorld);
  27591. this.cone.lookAt(_vector$3);
  27592. if (this.color !== undefined) {
  27593. this.cone.material.color.set(this.color);
  27594. } else {
  27595. this.cone.material.color.copy(this.light.color);
  27596. }
  27597. }
  27598. }
  27599. const _vector$2 = /*@__PURE__*/new Vector3();
  27600. const _boneMatrix = /*@__PURE__*/new Matrix4();
  27601. const _matrixWorldInv = /*@__PURE__*/new Matrix4();
  27602. class SkeletonHelper extends LineSegments {
  27603. constructor(object) {
  27604. const bones = getBoneList(object);
  27605. const geometry = new BufferGeometry();
  27606. const vertices = [];
  27607. const colors = [];
  27608. const color1 = new Color(0, 0, 1);
  27609. const color2 = new Color(0, 1, 0);
  27610. for (let i = 0; i < bones.length; i++) {
  27611. const bone = bones[i];
  27612. if (bone.parent && bone.parent.isBone) {
  27613. vertices.push(0, 0, 0);
  27614. vertices.push(0, 0, 0);
  27615. colors.push(color1.r, color1.g, color1.b);
  27616. colors.push(color2.r, color2.g, color2.b);
  27617. }
  27618. }
  27619. geometry.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  27620. geometry.setAttribute('color', new Float32BufferAttribute(colors, 3));
  27621. const material = new LineBasicMaterial({
  27622. vertexColors: true,
  27623. depthTest: false,
  27624. depthWrite: false,
  27625. toneMapped: false,
  27626. transparent: true
  27627. });
  27628. super(geometry, material);
  27629. this.isSkeletonHelper = true;
  27630. this.type = 'SkeletonHelper';
  27631. this.root = object;
  27632. this.bones = bones;
  27633. this.matrix = object.matrixWorld;
  27634. this.matrixAutoUpdate = false;
  27635. }
  27636. updateMatrixWorld(force) {
  27637. const bones = this.bones;
  27638. const geometry = this.geometry;
  27639. const position = geometry.getAttribute('position');
  27640. _matrixWorldInv.copy(this.root.matrixWorld).invert();
  27641. for (let i = 0, j = 0; i < bones.length; i++) {
  27642. const bone = bones[i];
  27643. if (bone.parent && bone.parent.isBone) {
  27644. _boneMatrix.multiplyMatrices(_matrixWorldInv, bone.matrixWorld);
  27645. _vector$2.setFromMatrixPosition(_boneMatrix);
  27646. position.setXYZ(j, _vector$2.x, _vector$2.y, _vector$2.z);
  27647. _boneMatrix.multiplyMatrices(_matrixWorldInv, bone.parent.matrixWorld);
  27648. _vector$2.setFromMatrixPosition(_boneMatrix);
  27649. position.setXYZ(j + 1, _vector$2.x, _vector$2.y, _vector$2.z);
  27650. j += 2;
  27651. }
  27652. }
  27653. geometry.getAttribute('position').needsUpdate = true;
  27654. super.updateMatrixWorld(force);
  27655. }
  27656. dispose() {
  27657. this.geometry.dispose();
  27658. this.material.dispose();
  27659. }
  27660. }
  27661. function getBoneList(object) {
  27662. const boneList = [];
  27663. if (object.isBone === true) {
  27664. boneList.push(object);
  27665. }
  27666. for (let i = 0; i < object.children.length; i++) {
  27667. boneList.push.apply(boneList, getBoneList(object.children[i]));
  27668. }
  27669. return boneList;
  27670. }
  27671. class PointLightHelper extends Mesh {
  27672. constructor(light, sphereSize, color) {
  27673. const geometry = new SphereGeometry(sphereSize, 4, 2);
  27674. const material = new MeshBasicMaterial({
  27675. wireframe: true,
  27676. fog: false,
  27677. toneMapped: false
  27678. });
  27679. super(geometry, material);
  27680. this.light = light;
  27681. this.light.updateMatrixWorld();
  27682. this.color = color;
  27683. this.type = 'PointLightHelper';
  27684. this.matrix = this.light.matrixWorld;
  27685. this.matrixAutoUpdate = false;
  27686. this.update();
  27687. /*
  27688. // TODO: delete this comment?
  27689. const distanceGeometry = new THREE.IcosahedronGeometry( 1, 2 );
  27690. const distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  27691. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  27692. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  27693. const d = light.distance;
  27694. if ( d === 0.0 ) {
  27695. this.lightDistance.visible = false;
  27696. } else {
  27697. this.lightDistance.scale.set( d, d, d );
  27698. }
  27699. this.add( this.lightDistance );
  27700. */
  27701. }
  27702. dispose() {
  27703. this.geometry.dispose();
  27704. this.material.dispose();
  27705. }
  27706. update() {
  27707. if (this.color !== undefined) {
  27708. this.material.color.set(this.color);
  27709. } else {
  27710. this.material.color.copy(this.light.color);
  27711. }
  27712. /*
  27713. const d = this.light.distance;
  27714. if ( d === 0.0 ) {
  27715. this.lightDistance.visible = false;
  27716. } else {
  27717. this.lightDistance.visible = true;
  27718. this.lightDistance.scale.set( d, d, d );
  27719. }
  27720. */
  27721. }
  27722. }
  27723. const _vector$1 = /*@__PURE__*/new Vector3();
  27724. const _color1 = /*@__PURE__*/new Color();
  27725. const _color2 = /*@__PURE__*/new Color();
  27726. class HemisphereLightHelper extends Object3D {
  27727. constructor(light, size, color) {
  27728. super();
  27729. this.light = light;
  27730. this.light.updateMatrixWorld();
  27731. this.matrix = light.matrixWorld;
  27732. this.matrixAutoUpdate = false;
  27733. this.color = color;
  27734. const geometry = new OctahedronGeometry(size);
  27735. geometry.rotateY(Math.PI * 0.5);
  27736. this.material = new MeshBasicMaterial({
  27737. wireframe: true,
  27738. fog: false,
  27739. toneMapped: false
  27740. });
  27741. if (this.color === undefined) this.material.vertexColors = true;
  27742. const position = geometry.getAttribute('position');
  27743. const colors = new Float32Array(position.count * 3);
  27744. geometry.setAttribute('color', new BufferAttribute(colors, 3));
  27745. this.add(new Mesh(geometry, this.material));
  27746. this.update();
  27747. }
  27748. dispose() {
  27749. this.children[0].geometry.dispose();
  27750. this.children[0].material.dispose();
  27751. }
  27752. update() {
  27753. const mesh = this.children[0];
  27754. if (this.color !== undefined) {
  27755. this.material.color.set(this.color);
  27756. } else {
  27757. const colors = mesh.geometry.getAttribute('color');
  27758. _color1.copy(this.light.color);
  27759. _color2.copy(this.light.groundColor);
  27760. for (let i = 0, l = colors.count; i < l; i++) {
  27761. const color = i < l / 2 ? _color1 : _color2;
  27762. colors.setXYZ(i, color.r, color.g, color.b);
  27763. }
  27764. colors.needsUpdate = true;
  27765. }
  27766. mesh.lookAt(_vector$1.setFromMatrixPosition(this.light.matrixWorld).negate());
  27767. }
  27768. }
  27769. class GridHelper extends LineSegments {
  27770. constructor(size = 10, divisions = 10, color1 = 0x444444, color2 = 0x888888) {
  27771. color1 = new Color(color1);
  27772. color2 = new Color(color2);
  27773. const center = divisions / 2;
  27774. const step = size / divisions;
  27775. const halfSize = size / 2;
  27776. const vertices = [],
  27777. colors = [];
  27778. for (let i = 0, j = 0, k = -halfSize; i <= divisions; i++, k += step) {
  27779. vertices.push(-halfSize, 0, k, halfSize, 0, k);
  27780. vertices.push(k, 0, -halfSize, k, 0, halfSize);
  27781. const color = i === center ? color1 : color2;
  27782. color.toArray(colors, j);
  27783. j += 3;
  27784. color.toArray(colors, j);
  27785. j += 3;
  27786. color.toArray(colors, j);
  27787. j += 3;
  27788. color.toArray(colors, j);
  27789. j += 3;
  27790. }
  27791. const geometry = new BufferGeometry();
  27792. geometry.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  27793. geometry.setAttribute('color', new Float32BufferAttribute(colors, 3));
  27794. const material = new LineBasicMaterial({
  27795. vertexColors: true,
  27796. toneMapped: false
  27797. });
  27798. super(geometry, material);
  27799. this.type = 'GridHelper';
  27800. }
  27801. dispose() {
  27802. this.geometry.dispose();
  27803. this.material.dispose();
  27804. }
  27805. }
  27806. class PolarGridHelper extends LineSegments {
  27807. constructor(radius = 10, sectors = 16, rings = 8, divisions = 64, color1 = 0x444444, color2 = 0x888888) {
  27808. color1 = new Color(color1);
  27809. color2 = new Color(color2);
  27810. const vertices = [];
  27811. const colors = []; // create the sectors
  27812. if (sectors > 1) {
  27813. for (let i = 0; i < sectors; i++) {
  27814. const v = i / sectors * (Math.PI * 2);
  27815. const x = Math.sin(v) * radius;
  27816. const z = Math.cos(v) * radius;
  27817. vertices.push(0, 0, 0);
  27818. vertices.push(x, 0, z);
  27819. const color = i & 1 ? color1 : color2;
  27820. colors.push(color.r, color.g, color.b);
  27821. colors.push(color.r, color.g, color.b);
  27822. }
  27823. } // create the rings
  27824. for (let i = 0; i < rings; i++) {
  27825. const color = i & 1 ? color1 : color2;
  27826. const r = radius - radius / rings * i;
  27827. for (let j = 0; j < divisions; j++) {
  27828. // first vertex
  27829. let v = j / divisions * (Math.PI * 2);
  27830. let x = Math.sin(v) * r;
  27831. let z = Math.cos(v) * r;
  27832. vertices.push(x, 0, z);
  27833. colors.push(color.r, color.g, color.b); // second vertex
  27834. v = (j + 1) / divisions * (Math.PI * 2);
  27835. x = Math.sin(v) * r;
  27836. z = Math.cos(v) * r;
  27837. vertices.push(x, 0, z);
  27838. colors.push(color.r, color.g, color.b);
  27839. }
  27840. }
  27841. const geometry = new BufferGeometry();
  27842. geometry.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  27843. geometry.setAttribute('color', new Float32BufferAttribute(colors, 3));
  27844. const material = new LineBasicMaterial({
  27845. vertexColors: true,
  27846. toneMapped: false
  27847. });
  27848. super(geometry, material);
  27849. this.type = 'PolarGridHelper';
  27850. }
  27851. dispose() {
  27852. this.geometry.dispose();
  27853. this.material.dispose();
  27854. }
  27855. }
  27856. const _v1 = /*@__PURE__*/new Vector3();
  27857. const _v2 = /*@__PURE__*/new Vector3();
  27858. const _v3 = /*@__PURE__*/new Vector3();
  27859. class DirectionalLightHelper extends Object3D {
  27860. constructor(light, size, color) {
  27861. super();
  27862. this.light = light;
  27863. this.light.updateMatrixWorld();
  27864. this.matrix = light.matrixWorld;
  27865. this.matrixAutoUpdate = false;
  27866. this.color = color;
  27867. if (size === undefined) size = 1;
  27868. let geometry = new BufferGeometry();
  27869. geometry.setAttribute('position', new Float32BufferAttribute([-size, size, 0, size, size, 0, size, -size, 0, -size, -size, 0, -size, size, 0], 3));
  27870. const material = new LineBasicMaterial({
  27871. fog: false,
  27872. toneMapped: false
  27873. });
  27874. this.lightPlane = new Line(geometry, material);
  27875. this.add(this.lightPlane);
  27876. geometry = new BufferGeometry();
  27877. geometry.setAttribute('position', new Float32BufferAttribute([0, 0, 0, 0, 0, 1], 3));
  27878. this.targetLine = new Line(geometry, material);
  27879. this.add(this.targetLine);
  27880. this.update();
  27881. }
  27882. dispose() {
  27883. this.lightPlane.geometry.dispose();
  27884. this.lightPlane.material.dispose();
  27885. this.targetLine.geometry.dispose();
  27886. this.targetLine.material.dispose();
  27887. }
  27888. update() {
  27889. _v1.setFromMatrixPosition(this.light.matrixWorld);
  27890. _v2.setFromMatrixPosition(this.light.target.matrixWorld);
  27891. _v3.subVectors(_v2, _v1);
  27892. this.lightPlane.lookAt(_v2);
  27893. if (this.color !== undefined) {
  27894. this.lightPlane.material.color.set(this.color);
  27895. this.targetLine.material.color.set(this.color);
  27896. } else {
  27897. this.lightPlane.material.color.copy(this.light.color);
  27898. this.targetLine.material.color.copy(this.light.color);
  27899. }
  27900. this.targetLine.lookAt(_v2);
  27901. this.targetLine.scale.z = _v3.length();
  27902. }
  27903. }
  27904. const _vector = /*@__PURE__*/new Vector3();
  27905. const _camera = /*@__PURE__*/new Camera();
  27906. /**
  27907. * - shows frustum, line of sight and up of the camera
  27908. * - suitable for fast updates
  27909. * - based on frustum visualization in lightgl.js shadowmap example
  27910. * https://github.com/evanw/lightgl.js/blob/master/tests/shadowmap.html
  27911. */
  27912. class CameraHelper extends LineSegments {
  27913. constructor(camera) {
  27914. const geometry = new BufferGeometry();
  27915. const material = new LineBasicMaterial({
  27916. color: 0xffffff,
  27917. vertexColors: true,
  27918. toneMapped: false
  27919. });
  27920. const vertices = [];
  27921. const colors = [];
  27922. const pointMap = {}; // near
  27923. addLine('n1', 'n2');
  27924. addLine('n2', 'n4');
  27925. addLine('n4', 'n3');
  27926. addLine('n3', 'n1'); // far
  27927. addLine('f1', 'f2');
  27928. addLine('f2', 'f4');
  27929. addLine('f4', 'f3');
  27930. addLine('f3', 'f1'); // sides
  27931. addLine('n1', 'f1');
  27932. addLine('n2', 'f2');
  27933. addLine('n3', 'f3');
  27934. addLine('n4', 'f4'); // cone
  27935. addLine('p', 'n1');
  27936. addLine('p', 'n2');
  27937. addLine('p', 'n3');
  27938. addLine('p', 'n4'); // up
  27939. addLine('u1', 'u2');
  27940. addLine('u2', 'u3');
  27941. addLine('u3', 'u1'); // target
  27942. addLine('c', 't');
  27943. addLine('p', 'c'); // cross
  27944. addLine('cn1', 'cn2');
  27945. addLine('cn3', 'cn4');
  27946. addLine('cf1', 'cf2');
  27947. addLine('cf3', 'cf4');
  27948. function addLine(a, b) {
  27949. addPoint(a);
  27950. addPoint(b);
  27951. }
  27952. function addPoint(id) {
  27953. vertices.push(0, 0, 0);
  27954. colors.push(0, 0, 0);
  27955. if (pointMap[id] === undefined) {
  27956. pointMap[id] = [];
  27957. }
  27958. pointMap[id].push(vertices.length / 3 - 1);
  27959. }
  27960. geometry.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  27961. geometry.setAttribute('color', new Float32BufferAttribute(colors, 3));
  27962. super(geometry, material);
  27963. this.type = 'CameraHelper';
  27964. this.camera = camera;
  27965. if (this.camera.updateProjectionMatrix) this.camera.updateProjectionMatrix();
  27966. this.matrix = camera.matrixWorld;
  27967. this.matrixAutoUpdate = false;
  27968. this.pointMap = pointMap;
  27969. this.update(); // colors
  27970. const colorFrustum = new Color(0xffaa00);
  27971. const colorCone = new Color(0xff0000);
  27972. const colorUp = new Color(0x00aaff);
  27973. const colorTarget = new Color(0xffffff);
  27974. const colorCross = new Color(0x333333);
  27975. this.setColors(colorFrustum, colorCone, colorUp, colorTarget, colorCross);
  27976. }
  27977. setColors(frustum, cone, up, target, cross) {
  27978. const geometry = this.geometry;
  27979. const colorAttribute = geometry.getAttribute('color'); // near
  27980. colorAttribute.setXYZ(0, frustum.r, frustum.g, frustum.b);
  27981. colorAttribute.setXYZ(1, frustum.r, frustum.g, frustum.b); // n1, n2
  27982. colorAttribute.setXYZ(2, frustum.r, frustum.g, frustum.b);
  27983. colorAttribute.setXYZ(3, frustum.r, frustum.g, frustum.b); // n2, n4
  27984. colorAttribute.setXYZ(4, frustum.r, frustum.g, frustum.b);
  27985. colorAttribute.setXYZ(5, frustum.r, frustum.g, frustum.b); // n4, n3
  27986. colorAttribute.setXYZ(6, frustum.r, frustum.g, frustum.b);
  27987. colorAttribute.setXYZ(7, frustum.r, frustum.g, frustum.b); // n3, n1
  27988. // far
  27989. colorAttribute.setXYZ(8, frustum.r, frustum.g, frustum.b);
  27990. colorAttribute.setXYZ(9, frustum.r, frustum.g, frustum.b); // f1, f2
  27991. colorAttribute.setXYZ(10, frustum.r, frustum.g, frustum.b);
  27992. colorAttribute.setXYZ(11, frustum.r, frustum.g, frustum.b); // f2, f4
  27993. colorAttribute.setXYZ(12, frustum.r, frustum.g, frustum.b);
  27994. colorAttribute.setXYZ(13, frustum.r, frustum.g, frustum.b); // f4, f3
  27995. colorAttribute.setXYZ(14, frustum.r, frustum.g, frustum.b);
  27996. colorAttribute.setXYZ(15, frustum.r, frustum.g, frustum.b); // f3, f1
  27997. // sides
  27998. colorAttribute.setXYZ(16, frustum.r, frustum.g, frustum.b);
  27999. colorAttribute.setXYZ(17, frustum.r, frustum.g, frustum.b); // n1, f1
  28000. colorAttribute.setXYZ(18, frustum.r, frustum.g, frustum.b);
  28001. colorAttribute.setXYZ(19, frustum.r, frustum.g, frustum.b); // n2, f2
  28002. colorAttribute.setXYZ(20, frustum.r, frustum.g, frustum.b);
  28003. colorAttribute.setXYZ(21, frustum.r, frustum.g, frustum.b); // n3, f3
  28004. colorAttribute.setXYZ(22, frustum.r, frustum.g, frustum.b);
  28005. colorAttribute.setXYZ(23, frustum.r, frustum.g, frustum.b); // n4, f4
  28006. // cone
  28007. colorAttribute.setXYZ(24, cone.r, cone.g, cone.b);
  28008. colorAttribute.setXYZ(25, cone.r, cone.g, cone.b); // p, n1
  28009. colorAttribute.setXYZ(26, cone.r, cone.g, cone.b);
  28010. colorAttribute.setXYZ(27, cone.r, cone.g, cone.b); // p, n2
  28011. colorAttribute.setXYZ(28, cone.r, cone.g, cone.b);
  28012. colorAttribute.setXYZ(29, cone.r, cone.g, cone.b); // p, n3
  28013. colorAttribute.setXYZ(30, cone.r, cone.g, cone.b);
  28014. colorAttribute.setXYZ(31, cone.r, cone.g, cone.b); // p, n4
  28015. // up
  28016. colorAttribute.setXYZ(32, up.r, up.g, up.b);
  28017. colorAttribute.setXYZ(33, up.r, up.g, up.b); // u1, u2
  28018. colorAttribute.setXYZ(34, up.r, up.g, up.b);
  28019. colorAttribute.setXYZ(35, up.r, up.g, up.b); // u2, u3
  28020. colorAttribute.setXYZ(36, up.r, up.g, up.b);
  28021. colorAttribute.setXYZ(37, up.r, up.g, up.b); // u3, u1
  28022. // target
  28023. colorAttribute.setXYZ(38, target.r, target.g, target.b);
  28024. colorAttribute.setXYZ(39, target.r, target.g, target.b); // c, t
  28025. colorAttribute.setXYZ(40, cross.r, cross.g, cross.b);
  28026. colorAttribute.setXYZ(41, cross.r, cross.g, cross.b); // p, c
  28027. // cross
  28028. colorAttribute.setXYZ(42, cross.r, cross.g, cross.b);
  28029. colorAttribute.setXYZ(43, cross.r, cross.g, cross.b); // cn1, cn2
  28030. colorAttribute.setXYZ(44, cross.r, cross.g, cross.b);
  28031. colorAttribute.setXYZ(45, cross.r, cross.g, cross.b); // cn3, cn4
  28032. colorAttribute.setXYZ(46, cross.r, cross.g, cross.b);
  28033. colorAttribute.setXYZ(47, cross.r, cross.g, cross.b); // cf1, cf2
  28034. colorAttribute.setXYZ(48, cross.r, cross.g, cross.b);
  28035. colorAttribute.setXYZ(49, cross.r, cross.g, cross.b); // cf3, cf4
  28036. colorAttribute.needsUpdate = true;
  28037. }
  28038. update() {
  28039. const geometry = this.geometry;
  28040. const pointMap = this.pointMap;
  28041. const w = 1,
  28042. h = 1; // we need just camera projection matrix inverse
  28043. // world matrix must be identity
  28044. _camera.projectionMatrixInverse.copy(this.camera.projectionMatrixInverse); // center / target
  28045. setPoint('c', pointMap, geometry, _camera, 0, 0, -1);
  28046. setPoint('t', pointMap, geometry, _camera, 0, 0, 1); // near
  28047. setPoint('n1', pointMap, geometry, _camera, -w, -h, -1);
  28048. setPoint('n2', pointMap, geometry, _camera, w, -h, -1);
  28049. setPoint('n3', pointMap, geometry, _camera, -w, h, -1);
  28050. setPoint('n4', pointMap, geometry, _camera, w, h, -1); // far
  28051. setPoint('f1', pointMap, geometry, _camera, -w, -h, 1);
  28052. setPoint('f2', pointMap, geometry, _camera, w, -h, 1);
  28053. setPoint('f3', pointMap, geometry, _camera, -w, h, 1);
  28054. setPoint('f4', pointMap, geometry, _camera, w, h, 1); // up
  28055. setPoint('u1', pointMap, geometry, _camera, w * 0.7, h * 1.1, -1);
  28056. setPoint('u2', pointMap, geometry, _camera, -w * 0.7, h * 1.1, -1);
  28057. setPoint('u3', pointMap, geometry, _camera, 0, h * 2, -1); // cross
  28058. setPoint('cf1', pointMap, geometry, _camera, -w, 0, 1);
  28059. setPoint('cf2', pointMap, geometry, _camera, w, 0, 1);
  28060. setPoint('cf3', pointMap, geometry, _camera, 0, -h, 1);
  28061. setPoint('cf4', pointMap, geometry, _camera, 0, h, 1);
  28062. setPoint('cn1', pointMap, geometry, _camera, -w, 0, -1);
  28063. setPoint('cn2', pointMap, geometry, _camera, w, 0, -1);
  28064. setPoint('cn3', pointMap, geometry, _camera, 0, -h, -1);
  28065. setPoint('cn4', pointMap, geometry, _camera, 0, h, -1);
  28066. geometry.getAttribute('position').needsUpdate = true;
  28067. }
  28068. dispose() {
  28069. this.geometry.dispose();
  28070. this.material.dispose();
  28071. }
  28072. }
  28073. function setPoint(point, pointMap, geometry, camera, x, y, z) {
  28074. _vector.set(x, y, z).unproject(camera);
  28075. const points = pointMap[point];
  28076. if (points !== undefined) {
  28077. const position = geometry.getAttribute('position');
  28078. for (let i = 0, l = points.length; i < l; i++) {
  28079. position.setXYZ(points[i], _vector.x, _vector.y, _vector.z);
  28080. }
  28081. }
  28082. }
  28083. const _box = /*@__PURE__*/new Box3();
  28084. class BoxHelper extends LineSegments {
  28085. constructor(object, color = 0xffff00) {
  28086. const indices = new Uint16Array([0, 1, 1, 2, 2, 3, 3, 0, 4, 5, 5, 6, 6, 7, 7, 4, 0, 4, 1, 5, 2, 6, 3, 7]);
  28087. const positions = new Float32Array(8 * 3);
  28088. const geometry = new BufferGeometry();
  28089. geometry.setIndex(new BufferAttribute(indices, 1));
  28090. geometry.setAttribute('position', new BufferAttribute(positions, 3));
  28091. super(geometry, new LineBasicMaterial({
  28092. color: color,
  28093. toneMapped: false
  28094. }));
  28095. this.object = object;
  28096. this.type = 'BoxHelper';
  28097. this.matrixAutoUpdate = false;
  28098. this.update();
  28099. }
  28100. update(object) {
  28101. if (object !== undefined) {
  28102. console.warn('THREE.BoxHelper: .update() has no longer arguments.');
  28103. }
  28104. if (this.object !== undefined) {
  28105. _box.setFromObject(this.object);
  28106. }
  28107. if (_box.isEmpty()) return;
  28108. const min = _box.min;
  28109. const max = _box.max;
  28110. /*
  28111. 5____4
  28112. 1/___0/|
  28113. | 6__|_7
  28114. 2/___3/
  28115. 0: max.x, max.y, max.z
  28116. 1: min.x, max.y, max.z
  28117. 2: min.x, min.y, max.z
  28118. 3: max.x, min.y, max.z
  28119. 4: max.x, max.y, min.z
  28120. 5: min.x, max.y, min.z
  28121. 6: min.x, min.y, min.z
  28122. 7: max.x, min.y, min.z
  28123. */
  28124. const position = this.geometry.attributes.position;
  28125. const array = position.array;
  28126. array[0] = max.x;
  28127. array[1] = max.y;
  28128. array[2] = max.z;
  28129. array[3] = min.x;
  28130. array[4] = max.y;
  28131. array[5] = max.z;
  28132. array[6] = min.x;
  28133. array[7] = min.y;
  28134. array[8] = max.z;
  28135. array[9] = max.x;
  28136. array[10] = min.y;
  28137. array[11] = max.z;
  28138. array[12] = max.x;
  28139. array[13] = max.y;
  28140. array[14] = min.z;
  28141. array[15] = min.x;
  28142. array[16] = max.y;
  28143. array[17] = min.z;
  28144. array[18] = min.x;
  28145. array[19] = min.y;
  28146. array[20] = min.z;
  28147. array[21] = max.x;
  28148. array[22] = min.y;
  28149. array[23] = min.z;
  28150. position.needsUpdate = true;
  28151. this.geometry.computeBoundingSphere();
  28152. }
  28153. setFromObject(object) {
  28154. this.object = object;
  28155. this.update();
  28156. return this;
  28157. }
  28158. copy(source, recursive) {
  28159. super.copy(source, recursive);
  28160. this.object = source.object;
  28161. return this;
  28162. }
  28163. dispose() {
  28164. this.geometry.dispose();
  28165. this.material.dispose();
  28166. }
  28167. }
  28168. class Box3Helper extends LineSegments {
  28169. constructor(box, color = 0xffff00) {
  28170. const indices = new Uint16Array([0, 1, 1, 2, 2, 3, 3, 0, 4, 5, 5, 6, 6, 7, 7, 4, 0, 4, 1, 5, 2, 6, 3, 7]);
  28171. const positions = [1, 1, 1, -1, 1, 1, -1, -1, 1, 1, -1, 1, 1, 1, -1, -1, 1, -1, -1, -1, -1, 1, -1, -1];
  28172. const geometry = new BufferGeometry();
  28173. geometry.setIndex(new BufferAttribute(indices, 1));
  28174. geometry.setAttribute('position', new Float32BufferAttribute(positions, 3));
  28175. super(geometry, new LineBasicMaterial({
  28176. color: color,
  28177. toneMapped: false
  28178. }));
  28179. this.box = box;
  28180. this.type = 'Box3Helper';
  28181. this.geometry.computeBoundingSphere();
  28182. }
  28183. updateMatrixWorld(force) {
  28184. const box = this.box;
  28185. if (box.isEmpty()) return;
  28186. box.getCenter(this.position);
  28187. box.getSize(this.scale);
  28188. this.scale.multiplyScalar(0.5);
  28189. super.updateMatrixWorld(force);
  28190. }
  28191. dispose() {
  28192. this.geometry.dispose();
  28193. this.material.dispose();
  28194. }
  28195. }
  28196. class PlaneHelper extends Line {
  28197. constructor(plane, size = 1, hex = 0xffff00) {
  28198. const color = hex;
  28199. const positions = [1, -1, 0, -1, 1, 0, -1, -1, 0, 1, 1, 0, -1, 1, 0, -1, -1, 0, 1, -1, 0, 1, 1, 0];
  28200. const geometry = new BufferGeometry();
  28201. geometry.setAttribute('position', new Float32BufferAttribute(positions, 3));
  28202. geometry.computeBoundingSphere();
  28203. super(geometry, new LineBasicMaterial({
  28204. color: color,
  28205. toneMapped: false
  28206. }));
  28207. this.type = 'PlaneHelper';
  28208. this.plane = plane;
  28209. this.size = size;
  28210. const positions2 = [1, 1, 0, -1, 1, 0, -1, -1, 0, 1, 1, 0, -1, -1, 0, 1, -1, 0];
  28211. const geometry2 = new BufferGeometry();
  28212. geometry2.setAttribute('position', new Float32BufferAttribute(positions2, 3));
  28213. geometry2.computeBoundingSphere();
  28214. this.add(new Mesh(geometry2, new MeshBasicMaterial({
  28215. color: color,
  28216. opacity: 0.2,
  28217. transparent: true,
  28218. depthWrite: false,
  28219. toneMapped: false
  28220. })));
  28221. }
  28222. updateMatrixWorld(force) {
  28223. this.position.set(0, 0, 0);
  28224. this.scale.set(0.5 * this.size, 0.5 * this.size, 1);
  28225. this.lookAt(this.plane.normal);
  28226. this.translateZ(-this.plane.constant);
  28227. super.updateMatrixWorld(force);
  28228. }
  28229. dispose() {
  28230. this.geometry.dispose();
  28231. this.material.dispose();
  28232. this.children[0].geometry.dispose();
  28233. this.children[0].material.dispose();
  28234. }
  28235. }
  28236. const _axis = /*@__PURE__*/new Vector3();
  28237. let _lineGeometry, _coneGeometry;
  28238. class ArrowHelper extends Object3D {
  28239. // dir is assumed to be normalized
  28240. constructor(dir = new Vector3(0, 0, 1), origin = new Vector3(0, 0, 0), length = 1, color = 0xffff00, headLength = length * 0.2, headWidth = headLength * 0.2) {
  28241. super();
  28242. this.type = 'ArrowHelper';
  28243. if (_lineGeometry === undefined) {
  28244. _lineGeometry = new BufferGeometry();
  28245. _lineGeometry.setAttribute('position', new Float32BufferAttribute([0, 0, 0, 0, 1, 0], 3));
  28246. _coneGeometry = new CylinderGeometry(0, 0.5, 1, 5, 1);
  28247. _coneGeometry.translate(0, -0.5, 0);
  28248. }
  28249. this.position.copy(origin);
  28250. this.line = new Line(_lineGeometry, new LineBasicMaterial({
  28251. color: color,
  28252. toneMapped: false
  28253. }));
  28254. this.line.matrixAutoUpdate = false;
  28255. this.add(this.line);
  28256. this.cone = new Mesh(_coneGeometry, new MeshBasicMaterial({
  28257. color: color,
  28258. toneMapped: false
  28259. }));
  28260. this.cone.matrixAutoUpdate = false;
  28261. this.add(this.cone);
  28262. this.setDirection(dir);
  28263. this.setLength(length, headLength, headWidth);
  28264. }
  28265. setDirection(dir) {
  28266. // dir is assumed to be normalized
  28267. if (dir.y > 0.99999) {
  28268. this.quaternion.set(0, 0, 0, 1);
  28269. } else if (dir.y < -0.99999) {
  28270. this.quaternion.set(1, 0, 0, 0);
  28271. } else {
  28272. _axis.set(dir.z, 0, -dir.x).normalize();
  28273. const radians = Math.acos(dir.y);
  28274. this.quaternion.setFromAxisAngle(_axis, radians);
  28275. }
  28276. }
  28277. setLength(length, headLength = length * 0.2, headWidth = headLength * 0.2) {
  28278. this.line.scale.set(1, Math.max(0.0001, length - headLength), 1); // see #17458
  28279. this.line.updateMatrix();
  28280. this.cone.scale.set(headWidth, headLength, headWidth);
  28281. this.cone.position.y = length;
  28282. this.cone.updateMatrix();
  28283. }
  28284. setColor(color) {
  28285. this.line.material.color.set(color);
  28286. this.cone.material.color.set(color);
  28287. }
  28288. copy(source) {
  28289. super.copy(source, false);
  28290. this.line.copy(source.line);
  28291. this.cone.copy(source.cone);
  28292. return this;
  28293. }
  28294. dispose() {
  28295. this.line.geometry.dispose();
  28296. this.line.material.dispose();
  28297. this.cone.geometry.dispose();
  28298. this.cone.material.dispose();
  28299. }
  28300. }
  28301. class AxesHelper extends LineSegments {
  28302. constructor(size = 1) {
  28303. const vertices = [0, 0, 0, size, 0, 0, 0, 0, 0, 0, size, 0, 0, 0, 0, 0, 0, size];
  28304. const colors = [1, 0, 0, 1, 0.6, 0, 0, 1, 0, 0.6, 1, 0, 0, 0, 1, 0, 0.6, 1];
  28305. const geometry = new BufferGeometry();
  28306. geometry.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  28307. geometry.setAttribute('color', new Float32BufferAttribute(colors, 3));
  28308. const material = new LineBasicMaterial({
  28309. vertexColors: true,
  28310. toneMapped: false
  28311. });
  28312. super(geometry, material);
  28313. this.type = 'AxesHelper';
  28314. }
  28315. setColors(xAxisColor, yAxisColor, zAxisColor) {
  28316. const color = new Color();
  28317. const array = this.geometry.attributes.color.array;
  28318. color.set(xAxisColor);
  28319. color.toArray(array, 0);
  28320. color.toArray(array, 3);
  28321. color.set(yAxisColor);
  28322. color.toArray(array, 6);
  28323. color.toArray(array, 9);
  28324. color.set(zAxisColor);
  28325. color.toArray(array, 12);
  28326. color.toArray(array, 15);
  28327. this.geometry.attributes.color.needsUpdate = true;
  28328. return this;
  28329. }
  28330. dispose() {
  28331. this.geometry.dispose();
  28332. this.material.dispose();
  28333. }
  28334. }
  28335. class ShapePath {
  28336. constructor() {
  28337. this.type = 'ShapePath';
  28338. this.color = new Color();
  28339. this.subPaths = [];
  28340. this.currentPath = null;
  28341. }
  28342. moveTo(x, y) {
  28343. this.currentPath = new Path();
  28344. this.subPaths.push(this.currentPath);
  28345. this.currentPath.moveTo(x, y);
  28346. return this;
  28347. }
  28348. lineTo(x, y) {
  28349. this.currentPath.lineTo(x, y);
  28350. return this;
  28351. }
  28352. quadraticCurveTo(aCPx, aCPy, aX, aY) {
  28353. this.currentPath.quadraticCurveTo(aCPx, aCPy, aX, aY);
  28354. return this;
  28355. }
  28356. bezierCurveTo(aCP1x, aCP1y, aCP2x, aCP2y, aX, aY) {
  28357. this.currentPath.bezierCurveTo(aCP1x, aCP1y, aCP2x, aCP2y, aX, aY);
  28358. return this;
  28359. }
  28360. splineThru(pts) {
  28361. this.currentPath.splineThru(pts);
  28362. return this;
  28363. }
  28364. toShapes(isCCW) {
  28365. function toShapesNoHoles(inSubpaths) {
  28366. const shapes = [];
  28367. for (let i = 0, l = inSubpaths.length; i < l; i++) {
  28368. const tmpPath = inSubpaths[i];
  28369. const tmpShape = new Shape();
  28370. tmpShape.curves = tmpPath.curves;
  28371. shapes.push(tmpShape);
  28372. }
  28373. return shapes;
  28374. }
  28375. function isPointInsidePolygon(inPt, inPolygon) {
  28376. const polyLen = inPolygon.length; // inPt on polygon contour => immediate success or
  28377. // toggling of inside/outside at every single! intersection point of an edge
  28378. // with the horizontal line through inPt, left of inPt
  28379. // not counting lowerY endpoints of edges and whole edges on that line
  28380. let inside = false;
  28381. for (let p = polyLen - 1, q = 0; q < polyLen; p = q++) {
  28382. let edgeLowPt = inPolygon[p];
  28383. let edgeHighPt = inPolygon[q];
  28384. let edgeDx = edgeHighPt.x - edgeLowPt.x;
  28385. let edgeDy = edgeHighPt.y - edgeLowPt.y;
  28386. if (Math.abs(edgeDy) > Number.EPSILON) {
  28387. // not parallel
  28388. if (edgeDy < 0) {
  28389. edgeLowPt = inPolygon[q];
  28390. edgeDx = -edgeDx;
  28391. edgeHighPt = inPolygon[p];
  28392. edgeDy = -edgeDy;
  28393. }
  28394. if (inPt.y < edgeLowPt.y || inPt.y > edgeHighPt.y) continue;
  28395. if (inPt.y === edgeLowPt.y) {
  28396. if (inPt.x === edgeLowPt.x) return true; // inPt is on contour ?
  28397. // continue; // no intersection or edgeLowPt => doesn't count !!!
  28398. } else {
  28399. const perpEdge = edgeDy * (inPt.x - edgeLowPt.x) - edgeDx * (inPt.y - edgeLowPt.y);
  28400. if (perpEdge === 0) return true; // inPt is on contour ?
  28401. if (perpEdge < 0) continue;
  28402. inside = !inside; // true intersection left of inPt
  28403. }
  28404. } else {
  28405. // parallel or collinear
  28406. if (inPt.y !== edgeLowPt.y) continue; // parallel
  28407. // edge lies on the same horizontal line as inPt
  28408. if (edgeHighPt.x <= inPt.x && inPt.x <= edgeLowPt.x || edgeLowPt.x <= inPt.x && inPt.x <= edgeHighPt.x) return true; // inPt: Point on contour !
  28409. // continue;
  28410. }
  28411. }
  28412. return inside;
  28413. }
  28414. const isClockWise = ShapeUtils.isClockWise;
  28415. const subPaths = this.subPaths;
  28416. if (subPaths.length === 0) return [];
  28417. let solid, tmpPath, tmpShape;
  28418. const shapes = [];
  28419. if (subPaths.length === 1) {
  28420. tmpPath = subPaths[0];
  28421. tmpShape = new Shape();
  28422. tmpShape.curves = tmpPath.curves;
  28423. shapes.push(tmpShape);
  28424. return shapes;
  28425. }
  28426. let holesFirst = !isClockWise(subPaths[0].getPoints());
  28427. holesFirst = isCCW ? !holesFirst : holesFirst; // console.log("Holes first", holesFirst);
  28428. const betterShapeHoles = [];
  28429. const newShapes = [];
  28430. let newShapeHoles = [];
  28431. let mainIdx = 0;
  28432. let tmpPoints;
  28433. newShapes[mainIdx] = undefined;
  28434. newShapeHoles[mainIdx] = [];
  28435. for (let i = 0, l = subPaths.length; i < l; i++) {
  28436. tmpPath = subPaths[i];
  28437. tmpPoints = tmpPath.getPoints();
  28438. solid = isClockWise(tmpPoints);
  28439. solid = isCCW ? !solid : solid;
  28440. if (solid) {
  28441. if (!holesFirst && newShapes[mainIdx]) mainIdx++;
  28442. newShapes[mainIdx] = {
  28443. s: new Shape(),
  28444. p: tmpPoints
  28445. };
  28446. newShapes[mainIdx].s.curves = tmpPath.curves;
  28447. if (holesFirst) mainIdx++;
  28448. newShapeHoles[mainIdx] = []; //console.log('cw', i);
  28449. } else {
  28450. newShapeHoles[mainIdx].push({
  28451. h: tmpPath,
  28452. p: tmpPoints[0]
  28453. }); //console.log('ccw', i);
  28454. }
  28455. } // only Holes? -> probably all Shapes with wrong orientation
  28456. if (!newShapes[0]) return toShapesNoHoles(subPaths);
  28457. if (newShapes.length > 1) {
  28458. let ambiguous = false;
  28459. let toChange = 0;
  28460. for (let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx++) {
  28461. betterShapeHoles[sIdx] = [];
  28462. }
  28463. for (let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx++) {
  28464. const sho = newShapeHoles[sIdx];
  28465. for (let hIdx = 0; hIdx < sho.length; hIdx++) {
  28466. const ho = sho[hIdx];
  28467. let hole_unassigned = true;
  28468. for (let s2Idx = 0; s2Idx < newShapes.length; s2Idx++) {
  28469. if (isPointInsidePolygon(ho.p, newShapes[s2Idx].p)) {
  28470. if (sIdx !== s2Idx) toChange++;
  28471. if (hole_unassigned) {
  28472. hole_unassigned = false;
  28473. betterShapeHoles[s2Idx].push(ho);
  28474. } else {
  28475. ambiguous = true;
  28476. }
  28477. }
  28478. }
  28479. if (hole_unassigned) {
  28480. betterShapeHoles[sIdx].push(ho);
  28481. }
  28482. }
  28483. }
  28484. if (toChange > 0 && ambiguous === false) {
  28485. newShapeHoles = betterShapeHoles;
  28486. }
  28487. }
  28488. let tmpHoles;
  28489. for (let i = 0, il = newShapes.length; i < il; i++) {
  28490. tmpShape = newShapes[i].s;
  28491. shapes.push(tmpShape);
  28492. tmpHoles = newShapeHoles[i];
  28493. for (let j = 0, jl = tmpHoles.length; j < jl; j++) {
  28494. tmpShape.holes.push(tmpHoles[j].h);
  28495. }
  28496. } //console.log("shape", shapes);
  28497. return shapes;
  28498. }
  28499. }
  28500. const _tables = /*@__PURE__*/_generateTables();
  28501. function _generateTables() {
  28502. // float32 to float16 helpers
  28503. const buffer = new ArrayBuffer(4);
  28504. const floatView = new Float32Array(buffer);
  28505. const uint32View = new Uint32Array(buffer);
  28506. const baseTable = new Uint32Array(512);
  28507. const shiftTable = new Uint32Array(512);
  28508. for (let i = 0; i < 256; ++i) {
  28509. const e = i - 127; // very small number (0, -0)
  28510. if (e < -27) {
  28511. baseTable[i] = 0x0000;
  28512. baseTable[i | 0x100] = 0x8000;
  28513. shiftTable[i] = 24;
  28514. shiftTable[i | 0x100] = 24; // small number (denorm)
  28515. } else if (e < -14) {
  28516. baseTable[i] = 0x0400 >> -e - 14;
  28517. baseTable[i | 0x100] = 0x0400 >> -e - 14 | 0x8000;
  28518. shiftTable[i] = -e - 1;
  28519. shiftTable[i | 0x100] = -e - 1; // normal number
  28520. } else if (e <= 15) {
  28521. baseTable[i] = e + 15 << 10;
  28522. baseTable[i | 0x100] = e + 15 << 10 | 0x8000;
  28523. shiftTable[i] = 13;
  28524. shiftTable[i | 0x100] = 13; // large number (Infinity, -Infinity)
  28525. } else if (e < 128) {
  28526. baseTable[i] = 0x7c00;
  28527. baseTable[i | 0x100] = 0xfc00;
  28528. shiftTable[i] = 24;
  28529. shiftTable[i | 0x100] = 24; // stay (NaN, Infinity, -Infinity)
  28530. } else {
  28531. baseTable[i] = 0x7c00;
  28532. baseTable[i | 0x100] = 0xfc00;
  28533. shiftTable[i] = 13;
  28534. shiftTable[i | 0x100] = 13;
  28535. }
  28536. } // float16 to float32 helpers
  28537. const mantissaTable = new Uint32Array(2048);
  28538. const exponentTable = new Uint32Array(64);
  28539. const offsetTable = new Uint32Array(64);
  28540. for (let i = 1; i < 1024; ++i) {
  28541. let m = i << 13; // zero pad mantissa bits
  28542. let e = 0; // zero exponent
  28543. // normalized
  28544. while ((m & 0x00800000) === 0) {
  28545. m <<= 1;
  28546. e -= 0x00800000; // decrement exponent
  28547. }
  28548. m &= ~0x00800000; // clear leading 1 bit
  28549. e += 0x38800000; // adjust bias
  28550. mantissaTable[i] = m | e;
  28551. }
  28552. for (let i = 1024; i < 2048; ++i) {
  28553. mantissaTable[i] = 0x38000000 + (i - 1024 << 13);
  28554. }
  28555. for (let i = 1; i < 31; ++i) {
  28556. exponentTable[i] = i << 23;
  28557. }
  28558. exponentTable[31] = 0x47800000;
  28559. exponentTable[32] = 0x80000000;
  28560. for (let i = 33; i < 63; ++i) {
  28561. exponentTable[i] = 0x80000000 + (i - 32 << 23);
  28562. }
  28563. exponentTable[63] = 0xc7800000;
  28564. for (let i = 1; i < 64; ++i) {
  28565. if (i !== 32) {
  28566. offsetTable[i] = 1024;
  28567. }
  28568. }
  28569. return {
  28570. floatView: floatView,
  28571. uint32View: uint32View,
  28572. baseTable: baseTable,
  28573. shiftTable: shiftTable,
  28574. mantissaTable: mantissaTable,
  28575. exponentTable: exponentTable,
  28576. offsetTable: offsetTable
  28577. };
  28578. } // float32 to float16
  28579. function toHalfFloat(val) {
  28580. if (Math.abs(val) > 65504) console.warn('THREE.DataUtils.toHalfFloat(): Value out of range.');
  28581. val = clamp(val, -65504, 65504);
  28582. _tables.floatView[0] = val;
  28583. const f = _tables.uint32View[0];
  28584. const e = f >> 23 & 0x1ff;
  28585. return _tables.baseTable[e] + ((f & 0x007fffff) >> _tables.shiftTable[e]);
  28586. } // float16 to float32
  28587. function fromHalfFloat(val) {
  28588. const m = val >> 10;
  28589. _tables.uint32View[0] = _tables.mantissaTable[_tables.offsetTable[m] + (val & 0x3ff)] + _tables.exponentTable[m];
  28590. return _tables.floatView[0];
  28591. }
  28592. var DataUtils = /*#__PURE__*/Object.freeze({
  28593. __proto__: null,
  28594. toHalfFloat: toHalfFloat,
  28595. fromHalfFloat: fromHalfFloat
  28596. });
  28597. function ImmediateRenderObject() {
  28598. console.error('THREE.ImmediateRenderObject has been removed.');
  28599. } // r138, 48b05d3500acc084df50be9b4c90781ad9b8cb17
  28600. class WebGLMultisampleRenderTarget extends WebGLRenderTarget {
  28601. constructor(width, height, options) {
  28602. console.error('THREE.WebGLMultisampleRenderTarget has been removed. Use a normal render target and set the "samples" property to greater 0 to enable multisampling.');
  28603. super(width, height, options);
  28604. this.samples = 4;
  28605. }
  28606. } // r138, f9cd9cab03b7b64244e304900a3a2eeaa3a588ce
  28607. class DataTexture2DArray extends DataArrayTexture {
  28608. constructor(data, width, height, depth) {
  28609. console.warn('THREE.DataTexture2DArray has been renamed to DataArrayTexture.');
  28610. super(data, width, height, depth);
  28611. }
  28612. } // r138, f9cd9cab03b7b64244e304900a3a2eeaa3a588ce
  28613. class DataTexture3D extends Data3DTexture {
  28614. constructor(data, width, height, depth) {
  28615. console.warn('THREE.DataTexture3D has been renamed to Data3DTexture.');
  28616. super(data, width, height, depth);
  28617. }
  28618. } // r144
  28619. class BoxBufferGeometry extends BoxGeometry {
  28620. constructor(width, height, depth, widthSegments, heightSegments, depthSegments) {
  28621. console.warn('THREE.BoxBufferGeometry has been renamed to THREE.BoxGeometry.');
  28622. super(width, height, depth, widthSegments, heightSegments, depthSegments);
  28623. }
  28624. } // r144
  28625. class CapsuleBufferGeometry extends CapsuleGeometry {
  28626. constructor(radius, length, capSegments, radialSegments) {
  28627. console.warn('THREE.CapsuleBufferGeometry has been renamed to THREE.CapsuleGeometry.');
  28628. super(radius, length, capSegments, radialSegments);
  28629. }
  28630. } // r144
  28631. class CircleBufferGeometry extends CircleGeometry {
  28632. constructor(radius, segments, thetaStart, thetaLength) {
  28633. console.warn('THREE.CircleBufferGeometry has been renamed to THREE.CircleGeometry.');
  28634. super(radius, segments, thetaStart, thetaLength);
  28635. }
  28636. } // r144
  28637. class ConeBufferGeometry extends ConeGeometry {
  28638. constructor(radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength) {
  28639. console.warn('THREE.ConeBufferGeometry has been renamed to THREE.ConeGeometry.');
  28640. super(radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength);
  28641. }
  28642. } // r144
  28643. class CylinderBufferGeometry extends CylinderGeometry {
  28644. constructor(radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength) {
  28645. console.warn('THREE.CylinderBufferGeometry has been renamed to THREE.CylinderGeometry.');
  28646. super(radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength);
  28647. }
  28648. } // r144
  28649. class DodecahedronBufferGeometry extends DodecahedronGeometry {
  28650. constructor(radius, detail) {
  28651. console.warn('THREE.DodecahedronBufferGeometry has been renamed to THREE.DodecahedronGeometry.');
  28652. super(radius, detail);
  28653. }
  28654. } // r144
  28655. class ExtrudeBufferGeometry extends ExtrudeGeometry {
  28656. constructor(shapes, options) {
  28657. console.warn('THREE.ExtrudeBufferGeometry has been renamed to THREE.ExtrudeGeometry.');
  28658. super(shapes, options);
  28659. }
  28660. } // r144
  28661. class IcosahedronBufferGeometry extends IcosahedronGeometry {
  28662. constructor(radius, detail) {
  28663. console.warn('THREE.IcosahedronBufferGeometry has been renamed to THREE.IcosahedronGeometry.');
  28664. super(radius, detail);
  28665. }
  28666. } // r144
  28667. class LatheBufferGeometry extends LatheGeometry {
  28668. constructor(points, segments, phiStart, phiLength) {
  28669. console.warn('THREE.LatheBufferGeometry has been renamed to THREE.LatheGeometry.');
  28670. super(points, segments, phiStart, phiLength);
  28671. }
  28672. } // r144
  28673. class OctahedronBufferGeometry extends OctahedronGeometry {
  28674. constructor(radius, detail) {
  28675. console.warn('THREE.OctahedronBufferGeometry has been renamed to THREE.OctahedronGeometry.');
  28676. super(radius, detail);
  28677. }
  28678. } // r144
  28679. class PlaneBufferGeometry extends PlaneGeometry {
  28680. constructor(width, height, widthSegments, heightSegments) {
  28681. console.warn('THREE.PlaneBufferGeometry has been renamed to THREE.PlaneGeometry.');
  28682. super(width, height, widthSegments, heightSegments);
  28683. }
  28684. } // r144
  28685. class PolyhedronBufferGeometry extends PolyhedronGeometry {
  28686. constructor(vertices, indices, radius, detail) {
  28687. console.warn('THREE.PolyhedronBufferGeometry has been renamed to THREE.PolyhedronGeometry.');
  28688. super(vertices, indices, radius, detail);
  28689. }
  28690. } // r144
  28691. class RingBufferGeometry extends RingGeometry {
  28692. constructor(innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength) {
  28693. console.warn('THREE.RingBufferGeometry has been renamed to THREE.RingGeometry.');
  28694. super(innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength);
  28695. }
  28696. } // r144
  28697. class ShapeBufferGeometry extends ShapeGeometry {
  28698. constructor(shapes, curveSegments) {
  28699. console.warn('THREE.ShapeBufferGeometry has been renamed to THREE.ShapeGeometry.');
  28700. super(shapes, curveSegments);
  28701. }
  28702. } // r144
  28703. class SphereBufferGeometry extends SphereGeometry {
  28704. constructor(radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength) {
  28705. console.warn('THREE.SphereBufferGeometry has been renamed to THREE.SphereGeometry.');
  28706. super(radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength);
  28707. }
  28708. } // r144
  28709. class TetrahedronBufferGeometry extends TetrahedronGeometry {
  28710. constructor(radius, detail) {
  28711. console.warn('THREE.TetrahedronBufferGeometry has been renamed to THREE.TetrahedronGeometry.');
  28712. super(radius, detail);
  28713. }
  28714. } // r144
  28715. class TorusBufferGeometry extends TorusGeometry {
  28716. constructor(radius, tube, radialSegments, tubularSegments, arc) {
  28717. console.warn('THREE.TorusBufferGeometry has been renamed to THREE.TorusGeometry.');
  28718. super(radius, tube, radialSegments, tubularSegments, arc);
  28719. }
  28720. } // r144
  28721. class TorusKnotBufferGeometry extends TorusKnotGeometry {
  28722. constructor(radius, tube, tubularSegments, radialSegments, p, q) {
  28723. console.warn('THREE.TorusKnotBufferGeometry has been renamed to THREE.TorusKnotGeometry.');
  28724. super(radius, tube, tubularSegments, radialSegments, p, q);
  28725. }
  28726. } // r144
  28727. class TubeBufferGeometry extends TubeGeometry {
  28728. constructor(path, tubularSegments, radius, radialSegments, closed) {
  28729. console.warn('THREE.TubeBufferGeometry has been renamed to THREE.TubeGeometry.');
  28730. super(path, tubularSegments, radius, radialSegments, closed);
  28731. }
  28732. }
  28733. if (typeof __THREE_DEVTOOLS__ !== 'undefined') {
  28734. __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent('register', {
  28735. detail: {
  28736. revision: REVISION
  28737. }
  28738. }));
  28739. }
  28740. if (typeof window !== 'undefined') {
  28741. if (window.__THREE__) {
  28742. console.warn('WARNING: Multiple instances of Three.js being imported.');
  28743. } else {
  28744. window.__THREE__ = REVISION;
  28745. }
  28746. }
  28747. exports.ACESFilmicToneMapping = ACESFilmicToneMapping;
  28748. exports.AddEquation = AddEquation;
  28749. exports.AddOperation = AddOperation;
  28750. exports.AdditiveAnimationBlendMode = AdditiveAnimationBlendMode;
  28751. exports.AdditiveBlending = AdditiveBlending;
  28752. exports.AlphaFormat = AlphaFormat;
  28753. exports.AlwaysDepth = AlwaysDepth;
  28754. exports.AlwaysStencilFunc = AlwaysStencilFunc;
  28755. exports.AmbientLight = AmbientLight;
  28756. exports.AmbientLightProbe = AmbientLightProbe;
  28757. exports.AnimationClip = AnimationClip;
  28758. exports.AnimationLoader = AnimationLoader;
  28759. exports.AnimationMixer = AnimationMixer;
  28760. exports.AnimationObjectGroup = AnimationObjectGroup;
  28761. exports.AnimationUtils = AnimationUtils;
  28762. exports.ArcCurve = ArcCurve;
  28763. exports.ArrayCamera = ArrayCamera;
  28764. exports.ArrowHelper = ArrowHelper;
  28765. exports.Audio = Audio;
  28766. exports.AudioAnalyser = AudioAnalyser;
  28767. exports.AudioContext = AudioContext;
  28768. exports.AudioListener = AudioListener;
  28769. exports.AudioLoader = AudioLoader;
  28770. exports.AxesHelper = AxesHelper;
  28771. exports.BackSide = BackSide;
  28772. exports.BasicDepthPacking = BasicDepthPacking;
  28773. exports.BasicShadowMap = BasicShadowMap;
  28774. exports.Bone = Bone;
  28775. exports.BooleanKeyframeTrack = BooleanKeyframeTrack;
  28776. exports.Box2 = Box2;
  28777. exports.Box3 = Box3;
  28778. exports.Box3Helper = Box3Helper;
  28779. exports.BoxBufferGeometry = BoxBufferGeometry;
  28780. exports.BoxGeometry = BoxGeometry;
  28781. exports.BoxHelper = BoxHelper;
  28782. exports.BufferAttribute = BufferAttribute;
  28783. exports.BufferGeometry = BufferGeometry;
  28784. exports.BufferGeometryLoader = BufferGeometryLoader;
  28785. exports.ByteType = ByteType;
  28786. exports.Cache = Cache;
  28787. exports.Camera = Camera;
  28788. exports.CameraHelper = CameraHelper;
  28789. exports.CanvasTexture = CanvasTexture;
  28790. exports.CapsuleBufferGeometry = CapsuleBufferGeometry;
  28791. exports.CapsuleGeometry = CapsuleGeometry;
  28792. exports.CatmullRomCurve3 = CatmullRomCurve3;
  28793. exports.CineonToneMapping = CineonToneMapping;
  28794. exports.CircleBufferGeometry = CircleBufferGeometry;
  28795. exports.CircleGeometry = CircleGeometry;
  28796. exports.ClampToEdgeWrapping = ClampToEdgeWrapping;
  28797. exports.Clock = Clock;
  28798. exports.Color = Color;
  28799. exports.ColorKeyframeTrack = ColorKeyframeTrack;
  28800. exports.ColorManagement = ColorManagement;
  28801. exports.CompressedTexture = CompressedTexture;
  28802. exports.CompressedTextureLoader = CompressedTextureLoader;
  28803. exports.ConeBufferGeometry = ConeBufferGeometry;
  28804. exports.ConeGeometry = ConeGeometry;
  28805. exports.CubeCamera = CubeCamera;
  28806. exports.CubeReflectionMapping = CubeReflectionMapping;
  28807. exports.CubeRefractionMapping = CubeRefractionMapping;
  28808. exports.CubeTexture = CubeTexture;
  28809. exports.CubeTextureLoader = CubeTextureLoader;
  28810. exports.CubeUVReflectionMapping = CubeUVReflectionMapping;
  28811. exports.CubicBezierCurve = CubicBezierCurve;
  28812. exports.CubicBezierCurve3 = CubicBezierCurve3;
  28813. exports.CubicInterpolant = CubicInterpolant;
  28814. exports.CullFaceBack = CullFaceBack;
  28815. exports.CullFaceFront = CullFaceFront;
  28816. exports.CullFaceFrontBack = CullFaceFrontBack;
  28817. exports.CullFaceNone = CullFaceNone;
  28818. exports.Curve = Curve;
  28819. exports.CurvePath = CurvePath;
  28820. exports.CustomBlending = CustomBlending;
  28821. exports.CustomToneMapping = CustomToneMapping;
  28822. exports.CylinderBufferGeometry = CylinderBufferGeometry;
  28823. exports.CylinderGeometry = CylinderGeometry;
  28824. exports.Cylindrical = Cylindrical;
  28825. exports.Data3DTexture = Data3DTexture;
  28826. exports.DataArrayTexture = DataArrayTexture;
  28827. exports.DataTexture = DataTexture;
  28828. exports.DataTexture2DArray = DataTexture2DArray;
  28829. exports.DataTexture3D = DataTexture3D;
  28830. exports.DataTextureLoader = DataTextureLoader;
  28831. exports.DataUtils = DataUtils;
  28832. exports.DecrementStencilOp = DecrementStencilOp;
  28833. exports.DecrementWrapStencilOp = DecrementWrapStencilOp;
  28834. exports.DefaultLoadingManager = DefaultLoadingManager;
  28835. exports.DepthFormat = DepthFormat;
  28836. exports.DepthStencilFormat = DepthStencilFormat;
  28837. exports.DepthTexture = DepthTexture;
  28838. exports.DirectionalLight = DirectionalLight;
  28839. exports.DirectionalLightHelper = DirectionalLightHelper;
  28840. exports.DiscreteInterpolant = DiscreteInterpolant;
  28841. exports.DodecahedronBufferGeometry = DodecahedronBufferGeometry;
  28842. exports.DodecahedronGeometry = DodecahedronGeometry;
  28843. exports.DoubleSide = DoubleSide;
  28844. exports.DstAlphaFactor = DstAlphaFactor;
  28845. exports.DstColorFactor = DstColorFactor;
  28846. exports.DynamicCopyUsage = DynamicCopyUsage;
  28847. exports.DynamicDrawUsage = DynamicDrawUsage;
  28848. exports.DynamicReadUsage = DynamicReadUsage;
  28849. exports.EdgesGeometry = EdgesGeometry;
  28850. exports.EllipseCurve = EllipseCurve;
  28851. exports.EqualDepth = EqualDepth;
  28852. exports.EqualStencilFunc = EqualStencilFunc;
  28853. exports.EquirectangularReflectionMapping = EquirectangularReflectionMapping;
  28854. exports.EquirectangularRefractionMapping = EquirectangularRefractionMapping;
  28855. exports.Euler = Euler;
  28856. exports.EventDispatcher = EventDispatcher;
  28857. exports.ExtrudeBufferGeometry = ExtrudeBufferGeometry;
  28858. exports.ExtrudeGeometry = ExtrudeGeometry;
  28859. exports.FileLoader = FileLoader;
  28860. exports.Float16BufferAttribute = Float16BufferAttribute;
  28861. exports.Float32BufferAttribute = Float32BufferAttribute;
  28862. exports.Float64BufferAttribute = Float64BufferAttribute;
  28863. exports.FloatType = FloatType;
  28864. exports.Fog = Fog;
  28865. exports.FogExp2 = FogExp2;
  28866. exports.FramebufferTexture = FramebufferTexture;
  28867. exports.FrontSide = FrontSide;
  28868. exports.Frustum = Frustum;
  28869. exports.GLBufferAttribute = GLBufferAttribute;
  28870. exports.GLSL1 = GLSL1;
  28871. exports.GLSL3 = GLSL3;
  28872. exports.GreaterDepth = GreaterDepth;
  28873. exports.GreaterEqualDepth = GreaterEqualDepth;
  28874. exports.GreaterEqualStencilFunc = GreaterEqualStencilFunc;
  28875. exports.GreaterStencilFunc = GreaterStencilFunc;
  28876. exports.GridHelper = GridHelper;
  28877. exports.Group = Group;
  28878. exports.HalfFloatType = HalfFloatType;
  28879. exports.HemisphereLight = HemisphereLight;
  28880. exports.HemisphereLightHelper = HemisphereLightHelper;
  28881. exports.HemisphereLightProbe = HemisphereLightProbe;
  28882. exports.IcosahedronBufferGeometry = IcosahedronBufferGeometry;
  28883. exports.IcosahedronGeometry = IcosahedronGeometry;
  28884. exports.ImageBitmapLoader = ImageBitmapLoader;
  28885. exports.ImageLoader = ImageLoader;
  28886. exports.ImageUtils = ImageUtils;
  28887. exports.ImmediateRenderObject = ImmediateRenderObject;
  28888. exports.IncrementStencilOp = IncrementStencilOp;
  28889. exports.IncrementWrapStencilOp = IncrementWrapStencilOp;
  28890. exports.InstancedBufferAttribute = InstancedBufferAttribute;
  28891. exports.InstancedBufferGeometry = InstancedBufferGeometry;
  28892. exports.InstancedInterleavedBuffer = InstancedInterleavedBuffer;
  28893. exports.InstancedMesh = InstancedMesh;
  28894. exports.Int16BufferAttribute = Int16BufferAttribute;
  28895. exports.Int32BufferAttribute = Int32BufferAttribute;
  28896. exports.Int8BufferAttribute = Int8BufferAttribute;
  28897. exports.IntType = IntType;
  28898. exports.InterleavedBuffer = InterleavedBuffer;
  28899. exports.InterleavedBufferAttribute = InterleavedBufferAttribute;
  28900. exports.Interpolant = Interpolant;
  28901. exports.InterpolateDiscrete = InterpolateDiscrete;
  28902. exports.InterpolateLinear = InterpolateLinear;
  28903. exports.InterpolateSmooth = InterpolateSmooth;
  28904. exports.InvertStencilOp = InvertStencilOp;
  28905. exports.KeepStencilOp = KeepStencilOp;
  28906. exports.KeyframeTrack = KeyframeTrack;
  28907. exports.LOD = LOD;
  28908. exports.LatheBufferGeometry = LatheBufferGeometry;
  28909. exports.LatheGeometry = LatheGeometry;
  28910. exports.Layers = Layers;
  28911. exports.LessDepth = LessDepth;
  28912. exports.LessEqualDepth = LessEqualDepth;
  28913. exports.LessEqualStencilFunc = LessEqualStencilFunc;
  28914. exports.LessStencilFunc = LessStencilFunc;
  28915. exports.Light = Light;
  28916. exports.LightProbe = LightProbe;
  28917. exports.Line = Line;
  28918. exports.Line3 = Line3;
  28919. exports.LineBasicMaterial = LineBasicMaterial;
  28920. exports.LineCurve = LineCurve;
  28921. exports.LineCurve3 = LineCurve3;
  28922. exports.LineDashedMaterial = LineDashedMaterial;
  28923. exports.LineLoop = LineLoop;
  28924. exports.LineSegments = LineSegments;
  28925. exports.LinearEncoding = LinearEncoding;
  28926. exports.LinearFilter = LinearFilter;
  28927. exports.LinearInterpolant = LinearInterpolant;
  28928. exports.LinearMipMapLinearFilter = LinearMipMapLinearFilter;
  28929. exports.LinearMipMapNearestFilter = LinearMipMapNearestFilter;
  28930. exports.LinearMipmapLinearFilter = LinearMipmapLinearFilter;
  28931. exports.LinearMipmapNearestFilter = LinearMipmapNearestFilter;
  28932. exports.LinearSRGBColorSpace = LinearSRGBColorSpace;
  28933. exports.LinearToneMapping = LinearToneMapping;
  28934. exports.Loader = Loader;
  28935. exports.LoaderUtils = LoaderUtils;
  28936. exports.LoadingManager = LoadingManager;
  28937. exports.LoopOnce = LoopOnce;
  28938. exports.LoopPingPong = LoopPingPong;
  28939. exports.LoopRepeat = LoopRepeat;
  28940. exports.LuminanceAlphaFormat = LuminanceAlphaFormat;
  28941. exports.LuminanceFormat = LuminanceFormat;
  28942. exports.MOUSE = MOUSE;
  28943. exports.Material = Material;
  28944. exports.MaterialLoader = MaterialLoader;
  28945. exports.MathUtils = MathUtils;
  28946. exports.Matrix3 = Matrix3;
  28947. exports.Matrix4 = Matrix4;
  28948. exports.MaxEquation = MaxEquation;
  28949. exports.Mesh = Mesh;
  28950. exports.MeshBasicMaterial = MeshBasicMaterial;
  28951. exports.MeshDepthMaterial = MeshDepthMaterial;
  28952. exports.MeshDistanceMaterial = MeshDistanceMaterial;
  28953. exports.MeshLambertMaterial = MeshLambertMaterial;
  28954. exports.MeshMatcapMaterial = MeshMatcapMaterial;
  28955. exports.MeshNormalMaterial = MeshNormalMaterial;
  28956. exports.MeshPhongMaterial = MeshPhongMaterial;
  28957. exports.MeshPhysicalMaterial = MeshPhysicalMaterial;
  28958. exports.MeshStandardMaterial = MeshStandardMaterial;
  28959. exports.MeshToonMaterial = MeshToonMaterial;
  28960. exports.MinEquation = MinEquation;
  28961. exports.MirroredRepeatWrapping = MirroredRepeatWrapping;
  28962. exports.MixOperation = MixOperation;
  28963. exports.MultiplyBlending = MultiplyBlending;
  28964. exports.MultiplyOperation = MultiplyOperation;
  28965. exports.NearestFilter = NearestFilter;
  28966. exports.NearestMipMapLinearFilter = NearestMipMapLinearFilter;
  28967. exports.NearestMipMapNearestFilter = NearestMipMapNearestFilter;
  28968. exports.NearestMipmapLinearFilter = NearestMipmapLinearFilter;
  28969. exports.NearestMipmapNearestFilter = NearestMipmapNearestFilter;
  28970. exports.NeverDepth = NeverDepth;
  28971. exports.NeverStencilFunc = NeverStencilFunc;
  28972. exports.NoBlending = NoBlending;
  28973. exports.NoColorSpace = NoColorSpace;
  28974. exports.NoToneMapping = NoToneMapping;
  28975. exports.NormalAnimationBlendMode = NormalAnimationBlendMode;
  28976. exports.NormalBlending = NormalBlending;
  28977. exports.NotEqualDepth = NotEqualDepth;
  28978. exports.NotEqualStencilFunc = NotEqualStencilFunc;
  28979. exports.NumberKeyframeTrack = NumberKeyframeTrack;
  28980. exports.Object3D = Object3D;
  28981. exports.ObjectLoader = ObjectLoader;
  28982. exports.ObjectSpaceNormalMap = ObjectSpaceNormalMap;
  28983. exports.OctahedronBufferGeometry = OctahedronBufferGeometry;
  28984. exports.OctahedronGeometry = OctahedronGeometry;
  28985. exports.OneFactor = OneFactor;
  28986. exports.OneMinusDstAlphaFactor = OneMinusDstAlphaFactor;
  28987. exports.OneMinusDstColorFactor = OneMinusDstColorFactor;
  28988. exports.OneMinusSrcAlphaFactor = OneMinusSrcAlphaFactor;
  28989. exports.OneMinusSrcColorFactor = OneMinusSrcColorFactor;
  28990. exports.OrthographicCamera = OrthographicCamera;
  28991. exports.PCFShadowMap = PCFShadowMap;
  28992. exports.PCFSoftShadowMap = PCFSoftShadowMap;
  28993. exports.PMREMGenerator = PMREMGenerator;
  28994. exports.Path = Path;
  28995. exports.PerspectiveCamera = PerspectiveCamera;
  28996. exports.Plane = Plane;
  28997. exports.PlaneBufferGeometry = PlaneBufferGeometry;
  28998. exports.PlaneGeometry = PlaneGeometry;
  28999. exports.PlaneHelper = PlaneHelper;
  29000. exports.PointLight = PointLight;
  29001. exports.PointLightHelper = PointLightHelper;
  29002. exports.Points = Points;
  29003. exports.PointsMaterial = PointsMaterial;
  29004. exports.PolarGridHelper = PolarGridHelper;
  29005. exports.PolyhedronBufferGeometry = PolyhedronBufferGeometry;
  29006. exports.PolyhedronGeometry = PolyhedronGeometry;
  29007. exports.PositionalAudio = PositionalAudio;
  29008. exports.PropertyBinding = PropertyBinding;
  29009. exports.PropertyMixer = PropertyMixer;
  29010. exports.QuadraticBezierCurve = QuadraticBezierCurve;
  29011. exports.QuadraticBezierCurve3 = QuadraticBezierCurve3;
  29012. exports.Quaternion = Quaternion;
  29013. exports.QuaternionKeyframeTrack = QuaternionKeyframeTrack;
  29014. exports.QuaternionLinearInterpolant = QuaternionLinearInterpolant;
  29015. exports.REVISION = REVISION;
  29016. exports.RGBADepthPacking = RGBADepthPacking;
  29017. exports.RGBAFormat = RGBAFormat;
  29018. exports.RGBAIntegerFormat = RGBAIntegerFormat;
  29019. exports.RGBA_ASTC_10x10_Format = RGBA_ASTC_10x10_Format;
  29020. exports.RGBA_ASTC_10x5_Format = RGBA_ASTC_10x5_Format;
  29021. exports.RGBA_ASTC_10x6_Format = RGBA_ASTC_10x6_Format;
  29022. exports.RGBA_ASTC_10x8_Format = RGBA_ASTC_10x8_Format;
  29023. exports.RGBA_ASTC_12x10_Format = RGBA_ASTC_12x10_Format;
  29024. exports.RGBA_ASTC_12x12_Format = RGBA_ASTC_12x12_Format;
  29025. exports.RGBA_ASTC_4x4_Format = RGBA_ASTC_4x4_Format;
  29026. exports.RGBA_ASTC_5x4_Format = RGBA_ASTC_5x4_Format;
  29027. exports.RGBA_ASTC_5x5_Format = RGBA_ASTC_5x5_Format;
  29028. exports.RGBA_ASTC_6x5_Format = RGBA_ASTC_6x5_Format;
  29029. exports.RGBA_ASTC_6x6_Format = RGBA_ASTC_6x6_Format;
  29030. exports.RGBA_ASTC_8x5_Format = RGBA_ASTC_8x5_Format;
  29031. exports.RGBA_ASTC_8x6_Format = RGBA_ASTC_8x6_Format;
  29032. exports.RGBA_ASTC_8x8_Format = RGBA_ASTC_8x8_Format;
  29033. exports.RGBA_BPTC_Format = RGBA_BPTC_Format;
  29034. exports.RGBA_ETC2_EAC_Format = RGBA_ETC2_EAC_Format;
  29035. exports.RGBA_PVRTC_2BPPV1_Format = RGBA_PVRTC_2BPPV1_Format;
  29036. exports.RGBA_PVRTC_4BPPV1_Format = RGBA_PVRTC_4BPPV1_Format;
  29037. exports.RGBA_S3TC_DXT1_Format = RGBA_S3TC_DXT1_Format;
  29038. exports.RGBA_S3TC_DXT3_Format = RGBA_S3TC_DXT3_Format;
  29039. exports.RGBA_S3TC_DXT5_Format = RGBA_S3TC_DXT5_Format;
  29040. exports.RGBFormat = RGBFormat;
  29041. exports.RGB_ETC1_Format = RGB_ETC1_Format;
  29042. exports.RGB_ETC2_Format = RGB_ETC2_Format;
  29043. exports.RGB_PVRTC_2BPPV1_Format = RGB_PVRTC_2BPPV1_Format;
  29044. exports.RGB_PVRTC_4BPPV1_Format = RGB_PVRTC_4BPPV1_Format;
  29045. exports.RGB_S3TC_DXT1_Format = RGB_S3TC_DXT1_Format;
  29046. exports.RGFormat = RGFormat;
  29047. exports.RGIntegerFormat = RGIntegerFormat;
  29048. exports.RawShaderMaterial = RawShaderMaterial;
  29049. exports.Ray = Ray;
  29050. exports.Raycaster = Raycaster;
  29051. exports.RectAreaLight = RectAreaLight;
  29052. exports.RedFormat = RedFormat;
  29053. exports.RedIntegerFormat = RedIntegerFormat;
  29054. exports.ReinhardToneMapping = ReinhardToneMapping;
  29055. exports.RepeatWrapping = RepeatWrapping;
  29056. exports.ReplaceStencilOp = ReplaceStencilOp;
  29057. exports.ReverseSubtractEquation = ReverseSubtractEquation;
  29058. exports.RingBufferGeometry = RingBufferGeometry;
  29059. exports.RingGeometry = RingGeometry;
  29060. exports.SRGBColorSpace = SRGBColorSpace;
  29061. exports.Scene = Scene;
  29062. exports.ShaderChunk = ShaderChunk;
  29063. exports.ShaderLib = ShaderLib;
  29064. exports.ShaderMaterial = ShaderMaterial;
  29065. exports.ShadowMaterial = ShadowMaterial;
  29066. exports.Shape = Shape;
  29067. exports.ShapeBufferGeometry = ShapeBufferGeometry;
  29068. exports.ShapeGeometry = ShapeGeometry;
  29069. exports.ShapePath = ShapePath;
  29070. exports.ShapeUtils = ShapeUtils;
  29071. exports.ShortType = ShortType;
  29072. exports.Skeleton = Skeleton;
  29073. exports.SkeletonHelper = SkeletonHelper;
  29074. exports.SkinnedMesh = SkinnedMesh;
  29075. exports.Source = Source;
  29076. exports.Sphere = Sphere;
  29077. exports.SphereBufferGeometry = SphereBufferGeometry;
  29078. exports.SphereGeometry = SphereGeometry;
  29079. exports.Spherical = Spherical;
  29080. exports.SphericalHarmonics3 = SphericalHarmonics3;
  29081. exports.SplineCurve = SplineCurve;
  29082. exports.SpotLight = SpotLight;
  29083. exports.SpotLightHelper = SpotLightHelper;
  29084. exports.Sprite = Sprite;
  29085. exports.SpriteMaterial = SpriteMaterial;
  29086. exports.SrcAlphaFactor = SrcAlphaFactor;
  29087. exports.SrcAlphaSaturateFactor = SrcAlphaSaturateFactor;
  29088. exports.SrcColorFactor = SrcColorFactor;
  29089. exports.StaticCopyUsage = StaticCopyUsage;
  29090. exports.StaticDrawUsage = StaticDrawUsage;
  29091. exports.StaticReadUsage = StaticReadUsage;
  29092. exports.StereoCamera = StereoCamera;
  29093. exports.StreamCopyUsage = StreamCopyUsage;
  29094. exports.StreamDrawUsage = StreamDrawUsage;
  29095. exports.StreamReadUsage = StreamReadUsage;
  29096. exports.StringKeyframeTrack = StringKeyframeTrack;
  29097. exports.SubtractEquation = SubtractEquation;
  29098. exports.SubtractiveBlending = SubtractiveBlending;
  29099. exports.TOUCH = TOUCH;
  29100. exports.TangentSpaceNormalMap = TangentSpaceNormalMap;
  29101. exports.TetrahedronBufferGeometry = TetrahedronBufferGeometry;
  29102. exports.TetrahedronGeometry = TetrahedronGeometry;
  29103. exports.Texture = Texture;
  29104. exports.TextureLoader = TextureLoader;
  29105. exports.TorusBufferGeometry = TorusBufferGeometry;
  29106. exports.TorusGeometry = TorusGeometry;
  29107. exports.TorusKnotBufferGeometry = TorusKnotBufferGeometry;
  29108. exports.TorusKnotGeometry = TorusKnotGeometry;
  29109. exports.Triangle = Triangle;
  29110. exports.TriangleFanDrawMode = TriangleFanDrawMode;
  29111. exports.TriangleStripDrawMode = TriangleStripDrawMode;
  29112. exports.TrianglesDrawMode = TrianglesDrawMode;
  29113. exports.TubeBufferGeometry = TubeBufferGeometry;
  29114. exports.TubeGeometry = TubeGeometry;
  29115. exports.UVMapping = UVMapping;
  29116. exports.Uint16BufferAttribute = Uint16BufferAttribute;
  29117. exports.Uint32BufferAttribute = Uint32BufferAttribute;
  29118. exports.Uint8BufferAttribute = Uint8BufferAttribute;
  29119. exports.Uint8ClampedBufferAttribute = Uint8ClampedBufferAttribute;
  29120. exports.Uniform = Uniform;
  29121. exports.UniformsGroup = UniformsGroup;
  29122. exports.UniformsLib = UniformsLib;
  29123. exports.UniformsUtils = UniformsUtils;
  29124. exports.UnsignedByteType = UnsignedByteType;
  29125. exports.UnsignedInt248Type = UnsignedInt248Type;
  29126. exports.UnsignedIntType = UnsignedIntType;
  29127. exports.UnsignedShort4444Type = UnsignedShort4444Type;
  29128. exports.UnsignedShort5551Type = UnsignedShort5551Type;
  29129. exports.UnsignedShortType = UnsignedShortType;
  29130. exports.VSMShadowMap = VSMShadowMap;
  29131. exports.Vector2 = Vector2;
  29132. exports.Vector3 = Vector3;
  29133. exports.Vector4 = Vector4;
  29134. exports.VectorKeyframeTrack = VectorKeyframeTrack;
  29135. exports.VideoTexture = VideoTexture;
  29136. exports.WebGL1Renderer = WebGL1Renderer;
  29137. exports.WebGL3DRenderTarget = WebGL3DRenderTarget;
  29138. exports.WebGLArrayRenderTarget = WebGLArrayRenderTarget;
  29139. exports.WebGLCubeRenderTarget = WebGLCubeRenderTarget;
  29140. exports.WebGLMultipleRenderTargets = WebGLMultipleRenderTargets;
  29141. exports.WebGLMultisampleRenderTarget = WebGLMultisampleRenderTarget;
  29142. exports.WebGLRenderTarget = WebGLRenderTarget;
  29143. exports.WebGLRenderer = WebGLRenderer;
  29144. exports.WebGLUtils = WebGLUtils;
  29145. exports.WireframeGeometry = WireframeGeometry;
  29146. exports.WrapAroundEnding = WrapAroundEnding;
  29147. exports.ZeroCurvatureEnding = ZeroCurvatureEnding;
  29148. exports.ZeroFactor = ZeroFactor;
  29149. exports.ZeroSlopeEnding = ZeroSlopeEnding;
  29150. exports.ZeroStencilOp = ZeroStencilOp;
  29151. exports._SRGBAFormat = _SRGBAFormat;
  29152. exports.sRGBEncoding = sRGBEncoding;