three.cjs 1.1 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704
  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 = '148dev';
  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;
  161. // Color space string identifiers, matching CSS Color Module Level 4 and WebGPU names where available.
  162. const NoColorSpace = '';
  163. const SRGBColorSpace = 'srgb';
  164. const LinearSRGBColorSpace = 'srgb-linear';
  165. const ZeroStencilOp = 0;
  166. const KeepStencilOp = 7680;
  167. const ReplaceStencilOp = 7681;
  168. const IncrementStencilOp = 7682;
  169. const DecrementStencilOp = 7683;
  170. const IncrementWrapStencilOp = 34055;
  171. const DecrementWrapStencilOp = 34056;
  172. const InvertStencilOp = 5386;
  173. const NeverStencilFunc = 512;
  174. const LessStencilFunc = 513;
  175. const EqualStencilFunc = 514;
  176. const LessEqualStencilFunc = 515;
  177. const GreaterStencilFunc = 516;
  178. const NotEqualStencilFunc = 517;
  179. const GreaterEqualStencilFunc = 518;
  180. const AlwaysStencilFunc = 519;
  181. const StaticDrawUsage = 35044;
  182. const DynamicDrawUsage = 35048;
  183. const StreamDrawUsage = 35040;
  184. const StaticReadUsage = 35045;
  185. const DynamicReadUsage = 35049;
  186. const StreamReadUsage = 35041;
  187. const StaticCopyUsage = 35046;
  188. const DynamicCopyUsage = 35050;
  189. const StreamCopyUsage = 35042;
  190. const GLSL1 = '100';
  191. const GLSL3 = '300 es';
  192. const _SRGBAFormat = 1035; // fallback for WebGL 1
  193. /**
  194. * https://github.com/mrdoob/eventdispatcher.js/
  195. */
  196. class EventDispatcher {
  197. addEventListener(type, listener) {
  198. if (this._listeners === undefined) this._listeners = {};
  199. const listeners = this._listeners;
  200. if (listeners[type] === undefined) {
  201. listeners[type] = [];
  202. }
  203. if (listeners[type].indexOf(listener) === -1) {
  204. listeners[type].push(listener);
  205. }
  206. }
  207. hasEventListener(type, listener) {
  208. if (this._listeners === undefined) return false;
  209. const listeners = this._listeners;
  210. return listeners[type] !== undefined && listeners[type].indexOf(listener) !== -1;
  211. }
  212. removeEventListener(type, listener) {
  213. if (this._listeners === undefined) return;
  214. const listeners = this._listeners;
  215. const listenerArray = listeners[type];
  216. if (listenerArray !== undefined) {
  217. const index = listenerArray.indexOf(listener);
  218. if (index !== -1) {
  219. listenerArray.splice(index, 1);
  220. }
  221. }
  222. }
  223. dispatchEvent(event) {
  224. if (this._listeners === undefined) return;
  225. const listeners = this._listeners;
  226. const listenerArray = listeners[event.type];
  227. if (listenerArray !== undefined) {
  228. event.target = this;
  229. // Make a copy, in case listeners are removed while iterating.
  230. const array = listenerArray.slice(0);
  231. for (let i = 0, l = array.length; i < l; i++) {
  232. array[i].call(this, event);
  233. }
  234. event.target = null;
  235. }
  236. }
  237. }
  238. 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'];
  239. let _seed = 1234567;
  240. const DEG2RAD = Math.PI / 180;
  241. const RAD2DEG = 180 / Math.PI;
  242. // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/21963136#21963136
  243. function generateUUID() {
  244. const d0 = Math.random() * 0xffffffff | 0;
  245. const d1 = Math.random() * 0xffffffff | 0;
  246. const d2 = Math.random() * 0xffffffff | 0;
  247. const d3 = Math.random() * 0xffffffff | 0;
  248. 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];
  249. // .toLowerCase() here flattens concatenated strings to save heap memory space.
  250. return uuid.toLowerCase();
  251. }
  252. function clamp(value, min, max) {
  253. return Math.max(min, Math.min(max, value));
  254. }
  255. // compute euclidean modulo of m % n
  256. // https://en.wikipedia.org/wiki/Modulo_operation
  257. function euclideanModulo(n, m) {
  258. return (n % m + m) % m;
  259. }
  260. // Linear mapping from range <a1, a2> to range <b1, b2>
  261. function mapLinear(x, a1, a2, b1, b2) {
  262. return b1 + (x - a1) * (b2 - b1) / (a2 - a1);
  263. }
  264. // https://www.gamedev.net/tutorials/programming/general-and-gameplay-programming/inverse-lerp-a-super-useful-yet-often-overlooked-function-r5230/
  265. function inverseLerp(x, y, value) {
  266. if (x !== y) {
  267. return (value - x) / (y - x);
  268. } else {
  269. return 0;
  270. }
  271. }
  272. // https://en.wikipedia.org/wiki/Linear_interpolation
  273. function lerp(x, y, t) {
  274. return (1 - t) * x + t * y;
  275. }
  276. // http://www.rorydriscoll.com/2016/03/07/frame-rate-independent-damping-using-lerp/
  277. function damp(x, y, lambda, dt) {
  278. return lerp(x, y, 1 - Math.exp(-lambda * dt));
  279. }
  280. // https://www.desmos.com/calculator/vcsjnyz7x4
  281. function pingpong(x, length = 1) {
  282. return length - Math.abs(euclideanModulo(x, length * 2) - length);
  283. }
  284. // http://en.wikipedia.org/wiki/Smoothstep
  285. function smoothstep(x, min, max) {
  286. if (x <= min) return 0;
  287. if (x >= max) return 1;
  288. x = (x - min) / (max - min);
  289. return x * x * (3 - 2 * x);
  290. }
  291. function smootherstep(x, min, max) {
  292. if (x <= min) return 0;
  293. if (x >= max) return 1;
  294. x = (x - min) / (max - min);
  295. return x * x * x * (x * (x * 6 - 15) + 10);
  296. }
  297. // Random integer from <low, high> interval
  298. function randInt(low, high) {
  299. return low + Math.floor(Math.random() * (high - low + 1));
  300. }
  301. // Random float from <low, high> interval
  302. function randFloat(low, high) {
  303. return low + Math.random() * (high - low);
  304. }
  305. // Random float from <-range/2, range/2> interval
  306. function randFloatSpread(range) {
  307. return range * (0.5 - Math.random());
  308. }
  309. // Deterministic pseudo-random float in the interval [ 0, 1 ]
  310. function seededRandom(s) {
  311. if (s !== undefined) _seed = s;
  312. // Mulberry32 generator
  313. let t = _seed += 0x6D2B79F5;
  314. t = Math.imul(t ^ t >>> 15, t | 1);
  315. t ^= t + Math.imul(t ^ t >>> 7, t | 61);
  316. return ((t ^ t >>> 14) >>> 0) / 4294967296;
  317. }
  318. function degToRad(degrees) {
  319. return degrees * DEG2RAD;
  320. }
  321. function radToDeg(radians) {
  322. return radians * RAD2DEG;
  323. }
  324. function isPowerOfTwo(value) {
  325. return (value & value - 1) === 0 && value !== 0;
  326. }
  327. function ceilPowerOfTwo(value) {
  328. return Math.pow(2, Math.ceil(Math.log(value) / Math.LN2));
  329. }
  330. function floorPowerOfTwo(value) {
  331. return Math.pow(2, Math.floor(Math.log(value) / Math.LN2));
  332. }
  333. function setQuaternionFromProperEuler(q, a, b, c, order) {
  334. // Intrinsic Proper Euler Angles - see https://en.wikipedia.org/wiki/Euler_angles
  335. // rotations are applied to the axes in the order specified by 'order'
  336. // rotation by angle 'a' is applied first, then by angle 'b', then by angle 'c'
  337. // angles are in radians
  338. const cos = Math.cos;
  339. const sin = Math.sin;
  340. const c2 = cos(b / 2);
  341. const s2 = sin(b / 2);
  342. const c13 = cos((a + c) / 2);
  343. const s13 = sin((a + c) / 2);
  344. const c1_3 = cos((a - c) / 2);
  345. const s1_3 = sin((a - c) / 2);
  346. const c3_1 = cos((c - a) / 2);
  347. const s3_1 = sin((c - a) / 2);
  348. switch (order) {
  349. case 'XYX':
  350. q.set(c2 * s13, s2 * c1_3, s2 * s1_3, c2 * c13);
  351. break;
  352. case 'YZY':
  353. q.set(s2 * s1_3, c2 * s13, s2 * c1_3, c2 * c13);
  354. break;
  355. case 'ZXZ':
  356. q.set(s2 * c1_3, s2 * s1_3, c2 * s13, c2 * c13);
  357. break;
  358. case 'XZX':
  359. q.set(c2 * s13, s2 * s3_1, s2 * c3_1, c2 * c13);
  360. break;
  361. case 'YXY':
  362. q.set(s2 * c3_1, c2 * s13, s2 * s3_1, c2 * c13);
  363. break;
  364. case 'ZYZ':
  365. q.set(s2 * s3_1, s2 * c3_1, c2 * s13, c2 * c13);
  366. break;
  367. default:
  368. console.warn('THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: ' + order);
  369. }
  370. }
  371. function denormalize(value, array) {
  372. switch (array.constructor) {
  373. case Float32Array:
  374. return value;
  375. case Uint16Array:
  376. return value / 65535.0;
  377. case Uint8Array:
  378. return value / 255.0;
  379. case Int16Array:
  380. return Math.max(value / 32767.0, -1.0);
  381. case Int8Array:
  382. return Math.max(value / 127.0, -1.0);
  383. default:
  384. throw new Error('Invalid component type.');
  385. }
  386. }
  387. function normalize(value, array) {
  388. switch (array.constructor) {
  389. case Float32Array:
  390. return value;
  391. case Uint16Array:
  392. return Math.round(value * 65535.0);
  393. case Uint8Array:
  394. return Math.round(value * 255.0);
  395. case Int16Array:
  396. return Math.round(value * 32767.0);
  397. case Int8Array:
  398. return Math.round(value * 127.0);
  399. default:
  400. throw new Error('Invalid component type.');
  401. }
  402. }
  403. var MathUtils = /*#__PURE__*/Object.freeze({
  404. __proto__: null,
  405. DEG2RAD: DEG2RAD,
  406. RAD2DEG: RAD2DEG,
  407. generateUUID: generateUUID,
  408. clamp: clamp,
  409. euclideanModulo: euclideanModulo,
  410. mapLinear: mapLinear,
  411. inverseLerp: inverseLerp,
  412. lerp: lerp,
  413. damp: damp,
  414. pingpong: pingpong,
  415. smoothstep: smoothstep,
  416. smootherstep: smootherstep,
  417. randInt: randInt,
  418. randFloat: randFloat,
  419. randFloatSpread: randFloatSpread,
  420. seededRandom: seededRandom,
  421. degToRad: degToRad,
  422. radToDeg: radToDeg,
  423. isPowerOfTwo: isPowerOfTwo,
  424. ceilPowerOfTwo: ceilPowerOfTwo,
  425. floorPowerOfTwo: floorPowerOfTwo,
  426. setQuaternionFromProperEuler: setQuaternionFromProperEuler,
  427. normalize: normalize,
  428. denormalize: denormalize
  429. });
  430. class Vector2 {
  431. constructor(x = 0, y = 0) {
  432. Vector2.prototype.isVector2 = true;
  433. this.x = x;
  434. this.y = y;
  435. }
  436. get width() {
  437. return this.x;
  438. }
  439. set width(value) {
  440. this.x = value;
  441. }
  442. get height() {
  443. return this.y;
  444. }
  445. set height(value) {
  446. this.y = value;
  447. }
  448. set(x, y) {
  449. this.x = x;
  450. this.y = y;
  451. return this;
  452. }
  453. setScalar(scalar) {
  454. this.x = scalar;
  455. this.y = scalar;
  456. return this;
  457. }
  458. setX(x) {
  459. this.x = x;
  460. return this;
  461. }
  462. setY(y) {
  463. this.y = y;
  464. return this;
  465. }
  466. setComponent(index, value) {
  467. switch (index) {
  468. case 0:
  469. this.x = value;
  470. break;
  471. case 1:
  472. this.y = value;
  473. break;
  474. default:
  475. throw new Error('index is out of range: ' + index);
  476. }
  477. return this;
  478. }
  479. getComponent(index) {
  480. switch (index) {
  481. case 0:
  482. return this.x;
  483. case 1:
  484. return this.y;
  485. default:
  486. throw new Error('index is out of range: ' + index);
  487. }
  488. }
  489. clone() {
  490. return new this.constructor(this.x, this.y);
  491. }
  492. copy(v) {
  493. this.x = v.x;
  494. this.y = v.y;
  495. return this;
  496. }
  497. add(v) {
  498. this.x += v.x;
  499. this.y += v.y;
  500. return this;
  501. }
  502. addScalar(s) {
  503. this.x += s;
  504. this.y += s;
  505. return this;
  506. }
  507. addVectors(a, b) {
  508. this.x = a.x + b.x;
  509. this.y = a.y + b.y;
  510. return this;
  511. }
  512. addScaledVector(v, s) {
  513. this.x += v.x * s;
  514. this.y += v.y * s;
  515. return this;
  516. }
  517. sub(v) {
  518. this.x -= v.x;
  519. this.y -= v.y;
  520. return this;
  521. }
  522. subScalar(s) {
  523. this.x -= s;
  524. this.y -= s;
  525. return this;
  526. }
  527. subVectors(a, b) {
  528. this.x = a.x - b.x;
  529. this.y = a.y - b.y;
  530. return this;
  531. }
  532. multiply(v) {
  533. this.x *= v.x;
  534. this.y *= v.y;
  535. return this;
  536. }
  537. multiplyScalar(scalar) {
  538. this.x *= scalar;
  539. this.y *= scalar;
  540. return this;
  541. }
  542. divide(v) {
  543. this.x /= v.x;
  544. this.y /= v.y;
  545. return this;
  546. }
  547. divideScalar(scalar) {
  548. return this.multiplyScalar(1 / scalar);
  549. }
  550. applyMatrix3(m) {
  551. const x = this.x,
  552. y = this.y;
  553. const e = m.elements;
  554. this.x = e[0] * x + e[3] * y + e[6];
  555. this.y = e[1] * x + e[4] * y + e[7];
  556. return this;
  557. }
  558. min(v) {
  559. this.x = Math.min(this.x, v.x);
  560. this.y = Math.min(this.y, v.y);
  561. return this;
  562. }
  563. max(v) {
  564. this.x = Math.max(this.x, v.x);
  565. this.y = Math.max(this.y, v.y);
  566. return this;
  567. }
  568. clamp(min, max) {
  569. // assumes min < max, componentwise
  570. this.x = Math.max(min.x, Math.min(max.x, this.x));
  571. this.y = Math.max(min.y, Math.min(max.y, this.y));
  572. return this;
  573. }
  574. clampScalar(minVal, maxVal) {
  575. this.x = Math.max(minVal, Math.min(maxVal, this.x));
  576. this.y = Math.max(minVal, Math.min(maxVal, this.y));
  577. return this;
  578. }
  579. clampLength(min, max) {
  580. const length = this.length();
  581. return this.divideScalar(length || 1).multiplyScalar(Math.max(min, Math.min(max, length)));
  582. }
  583. floor() {
  584. this.x = Math.floor(this.x);
  585. this.y = Math.floor(this.y);
  586. return this;
  587. }
  588. ceil() {
  589. this.x = Math.ceil(this.x);
  590. this.y = Math.ceil(this.y);
  591. return this;
  592. }
  593. round() {
  594. this.x = Math.round(this.x);
  595. this.y = Math.round(this.y);
  596. return this;
  597. }
  598. roundToZero() {
  599. this.x = this.x < 0 ? Math.ceil(this.x) : Math.floor(this.x);
  600. this.y = this.y < 0 ? Math.ceil(this.y) : Math.floor(this.y);
  601. return this;
  602. }
  603. negate() {
  604. this.x = -this.x;
  605. this.y = -this.y;
  606. return this;
  607. }
  608. dot(v) {
  609. return this.x * v.x + this.y * v.y;
  610. }
  611. cross(v) {
  612. return this.x * v.y - this.y * v.x;
  613. }
  614. lengthSq() {
  615. return this.x * this.x + this.y * this.y;
  616. }
  617. length() {
  618. return Math.sqrt(this.x * this.x + this.y * this.y);
  619. }
  620. manhattanLength() {
  621. return Math.abs(this.x) + Math.abs(this.y);
  622. }
  623. normalize() {
  624. return this.divideScalar(this.length() || 1);
  625. }
  626. angle() {
  627. // computes the angle in radians with respect to the positive x-axis
  628. const angle = Math.atan2(-this.y, -this.x) + Math.PI;
  629. return angle;
  630. }
  631. distanceTo(v) {
  632. return Math.sqrt(this.distanceToSquared(v));
  633. }
  634. distanceToSquared(v) {
  635. const dx = this.x - v.x,
  636. dy = this.y - v.y;
  637. return dx * dx + dy * dy;
  638. }
  639. manhattanDistanceTo(v) {
  640. return Math.abs(this.x - v.x) + Math.abs(this.y - v.y);
  641. }
  642. setLength(length) {
  643. return this.normalize().multiplyScalar(length);
  644. }
  645. lerp(v, alpha) {
  646. this.x += (v.x - this.x) * alpha;
  647. this.y += (v.y - this.y) * alpha;
  648. return this;
  649. }
  650. lerpVectors(v1, v2, alpha) {
  651. this.x = v1.x + (v2.x - v1.x) * alpha;
  652. this.y = v1.y + (v2.y - v1.y) * alpha;
  653. return this;
  654. }
  655. equals(v) {
  656. return v.x === this.x && v.y === this.y;
  657. }
  658. fromArray(array, offset = 0) {
  659. this.x = array[offset];
  660. this.y = array[offset + 1];
  661. return this;
  662. }
  663. toArray(array = [], offset = 0) {
  664. array[offset] = this.x;
  665. array[offset + 1] = this.y;
  666. return array;
  667. }
  668. fromBufferAttribute(attribute, index) {
  669. this.x = attribute.getX(index);
  670. this.y = attribute.getY(index);
  671. return this;
  672. }
  673. rotateAround(center, angle) {
  674. const c = Math.cos(angle),
  675. s = Math.sin(angle);
  676. const x = this.x - center.x;
  677. const y = this.y - center.y;
  678. this.x = x * c - y * s + center.x;
  679. this.y = x * s + y * c + center.y;
  680. return this;
  681. }
  682. random() {
  683. this.x = Math.random();
  684. this.y = Math.random();
  685. return this;
  686. }
  687. *[Symbol.iterator]() {
  688. yield this.x;
  689. yield this.y;
  690. }
  691. }
  692. class Matrix3 {
  693. constructor() {
  694. Matrix3.prototype.isMatrix3 = true;
  695. this.elements = [1, 0, 0, 0, 1, 0, 0, 0, 1];
  696. }
  697. set(n11, n12, n13, n21, n22, n23, n31, n32, n33) {
  698. const te = this.elements;
  699. te[0] = n11;
  700. te[1] = n21;
  701. te[2] = n31;
  702. te[3] = n12;
  703. te[4] = n22;
  704. te[5] = n32;
  705. te[6] = n13;
  706. te[7] = n23;
  707. te[8] = n33;
  708. return this;
  709. }
  710. identity() {
  711. this.set(1, 0, 0, 0, 1, 0, 0, 0, 1);
  712. return this;
  713. }
  714. copy(m) {
  715. const te = this.elements;
  716. const me = m.elements;
  717. te[0] = me[0];
  718. te[1] = me[1];
  719. te[2] = me[2];
  720. te[3] = me[3];
  721. te[4] = me[4];
  722. te[5] = me[5];
  723. te[6] = me[6];
  724. te[7] = me[7];
  725. te[8] = me[8];
  726. return this;
  727. }
  728. extractBasis(xAxis, yAxis, zAxis) {
  729. xAxis.setFromMatrix3Column(this, 0);
  730. yAxis.setFromMatrix3Column(this, 1);
  731. zAxis.setFromMatrix3Column(this, 2);
  732. return this;
  733. }
  734. setFromMatrix4(m) {
  735. const me = m.elements;
  736. this.set(me[0], me[4], me[8], me[1], me[5], me[9], me[2], me[6], me[10]);
  737. return this;
  738. }
  739. multiply(m) {
  740. return this.multiplyMatrices(this, m);
  741. }
  742. premultiply(m) {
  743. return this.multiplyMatrices(m, this);
  744. }
  745. multiplyMatrices(a, b) {
  746. const ae = a.elements;
  747. const be = b.elements;
  748. const te = this.elements;
  749. const a11 = ae[0],
  750. a12 = ae[3],
  751. a13 = ae[6];
  752. const a21 = ae[1],
  753. a22 = ae[4],
  754. a23 = ae[7];
  755. const a31 = ae[2],
  756. a32 = ae[5],
  757. a33 = ae[8];
  758. const b11 = be[0],
  759. b12 = be[3],
  760. b13 = be[6];
  761. const b21 = be[1],
  762. b22 = be[4],
  763. b23 = be[7];
  764. const b31 = be[2],
  765. b32 = be[5],
  766. b33 = be[8];
  767. te[0] = a11 * b11 + a12 * b21 + a13 * b31;
  768. te[3] = a11 * b12 + a12 * b22 + a13 * b32;
  769. te[6] = a11 * b13 + a12 * b23 + a13 * b33;
  770. te[1] = a21 * b11 + a22 * b21 + a23 * b31;
  771. te[4] = a21 * b12 + a22 * b22 + a23 * b32;
  772. te[7] = a21 * b13 + a22 * b23 + a23 * b33;
  773. te[2] = a31 * b11 + a32 * b21 + a33 * b31;
  774. te[5] = a31 * b12 + a32 * b22 + a33 * b32;
  775. te[8] = a31 * b13 + a32 * b23 + a33 * b33;
  776. return this;
  777. }
  778. multiplyScalar(s) {
  779. const te = this.elements;
  780. te[0] *= s;
  781. te[3] *= s;
  782. te[6] *= s;
  783. te[1] *= s;
  784. te[4] *= s;
  785. te[7] *= s;
  786. te[2] *= s;
  787. te[5] *= s;
  788. te[8] *= s;
  789. return this;
  790. }
  791. determinant() {
  792. const te = this.elements;
  793. const a = te[0],
  794. b = te[1],
  795. c = te[2],
  796. d = te[3],
  797. e = te[4],
  798. f = te[5],
  799. g = te[6],
  800. h = te[7],
  801. i = te[8];
  802. return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g;
  803. }
  804. invert() {
  805. const te = this.elements,
  806. n11 = te[0],
  807. n21 = te[1],
  808. n31 = te[2],
  809. n12 = te[3],
  810. n22 = te[4],
  811. n32 = te[5],
  812. n13 = te[6],
  813. n23 = te[7],
  814. n33 = te[8],
  815. t11 = n33 * n22 - n32 * n23,
  816. t12 = n32 * n13 - n33 * n12,
  817. t13 = n23 * n12 - n22 * n13,
  818. det = n11 * t11 + n21 * t12 + n31 * t13;
  819. if (det === 0) return this.set(0, 0, 0, 0, 0, 0, 0, 0, 0);
  820. const detInv = 1 / det;
  821. te[0] = t11 * detInv;
  822. te[1] = (n31 * n23 - n33 * n21) * detInv;
  823. te[2] = (n32 * n21 - n31 * n22) * detInv;
  824. te[3] = t12 * detInv;
  825. te[4] = (n33 * n11 - n31 * n13) * detInv;
  826. te[5] = (n31 * n12 - n32 * n11) * detInv;
  827. te[6] = t13 * detInv;
  828. te[7] = (n21 * n13 - n23 * n11) * detInv;
  829. te[8] = (n22 * n11 - n21 * n12) * detInv;
  830. return this;
  831. }
  832. transpose() {
  833. let tmp;
  834. const m = this.elements;
  835. tmp = m[1];
  836. m[1] = m[3];
  837. m[3] = tmp;
  838. tmp = m[2];
  839. m[2] = m[6];
  840. m[6] = tmp;
  841. tmp = m[5];
  842. m[5] = m[7];
  843. m[7] = tmp;
  844. return this;
  845. }
  846. getNormalMatrix(matrix4) {
  847. return this.setFromMatrix4(matrix4).invert().transpose();
  848. }
  849. transposeIntoArray(r) {
  850. const m = this.elements;
  851. r[0] = m[0];
  852. r[1] = m[3];
  853. r[2] = m[6];
  854. r[3] = m[1];
  855. r[4] = m[4];
  856. r[5] = m[7];
  857. r[6] = m[2];
  858. r[7] = m[5];
  859. r[8] = m[8];
  860. return this;
  861. }
  862. setUvTransform(tx, ty, sx, sy, rotation, cx, cy) {
  863. const c = Math.cos(rotation);
  864. const s = Math.sin(rotation);
  865. 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);
  866. return this;
  867. }
  868. //
  869. scale(sx, sy) {
  870. this.premultiply(_m3.makeScale(sx, sy));
  871. return this;
  872. }
  873. rotate(theta) {
  874. this.premultiply(_m3.makeRotation(-theta));
  875. return this;
  876. }
  877. translate(tx, ty) {
  878. this.premultiply(_m3.makeTranslation(tx, ty));
  879. return this;
  880. }
  881. // for 2D Transforms
  882. makeTranslation(x, y) {
  883. this.set(1, 0, x, 0, 1, y, 0, 0, 1);
  884. return this;
  885. }
  886. makeRotation(theta) {
  887. // counterclockwise
  888. const c = Math.cos(theta);
  889. const s = Math.sin(theta);
  890. this.set(c, -s, 0, s, c, 0, 0, 0, 1);
  891. return this;
  892. }
  893. makeScale(x, y) {
  894. this.set(x, 0, 0, 0, y, 0, 0, 0, 1);
  895. return this;
  896. }
  897. //
  898. equals(matrix) {
  899. const te = this.elements;
  900. const me = matrix.elements;
  901. for (let i = 0; i < 9; i++) {
  902. if (te[i] !== me[i]) return false;
  903. }
  904. return true;
  905. }
  906. fromArray(array, offset = 0) {
  907. for (let i = 0; i < 9; i++) {
  908. this.elements[i] = array[i + offset];
  909. }
  910. return this;
  911. }
  912. toArray(array = [], offset = 0) {
  913. const te = this.elements;
  914. array[offset] = te[0];
  915. array[offset + 1] = te[1];
  916. array[offset + 2] = te[2];
  917. array[offset + 3] = te[3];
  918. array[offset + 4] = te[4];
  919. array[offset + 5] = te[5];
  920. array[offset + 6] = te[6];
  921. array[offset + 7] = te[7];
  922. array[offset + 8] = te[8];
  923. return array;
  924. }
  925. clone() {
  926. return new this.constructor().fromArray(this.elements);
  927. }
  928. }
  929. const _m3 = /*@__PURE__*/new Matrix3();
  930. function arrayNeedsUint32(array) {
  931. // assumes larger values usually on last
  932. for (let i = array.length - 1; i >= 0; --i) {
  933. if (array[i] >= 65535) return true; // account for PRIMITIVE_RESTART_FIXED_INDEX, #24565
  934. }
  935. return false;
  936. }
  937. const TYPED_ARRAYS = {
  938. Int8Array: Int8Array,
  939. Uint8Array: Uint8Array,
  940. Uint8ClampedArray: Uint8ClampedArray,
  941. Int16Array: Int16Array,
  942. Uint16Array: Uint16Array,
  943. Int32Array: Int32Array,
  944. Uint32Array: Uint32Array,
  945. Float32Array: Float32Array,
  946. Float64Array: Float64Array
  947. };
  948. function getTypedArray(type, buffer) {
  949. return new TYPED_ARRAYS[type](buffer);
  950. }
  951. function createElementNS(name) {
  952. return document.createElementNS('http://www.w3.org/1999/xhtml', name);
  953. }
  954. function SRGBToLinear(c) {
  955. return c < 0.04045 ? c * 0.0773993808 : Math.pow(c * 0.9478672986 + 0.0521327014, 2.4);
  956. }
  957. function LinearToSRGB(c) {
  958. return c < 0.0031308 ? c * 12.92 : 1.055 * Math.pow(c, 0.41666) - 0.055;
  959. }
  960. // JavaScript RGB-to-RGB transforms, defined as
  961. // FN[InputColorSpace][OutputColorSpace] callback functions.
  962. const FN = {
  963. [SRGBColorSpace]: {
  964. [LinearSRGBColorSpace]: SRGBToLinear
  965. },
  966. [LinearSRGBColorSpace]: {
  967. [SRGBColorSpace]: LinearToSRGB
  968. }
  969. };
  970. const ColorManagement = {
  971. legacyMode: true,
  972. get workingColorSpace() {
  973. return LinearSRGBColorSpace;
  974. },
  975. set workingColorSpace(colorSpace) {
  976. console.warn('THREE.ColorManagement: .workingColorSpace is readonly.');
  977. },
  978. convert: function (color, sourceColorSpace, targetColorSpace) {
  979. if (this.legacyMode || sourceColorSpace === targetColorSpace || !sourceColorSpace || !targetColorSpace) {
  980. return color;
  981. }
  982. if (FN[sourceColorSpace] && FN[sourceColorSpace][targetColorSpace] !== undefined) {
  983. const fn = FN[sourceColorSpace][targetColorSpace];
  984. color.r = fn(color.r);
  985. color.g = fn(color.g);
  986. color.b = fn(color.b);
  987. return color;
  988. }
  989. throw new Error('Unsupported color space conversion.');
  990. },
  991. fromWorkingColorSpace: function (color, targetColorSpace) {
  992. return this.convert(color, this.workingColorSpace, targetColorSpace);
  993. },
  994. toWorkingColorSpace: function (color, sourceColorSpace) {
  995. return this.convert(color, sourceColorSpace, this.workingColorSpace);
  996. }
  997. };
  998. const _colorKeywords = {
  999. 'aliceblue': 0xF0F8FF,
  1000. 'antiquewhite': 0xFAEBD7,
  1001. 'aqua': 0x00FFFF,
  1002. 'aquamarine': 0x7FFFD4,
  1003. 'azure': 0xF0FFFF,
  1004. 'beige': 0xF5F5DC,
  1005. 'bisque': 0xFFE4C4,
  1006. 'black': 0x000000,
  1007. 'blanchedalmond': 0xFFEBCD,
  1008. 'blue': 0x0000FF,
  1009. 'blueviolet': 0x8A2BE2,
  1010. 'brown': 0xA52A2A,
  1011. 'burlywood': 0xDEB887,
  1012. 'cadetblue': 0x5F9EA0,
  1013. 'chartreuse': 0x7FFF00,
  1014. 'chocolate': 0xD2691E,
  1015. 'coral': 0xFF7F50,
  1016. 'cornflowerblue': 0x6495ED,
  1017. 'cornsilk': 0xFFF8DC,
  1018. 'crimson': 0xDC143C,
  1019. 'cyan': 0x00FFFF,
  1020. 'darkblue': 0x00008B,
  1021. 'darkcyan': 0x008B8B,
  1022. 'darkgoldenrod': 0xB8860B,
  1023. 'darkgray': 0xA9A9A9,
  1024. 'darkgreen': 0x006400,
  1025. 'darkgrey': 0xA9A9A9,
  1026. 'darkkhaki': 0xBDB76B,
  1027. 'darkmagenta': 0x8B008B,
  1028. 'darkolivegreen': 0x556B2F,
  1029. 'darkorange': 0xFF8C00,
  1030. 'darkorchid': 0x9932CC,
  1031. 'darkred': 0x8B0000,
  1032. 'darksalmon': 0xE9967A,
  1033. 'darkseagreen': 0x8FBC8F,
  1034. 'darkslateblue': 0x483D8B,
  1035. 'darkslategray': 0x2F4F4F,
  1036. 'darkslategrey': 0x2F4F4F,
  1037. 'darkturquoise': 0x00CED1,
  1038. 'darkviolet': 0x9400D3,
  1039. 'deeppink': 0xFF1493,
  1040. 'deepskyblue': 0x00BFFF,
  1041. 'dimgray': 0x696969,
  1042. 'dimgrey': 0x696969,
  1043. 'dodgerblue': 0x1E90FF,
  1044. 'firebrick': 0xB22222,
  1045. 'floralwhite': 0xFFFAF0,
  1046. 'forestgreen': 0x228B22,
  1047. 'fuchsia': 0xFF00FF,
  1048. 'gainsboro': 0xDCDCDC,
  1049. 'ghostwhite': 0xF8F8FF,
  1050. 'gold': 0xFFD700,
  1051. 'goldenrod': 0xDAA520,
  1052. 'gray': 0x808080,
  1053. 'green': 0x008000,
  1054. 'greenyellow': 0xADFF2F,
  1055. 'grey': 0x808080,
  1056. 'honeydew': 0xF0FFF0,
  1057. 'hotpink': 0xFF69B4,
  1058. 'indianred': 0xCD5C5C,
  1059. 'indigo': 0x4B0082,
  1060. 'ivory': 0xFFFFF0,
  1061. 'khaki': 0xF0E68C,
  1062. 'lavender': 0xE6E6FA,
  1063. 'lavenderblush': 0xFFF0F5,
  1064. 'lawngreen': 0x7CFC00,
  1065. 'lemonchiffon': 0xFFFACD,
  1066. 'lightblue': 0xADD8E6,
  1067. 'lightcoral': 0xF08080,
  1068. 'lightcyan': 0xE0FFFF,
  1069. 'lightgoldenrodyellow': 0xFAFAD2,
  1070. 'lightgray': 0xD3D3D3,
  1071. 'lightgreen': 0x90EE90,
  1072. 'lightgrey': 0xD3D3D3,
  1073. 'lightpink': 0xFFB6C1,
  1074. 'lightsalmon': 0xFFA07A,
  1075. 'lightseagreen': 0x20B2AA,
  1076. 'lightskyblue': 0x87CEFA,
  1077. 'lightslategray': 0x778899,
  1078. 'lightslategrey': 0x778899,
  1079. 'lightsteelblue': 0xB0C4DE,
  1080. 'lightyellow': 0xFFFFE0,
  1081. 'lime': 0x00FF00,
  1082. 'limegreen': 0x32CD32,
  1083. 'linen': 0xFAF0E6,
  1084. 'magenta': 0xFF00FF,
  1085. 'maroon': 0x800000,
  1086. 'mediumaquamarine': 0x66CDAA,
  1087. 'mediumblue': 0x0000CD,
  1088. 'mediumorchid': 0xBA55D3,
  1089. 'mediumpurple': 0x9370DB,
  1090. 'mediumseagreen': 0x3CB371,
  1091. 'mediumslateblue': 0x7B68EE,
  1092. 'mediumspringgreen': 0x00FA9A,
  1093. 'mediumturquoise': 0x48D1CC,
  1094. 'mediumvioletred': 0xC71585,
  1095. 'midnightblue': 0x191970,
  1096. 'mintcream': 0xF5FFFA,
  1097. 'mistyrose': 0xFFE4E1,
  1098. 'moccasin': 0xFFE4B5,
  1099. 'navajowhite': 0xFFDEAD,
  1100. 'navy': 0x000080,
  1101. 'oldlace': 0xFDF5E6,
  1102. 'olive': 0x808000,
  1103. 'olivedrab': 0x6B8E23,
  1104. 'orange': 0xFFA500,
  1105. 'orangered': 0xFF4500,
  1106. 'orchid': 0xDA70D6,
  1107. 'palegoldenrod': 0xEEE8AA,
  1108. 'palegreen': 0x98FB98,
  1109. 'paleturquoise': 0xAFEEEE,
  1110. 'palevioletred': 0xDB7093,
  1111. 'papayawhip': 0xFFEFD5,
  1112. 'peachpuff': 0xFFDAB9,
  1113. 'peru': 0xCD853F,
  1114. 'pink': 0xFFC0CB,
  1115. 'plum': 0xDDA0DD,
  1116. 'powderblue': 0xB0E0E6,
  1117. 'purple': 0x800080,
  1118. 'rebeccapurple': 0x663399,
  1119. 'red': 0xFF0000,
  1120. 'rosybrown': 0xBC8F8F,
  1121. 'royalblue': 0x4169E1,
  1122. 'saddlebrown': 0x8B4513,
  1123. 'salmon': 0xFA8072,
  1124. 'sandybrown': 0xF4A460,
  1125. 'seagreen': 0x2E8B57,
  1126. 'seashell': 0xFFF5EE,
  1127. 'sienna': 0xA0522D,
  1128. 'silver': 0xC0C0C0,
  1129. 'skyblue': 0x87CEEB,
  1130. 'slateblue': 0x6A5ACD,
  1131. 'slategray': 0x708090,
  1132. 'slategrey': 0x708090,
  1133. 'snow': 0xFFFAFA,
  1134. 'springgreen': 0x00FF7F,
  1135. 'steelblue': 0x4682B4,
  1136. 'tan': 0xD2B48C,
  1137. 'teal': 0x008080,
  1138. 'thistle': 0xD8BFD8,
  1139. 'tomato': 0xFF6347,
  1140. 'turquoise': 0x40E0D0,
  1141. 'violet': 0xEE82EE,
  1142. 'wheat': 0xF5DEB3,
  1143. 'white': 0xFFFFFF,
  1144. 'whitesmoke': 0xF5F5F5,
  1145. 'yellow': 0xFFFF00,
  1146. 'yellowgreen': 0x9ACD32
  1147. };
  1148. const _rgb$1 = {
  1149. r: 0,
  1150. g: 0,
  1151. b: 0
  1152. };
  1153. const _hslA = {
  1154. h: 0,
  1155. s: 0,
  1156. l: 0
  1157. };
  1158. const _hslB = {
  1159. h: 0,
  1160. s: 0,
  1161. l: 0
  1162. };
  1163. function hue2rgb(p, q, t) {
  1164. if (t < 0) t += 1;
  1165. if (t > 1) t -= 1;
  1166. if (t < 1 / 6) return p + (q - p) * 6 * t;
  1167. if (t < 1 / 2) return q;
  1168. if (t < 2 / 3) return p + (q - p) * 6 * (2 / 3 - t);
  1169. return p;
  1170. }
  1171. function toComponents(source, target) {
  1172. target.r = source.r;
  1173. target.g = source.g;
  1174. target.b = source.b;
  1175. return target;
  1176. }
  1177. class Color {
  1178. constructor(r, g, b) {
  1179. this.isColor = true;
  1180. this.r = 1;
  1181. this.g = 1;
  1182. this.b = 1;
  1183. if (g === undefined && b === undefined) {
  1184. // r is THREE.Color, hex or string
  1185. return this.set(r);
  1186. }
  1187. return this.setRGB(r, g, b);
  1188. }
  1189. set(value) {
  1190. if (value && value.isColor) {
  1191. this.copy(value);
  1192. } else if (typeof value === 'number') {
  1193. this.setHex(value);
  1194. } else if (typeof value === 'string') {
  1195. this.setStyle(value);
  1196. }
  1197. return this;
  1198. }
  1199. setScalar(scalar) {
  1200. this.r = scalar;
  1201. this.g = scalar;
  1202. this.b = scalar;
  1203. return this;
  1204. }
  1205. setHex(hex, colorSpace = SRGBColorSpace) {
  1206. hex = Math.floor(hex);
  1207. this.r = (hex >> 16 & 255) / 255;
  1208. this.g = (hex >> 8 & 255) / 255;
  1209. this.b = (hex & 255) / 255;
  1210. ColorManagement.toWorkingColorSpace(this, colorSpace);
  1211. return this;
  1212. }
  1213. setRGB(r, g, b, colorSpace = ColorManagement.workingColorSpace) {
  1214. this.r = r;
  1215. this.g = g;
  1216. this.b = b;
  1217. ColorManagement.toWorkingColorSpace(this, colorSpace);
  1218. return this;
  1219. }
  1220. setHSL(h, s, l, colorSpace = ColorManagement.workingColorSpace) {
  1221. // h,s,l ranges are in 0.0 - 1.0
  1222. h = euclideanModulo(h, 1);
  1223. s = clamp(s, 0, 1);
  1224. l = clamp(l, 0, 1);
  1225. if (s === 0) {
  1226. this.r = this.g = this.b = l;
  1227. } else {
  1228. const p = l <= 0.5 ? l * (1 + s) : l + s - l * s;
  1229. const q = 2 * l - p;
  1230. this.r = hue2rgb(q, p, h + 1 / 3);
  1231. this.g = hue2rgb(q, p, h);
  1232. this.b = hue2rgb(q, p, h - 1 / 3);
  1233. }
  1234. ColorManagement.toWorkingColorSpace(this, colorSpace);
  1235. return this;
  1236. }
  1237. setStyle(style, colorSpace = SRGBColorSpace) {
  1238. function handleAlpha(string) {
  1239. if (string === undefined) return;
  1240. if (parseFloat(string) < 1) {
  1241. console.warn('THREE.Color: Alpha component of ' + style + ' will be ignored.');
  1242. }
  1243. }
  1244. let m;
  1245. if (m = /^((?:rgb|hsl)a?)\(([^\)]*)\)/.exec(style)) {
  1246. // rgb / hsl
  1247. let color;
  1248. const name = m[1];
  1249. const components = m[2];
  1250. switch (name) {
  1251. case 'rgb':
  1252. case 'rgba':
  1253. if (color = /^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(components)) {
  1254. // rgb(255,0,0) rgba(255,0,0,0.5)
  1255. this.r = Math.min(255, parseInt(color[1], 10)) / 255;
  1256. this.g = Math.min(255, parseInt(color[2], 10)) / 255;
  1257. this.b = Math.min(255, parseInt(color[3], 10)) / 255;
  1258. ColorManagement.toWorkingColorSpace(this, colorSpace);
  1259. handleAlpha(color[4]);
  1260. return this;
  1261. }
  1262. if (color = /^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(components)) {
  1263. // rgb(100%,0%,0%) rgba(100%,0%,0%,0.5)
  1264. this.r = Math.min(100, parseInt(color[1], 10)) / 100;
  1265. this.g = Math.min(100, parseInt(color[2], 10)) / 100;
  1266. this.b = Math.min(100, parseInt(color[3], 10)) / 100;
  1267. ColorManagement.toWorkingColorSpace(this, colorSpace);
  1268. handleAlpha(color[4]);
  1269. return this;
  1270. }
  1271. break;
  1272. case 'hsl':
  1273. case 'hsla':
  1274. if (color = /^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(components)) {
  1275. // hsl(120,50%,50%) hsla(120,50%,50%,0.5)
  1276. const h = parseFloat(color[1]) / 360;
  1277. const s = parseFloat(color[2]) / 100;
  1278. const l = parseFloat(color[3]) / 100;
  1279. handleAlpha(color[4]);
  1280. return this.setHSL(h, s, l, colorSpace);
  1281. }
  1282. break;
  1283. }
  1284. } else if (m = /^\#([A-Fa-f\d]+)$/.exec(style)) {
  1285. // hex color
  1286. const hex = m[1];
  1287. const size = hex.length;
  1288. if (size === 3) {
  1289. // #ff0
  1290. this.r = parseInt(hex.charAt(0) + hex.charAt(0), 16) / 255;
  1291. this.g = parseInt(hex.charAt(1) + hex.charAt(1), 16) / 255;
  1292. this.b = parseInt(hex.charAt(2) + hex.charAt(2), 16) / 255;
  1293. ColorManagement.toWorkingColorSpace(this, colorSpace);
  1294. return this;
  1295. } else if (size === 6) {
  1296. // #ff0000
  1297. this.r = parseInt(hex.charAt(0) + hex.charAt(1), 16) / 255;
  1298. this.g = parseInt(hex.charAt(2) + hex.charAt(3), 16) / 255;
  1299. this.b = parseInt(hex.charAt(4) + hex.charAt(5), 16) / 255;
  1300. ColorManagement.toWorkingColorSpace(this, colorSpace);
  1301. return this;
  1302. }
  1303. }
  1304. if (style && style.length > 0) {
  1305. return this.setColorName(style, colorSpace);
  1306. }
  1307. return this;
  1308. }
  1309. setColorName(style, colorSpace = SRGBColorSpace) {
  1310. // color keywords
  1311. const hex = _colorKeywords[style.toLowerCase()];
  1312. if (hex !== undefined) {
  1313. // red
  1314. this.setHex(hex, colorSpace);
  1315. } else {
  1316. // unknown color
  1317. console.warn('THREE.Color: Unknown color ' + style);
  1318. }
  1319. return this;
  1320. }
  1321. clone() {
  1322. return new this.constructor(this.r, this.g, this.b);
  1323. }
  1324. copy(color) {
  1325. this.r = color.r;
  1326. this.g = color.g;
  1327. this.b = color.b;
  1328. return this;
  1329. }
  1330. copySRGBToLinear(color) {
  1331. this.r = SRGBToLinear(color.r);
  1332. this.g = SRGBToLinear(color.g);
  1333. this.b = SRGBToLinear(color.b);
  1334. return this;
  1335. }
  1336. copyLinearToSRGB(color) {
  1337. this.r = LinearToSRGB(color.r);
  1338. this.g = LinearToSRGB(color.g);
  1339. this.b = LinearToSRGB(color.b);
  1340. return this;
  1341. }
  1342. convertSRGBToLinear() {
  1343. this.copySRGBToLinear(this);
  1344. return this;
  1345. }
  1346. convertLinearToSRGB() {
  1347. this.copyLinearToSRGB(this);
  1348. return this;
  1349. }
  1350. getHex(colorSpace = SRGBColorSpace) {
  1351. ColorManagement.fromWorkingColorSpace(toComponents(this, _rgb$1), colorSpace);
  1352. return clamp(_rgb$1.r * 255, 0, 255) << 16 ^ clamp(_rgb$1.g * 255, 0, 255) << 8 ^ clamp(_rgb$1.b * 255, 0, 255) << 0;
  1353. }
  1354. getHexString(colorSpace = SRGBColorSpace) {
  1355. return ('000000' + this.getHex(colorSpace).toString(16)).slice(-6);
  1356. }
  1357. getHSL(target, colorSpace = ColorManagement.workingColorSpace) {
  1358. // h,s,l ranges are in 0.0 - 1.0
  1359. ColorManagement.fromWorkingColorSpace(toComponents(this, _rgb$1), colorSpace);
  1360. const r = _rgb$1.r,
  1361. g = _rgb$1.g,
  1362. b = _rgb$1.b;
  1363. const max = Math.max(r, g, b);
  1364. const min = Math.min(r, g, b);
  1365. let hue, saturation;
  1366. const lightness = (min + max) / 2.0;
  1367. if (min === max) {
  1368. hue = 0;
  1369. saturation = 0;
  1370. } else {
  1371. const delta = max - min;
  1372. saturation = lightness <= 0.5 ? delta / (max + min) : delta / (2 - max - min);
  1373. switch (max) {
  1374. case r:
  1375. hue = (g - b) / delta + (g < b ? 6 : 0);
  1376. break;
  1377. case g:
  1378. hue = (b - r) / delta + 2;
  1379. break;
  1380. case b:
  1381. hue = (r - g) / delta + 4;
  1382. break;
  1383. }
  1384. hue /= 6;
  1385. }
  1386. target.h = hue;
  1387. target.s = saturation;
  1388. target.l = lightness;
  1389. return target;
  1390. }
  1391. getRGB(target, colorSpace = ColorManagement.workingColorSpace) {
  1392. ColorManagement.fromWorkingColorSpace(toComponents(this, _rgb$1), colorSpace);
  1393. target.r = _rgb$1.r;
  1394. target.g = _rgb$1.g;
  1395. target.b = _rgb$1.b;
  1396. return target;
  1397. }
  1398. getStyle(colorSpace = SRGBColorSpace) {
  1399. ColorManagement.fromWorkingColorSpace(toComponents(this, _rgb$1), colorSpace);
  1400. if (colorSpace !== SRGBColorSpace) {
  1401. // Requires CSS Color Module Level 4 (https://www.w3.org/TR/css-color-4/).
  1402. return `color(${colorSpace} ${_rgb$1.r} ${_rgb$1.g} ${_rgb$1.b})`;
  1403. }
  1404. return `rgb(${_rgb$1.r * 255 | 0},${_rgb$1.g * 255 | 0},${_rgb$1.b * 255 | 0})`;
  1405. }
  1406. offsetHSL(h, s, l) {
  1407. this.getHSL(_hslA);
  1408. _hslA.h += h;
  1409. _hslA.s += s;
  1410. _hslA.l += l;
  1411. this.setHSL(_hslA.h, _hslA.s, _hslA.l);
  1412. return this;
  1413. }
  1414. add(color) {
  1415. this.r += color.r;
  1416. this.g += color.g;
  1417. this.b += color.b;
  1418. return this;
  1419. }
  1420. addColors(color1, color2) {
  1421. this.r = color1.r + color2.r;
  1422. this.g = color1.g + color2.g;
  1423. this.b = color1.b + color2.b;
  1424. return this;
  1425. }
  1426. addScalar(s) {
  1427. this.r += s;
  1428. this.g += s;
  1429. this.b += s;
  1430. return this;
  1431. }
  1432. sub(color) {
  1433. this.r = Math.max(0, this.r - color.r);
  1434. this.g = Math.max(0, this.g - color.g);
  1435. this.b = Math.max(0, this.b - color.b);
  1436. return this;
  1437. }
  1438. multiply(color) {
  1439. this.r *= color.r;
  1440. this.g *= color.g;
  1441. this.b *= color.b;
  1442. return this;
  1443. }
  1444. multiplyScalar(s) {
  1445. this.r *= s;
  1446. this.g *= s;
  1447. this.b *= s;
  1448. return this;
  1449. }
  1450. lerp(color, alpha) {
  1451. this.r += (color.r - this.r) * alpha;
  1452. this.g += (color.g - this.g) * alpha;
  1453. this.b += (color.b - this.b) * alpha;
  1454. return this;
  1455. }
  1456. lerpColors(color1, color2, alpha) {
  1457. this.r = color1.r + (color2.r - color1.r) * alpha;
  1458. this.g = color1.g + (color2.g - color1.g) * alpha;
  1459. this.b = color1.b + (color2.b - color1.b) * alpha;
  1460. return this;
  1461. }
  1462. lerpHSL(color, alpha) {
  1463. this.getHSL(_hslA);
  1464. color.getHSL(_hslB);
  1465. const h = lerp(_hslA.h, _hslB.h, alpha);
  1466. const s = lerp(_hslA.s, _hslB.s, alpha);
  1467. const l = lerp(_hslA.l, _hslB.l, alpha);
  1468. this.setHSL(h, s, l);
  1469. return this;
  1470. }
  1471. equals(c) {
  1472. return c.r === this.r && c.g === this.g && c.b === this.b;
  1473. }
  1474. fromArray(array, offset = 0) {
  1475. this.r = array[offset];
  1476. this.g = array[offset + 1];
  1477. this.b = array[offset + 2];
  1478. return this;
  1479. }
  1480. toArray(array = [], offset = 0) {
  1481. array[offset] = this.r;
  1482. array[offset + 1] = this.g;
  1483. array[offset + 2] = this.b;
  1484. return array;
  1485. }
  1486. fromBufferAttribute(attribute, index) {
  1487. this.r = attribute.getX(index);
  1488. this.g = attribute.getY(index);
  1489. this.b = attribute.getZ(index);
  1490. return this;
  1491. }
  1492. toJSON() {
  1493. return this.getHex();
  1494. }
  1495. *[Symbol.iterator]() {
  1496. yield this.r;
  1497. yield this.g;
  1498. yield this.b;
  1499. }
  1500. }
  1501. Color.NAMES = _colorKeywords;
  1502. let _canvas;
  1503. class ImageUtils {
  1504. static getDataURL(image) {
  1505. if (/^data:/i.test(image.src)) {
  1506. return image.src;
  1507. }
  1508. if (typeof HTMLCanvasElement == 'undefined') {
  1509. return image.src;
  1510. }
  1511. let canvas;
  1512. if (image instanceof HTMLCanvasElement) {
  1513. canvas = image;
  1514. } else {
  1515. if (_canvas === undefined) _canvas = createElementNS('canvas');
  1516. _canvas.width = image.width;
  1517. _canvas.height = image.height;
  1518. const context = _canvas.getContext('2d');
  1519. if (image instanceof ImageData) {
  1520. context.putImageData(image, 0, 0);
  1521. } else {
  1522. context.drawImage(image, 0, 0, image.width, image.height);
  1523. }
  1524. canvas = _canvas;
  1525. }
  1526. if (canvas.width > 2048 || canvas.height > 2048) {
  1527. console.warn('THREE.ImageUtils.getDataURL: Image converted to jpg for performance reasons', image);
  1528. return canvas.toDataURL('image/jpeg', 0.6);
  1529. } else {
  1530. return canvas.toDataURL('image/png');
  1531. }
  1532. }
  1533. static sRGBToLinear(image) {
  1534. if (typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement || typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement || typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap) {
  1535. const canvas = createElementNS('canvas');
  1536. canvas.width = image.width;
  1537. canvas.height = image.height;
  1538. const context = canvas.getContext('2d');
  1539. context.drawImage(image, 0, 0, image.width, image.height);
  1540. const imageData = context.getImageData(0, 0, image.width, image.height);
  1541. const data = imageData.data;
  1542. for (let i = 0; i < data.length; i++) {
  1543. data[i] = SRGBToLinear(data[i] / 255) * 255;
  1544. }
  1545. context.putImageData(imageData, 0, 0);
  1546. return canvas;
  1547. } else if (image.data) {
  1548. const data = image.data.slice(0);
  1549. for (let i = 0; i < data.length; i++) {
  1550. if (data instanceof Uint8Array || data instanceof Uint8ClampedArray) {
  1551. data[i] = Math.floor(SRGBToLinear(data[i] / 255) * 255);
  1552. } else {
  1553. // assuming float
  1554. data[i] = SRGBToLinear(data[i]);
  1555. }
  1556. }
  1557. return {
  1558. data: data,
  1559. width: image.width,
  1560. height: image.height
  1561. };
  1562. } else {
  1563. console.warn('THREE.ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied.');
  1564. return image;
  1565. }
  1566. }
  1567. }
  1568. class Source {
  1569. constructor(data = null) {
  1570. this.isSource = true;
  1571. this.uuid = generateUUID();
  1572. this.data = data;
  1573. this.version = 0;
  1574. }
  1575. set needsUpdate(value) {
  1576. if (value === true) this.version++;
  1577. }
  1578. toJSON(meta) {
  1579. const isRootObject = meta === undefined || typeof meta === 'string';
  1580. if (!isRootObject && meta.images[this.uuid] !== undefined) {
  1581. return meta.images[this.uuid];
  1582. }
  1583. const output = {
  1584. uuid: this.uuid,
  1585. url: ''
  1586. };
  1587. const data = this.data;
  1588. if (data !== null) {
  1589. let url;
  1590. if (Array.isArray(data)) {
  1591. // cube texture
  1592. url = [];
  1593. for (let i = 0, l = data.length; i < l; i++) {
  1594. if (data[i].isDataTexture) {
  1595. url.push(serializeImage(data[i].image));
  1596. } else {
  1597. url.push(serializeImage(data[i]));
  1598. }
  1599. }
  1600. } else {
  1601. // texture
  1602. url = serializeImage(data);
  1603. }
  1604. output.url = url;
  1605. }
  1606. if (!isRootObject) {
  1607. meta.images[this.uuid] = output;
  1608. }
  1609. return output;
  1610. }
  1611. }
  1612. function serializeImage(image) {
  1613. if (typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement || typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement || typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap) {
  1614. // default images
  1615. return ImageUtils.getDataURL(image);
  1616. } else {
  1617. if (image.data) {
  1618. // images of DataTexture
  1619. return {
  1620. data: Array.from(image.data),
  1621. width: image.width,
  1622. height: image.height,
  1623. type: image.data.constructor.name
  1624. };
  1625. } else {
  1626. console.warn('THREE.Texture: Unable to serialize Texture.');
  1627. return {};
  1628. }
  1629. }
  1630. }
  1631. let textureId = 0;
  1632. class Texture extends EventDispatcher {
  1633. constructor(image = Texture.DEFAULT_IMAGE, mapping = Texture.DEFAULT_MAPPING, wrapS = ClampToEdgeWrapping, wrapT = ClampToEdgeWrapping, magFilter = LinearFilter, minFilter = LinearMipmapLinearFilter, format = RGBAFormat, type = UnsignedByteType, anisotropy = Texture.DEFAULT_ANISOTROPY, encoding = LinearEncoding) {
  1634. super();
  1635. this.isTexture = true;
  1636. Object.defineProperty(this, 'id', {
  1637. value: textureId++
  1638. });
  1639. this.uuid = generateUUID();
  1640. this.name = '';
  1641. this.source = new Source(image);
  1642. this.mipmaps = [];
  1643. this.mapping = mapping;
  1644. this.wrapS = wrapS;
  1645. this.wrapT = wrapT;
  1646. this.magFilter = magFilter;
  1647. this.minFilter = minFilter;
  1648. this.anisotropy = anisotropy;
  1649. this.format = format;
  1650. this.internalFormat = null;
  1651. this.type = type;
  1652. this.offset = new Vector2(0, 0);
  1653. this.repeat = new Vector2(1, 1);
  1654. this.center = new Vector2(0, 0);
  1655. this.rotation = 0;
  1656. this.matrixAutoUpdate = true;
  1657. this.matrix = new Matrix3();
  1658. this.generateMipmaps = true;
  1659. this.premultiplyAlpha = false;
  1660. this.flipY = true;
  1661. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  1662. // Values of encoding !== THREE.LinearEncoding only supported on map, envMap and emissiveMap.
  1663. //
  1664. // Also changing the encoding after already used by a Material will not automatically make the Material
  1665. // update. You need to explicitly call Material.needsUpdate to trigger it to recompile.
  1666. this.encoding = encoding;
  1667. this.userData = {};
  1668. this.version = 0;
  1669. this.onUpdate = null;
  1670. this.isRenderTargetTexture = false; // indicates whether a texture belongs to a render target or not
  1671. this.needsPMREMUpdate = false; // indicates whether this texture should be processed by PMREMGenerator or not (only relevant for render target textures)
  1672. }
  1673. get image() {
  1674. return this.source.data;
  1675. }
  1676. set image(value) {
  1677. this.source.data = value;
  1678. }
  1679. updateMatrix() {
  1680. this.matrix.setUvTransform(this.offset.x, this.offset.y, this.repeat.x, this.repeat.y, this.rotation, this.center.x, this.center.y);
  1681. }
  1682. clone() {
  1683. return new this.constructor().copy(this);
  1684. }
  1685. copy(source) {
  1686. this.name = source.name;
  1687. this.source = source.source;
  1688. this.mipmaps = source.mipmaps.slice(0);
  1689. this.mapping = source.mapping;
  1690. this.wrapS = source.wrapS;
  1691. this.wrapT = source.wrapT;
  1692. this.magFilter = source.magFilter;
  1693. this.minFilter = source.minFilter;
  1694. this.anisotropy = source.anisotropy;
  1695. this.format = source.format;
  1696. this.internalFormat = source.internalFormat;
  1697. this.type = source.type;
  1698. this.offset.copy(source.offset);
  1699. this.repeat.copy(source.repeat);
  1700. this.center.copy(source.center);
  1701. this.rotation = source.rotation;
  1702. this.matrixAutoUpdate = source.matrixAutoUpdate;
  1703. this.matrix.copy(source.matrix);
  1704. this.generateMipmaps = source.generateMipmaps;
  1705. this.premultiplyAlpha = source.premultiplyAlpha;
  1706. this.flipY = source.flipY;
  1707. this.unpackAlignment = source.unpackAlignment;
  1708. this.encoding = source.encoding;
  1709. this.userData = JSON.parse(JSON.stringify(source.userData));
  1710. this.needsUpdate = true;
  1711. return this;
  1712. }
  1713. toJSON(meta) {
  1714. const isRootObject = meta === undefined || typeof meta === 'string';
  1715. if (!isRootObject && meta.textures[this.uuid] !== undefined) {
  1716. return meta.textures[this.uuid];
  1717. }
  1718. const output = {
  1719. metadata: {
  1720. version: 4.5,
  1721. type: 'Texture',
  1722. generator: 'Texture.toJSON'
  1723. },
  1724. uuid: this.uuid,
  1725. name: this.name,
  1726. image: this.source.toJSON(meta).uuid,
  1727. mapping: this.mapping,
  1728. repeat: [this.repeat.x, this.repeat.y],
  1729. offset: [this.offset.x, this.offset.y],
  1730. center: [this.center.x, this.center.y],
  1731. rotation: this.rotation,
  1732. wrap: [this.wrapS, this.wrapT],
  1733. format: this.format,
  1734. type: this.type,
  1735. encoding: this.encoding,
  1736. minFilter: this.minFilter,
  1737. magFilter: this.magFilter,
  1738. anisotropy: this.anisotropy,
  1739. flipY: this.flipY,
  1740. generateMipmaps: this.generateMipmaps,
  1741. premultiplyAlpha: this.premultiplyAlpha,
  1742. unpackAlignment: this.unpackAlignment
  1743. };
  1744. if (Object.keys(this.userData).length > 0) output.userData = this.userData;
  1745. if (!isRootObject) {
  1746. meta.textures[this.uuid] = output;
  1747. }
  1748. return output;
  1749. }
  1750. dispose() {
  1751. this.dispatchEvent({
  1752. type: 'dispose'
  1753. });
  1754. }
  1755. transformUv(uv) {
  1756. if (this.mapping !== UVMapping) return uv;
  1757. uv.applyMatrix3(this.matrix);
  1758. if (uv.x < 0 || uv.x > 1) {
  1759. switch (this.wrapS) {
  1760. case RepeatWrapping:
  1761. uv.x = uv.x - Math.floor(uv.x);
  1762. break;
  1763. case ClampToEdgeWrapping:
  1764. uv.x = uv.x < 0 ? 0 : 1;
  1765. break;
  1766. case MirroredRepeatWrapping:
  1767. if (Math.abs(Math.floor(uv.x) % 2) === 1) {
  1768. uv.x = Math.ceil(uv.x) - uv.x;
  1769. } else {
  1770. uv.x = uv.x - Math.floor(uv.x);
  1771. }
  1772. break;
  1773. }
  1774. }
  1775. if (uv.y < 0 || uv.y > 1) {
  1776. switch (this.wrapT) {
  1777. case RepeatWrapping:
  1778. uv.y = uv.y - Math.floor(uv.y);
  1779. break;
  1780. case ClampToEdgeWrapping:
  1781. uv.y = uv.y < 0 ? 0 : 1;
  1782. break;
  1783. case MirroredRepeatWrapping:
  1784. if (Math.abs(Math.floor(uv.y) % 2) === 1) {
  1785. uv.y = Math.ceil(uv.y) - uv.y;
  1786. } else {
  1787. uv.y = uv.y - Math.floor(uv.y);
  1788. }
  1789. break;
  1790. }
  1791. }
  1792. if (this.flipY) {
  1793. uv.y = 1 - uv.y;
  1794. }
  1795. return uv;
  1796. }
  1797. set needsUpdate(value) {
  1798. if (value === true) {
  1799. this.version++;
  1800. this.source.needsUpdate = true;
  1801. }
  1802. }
  1803. }
  1804. Texture.DEFAULT_IMAGE = null;
  1805. Texture.DEFAULT_MAPPING = UVMapping;
  1806. Texture.DEFAULT_ANISOTROPY = 1;
  1807. class Vector4 {
  1808. constructor(x = 0, y = 0, z = 0, w = 1) {
  1809. Vector4.prototype.isVector4 = true;
  1810. this.x = x;
  1811. this.y = y;
  1812. this.z = z;
  1813. this.w = w;
  1814. }
  1815. get width() {
  1816. return this.z;
  1817. }
  1818. set width(value) {
  1819. this.z = value;
  1820. }
  1821. get height() {
  1822. return this.w;
  1823. }
  1824. set height(value) {
  1825. this.w = value;
  1826. }
  1827. set(x, y, z, w) {
  1828. this.x = x;
  1829. this.y = y;
  1830. this.z = z;
  1831. this.w = w;
  1832. return this;
  1833. }
  1834. setScalar(scalar) {
  1835. this.x = scalar;
  1836. this.y = scalar;
  1837. this.z = scalar;
  1838. this.w = scalar;
  1839. return this;
  1840. }
  1841. setX(x) {
  1842. this.x = x;
  1843. return this;
  1844. }
  1845. setY(y) {
  1846. this.y = y;
  1847. return this;
  1848. }
  1849. setZ(z) {
  1850. this.z = z;
  1851. return this;
  1852. }
  1853. setW(w) {
  1854. this.w = w;
  1855. return this;
  1856. }
  1857. setComponent(index, value) {
  1858. switch (index) {
  1859. case 0:
  1860. this.x = value;
  1861. break;
  1862. case 1:
  1863. this.y = value;
  1864. break;
  1865. case 2:
  1866. this.z = value;
  1867. break;
  1868. case 3:
  1869. this.w = value;
  1870. break;
  1871. default:
  1872. throw new Error('index is out of range: ' + index);
  1873. }
  1874. return this;
  1875. }
  1876. getComponent(index) {
  1877. switch (index) {
  1878. case 0:
  1879. return this.x;
  1880. case 1:
  1881. return this.y;
  1882. case 2:
  1883. return this.z;
  1884. case 3:
  1885. return this.w;
  1886. default:
  1887. throw new Error('index is out of range: ' + index);
  1888. }
  1889. }
  1890. clone() {
  1891. return new this.constructor(this.x, this.y, this.z, this.w);
  1892. }
  1893. copy(v) {
  1894. this.x = v.x;
  1895. this.y = v.y;
  1896. this.z = v.z;
  1897. this.w = v.w !== undefined ? v.w : 1;
  1898. return this;
  1899. }
  1900. add(v) {
  1901. this.x += v.x;
  1902. this.y += v.y;
  1903. this.z += v.z;
  1904. this.w += v.w;
  1905. return this;
  1906. }
  1907. addScalar(s) {
  1908. this.x += s;
  1909. this.y += s;
  1910. this.z += s;
  1911. this.w += s;
  1912. return this;
  1913. }
  1914. addVectors(a, b) {
  1915. this.x = a.x + b.x;
  1916. this.y = a.y + b.y;
  1917. this.z = a.z + b.z;
  1918. this.w = a.w + b.w;
  1919. return this;
  1920. }
  1921. addScaledVector(v, s) {
  1922. this.x += v.x * s;
  1923. this.y += v.y * s;
  1924. this.z += v.z * s;
  1925. this.w += v.w * s;
  1926. return this;
  1927. }
  1928. sub(v) {
  1929. this.x -= v.x;
  1930. this.y -= v.y;
  1931. this.z -= v.z;
  1932. this.w -= v.w;
  1933. return this;
  1934. }
  1935. subScalar(s) {
  1936. this.x -= s;
  1937. this.y -= s;
  1938. this.z -= s;
  1939. this.w -= s;
  1940. return this;
  1941. }
  1942. subVectors(a, b) {
  1943. this.x = a.x - b.x;
  1944. this.y = a.y - b.y;
  1945. this.z = a.z - b.z;
  1946. this.w = a.w - b.w;
  1947. return this;
  1948. }
  1949. multiply(v) {
  1950. this.x *= v.x;
  1951. this.y *= v.y;
  1952. this.z *= v.z;
  1953. this.w *= v.w;
  1954. return this;
  1955. }
  1956. multiplyScalar(scalar) {
  1957. this.x *= scalar;
  1958. this.y *= scalar;
  1959. this.z *= scalar;
  1960. this.w *= scalar;
  1961. return this;
  1962. }
  1963. applyMatrix4(m) {
  1964. const x = this.x,
  1965. y = this.y,
  1966. z = this.z,
  1967. w = this.w;
  1968. const e = m.elements;
  1969. this.x = e[0] * x + e[4] * y + e[8] * z + e[12] * w;
  1970. this.y = e[1] * x + e[5] * y + e[9] * z + e[13] * w;
  1971. this.z = e[2] * x + e[6] * y + e[10] * z + e[14] * w;
  1972. this.w = e[3] * x + e[7] * y + e[11] * z + e[15] * w;
  1973. return this;
  1974. }
  1975. divideScalar(scalar) {
  1976. return this.multiplyScalar(1 / scalar);
  1977. }
  1978. setAxisAngleFromQuaternion(q) {
  1979. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  1980. // q is assumed to be normalized
  1981. this.w = 2 * Math.acos(q.w);
  1982. const s = Math.sqrt(1 - q.w * q.w);
  1983. if (s < 0.0001) {
  1984. this.x = 1;
  1985. this.y = 0;
  1986. this.z = 0;
  1987. } else {
  1988. this.x = q.x / s;
  1989. this.y = q.y / s;
  1990. this.z = q.z / s;
  1991. }
  1992. return this;
  1993. }
  1994. setAxisAngleFromRotationMatrix(m) {
  1995. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  1996. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1997. let angle, x, y, z; // variables for result
  1998. const epsilon = 0.01,
  1999. // margin to allow for rounding errors
  2000. epsilon2 = 0.1,
  2001. // margin to distinguish between 0 and 180 degrees
  2002. te = m.elements,
  2003. m11 = te[0],
  2004. m12 = te[4],
  2005. m13 = te[8],
  2006. m21 = te[1],
  2007. m22 = te[5],
  2008. m23 = te[9],
  2009. m31 = te[2],
  2010. m32 = te[6],
  2011. m33 = te[10];
  2012. if (Math.abs(m12 - m21) < epsilon && Math.abs(m13 - m31) < epsilon && Math.abs(m23 - m32) < epsilon) {
  2013. // singularity found
  2014. // first check for identity matrix which must have +1 for all terms
  2015. // in leading diagonal and zero in other terms
  2016. if (Math.abs(m12 + m21) < epsilon2 && Math.abs(m13 + m31) < epsilon2 && Math.abs(m23 + m32) < epsilon2 && Math.abs(m11 + m22 + m33 - 3) < epsilon2) {
  2017. // this singularity is identity matrix so angle = 0
  2018. this.set(1, 0, 0, 0);
  2019. return this; // zero angle, arbitrary axis
  2020. }
  2021. // otherwise this singularity is angle = 180
  2022. angle = Math.PI;
  2023. const xx = (m11 + 1) / 2;
  2024. const yy = (m22 + 1) / 2;
  2025. const zz = (m33 + 1) / 2;
  2026. const xy = (m12 + m21) / 4;
  2027. const xz = (m13 + m31) / 4;
  2028. const yz = (m23 + m32) / 4;
  2029. if (xx > yy && xx > zz) {
  2030. // m11 is the largest diagonal term
  2031. if (xx < epsilon) {
  2032. x = 0;
  2033. y = 0.707106781;
  2034. z = 0.707106781;
  2035. } else {
  2036. x = Math.sqrt(xx);
  2037. y = xy / x;
  2038. z = xz / x;
  2039. }
  2040. } else if (yy > zz) {
  2041. // m22 is the largest diagonal term
  2042. if (yy < epsilon) {
  2043. x = 0.707106781;
  2044. y = 0;
  2045. z = 0.707106781;
  2046. } else {
  2047. y = Math.sqrt(yy);
  2048. x = xy / y;
  2049. z = yz / y;
  2050. }
  2051. } else {
  2052. // m33 is the largest diagonal term so base result on this
  2053. if (zz < epsilon) {
  2054. x = 0.707106781;
  2055. y = 0.707106781;
  2056. z = 0;
  2057. } else {
  2058. z = Math.sqrt(zz);
  2059. x = xz / z;
  2060. y = yz / z;
  2061. }
  2062. }
  2063. this.set(x, y, z, angle);
  2064. return this; // return 180 deg rotation
  2065. }
  2066. // as we have reached here there are no singularities so we can handle normally
  2067. let s = Math.sqrt((m32 - m23) * (m32 - m23) + (m13 - m31) * (m13 - m31) + (m21 - m12) * (m21 - m12)); // used to normalize
  2068. if (Math.abs(s) < 0.001) s = 1;
  2069. // prevent divide by zero, should not happen if matrix is orthogonal and should be
  2070. // caught by singularity test above, but I've left it in just in case
  2071. this.x = (m32 - m23) / s;
  2072. this.y = (m13 - m31) / s;
  2073. this.z = (m21 - m12) / s;
  2074. this.w = Math.acos((m11 + m22 + m33 - 1) / 2);
  2075. return this;
  2076. }
  2077. min(v) {
  2078. this.x = Math.min(this.x, v.x);
  2079. this.y = Math.min(this.y, v.y);
  2080. this.z = Math.min(this.z, v.z);
  2081. this.w = Math.min(this.w, v.w);
  2082. return this;
  2083. }
  2084. max(v) {
  2085. this.x = Math.max(this.x, v.x);
  2086. this.y = Math.max(this.y, v.y);
  2087. this.z = Math.max(this.z, v.z);
  2088. this.w = Math.max(this.w, v.w);
  2089. return this;
  2090. }
  2091. clamp(min, max) {
  2092. // assumes min < max, componentwise
  2093. this.x = Math.max(min.x, Math.min(max.x, this.x));
  2094. this.y = Math.max(min.y, Math.min(max.y, this.y));
  2095. this.z = Math.max(min.z, Math.min(max.z, this.z));
  2096. this.w = Math.max(min.w, Math.min(max.w, this.w));
  2097. return this;
  2098. }
  2099. clampScalar(minVal, maxVal) {
  2100. this.x = Math.max(minVal, Math.min(maxVal, this.x));
  2101. this.y = Math.max(minVal, Math.min(maxVal, this.y));
  2102. this.z = Math.max(minVal, Math.min(maxVal, this.z));
  2103. this.w = Math.max(minVal, Math.min(maxVal, this.w));
  2104. return this;
  2105. }
  2106. clampLength(min, max) {
  2107. const length = this.length();
  2108. return this.divideScalar(length || 1).multiplyScalar(Math.max(min, Math.min(max, length)));
  2109. }
  2110. floor() {
  2111. this.x = Math.floor(this.x);
  2112. this.y = Math.floor(this.y);
  2113. this.z = Math.floor(this.z);
  2114. this.w = Math.floor(this.w);
  2115. return this;
  2116. }
  2117. ceil() {
  2118. this.x = Math.ceil(this.x);
  2119. this.y = Math.ceil(this.y);
  2120. this.z = Math.ceil(this.z);
  2121. this.w = Math.ceil(this.w);
  2122. return this;
  2123. }
  2124. round() {
  2125. this.x = Math.round(this.x);
  2126. this.y = Math.round(this.y);
  2127. this.z = Math.round(this.z);
  2128. this.w = Math.round(this.w);
  2129. return this;
  2130. }
  2131. roundToZero() {
  2132. this.x = this.x < 0 ? Math.ceil(this.x) : Math.floor(this.x);
  2133. this.y = this.y < 0 ? Math.ceil(this.y) : Math.floor(this.y);
  2134. this.z = this.z < 0 ? Math.ceil(this.z) : Math.floor(this.z);
  2135. this.w = this.w < 0 ? Math.ceil(this.w) : Math.floor(this.w);
  2136. return this;
  2137. }
  2138. negate() {
  2139. this.x = -this.x;
  2140. this.y = -this.y;
  2141. this.z = -this.z;
  2142. this.w = -this.w;
  2143. return this;
  2144. }
  2145. dot(v) {
  2146. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  2147. }
  2148. lengthSq() {
  2149. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  2150. }
  2151. length() {
  2152. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  2153. }
  2154. manhattanLength() {
  2155. return Math.abs(this.x) + Math.abs(this.y) + Math.abs(this.z) + Math.abs(this.w);
  2156. }
  2157. normalize() {
  2158. return this.divideScalar(this.length() || 1);
  2159. }
  2160. setLength(length) {
  2161. return this.normalize().multiplyScalar(length);
  2162. }
  2163. lerp(v, alpha) {
  2164. this.x += (v.x - this.x) * alpha;
  2165. this.y += (v.y - this.y) * alpha;
  2166. this.z += (v.z - this.z) * alpha;
  2167. this.w += (v.w - this.w) * alpha;
  2168. return this;
  2169. }
  2170. lerpVectors(v1, v2, alpha) {
  2171. this.x = v1.x + (v2.x - v1.x) * alpha;
  2172. this.y = v1.y + (v2.y - v1.y) * alpha;
  2173. this.z = v1.z + (v2.z - v1.z) * alpha;
  2174. this.w = v1.w + (v2.w - v1.w) * alpha;
  2175. return this;
  2176. }
  2177. equals(v) {
  2178. return v.x === this.x && v.y === this.y && v.z === this.z && v.w === this.w;
  2179. }
  2180. fromArray(array, offset = 0) {
  2181. this.x = array[offset];
  2182. this.y = array[offset + 1];
  2183. this.z = array[offset + 2];
  2184. this.w = array[offset + 3];
  2185. return this;
  2186. }
  2187. toArray(array = [], offset = 0) {
  2188. array[offset] = this.x;
  2189. array[offset + 1] = this.y;
  2190. array[offset + 2] = this.z;
  2191. array[offset + 3] = this.w;
  2192. return array;
  2193. }
  2194. fromBufferAttribute(attribute, index) {
  2195. this.x = attribute.getX(index);
  2196. this.y = attribute.getY(index);
  2197. this.z = attribute.getZ(index);
  2198. this.w = attribute.getW(index);
  2199. return this;
  2200. }
  2201. random() {
  2202. this.x = Math.random();
  2203. this.y = Math.random();
  2204. this.z = Math.random();
  2205. this.w = Math.random();
  2206. return this;
  2207. }
  2208. *[Symbol.iterator]() {
  2209. yield this.x;
  2210. yield this.y;
  2211. yield this.z;
  2212. yield this.w;
  2213. }
  2214. }
  2215. /*
  2216. In options, we can specify:
  2217. * Texture parameters for an auto-generated target texture
  2218. * depthBuffer/stencilBuffer: Booleans to indicate if we should generate these buffers
  2219. */
  2220. class WebGLRenderTarget extends EventDispatcher {
  2221. constructor(width = 1, height = 1, options = {}) {
  2222. super();
  2223. this.isWebGLRenderTarget = true;
  2224. this.width = width;
  2225. this.height = height;
  2226. this.depth = 1;
  2227. this.scissor = new Vector4(0, 0, width, height);
  2228. this.scissorTest = false;
  2229. this.viewport = new Vector4(0, 0, width, height);
  2230. const image = {
  2231. width: width,
  2232. height: height,
  2233. depth: 1
  2234. };
  2235. this.texture = new Texture(image, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding);
  2236. this.texture.isRenderTargetTexture = true;
  2237. this.texture.flipY = false;
  2238. this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false;
  2239. this.texture.internalFormat = options.internalFormat !== undefined ? options.internalFormat : null;
  2240. this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter;
  2241. this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
  2242. this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : false;
  2243. this.depthTexture = options.depthTexture !== undefined ? options.depthTexture : null;
  2244. this.samples = options.samples !== undefined ? options.samples : 0;
  2245. }
  2246. setSize(width, height, depth = 1) {
  2247. if (this.width !== width || this.height !== height || this.depth !== depth) {
  2248. this.width = width;
  2249. this.height = height;
  2250. this.depth = depth;
  2251. this.texture.image.width = width;
  2252. this.texture.image.height = height;
  2253. this.texture.image.depth = depth;
  2254. this.dispose();
  2255. }
  2256. this.viewport.set(0, 0, width, height);
  2257. this.scissor.set(0, 0, width, height);
  2258. }
  2259. clone() {
  2260. return new this.constructor().copy(this);
  2261. }
  2262. copy(source) {
  2263. this.width = source.width;
  2264. this.height = source.height;
  2265. this.depth = source.depth;
  2266. this.viewport.copy(source.viewport);
  2267. this.texture = source.texture.clone();
  2268. this.texture.isRenderTargetTexture = true;
  2269. // ensure image object is not shared, see #20328
  2270. const image = Object.assign({}, source.texture.image);
  2271. this.texture.source = new Source(image);
  2272. this.depthBuffer = source.depthBuffer;
  2273. this.stencilBuffer = source.stencilBuffer;
  2274. if (source.depthTexture !== null) this.depthTexture = source.depthTexture.clone();
  2275. this.samples = source.samples;
  2276. return this;
  2277. }
  2278. dispose() {
  2279. this.dispatchEvent({
  2280. type: 'dispose'
  2281. });
  2282. }
  2283. }
  2284. class DataArrayTexture extends Texture {
  2285. constructor(data = null, width = 1, height = 1, depth = 1) {
  2286. super(null);
  2287. this.isDataArrayTexture = true;
  2288. this.image = {
  2289. data,
  2290. width,
  2291. height,
  2292. depth
  2293. };
  2294. this.magFilter = NearestFilter;
  2295. this.minFilter = NearestFilter;
  2296. this.wrapR = ClampToEdgeWrapping;
  2297. this.generateMipmaps = false;
  2298. this.flipY = false;
  2299. this.unpackAlignment = 1;
  2300. }
  2301. }
  2302. class WebGLArrayRenderTarget extends WebGLRenderTarget {
  2303. constructor(width = 1, height = 1, depth = 1) {
  2304. super(width, height);
  2305. this.isWebGLArrayRenderTarget = true;
  2306. this.depth = depth;
  2307. this.texture = new DataArrayTexture(null, width, height, depth);
  2308. this.texture.isRenderTargetTexture = true;
  2309. }
  2310. }
  2311. class Data3DTexture extends Texture {
  2312. constructor(data = null, width = 1, height = 1, depth = 1) {
  2313. // We're going to add .setXXX() methods for setting properties later.
  2314. // Users can still set in DataTexture3D directly.
  2315. //
  2316. // const texture = new THREE.DataTexture3D( data, width, height, depth );
  2317. // texture.anisotropy = 16;
  2318. //
  2319. // See #14839
  2320. super(null);
  2321. this.isData3DTexture = true;
  2322. this.image = {
  2323. data,
  2324. width,
  2325. height,
  2326. depth
  2327. };
  2328. this.magFilter = NearestFilter;
  2329. this.minFilter = NearestFilter;
  2330. this.wrapR = ClampToEdgeWrapping;
  2331. this.generateMipmaps = false;
  2332. this.flipY = false;
  2333. this.unpackAlignment = 1;
  2334. }
  2335. }
  2336. class WebGL3DRenderTarget extends WebGLRenderTarget {
  2337. constructor(width = 1, height = 1, depth = 1) {
  2338. super(width, height);
  2339. this.isWebGL3DRenderTarget = true;
  2340. this.depth = depth;
  2341. this.texture = new Data3DTexture(null, width, height, depth);
  2342. this.texture.isRenderTargetTexture = true;
  2343. }
  2344. }
  2345. class WebGLMultipleRenderTargets extends WebGLRenderTarget {
  2346. constructor(width = 1, height = 1, count = 1, options = {}) {
  2347. super(width, height, options);
  2348. this.isWebGLMultipleRenderTargets = true;
  2349. const texture = this.texture;
  2350. this.texture = [];
  2351. for (let i = 0; i < count; i++) {
  2352. this.texture[i] = texture.clone();
  2353. this.texture[i].isRenderTargetTexture = true;
  2354. }
  2355. }
  2356. setSize(width, height, depth = 1) {
  2357. if (this.width !== width || this.height !== height || this.depth !== depth) {
  2358. this.width = width;
  2359. this.height = height;
  2360. this.depth = depth;
  2361. for (let i = 0, il = this.texture.length; i < il; i++) {
  2362. this.texture[i].image.width = width;
  2363. this.texture[i].image.height = height;
  2364. this.texture[i].image.depth = depth;
  2365. }
  2366. this.dispose();
  2367. }
  2368. this.viewport.set(0, 0, width, height);
  2369. this.scissor.set(0, 0, width, height);
  2370. return this;
  2371. }
  2372. copy(source) {
  2373. this.dispose();
  2374. this.width = source.width;
  2375. this.height = source.height;
  2376. this.depth = source.depth;
  2377. this.viewport.set(0, 0, this.width, this.height);
  2378. this.scissor.set(0, 0, this.width, this.height);
  2379. this.depthBuffer = source.depthBuffer;
  2380. this.stencilBuffer = source.stencilBuffer;
  2381. if (source.depthTexture !== null) this.depthTexture = source.depthTexture.clone();
  2382. this.texture.length = 0;
  2383. for (let i = 0, il = source.texture.length; i < il; i++) {
  2384. this.texture[i] = source.texture[i].clone();
  2385. this.texture[i].isRenderTargetTexture = true;
  2386. }
  2387. return this;
  2388. }
  2389. }
  2390. class Quaternion {
  2391. constructor(x = 0, y = 0, z = 0, w = 1) {
  2392. this.isQuaternion = true;
  2393. this._x = x;
  2394. this._y = y;
  2395. this._z = z;
  2396. this._w = w;
  2397. }
  2398. static slerpFlat(dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t) {
  2399. // fuzz-free, array-based Quaternion SLERP operation
  2400. let x0 = src0[srcOffset0 + 0],
  2401. y0 = src0[srcOffset0 + 1],
  2402. z0 = src0[srcOffset0 + 2],
  2403. w0 = src0[srcOffset0 + 3];
  2404. const x1 = src1[srcOffset1 + 0],
  2405. y1 = src1[srcOffset1 + 1],
  2406. z1 = src1[srcOffset1 + 2],
  2407. w1 = src1[srcOffset1 + 3];
  2408. if (t === 0) {
  2409. dst[dstOffset + 0] = x0;
  2410. dst[dstOffset + 1] = y0;
  2411. dst[dstOffset + 2] = z0;
  2412. dst[dstOffset + 3] = w0;
  2413. return;
  2414. }
  2415. if (t === 1) {
  2416. dst[dstOffset + 0] = x1;
  2417. dst[dstOffset + 1] = y1;
  2418. dst[dstOffset + 2] = z1;
  2419. dst[dstOffset + 3] = w1;
  2420. return;
  2421. }
  2422. if (w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1) {
  2423. let s = 1 - t;
  2424. const cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1,
  2425. dir = cos >= 0 ? 1 : -1,
  2426. sqrSin = 1 - cos * cos;
  2427. // Skip the Slerp for tiny steps to avoid numeric problems:
  2428. if (sqrSin > Number.EPSILON) {
  2429. const sin = Math.sqrt(sqrSin),
  2430. len = Math.atan2(sin, cos * dir);
  2431. s = Math.sin(s * len) / sin;
  2432. t = Math.sin(t * len) / sin;
  2433. }
  2434. const tDir = t * dir;
  2435. x0 = x0 * s + x1 * tDir;
  2436. y0 = y0 * s + y1 * tDir;
  2437. z0 = z0 * s + z1 * tDir;
  2438. w0 = w0 * s + w1 * tDir;
  2439. // Normalize in case we just did a lerp:
  2440. if (s === 1 - t) {
  2441. const f = 1 / Math.sqrt(x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0);
  2442. x0 *= f;
  2443. y0 *= f;
  2444. z0 *= f;
  2445. w0 *= f;
  2446. }
  2447. }
  2448. dst[dstOffset] = x0;
  2449. dst[dstOffset + 1] = y0;
  2450. dst[dstOffset + 2] = z0;
  2451. dst[dstOffset + 3] = w0;
  2452. }
  2453. static multiplyQuaternionsFlat(dst, dstOffset, src0, srcOffset0, src1, srcOffset1) {
  2454. const x0 = src0[srcOffset0];
  2455. const y0 = src0[srcOffset0 + 1];
  2456. const z0 = src0[srcOffset0 + 2];
  2457. const w0 = src0[srcOffset0 + 3];
  2458. const x1 = src1[srcOffset1];
  2459. const y1 = src1[srcOffset1 + 1];
  2460. const z1 = src1[srcOffset1 + 2];
  2461. const w1 = src1[srcOffset1 + 3];
  2462. dst[dstOffset] = x0 * w1 + w0 * x1 + y0 * z1 - z0 * y1;
  2463. dst[dstOffset + 1] = y0 * w1 + w0 * y1 + z0 * x1 - x0 * z1;
  2464. dst[dstOffset + 2] = z0 * w1 + w0 * z1 + x0 * y1 - y0 * x1;
  2465. dst[dstOffset + 3] = w0 * w1 - x0 * x1 - y0 * y1 - z0 * z1;
  2466. return dst;
  2467. }
  2468. get x() {
  2469. return this._x;
  2470. }
  2471. set x(value) {
  2472. this._x = value;
  2473. this._onChangeCallback();
  2474. }
  2475. get y() {
  2476. return this._y;
  2477. }
  2478. set y(value) {
  2479. this._y = value;
  2480. this._onChangeCallback();
  2481. }
  2482. get z() {
  2483. return this._z;
  2484. }
  2485. set z(value) {
  2486. this._z = value;
  2487. this._onChangeCallback();
  2488. }
  2489. get w() {
  2490. return this._w;
  2491. }
  2492. set w(value) {
  2493. this._w = value;
  2494. this._onChangeCallback();
  2495. }
  2496. set(x, y, z, w) {
  2497. this._x = x;
  2498. this._y = y;
  2499. this._z = z;
  2500. this._w = w;
  2501. this._onChangeCallback();
  2502. return this;
  2503. }
  2504. clone() {
  2505. return new this.constructor(this._x, this._y, this._z, this._w);
  2506. }
  2507. copy(quaternion) {
  2508. this._x = quaternion.x;
  2509. this._y = quaternion.y;
  2510. this._z = quaternion.z;
  2511. this._w = quaternion.w;
  2512. this._onChangeCallback();
  2513. return this;
  2514. }
  2515. setFromEuler(euler, update) {
  2516. const x = euler._x,
  2517. y = euler._y,
  2518. z = euler._z,
  2519. order = euler._order;
  2520. // http://www.mathworks.com/matlabcentral/fileexchange/
  2521. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  2522. // content/SpinCalc.m
  2523. const cos = Math.cos;
  2524. const sin = Math.sin;
  2525. const c1 = cos(x / 2);
  2526. const c2 = cos(y / 2);
  2527. const c3 = cos(z / 2);
  2528. const s1 = sin(x / 2);
  2529. const s2 = sin(y / 2);
  2530. const s3 = sin(z / 2);
  2531. switch (order) {
  2532. case 'XYZ':
  2533. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  2534. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  2535. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  2536. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  2537. break;
  2538. case 'YXZ':
  2539. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  2540. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  2541. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  2542. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  2543. break;
  2544. case 'ZXY':
  2545. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  2546. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  2547. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  2548. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  2549. break;
  2550. case 'ZYX':
  2551. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  2552. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  2553. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  2554. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  2555. break;
  2556. case 'YZX':
  2557. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  2558. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  2559. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  2560. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  2561. break;
  2562. case 'XZY':
  2563. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  2564. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  2565. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  2566. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  2567. break;
  2568. default:
  2569. console.warn('THREE.Quaternion: .setFromEuler() encountered an unknown order: ' + order);
  2570. }
  2571. if (update !== false) this._onChangeCallback();
  2572. return this;
  2573. }
  2574. setFromAxisAngle(axis, angle) {
  2575. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  2576. // assumes axis is normalized
  2577. const halfAngle = angle / 2,
  2578. s = Math.sin(halfAngle);
  2579. this._x = axis.x * s;
  2580. this._y = axis.y * s;
  2581. this._z = axis.z * s;
  2582. this._w = Math.cos(halfAngle);
  2583. this._onChangeCallback();
  2584. return this;
  2585. }
  2586. setFromRotationMatrix(m) {
  2587. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  2588. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  2589. const te = m.elements,
  2590. m11 = te[0],
  2591. m12 = te[4],
  2592. m13 = te[8],
  2593. m21 = te[1],
  2594. m22 = te[5],
  2595. m23 = te[9],
  2596. m31 = te[2],
  2597. m32 = te[6],
  2598. m33 = te[10],
  2599. trace = m11 + m22 + m33;
  2600. if (trace > 0) {
  2601. const s = 0.5 / Math.sqrt(trace + 1.0);
  2602. this._w = 0.25 / s;
  2603. this._x = (m32 - m23) * s;
  2604. this._y = (m13 - m31) * s;
  2605. this._z = (m21 - m12) * s;
  2606. } else if (m11 > m22 && m11 > m33) {
  2607. const s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  2608. this._w = (m32 - m23) / s;
  2609. this._x = 0.25 * s;
  2610. this._y = (m12 + m21) / s;
  2611. this._z = (m13 + m31) / s;
  2612. } else if (m22 > m33) {
  2613. const s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  2614. this._w = (m13 - m31) / s;
  2615. this._x = (m12 + m21) / s;
  2616. this._y = 0.25 * s;
  2617. this._z = (m23 + m32) / s;
  2618. } else {
  2619. const s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  2620. this._w = (m21 - m12) / s;
  2621. this._x = (m13 + m31) / s;
  2622. this._y = (m23 + m32) / s;
  2623. this._z = 0.25 * s;
  2624. }
  2625. this._onChangeCallback();
  2626. return this;
  2627. }
  2628. setFromUnitVectors(vFrom, vTo) {
  2629. // assumes direction vectors vFrom and vTo are normalized
  2630. let r = vFrom.dot(vTo) + 1;
  2631. if (r < Number.EPSILON) {
  2632. // vFrom and vTo point in opposite directions
  2633. r = 0;
  2634. if (Math.abs(vFrom.x) > Math.abs(vFrom.z)) {
  2635. this._x = -vFrom.y;
  2636. this._y = vFrom.x;
  2637. this._z = 0;
  2638. this._w = r;
  2639. } else {
  2640. this._x = 0;
  2641. this._y = -vFrom.z;
  2642. this._z = vFrom.y;
  2643. this._w = r;
  2644. }
  2645. } else {
  2646. // crossVectors( vFrom, vTo ); // inlined to avoid cyclic dependency on Vector3
  2647. this._x = vFrom.y * vTo.z - vFrom.z * vTo.y;
  2648. this._y = vFrom.z * vTo.x - vFrom.x * vTo.z;
  2649. this._z = vFrom.x * vTo.y - vFrom.y * vTo.x;
  2650. this._w = r;
  2651. }
  2652. return this.normalize();
  2653. }
  2654. angleTo(q) {
  2655. return 2 * Math.acos(Math.abs(clamp(this.dot(q), -1, 1)));
  2656. }
  2657. rotateTowards(q, step) {
  2658. const angle = this.angleTo(q);
  2659. if (angle === 0) return this;
  2660. const t = Math.min(1, step / angle);
  2661. this.slerp(q, t);
  2662. return this;
  2663. }
  2664. identity() {
  2665. return this.set(0, 0, 0, 1);
  2666. }
  2667. invert() {
  2668. // quaternion is assumed to have unit length
  2669. return this.conjugate();
  2670. }
  2671. conjugate() {
  2672. this._x *= -1;
  2673. this._y *= -1;
  2674. this._z *= -1;
  2675. this._onChangeCallback();
  2676. return this;
  2677. }
  2678. dot(v) {
  2679. return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w;
  2680. }
  2681. lengthSq() {
  2682. return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  2683. }
  2684. length() {
  2685. return Math.sqrt(this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w);
  2686. }
  2687. normalize() {
  2688. let l = this.length();
  2689. if (l === 0) {
  2690. this._x = 0;
  2691. this._y = 0;
  2692. this._z = 0;
  2693. this._w = 1;
  2694. } else {
  2695. l = 1 / l;
  2696. this._x = this._x * l;
  2697. this._y = this._y * l;
  2698. this._z = this._z * l;
  2699. this._w = this._w * l;
  2700. }
  2701. this._onChangeCallback();
  2702. return this;
  2703. }
  2704. multiply(q) {
  2705. return this.multiplyQuaternions(this, q);
  2706. }
  2707. premultiply(q) {
  2708. return this.multiplyQuaternions(q, this);
  2709. }
  2710. multiplyQuaternions(a, b) {
  2711. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  2712. const qax = a._x,
  2713. qay = a._y,
  2714. qaz = a._z,
  2715. qaw = a._w;
  2716. const qbx = b._x,
  2717. qby = b._y,
  2718. qbz = b._z,
  2719. qbw = b._w;
  2720. this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  2721. this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  2722. this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  2723. this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  2724. this._onChangeCallback();
  2725. return this;
  2726. }
  2727. slerp(qb, t) {
  2728. if (t === 0) return this;
  2729. if (t === 1) return this.copy(qb);
  2730. const x = this._x,
  2731. y = this._y,
  2732. z = this._z,
  2733. w = this._w;
  2734. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  2735. let cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z;
  2736. if (cosHalfTheta < 0) {
  2737. this._w = -qb._w;
  2738. this._x = -qb._x;
  2739. this._y = -qb._y;
  2740. this._z = -qb._z;
  2741. cosHalfTheta = -cosHalfTheta;
  2742. } else {
  2743. this.copy(qb);
  2744. }
  2745. if (cosHalfTheta >= 1.0) {
  2746. this._w = w;
  2747. this._x = x;
  2748. this._y = y;
  2749. this._z = z;
  2750. return this;
  2751. }
  2752. const sqrSinHalfTheta = 1.0 - cosHalfTheta * cosHalfTheta;
  2753. if (sqrSinHalfTheta <= Number.EPSILON) {
  2754. const s = 1 - t;
  2755. this._w = s * w + t * this._w;
  2756. this._x = s * x + t * this._x;
  2757. this._y = s * y + t * this._y;
  2758. this._z = s * z + t * this._z;
  2759. this.normalize();
  2760. this._onChangeCallback();
  2761. return this;
  2762. }
  2763. const sinHalfTheta = Math.sqrt(sqrSinHalfTheta);
  2764. const halfTheta = Math.atan2(sinHalfTheta, cosHalfTheta);
  2765. const ratioA = Math.sin((1 - t) * halfTheta) / sinHalfTheta,
  2766. ratioB = Math.sin(t * halfTheta) / sinHalfTheta;
  2767. this._w = w * ratioA + this._w * ratioB;
  2768. this._x = x * ratioA + this._x * ratioB;
  2769. this._y = y * ratioA + this._y * ratioB;
  2770. this._z = z * ratioA + this._z * ratioB;
  2771. this._onChangeCallback();
  2772. return this;
  2773. }
  2774. slerpQuaternions(qa, qb, t) {
  2775. return this.copy(qa).slerp(qb, t);
  2776. }
  2777. random() {
  2778. // Derived from http://planning.cs.uiuc.edu/node198.html
  2779. // Note, this source uses w, x, y, z ordering,
  2780. // so we swap the order below.
  2781. const u1 = Math.random();
  2782. const sqrt1u1 = Math.sqrt(1 - u1);
  2783. const sqrtu1 = Math.sqrt(u1);
  2784. const u2 = 2 * Math.PI * Math.random();
  2785. const u3 = 2 * Math.PI * Math.random();
  2786. return this.set(sqrt1u1 * Math.cos(u2), sqrtu1 * Math.sin(u3), sqrtu1 * Math.cos(u3), sqrt1u1 * Math.sin(u2));
  2787. }
  2788. equals(quaternion) {
  2789. return quaternion._x === this._x && quaternion._y === this._y && quaternion._z === this._z && quaternion._w === this._w;
  2790. }
  2791. fromArray(array, offset = 0) {
  2792. this._x = array[offset];
  2793. this._y = array[offset + 1];
  2794. this._z = array[offset + 2];
  2795. this._w = array[offset + 3];
  2796. this._onChangeCallback();
  2797. return this;
  2798. }
  2799. toArray(array = [], offset = 0) {
  2800. array[offset] = this._x;
  2801. array[offset + 1] = this._y;
  2802. array[offset + 2] = this._z;
  2803. array[offset + 3] = this._w;
  2804. return array;
  2805. }
  2806. fromBufferAttribute(attribute, index) {
  2807. this._x = attribute.getX(index);
  2808. this._y = attribute.getY(index);
  2809. this._z = attribute.getZ(index);
  2810. this._w = attribute.getW(index);
  2811. return this;
  2812. }
  2813. _onChange(callback) {
  2814. this._onChangeCallback = callback;
  2815. return this;
  2816. }
  2817. _onChangeCallback() {}
  2818. *[Symbol.iterator]() {
  2819. yield this._x;
  2820. yield this._y;
  2821. yield this._z;
  2822. yield this._w;
  2823. }
  2824. }
  2825. class Vector3 {
  2826. constructor(x = 0, y = 0, z = 0) {
  2827. Vector3.prototype.isVector3 = true;
  2828. this.x = x;
  2829. this.y = y;
  2830. this.z = z;
  2831. }
  2832. set(x, y, z) {
  2833. if (z === undefined) z = this.z; // sprite.scale.set(x,y)
  2834. this.x = x;
  2835. this.y = y;
  2836. this.z = z;
  2837. return this;
  2838. }
  2839. setScalar(scalar) {
  2840. this.x = scalar;
  2841. this.y = scalar;
  2842. this.z = scalar;
  2843. return this;
  2844. }
  2845. setX(x) {
  2846. this.x = x;
  2847. return this;
  2848. }
  2849. setY(y) {
  2850. this.y = y;
  2851. return this;
  2852. }
  2853. setZ(z) {
  2854. this.z = z;
  2855. return this;
  2856. }
  2857. setComponent(index, value) {
  2858. switch (index) {
  2859. case 0:
  2860. this.x = value;
  2861. break;
  2862. case 1:
  2863. this.y = value;
  2864. break;
  2865. case 2:
  2866. this.z = value;
  2867. break;
  2868. default:
  2869. throw new Error('index is out of range: ' + index);
  2870. }
  2871. return this;
  2872. }
  2873. getComponent(index) {
  2874. switch (index) {
  2875. case 0:
  2876. return this.x;
  2877. case 1:
  2878. return this.y;
  2879. case 2:
  2880. return this.z;
  2881. default:
  2882. throw new Error('index is out of range: ' + index);
  2883. }
  2884. }
  2885. clone() {
  2886. return new this.constructor(this.x, this.y, this.z);
  2887. }
  2888. copy(v) {
  2889. this.x = v.x;
  2890. this.y = v.y;
  2891. this.z = v.z;
  2892. return this;
  2893. }
  2894. add(v) {
  2895. this.x += v.x;
  2896. this.y += v.y;
  2897. this.z += v.z;
  2898. return this;
  2899. }
  2900. addScalar(s) {
  2901. this.x += s;
  2902. this.y += s;
  2903. this.z += s;
  2904. return this;
  2905. }
  2906. addVectors(a, b) {
  2907. this.x = a.x + b.x;
  2908. this.y = a.y + b.y;
  2909. this.z = a.z + b.z;
  2910. return this;
  2911. }
  2912. addScaledVector(v, s) {
  2913. this.x += v.x * s;
  2914. this.y += v.y * s;
  2915. this.z += v.z * s;
  2916. return this;
  2917. }
  2918. sub(v) {
  2919. this.x -= v.x;
  2920. this.y -= v.y;
  2921. this.z -= v.z;
  2922. return this;
  2923. }
  2924. subScalar(s) {
  2925. this.x -= s;
  2926. this.y -= s;
  2927. this.z -= s;
  2928. return this;
  2929. }
  2930. subVectors(a, b) {
  2931. this.x = a.x - b.x;
  2932. this.y = a.y - b.y;
  2933. this.z = a.z - b.z;
  2934. return this;
  2935. }
  2936. multiply(v) {
  2937. this.x *= v.x;
  2938. this.y *= v.y;
  2939. this.z *= v.z;
  2940. return this;
  2941. }
  2942. multiplyScalar(scalar) {
  2943. this.x *= scalar;
  2944. this.y *= scalar;
  2945. this.z *= scalar;
  2946. return this;
  2947. }
  2948. multiplyVectors(a, b) {
  2949. this.x = a.x * b.x;
  2950. this.y = a.y * b.y;
  2951. this.z = a.z * b.z;
  2952. return this;
  2953. }
  2954. applyEuler(euler) {
  2955. return this.applyQuaternion(_quaternion$4.setFromEuler(euler));
  2956. }
  2957. applyAxisAngle(axis, angle) {
  2958. return this.applyQuaternion(_quaternion$4.setFromAxisAngle(axis, angle));
  2959. }
  2960. applyMatrix3(m) {
  2961. const x = this.x,
  2962. y = this.y,
  2963. z = this.z;
  2964. const e = m.elements;
  2965. this.x = e[0] * x + e[3] * y + e[6] * z;
  2966. this.y = e[1] * x + e[4] * y + e[7] * z;
  2967. this.z = e[2] * x + e[5] * y + e[8] * z;
  2968. return this;
  2969. }
  2970. applyNormalMatrix(m) {
  2971. return this.applyMatrix3(m).normalize();
  2972. }
  2973. applyMatrix4(m) {
  2974. const x = this.x,
  2975. y = this.y,
  2976. z = this.z;
  2977. const e = m.elements;
  2978. const w = 1 / (e[3] * x + e[7] * y + e[11] * z + e[15]);
  2979. this.x = (e[0] * x + e[4] * y + e[8] * z + e[12]) * w;
  2980. this.y = (e[1] * x + e[5] * y + e[9] * z + e[13]) * w;
  2981. this.z = (e[2] * x + e[6] * y + e[10] * z + e[14]) * w;
  2982. return this;
  2983. }
  2984. applyQuaternion(q) {
  2985. const x = this.x,
  2986. y = this.y,
  2987. z = this.z;
  2988. const qx = q.x,
  2989. qy = q.y,
  2990. qz = q.z,
  2991. qw = q.w;
  2992. // calculate quat * vector
  2993. const ix = qw * x + qy * z - qz * y;
  2994. const iy = qw * y + qz * x - qx * z;
  2995. const iz = qw * z + qx * y - qy * x;
  2996. const iw = -qx * x - qy * y - qz * z;
  2997. // calculate result * inverse quat
  2998. this.x = ix * qw + iw * -qx + iy * -qz - iz * -qy;
  2999. this.y = iy * qw + iw * -qy + iz * -qx - ix * -qz;
  3000. this.z = iz * qw + iw * -qz + ix * -qy - iy * -qx;
  3001. return this;
  3002. }
  3003. project(camera) {
  3004. return this.applyMatrix4(camera.matrixWorldInverse).applyMatrix4(camera.projectionMatrix);
  3005. }
  3006. unproject(camera) {
  3007. return this.applyMatrix4(camera.projectionMatrixInverse).applyMatrix4(camera.matrixWorld);
  3008. }
  3009. transformDirection(m) {
  3010. // input: THREE.Matrix4 affine matrix
  3011. // vector interpreted as a direction
  3012. const x = this.x,
  3013. y = this.y,
  3014. z = this.z;
  3015. const e = m.elements;
  3016. this.x = e[0] * x + e[4] * y + e[8] * z;
  3017. this.y = e[1] * x + e[5] * y + e[9] * z;
  3018. this.z = e[2] * x + e[6] * y + e[10] * z;
  3019. return this.normalize();
  3020. }
  3021. divide(v) {
  3022. this.x /= v.x;
  3023. this.y /= v.y;
  3024. this.z /= v.z;
  3025. return this;
  3026. }
  3027. divideScalar(scalar) {
  3028. return this.multiplyScalar(1 / scalar);
  3029. }
  3030. min(v) {
  3031. this.x = Math.min(this.x, v.x);
  3032. this.y = Math.min(this.y, v.y);
  3033. this.z = Math.min(this.z, v.z);
  3034. return this;
  3035. }
  3036. max(v) {
  3037. this.x = Math.max(this.x, v.x);
  3038. this.y = Math.max(this.y, v.y);
  3039. this.z = Math.max(this.z, v.z);
  3040. return this;
  3041. }
  3042. clamp(min, max) {
  3043. // assumes min < max, componentwise
  3044. this.x = Math.max(min.x, Math.min(max.x, this.x));
  3045. this.y = Math.max(min.y, Math.min(max.y, this.y));
  3046. this.z = Math.max(min.z, Math.min(max.z, this.z));
  3047. return this;
  3048. }
  3049. clampScalar(minVal, maxVal) {
  3050. this.x = Math.max(minVal, Math.min(maxVal, this.x));
  3051. this.y = Math.max(minVal, Math.min(maxVal, this.y));
  3052. this.z = Math.max(minVal, Math.min(maxVal, this.z));
  3053. return this;
  3054. }
  3055. clampLength(min, max) {
  3056. const length = this.length();
  3057. return this.divideScalar(length || 1).multiplyScalar(Math.max(min, Math.min(max, length)));
  3058. }
  3059. floor() {
  3060. this.x = Math.floor(this.x);
  3061. this.y = Math.floor(this.y);
  3062. this.z = Math.floor(this.z);
  3063. return this;
  3064. }
  3065. ceil() {
  3066. this.x = Math.ceil(this.x);
  3067. this.y = Math.ceil(this.y);
  3068. this.z = Math.ceil(this.z);
  3069. return this;
  3070. }
  3071. round() {
  3072. this.x = Math.round(this.x);
  3073. this.y = Math.round(this.y);
  3074. this.z = Math.round(this.z);
  3075. return this;
  3076. }
  3077. roundToZero() {
  3078. this.x = this.x < 0 ? Math.ceil(this.x) : Math.floor(this.x);
  3079. this.y = this.y < 0 ? Math.ceil(this.y) : Math.floor(this.y);
  3080. this.z = this.z < 0 ? Math.ceil(this.z) : Math.floor(this.z);
  3081. return this;
  3082. }
  3083. negate() {
  3084. this.x = -this.x;
  3085. this.y = -this.y;
  3086. this.z = -this.z;
  3087. return this;
  3088. }
  3089. dot(v) {
  3090. return this.x * v.x + this.y * v.y + this.z * v.z;
  3091. }
  3092. // TODO lengthSquared?
  3093. lengthSq() {
  3094. return this.x * this.x + this.y * this.y + this.z * this.z;
  3095. }
  3096. length() {
  3097. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  3098. }
  3099. manhattanLength() {
  3100. return Math.abs(this.x) + Math.abs(this.y) + Math.abs(this.z);
  3101. }
  3102. normalize() {
  3103. return this.divideScalar(this.length() || 1);
  3104. }
  3105. setLength(length) {
  3106. return this.normalize().multiplyScalar(length);
  3107. }
  3108. lerp(v, alpha) {
  3109. this.x += (v.x - this.x) * alpha;
  3110. this.y += (v.y - this.y) * alpha;
  3111. this.z += (v.z - this.z) * alpha;
  3112. return this;
  3113. }
  3114. lerpVectors(v1, v2, alpha) {
  3115. this.x = v1.x + (v2.x - v1.x) * alpha;
  3116. this.y = v1.y + (v2.y - v1.y) * alpha;
  3117. this.z = v1.z + (v2.z - v1.z) * alpha;
  3118. return this;
  3119. }
  3120. cross(v) {
  3121. return this.crossVectors(this, v);
  3122. }
  3123. crossVectors(a, b) {
  3124. const ax = a.x,
  3125. ay = a.y,
  3126. az = a.z;
  3127. const bx = b.x,
  3128. by = b.y,
  3129. bz = b.z;
  3130. this.x = ay * bz - az * by;
  3131. this.y = az * bx - ax * bz;
  3132. this.z = ax * by - ay * bx;
  3133. return this;
  3134. }
  3135. projectOnVector(v) {
  3136. const denominator = v.lengthSq();
  3137. if (denominator === 0) return this.set(0, 0, 0);
  3138. const scalar = v.dot(this) / denominator;
  3139. return this.copy(v).multiplyScalar(scalar);
  3140. }
  3141. projectOnPlane(planeNormal) {
  3142. _vector$c.copy(this).projectOnVector(planeNormal);
  3143. return this.sub(_vector$c);
  3144. }
  3145. reflect(normal) {
  3146. // reflect incident vector off plane orthogonal to normal
  3147. // normal is assumed to have unit length
  3148. return this.sub(_vector$c.copy(normal).multiplyScalar(2 * this.dot(normal)));
  3149. }
  3150. angleTo(v) {
  3151. const denominator = Math.sqrt(this.lengthSq() * v.lengthSq());
  3152. if (denominator === 0) return Math.PI / 2;
  3153. const theta = this.dot(v) / denominator;
  3154. // clamp, to handle numerical problems
  3155. return Math.acos(clamp(theta, -1, 1));
  3156. }
  3157. distanceTo(v) {
  3158. return Math.sqrt(this.distanceToSquared(v));
  3159. }
  3160. distanceToSquared(v) {
  3161. const dx = this.x - v.x,
  3162. dy = this.y - v.y,
  3163. dz = this.z - v.z;
  3164. return dx * dx + dy * dy + dz * dz;
  3165. }
  3166. manhattanDistanceTo(v) {
  3167. return Math.abs(this.x - v.x) + Math.abs(this.y - v.y) + Math.abs(this.z - v.z);
  3168. }
  3169. setFromSpherical(s) {
  3170. return this.setFromSphericalCoords(s.radius, s.phi, s.theta);
  3171. }
  3172. setFromSphericalCoords(radius, phi, theta) {
  3173. const sinPhiRadius = Math.sin(phi) * radius;
  3174. this.x = sinPhiRadius * Math.sin(theta);
  3175. this.y = Math.cos(phi) * radius;
  3176. this.z = sinPhiRadius * Math.cos(theta);
  3177. return this;
  3178. }
  3179. setFromCylindrical(c) {
  3180. return this.setFromCylindricalCoords(c.radius, c.theta, c.y);
  3181. }
  3182. setFromCylindricalCoords(radius, theta, y) {
  3183. this.x = radius * Math.sin(theta);
  3184. this.y = y;
  3185. this.z = radius * Math.cos(theta);
  3186. return this;
  3187. }
  3188. setFromMatrixPosition(m) {
  3189. const e = m.elements;
  3190. this.x = e[12];
  3191. this.y = e[13];
  3192. this.z = e[14];
  3193. return this;
  3194. }
  3195. setFromMatrixScale(m) {
  3196. const sx = this.setFromMatrixColumn(m, 0).length();
  3197. const sy = this.setFromMatrixColumn(m, 1).length();
  3198. const sz = this.setFromMatrixColumn(m, 2).length();
  3199. this.x = sx;
  3200. this.y = sy;
  3201. this.z = sz;
  3202. return this;
  3203. }
  3204. setFromMatrixColumn(m, index) {
  3205. return this.fromArray(m.elements, index * 4);
  3206. }
  3207. setFromMatrix3Column(m, index) {
  3208. return this.fromArray(m.elements, index * 3);
  3209. }
  3210. setFromEuler(e) {
  3211. this.x = e._x;
  3212. this.y = e._y;
  3213. this.z = e._z;
  3214. return this;
  3215. }
  3216. equals(v) {
  3217. return v.x === this.x && v.y === this.y && v.z === this.z;
  3218. }
  3219. fromArray(array, offset = 0) {
  3220. this.x = array[offset];
  3221. this.y = array[offset + 1];
  3222. this.z = array[offset + 2];
  3223. return this;
  3224. }
  3225. toArray(array = [], offset = 0) {
  3226. array[offset] = this.x;
  3227. array[offset + 1] = this.y;
  3228. array[offset + 2] = this.z;
  3229. return array;
  3230. }
  3231. fromBufferAttribute(attribute, index) {
  3232. this.x = attribute.getX(index);
  3233. this.y = attribute.getY(index);
  3234. this.z = attribute.getZ(index);
  3235. return this;
  3236. }
  3237. random() {
  3238. this.x = Math.random();
  3239. this.y = Math.random();
  3240. this.z = Math.random();
  3241. return this;
  3242. }
  3243. randomDirection() {
  3244. // Derived from https://mathworld.wolfram.com/SpherePointPicking.html
  3245. const u = (Math.random() - 0.5) * 2;
  3246. const t = Math.random() * Math.PI * 2;
  3247. const f = Math.sqrt(1 - u ** 2);
  3248. this.x = f * Math.cos(t);
  3249. this.y = f * Math.sin(t);
  3250. this.z = u;
  3251. return this;
  3252. }
  3253. *[Symbol.iterator]() {
  3254. yield this.x;
  3255. yield this.y;
  3256. yield this.z;
  3257. }
  3258. }
  3259. const _vector$c = /*@__PURE__*/new Vector3();
  3260. const _quaternion$4 = /*@__PURE__*/new Quaternion();
  3261. class Box3 {
  3262. constructor(min = new Vector3(+Infinity, +Infinity, +Infinity), max = new Vector3(-Infinity, -Infinity, -Infinity)) {
  3263. this.isBox3 = true;
  3264. this.min = min;
  3265. this.max = max;
  3266. }
  3267. set(min, max) {
  3268. this.min.copy(min);
  3269. this.max.copy(max);
  3270. return this;
  3271. }
  3272. setFromArray(array) {
  3273. let minX = +Infinity;
  3274. let minY = +Infinity;
  3275. let minZ = +Infinity;
  3276. let maxX = -Infinity;
  3277. let maxY = -Infinity;
  3278. let maxZ = -Infinity;
  3279. for (let i = 0, l = array.length; i < l; i += 3) {
  3280. const x = array[i];
  3281. const y = array[i + 1];
  3282. const z = array[i + 2];
  3283. if (x < minX) minX = x;
  3284. if (y < minY) minY = y;
  3285. if (z < minZ) minZ = z;
  3286. if (x > maxX) maxX = x;
  3287. if (y > maxY) maxY = y;
  3288. if (z > maxZ) maxZ = z;
  3289. }
  3290. this.min.set(minX, minY, minZ);
  3291. this.max.set(maxX, maxY, maxZ);
  3292. return this;
  3293. }
  3294. setFromBufferAttribute(attribute) {
  3295. let minX = +Infinity;
  3296. let minY = +Infinity;
  3297. let minZ = +Infinity;
  3298. let maxX = -Infinity;
  3299. let maxY = -Infinity;
  3300. let maxZ = -Infinity;
  3301. for (let i = 0, l = attribute.count; i < l; i++) {
  3302. const x = attribute.getX(i);
  3303. const y = attribute.getY(i);
  3304. const z = attribute.getZ(i);
  3305. if (x < minX) minX = x;
  3306. if (y < minY) minY = y;
  3307. if (z < minZ) minZ = z;
  3308. if (x > maxX) maxX = x;
  3309. if (y > maxY) maxY = y;
  3310. if (z > maxZ) maxZ = z;
  3311. }
  3312. this.min.set(minX, minY, minZ);
  3313. this.max.set(maxX, maxY, maxZ);
  3314. return this;
  3315. }
  3316. setFromPoints(points) {
  3317. this.makeEmpty();
  3318. for (let i = 0, il = points.length; i < il; i++) {
  3319. this.expandByPoint(points[i]);
  3320. }
  3321. return this;
  3322. }
  3323. setFromCenterAndSize(center, size) {
  3324. const halfSize = _vector$b.copy(size).multiplyScalar(0.5);
  3325. this.min.copy(center).sub(halfSize);
  3326. this.max.copy(center).add(halfSize);
  3327. return this;
  3328. }
  3329. setFromObject(object, precise = false) {
  3330. this.makeEmpty();
  3331. return this.expandByObject(object, precise);
  3332. }
  3333. clone() {
  3334. return new this.constructor().copy(this);
  3335. }
  3336. copy(box) {
  3337. this.min.copy(box.min);
  3338. this.max.copy(box.max);
  3339. return this;
  3340. }
  3341. makeEmpty() {
  3342. this.min.x = this.min.y = this.min.z = +Infinity;
  3343. this.max.x = this.max.y = this.max.z = -Infinity;
  3344. return this;
  3345. }
  3346. isEmpty() {
  3347. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  3348. return this.max.x < this.min.x || this.max.y < this.min.y || this.max.z < this.min.z;
  3349. }
  3350. getCenter(target) {
  3351. return this.isEmpty() ? target.set(0, 0, 0) : target.addVectors(this.min, this.max).multiplyScalar(0.5);
  3352. }
  3353. getSize(target) {
  3354. return this.isEmpty() ? target.set(0, 0, 0) : target.subVectors(this.max, this.min);
  3355. }
  3356. expandByPoint(point) {
  3357. this.min.min(point);
  3358. this.max.max(point);
  3359. return this;
  3360. }
  3361. expandByVector(vector) {
  3362. this.min.sub(vector);
  3363. this.max.add(vector);
  3364. return this;
  3365. }
  3366. expandByScalar(scalar) {
  3367. this.min.addScalar(-scalar);
  3368. this.max.addScalar(scalar);
  3369. return this;
  3370. }
  3371. expandByObject(object, precise = false) {
  3372. // Computes the world-axis-aligned bounding box of an object (including its children),
  3373. // accounting for both the object's, and children's, world transforms
  3374. object.updateWorldMatrix(false, false);
  3375. const geometry = object.geometry;
  3376. if (geometry !== undefined) {
  3377. if (precise && geometry.attributes != undefined && geometry.attributes.position !== undefined) {
  3378. const position = geometry.attributes.position;
  3379. for (let i = 0, l = position.count; i < l; i++) {
  3380. _vector$b.fromBufferAttribute(position, i).applyMatrix4(object.matrixWorld);
  3381. this.expandByPoint(_vector$b);
  3382. }
  3383. } else {
  3384. if (geometry.boundingBox === null) {
  3385. geometry.computeBoundingBox();
  3386. }
  3387. _box$3.copy(geometry.boundingBox);
  3388. _box$3.applyMatrix4(object.matrixWorld);
  3389. this.union(_box$3);
  3390. }
  3391. }
  3392. const children = object.children;
  3393. for (let i = 0, l = children.length; i < l; i++) {
  3394. this.expandByObject(children[i], precise);
  3395. }
  3396. return this;
  3397. }
  3398. containsPoint(point) {
  3399. 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;
  3400. }
  3401. containsBox(box) {
  3402. 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;
  3403. }
  3404. getParameter(point, target) {
  3405. // This can potentially have a divide by zero if the box
  3406. // has a size dimension of 0.
  3407. 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));
  3408. }
  3409. intersectsBox(box) {
  3410. // using 6 splitting planes to rule out intersections.
  3411. 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;
  3412. }
  3413. intersectsSphere(sphere) {
  3414. // Find the point on the AABB closest to the sphere center.
  3415. this.clampPoint(sphere.center, _vector$b);
  3416. // If that point is inside the sphere, the AABB and sphere intersect.
  3417. return _vector$b.distanceToSquared(sphere.center) <= sphere.radius * sphere.radius;
  3418. }
  3419. intersectsPlane(plane) {
  3420. // We compute the minimum and maximum dot product values. If those values
  3421. // are on the same side (back or front) of the plane, then there is no intersection.
  3422. let min, max;
  3423. if (plane.normal.x > 0) {
  3424. min = plane.normal.x * this.min.x;
  3425. max = plane.normal.x * this.max.x;
  3426. } else {
  3427. min = plane.normal.x * this.max.x;
  3428. max = plane.normal.x * this.min.x;
  3429. }
  3430. if (plane.normal.y > 0) {
  3431. min += plane.normal.y * this.min.y;
  3432. max += plane.normal.y * this.max.y;
  3433. } else {
  3434. min += plane.normal.y * this.max.y;
  3435. max += plane.normal.y * this.min.y;
  3436. }
  3437. if (plane.normal.z > 0) {
  3438. min += plane.normal.z * this.min.z;
  3439. max += plane.normal.z * this.max.z;
  3440. } else {
  3441. min += plane.normal.z * this.max.z;
  3442. max += plane.normal.z * this.min.z;
  3443. }
  3444. return min <= -plane.constant && max >= -plane.constant;
  3445. }
  3446. intersectsTriangle(triangle) {
  3447. if (this.isEmpty()) {
  3448. return false;
  3449. }
  3450. // compute box center and extents
  3451. this.getCenter(_center);
  3452. _extents.subVectors(this.max, _center);
  3453. // translate triangle to aabb origin
  3454. _v0$2.subVectors(triangle.a, _center);
  3455. _v1$7.subVectors(triangle.b, _center);
  3456. _v2$4.subVectors(triangle.c, _center);
  3457. // compute edge vectors for triangle
  3458. _f0.subVectors(_v1$7, _v0$2);
  3459. _f1.subVectors(_v2$4, _v1$7);
  3460. _f2.subVectors(_v0$2, _v2$4);
  3461. // test against axes that are given by cross product combinations of the edges of the triangle and the edges of the aabb
  3462. // 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
  3463. // axis_ij = u_i x f_j (u0, u1, u2 = face normals of aabb = x,y,z axes vectors since aabb is axis aligned)
  3464. 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];
  3465. if (!satForAxes(axes, _v0$2, _v1$7, _v2$4, _extents)) {
  3466. return false;
  3467. }
  3468. // test 3 face normals from the aabb
  3469. axes = [1, 0, 0, 0, 1, 0, 0, 0, 1];
  3470. if (!satForAxes(axes, _v0$2, _v1$7, _v2$4, _extents)) {
  3471. return false;
  3472. }
  3473. // finally testing the face normal of the triangle
  3474. // use already existing triangle edge vectors here
  3475. _triangleNormal.crossVectors(_f0, _f1);
  3476. axes = [_triangleNormal.x, _triangleNormal.y, _triangleNormal.z];
  3477. return satForAxes(axes, _v0$2, _v1$7, _v2$4, _extents);
  3478. }
  3479. clampPoint(point, target) {
  3480. return target.copy(point).clamp(this.min, this.max);
  3481. }
  3482. distanceToPoint(point) {
  3483. const clampedPoint = _vector$b.copy(point).clamp(this.min, this.max);
  3484. return clampedPoint.sub(point).length();
  3485. }
  3486. getBoundingSphere(target) {
  3487. this.getCenter(target.center);
  3488. target.radius = this.getSize(_vector$b).length() * 0.5;
  3489. return target;
  3490. }
  3491. intersect(box) {
  3492. this.min.max(box.min);
  3493. this.max.min(box.max);
  3494. // 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.
  3495. if (this.isEmpty()) this.makeEmpty();
  3496. return this;
  3497. }
  3498. union(box) {
  3499. this.min.min(box.min);
  3500. this.max.max(box.max);
  3501. return this;
  3502. }
  3503. applyMatrix4(matrix) {
  3504. // transform of empty box is an empty box.
  3505. if (this.isEmpty()) return this;
  3506. // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  3507. _points[0].set(this.min.x, this.min.y, this.min.z).applyMatrix4(matrix); // 000
  3508. _points[1].set(this.min.x, this.min.y, this.max.z).applyMatrix4(matrix); // 001
  3509. _points[2].set(this.min.x, this.max.y, this.min.z).applyMatrix4(matrix); // 010
  3510. _points[3].set(this.min.x, this.max.y, this.max.z).applyMatrix4(matrix); // 011
  3511. _points[4].set(this.max.x, this.min.y, this.min.z).applyMatrix4(matrix); // 100
  3512. _points[5].set(this.max.x, this.min.y, this.max.z).applyMatrix4(matrix); // 101
  3513. _points[6].set(this.max.x, this.max.y, this.min.z).applyMatrix4(matrix); // 110
  3514. _points[7].set(this.max.x, this.max.y, this.max.z).applyMatrix4(matrix); // 111
  3515. this.setFromPoints(_points);
  3516. return this;
  3517. }
  3518. translate(offset) {
  3519. this.min.add(offset);
  3520. this.max.add(offset);
  3521. return this;
  3522. }
  3523. equals(box) {
  3524. return box.min.equals(this.min) && box.max.equals(this.max);
  3525. }
  3526. }
  3527. 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()];
  3528. const _vector$b = /*@__PURE__*/new Vector3();
  3529. const _box$3 = /*@__PURE__*/new Box3();
  3530. // triangle centered vertices
  3531. const _v0$2 = /*@__PURE__*/new Vector3();
  3532. const _v1$7 = /*@__PURE__*/new Vector3();
  3533. const _v2$4 = /*@__PURE__*/new Vector3();
  3534. // triangle edge vectors
  3535. const _f0 = /*@__PURE__*/new Vector3();
  3536. const _f1 = /*@__PURE__*/new Vector3();
  3537. const _f2 = /*@__PURE__*/new Vector3();
  3538. const _center = /*@__PURE__*/new Vector3();
  3539. const _extents = /*@__PURE__*/new Vector3();
  3540. const _triangleNormal = /*@__PURE__*/new Vector3();
  3541. const _testAxis = /*@__PURE__*/new Vector3();
  3542. function satForAxes(axes, v0, v1, v2, extents) {
  3543. for (let i = 0, j = axes.length - 3; i <= j; i += 3) {
  3544. _testAxis.fromArray(axes, i);
  3545. // project the aabb onto the separating axis
  3546. const r = extents.x * Math.abs(_testAxis.x) + extents.y * Math.abs(_testAxis.y) + extents.z * Math.abs(_testAxis.z);
  3547. // project all 3 vertices of the triangle onto the separating axis
  3548. const p0 = v0.dot(_testAxis);
  3549. const p1 = v1.dot(_testAxis);
  3550. const p2 = v2.dot(_testAxis);
  3551. // actual test, basically see if either of the most extreme of the triangle points intersects r
  3552. if (Math.max(-Math.max(p0, p1, p2), Math.min(p0, p1, p2)) > r) {
  3553. // points of the projected triangle are outside the projected half-length of the aabb
  3554. // the axis is separating and we can exit
  3555. return false;
  3556. }
  3557. }
  3558. return true;
  3559. }
  3560. const _box$2 = /*@__PURE__*/new Box3();
  3561. const _v1$6 = /*@__PURE__*/new Vector3();
  3562. const _v2$3 = /*@__PURE__*/new Vector3();
  3563. class Sphere {
  3564. constructor(center = new Vector3(), radius = -1) {
  3565. this.center = center;
  3566. this.radius = radius;
  3567. }
  3568. set(center, radius) {
  3569. this.center.copy(center);
  3570. this.radius = radius;
  3571. return this;
  3572. }
  3573. setFromPoints(points, optionalCenter) {
  3574. const center = this.center;
  3575. if (optionalCenter !== undefined) {
  3576. center.copy(optionalCenter);
  3577. } else {
  3578. _box$2.setFromPoints(points).getCenter(center);
  3579. }
  3580. let maxRadiusSq = 0;
  3581. for (let i = 0, il = points.length; i < il; i++) {
  3582. maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(points[i]));
  3583. }
  3584. this.radius = Math.sqrt(maxRadiusSq);
  3585. return this;
  3586. }
  3587. copy(sphere) {
  3588. this.center.copy(sphere.center);
  3589. this.radius = sphere.radius;
  3590. return this;
  3591. }
  3592. isEmpty() {
  3593. return this.radius < 0;
  3594. }
  3595. makeEmpty() {
  3596. this.center.set(0, 0, 0);
  3597. this.radius = -1;
  3598. return this;
  3599. }
  3600. containsPoint(point) {
  3601. return point.distanceToSquared(this.center) <= this.radius * this.radius;
  3602. }
  3603. distanceToPoint(point) {
  3604. return point.distanceTo(this.center) - this.radius;
  3605. }
  3606. intersectsSphere(sphere) {
  3607. const radiusSum = this.radius + sphere.radius;
  3608. return sphere.center.distanceToSquared(this.center) <= radiusSum * radiusSum;
  3609. }
  3610. intersectsBox(box) {
  3611. return box.intersectsSphere(this);
  3612. }
  3613. intersectsPlane(plane) {
  3614. return Math.abs(plane.distanceToPoint(this.center)) <= this.radius;
  3615. }
  3616. clampPoint(point, target) {
  3617. const deltaLengthSq = this.center.distanceToSquared(point);
  3618. target.copy(point);
  3619. if (deltaLengthSq > this.radius * this.radius) {
  3620. target.sub(this.center).normalize();
  3621. target.multiplyScalar(this.radius).add(this.center);
  3622. }
  3623. return target;
  3624. }
  3625. getBoundingBox(target) {
  3626. if (this.isEmpty()) {
  3627. // Empty sphere produces empty bounding box
  3628. target.makeEmpty();
  3629. return target;
  3630. }
  3631. target.set(this.center, this.center);
  3632. target.expandByScalar(this.radius);
  3633. return target;
  3634. }
  3635. applyMatrix4(matrix) {
  3636. this.center.applyMatrix4(matrix);
  3637. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  3638. return this;
  3639. }
  3640. translate(offset) {
  3641. this.center.add(offset);
  3642. return this;
  3643. }
  3644. expandByPoint(point) {
  3645. if (this.isEmpty()) {
  3646. this.center.copy(point);
  3647. this.radius = 0;
  3648. return this;
  3649. }
  3650. _v1$6.subVectors(point, this.center);
  3651. const lengthSq = _v1$6.lengthSq();
  3652. if (lengthSq > this.radius * this.radius) {
  3653. // calculate the minimal sphere
  3654. const length = Math.sqrt(lengthSq);
  3655. const delta = (length - this.radius) * 0.5;
  3656. this.center.addScaledVector(_v1$6, delta / length);
  3657. this.radius += delta;
  3658. }
  3659. return this;
  3660. }
  3661. union(sphere) {
  3662. if (sphere.isEmpty()) {
  3663. return this;
  3664. }
  3665. if (this.isEmpty()) {
  3666. this.copy(sphere);
  3667. return this;
  3668. }
  3669. if (this.center.equals(sphere.center) === true) {
  3670. this.radius = Math.max(this.radius, sphere.radius);
  3671. } else {
  3672. _v2$3.subVectors(sphere.center, this.center).setLength(sphere.radius);
  3673. this.expandByPoint(_v1$6.copy(sphere.center).add(_v2$3));
  3674. this.expandByPoint(_v1$6.copy(sphere.center).sub(_v2$3));
  3675. }
  3676. return this;
  3677. }
  3678. equals(sphere) {
  3679. return sphere.center.equals(this.center) && sphere.radius === this.radius;
  3680. }
  3681. clone() {
  3682. return new this.constructor().copy(this);
  3683. }
  3684. }
  3685. const _vector$a = /*@__PURE__*/new Vector3();
  3686. const _segCenter = /*@__PURE__*/new Vector3();
  3687. const _segDir = /*@__PURE__*/new Vector3();
  3688. const _diff = /*@__PURE__*/new Vector3();
  3689. const _edge1 = /*@__PURE__*/new Vector3();
  3690. const _edge2 = /*@__PURE__*/new Vector3();
  3691. const _normal$1 = /*@__PURE__*/new Vector3();
  3692. class Ray {
  3693. constructor(origin = new Vector3(), direction = new Vector3(0, 0, -1)) {
  3694. this.origin = origin;
  3695. this.direction = direction;
  3696. }
  3697. set(origin, direction) {
  3698. this.origin.copy(origin);
  3699. this.direction.copy(direction);
  3700. return this;
  3701. }
  3702. copy(ray) {
  3703. this.origin.copy(ray.origin);
  3704. this.direction.copy(ray.direction);
  3705. return this;
  3706. }
  3707. at(t, target) {
  3708. return target.copy(this.direction).multiplyScalar(t).add(this.origin);
  3709. }
  3710. lookAt(v) {
  3711. this.direction.copy(v).sub(this.origin).normalize();
  3712. return this;
  3713. }
  3714. recast(t) {
  3715. this.origin.copy(this.at(t, _vector$a));
  3716. return this;
  3717. }
  3718. closestPointToPoint(point, target) {
  3719. target.subVectors(point, this.origin);
  3720. const directionDistance = target.dot(this.direction);
  3721. if (directionDistance < 0) {
  3722. return target.copy(this.origin);
  3723. }
  3724. return target.copy(this.direction).multiplyScalar(directionDistance).add(this.origin);
  3725. }
  3726. distanceToPoint(point) {
  3727. return Math.sqrt(this.distanceSqToPoint(point));
  3728. }
  3729. distanceSqToPoint(point) {
  3730. const directionDistance = _vector$a.subVectors(point, this.origin).dot(this.direction);
  3731. // point behind the ray
  3732. if (directionDistance < 0) {
  3733. return this.origin.distanceToSquared(point);
  3734. }
  3735. _vector$a.copy(this.direction).multiplyScalar(directionDistance).add(this.origin);
  3736. return _vector$a.distanceToSquared(point);
  3737. }
  3738. distanceSqToSegment(v0, v1, optionalPointOnRay, optionalPointOnSegment) {
  3739. // from https://github.com/pmjoniak/GeometricTools/blob/master/GTEngine/Include/Mathematics/GteDistRaySegment.h
  3740. // It returns the min distance between the ray and the segment
  3741. // defined by v0 and v1
  3742. // It can also set two optional targets :
  3743. // - The closest point on the ray
  3744. // - The closest point on the segment
  3745. _segCenter.copy(v0).add(v1).multiplyScalar(0.5);
  3746. _segDir.copy(v1).sub(v0).normalize();
  3747. _diff.copy(this.origin).sub(_segCenter);
  3748. const segExtent = v0.distanceTo(v1) * 0.5;
  3749. const a01 = -this.direction.dot(_segDir);
  3750. const b0 = _diff.dot(this.direction);
  3751. const b1 = -_diff.dot(_segDir);
  3752. const c = _diff.lengthSq();
  3753. const det = Math.abs(1 - a01 * a01);
  3754. let s0, s1, sqrDist, extDet;
  3755. if (det > 0) {
  3756. // The ray and segment are not parallel.
  3757. s0 = a01 * b1 - b0;
  3758. s1 = a01 * b0 - b1;
  3759. extDet = segExtent * det;
  3760. if (s0 >= 0) {
  3761. if (s1 >= -extDet) {
  3762. if (s1 <= extDet) {
  3763. // region 0
  3764. // Minimum at interior points of ray and segment.
  3765. const invDet = 1 / det;
  3766. s0 *= invDet;
  3767. s1 *= invDet;
  3768. sqrDist = s0 * (s0 + a01 * s1 + 2 * b0) + s1 * (a01 * s0 + s1 + 2 * b1) + c;
  3769. } else {
  3770. // region 1
  3771. s1 = segExtent;
  3772. s0 = Math.max(0, -(a01 * s1 + b0));
  3773. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  3774. }
  3775. } else {
  3776. // region 5
  3777. s1 = -segExtent;
  3778. s0 = Math.max(0, -(a01 * s1 + b0));
  3779. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  3780. }
  3781. } else {
  3782. if (s1 <= -extDet) {
  3783. // region 4
  3784. s0 = Math.max(0, -(-a01 * segExtent + b0));
  3785. s1 = s0 > 0 ? -segExtent : Math.min(Math.max(-segExtent, -b1), segExtent);
  3786. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  3787. } else if (s1 <= extDet) {
  3788. // region 3
  3789. s0 = 0;
  3790. s1 = Math.min(Math.max(-segExtent, -b1), segExtent);
  3791. sqrDist = s1 * (s1 + 2 * b1) + c;
  3792. } else {
  3793. // region 2
  3794. s0 = Math.max(0, -(a01 * segExtent + b0));
  3795. s1 = s0 > 0 ? segExtent : Math.min(Math.max(-segExtent, -b1), segExtent);
  3796. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  3797. }
  3798. }
  3799. } else {
  3800. // Ray and segment are parallel.
  3801. s1 = a01 > 0 ? -segExtent : segExtent;
  3802. s0 = Math.max(0, -(a01 * s1 + b0));
  3803. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  3804. }
  3805. if (optionalPointOnRay) {
  3806. optionalPointOnRay.copy(this.direction).multiplyScalar(s0).add(this.origin);
  3807. }
  3808. if (optionalPointOnSegment) {
  3809. optionalPointOnSegment.copy(_segDir).multiplyScalar(s1).add(_segCenter);
  3810. }
  3811. return sqrDist;
  3812. }
  3813. intersectSphere(sphere, target) {
  3814. _vector$a.subVectors(sphere.center, this.origin);
  3815. const tca = _vector$a.dot(this.direction);
  3816. const d2 = _vector$a.dot(_vector$a) - tca * tca;
  3817. const radius2 = sphere.radius * sphere.radius;
  3818. if (d2 > radius2) return null;
  3819. const thc = Math.sqrt(radius2 - d2);
  3820. // t0 = first intersect point - entrance on front of sphere
  3821. const t0 = tca - thc;
  3822. // t1 = second intersect point - exit point on back of sphere
  3823. const t1 = tca + thc;
  3824. // test to see if both t0 and t1 are behind the ray - if so, return null
  3825. if (t0 < 0 && t1 < 0) return null;
  3826. // test to see if t0 is behind the ray:
  3827. // if it is, the ray is inside the sphere, so return the second exit point scaled by t1,
  3828. // in order to always return an intersect point that is in front of the ray.
  3829. if (t0 < 0) return this.at(t1, target);
  3830. // else t0 is in front of the ray, so return the first collision point scaled by t0
  3831. return this.at(t0, target);
  3832. }
  3833. intersectsSphere(sphere) {
  3834. return this.distanceSqToPoint(sphere.center) <= sphere.radius * sphere.radius;
  3835. }
  3836. distanceToPlane(plane) {
  3837. const denominator = plane.normal.dot(this.direction);
  3838. if (denominator === 0) {
  3839. // line is coplanar, return origin
  3840. if (plane.distanceToPoint(this.origin) === 0) {
  3841. return 0;
  3842. }
  3843. // Null is preferable to undefined since undefined means.... it is undefined
  3844. return null;
  3845. }
  3846. const t = -(this.origin.dot(plane.normal) + plane.constant) / denominator;
  3847. // Return if the ray never intersects the plane
  3848. return t >= 0 ? t : null;
  3849. }
  3850. intersectPlane(plane, target) {
  3851. const t = this.distanceToPlane(plane);
  3852. if (t === null) {
  3853. return null;
  3854. }
  3855. return this.at(t, target);
  3856. }
  3857. intersectsPlane(plane) {
  3858. // check if the ray lies on the plane first
  3859. const distToPoint = plane.distanceToPoint(this.origin);
  3860. if (distToPoint === 0) {
  3861. return true;
  3862. }
  3863. const denominator = plane.normal.dot(this.direction);
  3864. if (denominator * distToPoint < 0) {
  3865. return true;
  3866. }
  3867. // ray origin is behind the plane (and is pointing behind it)
  3868. return false;
  3869. }
  3870. intersectBox(box, target) {
  3871. let tmin, tmax, tymin, tymax, tzmin, tzmax;
  3872. const invdirx = 1 / this.direction.x,
  3873. invdiry = 1 / this.direction.y,
  3874. invdirz = 1 / this.direction.z;
  3875. const origin = this.origin;
  3876. if (invdirx >= 0) {
  3877. tmin = (box.min.x - origin.x) * invdirx;
  3878. tmax = (box.max.x - origin.x) * invdirx;
  3879. } else {
  3880. tmin = (box.max.x - origin.x) * invdirx;
  3881. tmax = (box.min.x - origin.x) * invdirx;
  3882. }
  3883. if (invdiry >= 0) {
  3884. tymin = (box.min.y - origin.y) * invdiry;
  3885. tymax = (box.max.y - origin.y) * invdiry;
  3886. } else {
  3887. tymin = (box.max.y - origin.y) * invdiry;
  3888. tymax = (box.min.y - origin.y) * invdiry;
  3889. }
  3890. if (tmin > tymax || tymin > tmax) return null;
  3891. if (tymin > tmin || isNaN(tmin)) tmin = tymin;
  3892. if (tymax < tmax || isNaN(tmax)) tmax = tymax;
  3893. if (invdirz >= 0) {
  3894. tzmin = (box.min.z - origin.z) * invdirz;
  3895. tzmax = (box.max.z - origin.z) * invdirz;
  3896. } else {
  3897. tzmin = (box.max.z - origin.z) * invdirz;
  3898. tzmax = (box.min.z - origin.z) * invdirz;
  3899. }
  3900. if (tmin > tzmax || tzmin > tmax) return null;
  3901. if (tzmin > tmin || tmin !== tmin) tmin = tzmin;
  3902. if (tzmax < tmax || tmax !== tmax) tmax = tzmax;
  3903. //return point closest to the ray (positive side)
  3904. if (tmax < 0) return null;
  3905. return this.at(tmin >= 0 ? tmin : tmax, target);
  3906. }
  3907. intersectsBox(box) {
  3908. return this.intersectBox(box, _vector$a) !== null;
  3909. }
  3910. intersectTriangle(a, b, c, backfaceCulling, target) {
  3911. // Compute the offset origin, edges, and normal.
  3912. // from https://github.com/pmjoniak/GeometricTools/blob/master/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h
  3913. _edge1.subVectors(b, a);
  3914. _edge2.subVectors(c, a);
  3915. _normal$1.crossVectors(_edge1, _edge2);
  3916. // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  3917. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  3918. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  3919. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  3920. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  3921. let DdN = this.direction.dot(_normal$1);
  3922. let sign;
  3923. if (DdN > 0) {
  3924. if (backfaceCulling) return null;
  3925. sign = 1;
  3926. } else if (DdN < 0) {
  3927. sign = -1;
  3928. DdN = -DdN;
  3929. } else {
  3930. return null;
  3931. }
  3932. _diff.subVectors(this.origin, a);
  3933. const DdQxE2 = sign * this.direction.dot(_edge2.crossVectors(_diff, _edge2));
  3934. // b1 < 0, no intersection
  3935. if (DdQxE2 < 0) {
  3936. return null;
  3937. }
  3938. const DdE1xQ = sign * this.direction.dot(_edge1.cross(_diff));
  3939. // b2 < 0, no intersection
  3940. if (DdE1xQ < 0) {
  3941. return null;
  3942. }
  3943. // b1+b2 > 1, no intersection
  3944. if (DdQxE2 + DdE1xQ > DdN) {
  3945. return null;
  3946. }
  3947. // Line intersects triangle, check if ray does.
  3948. const QdN = -sign * _diff.dot(_normal$1);
  3949. // t < 0, no intersection
  3950. if (QdN < 0) {
  3951. return null;
  3952. }
  3953. // Ray intersects triangle.
  3954. return this.at(QdN / DdN, target);
  3955. }
  3956. applyMatrix4(matrix4) {
  3957. this.origin.applyMatrix4(matrix4);
  3958. this.direction.transformDirection(matrix4);
  3959. return this;
  3960. }
  3961. equals(ray) {
  3962. return ray.origin.equals(this.origin) && ray.direction.equals(this.direction);
  3963. }
  3964. clone() {
  3965. return new this.constructor().copy(this);
  3966. }
  3967. }
  3968. class Matrix4 {
  3969. constructor() {
  3970. Matrix4.prototype.isMatrix4 = true;
  3971. this.elements = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];
  3972. }
  3973. set(n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44) {
  3974. const te = this.elements;
  3975. te[0] = n11;
  3976. te[4] = n12;
  3977. te[8] = n13;
  3978. te[12] = n14;
  3979. te[1] = n21;
  3980. te[5] = n22;
  3981. te[9] = n23;
  3982. te[13] = n24;
  3983. te[2] = n31;
  3984. te[6] = n32;
  3985. te[10] = n33;
  3986. te[14] = n34;
  3987. te[3] = n41;
  3988. te[7] = n42;
  3989. te[11] = n43;
  3990. te[15] = n44;
  3991. return this;
  3992. }
  3993. identity() {
  3994. this.set(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1);
  3995. return this;
  3996. }
  3997. clone() {
  3998. return new Matrix4().fromArray(this.elements);
  3999. }
  4000. copy(m) {
  4001. const te = this.elements;
  4002. const me = m.elements;
  4003. te[0] = me[0];
  4004. te[1] = me[1];
  4005. te[2] = me[2];
  4006. te[3] = me[3];
  4007. te[4] = me[4];
  4008. te[5] = me[5];
  4009. te[6] = me[6];
  4010. te[7] = me[7];
  4011. te[8] = me[8];
  4012. te[9] = me[9];
  4013. te[10] = me[10];
  4014. te[11] = me[11];
  4015. te[12] = me[12];
  4016. te[13] = me[13];
  4017. te[14] = me[14];
  4018. te[15] = me[15];
  4019. return this;
  4020. }
  4021. copyPosition(m) {
  4022. const te = this.elements,
  4023. me = m.elements;
  4024. te[12] = me[12];
  4025. te[13] = me[13];
  4026. te[14] = me[14];
  4027. return this;
  4028. }
  4029. setFromMatrix3(m) {
  4030. const me = m.elements;
  4031. 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);
  4032. return this;
  4033. }
  4034. extractBasis(xAxis, yAxis, zAxis) {
  4035. xAxis.setFromMatrixColumn(this, 0);
  4036. yAxis.setFromMatrixColumn(this, 1);
  4037. zAxis.setFromMatrixColumn(this, 2);
  4038. return this;
  4039. }
  4040. makeBasis(xAxis, yAxis, zAxis) {
  4041. 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);
  4042. return this;
  4043. }
  4044. extractRotation(m) {
  4045. // this method does not support reflection matrices
  4046. const te = this.elements;
  4047. const me = m.elements;
  4048. const scaleX = 1 / _v1$5.setFromMatrixColumn(m, 0).length();
  4049. const scaleY = 1 / _v1$5.setFromMatrixColumn(m, 1).length();
  4050. const scaleZ = 1 / _v1$5.setFromMatrixColumn(m, 2).length();
  4051. te[0] = me[0] * scaleX;
  4052. te[1] = me[1] * scaleX;
  4053. te[2] = me[2] * scaleX;
  4054. te[3] = 0;
  4055. te[4] = me[4] * scaleY;
  4056. te[5] = me[5] * scaleY;
  4057. te[6] = me[6] * scaleY;
  4058. te[7] = 0;
  4059. te[8] = me[8] * scaleZ;
  4060. te[9] = me[9] * scaleZ;
  4061. te[10] = me[10] * scaleZ;
  4062. te[11] = 0;
  4063. te[12] = 0;
  4064. te[13] = 0;
  4065. te[14] = 0;
  4066. te[15] = 1;
  4067. return this;
  4068. }
  4069. makeRotationFromEuler(euler) {
  4070. const te = this.elements;
  4071. const x = euler.x,
  4072. y = euler.y,
  4073. z = euler.z;
  4074. const a = Math.cos(x),
  4075. b = Math.sin(x);
  4076. const c = Math.cos(y),
  4077. d = Math.sin(y);
  4078. const e = Math.cos(z),
  4079. f = Math.sin(z);
  4080. if (euler.order === 'XYZ') {
  4081. const ae = a * e,
  4082. af = a * f,
  4083. be = b * e,
  4084. bf = b * f;
  4085. te[0] = c * e;
  4086. te[4] = -c * f;
  4087. te[8] = d;
  4088. te[1] = af + be * d;
  4089. te[5] = ae - bf * d;
  4090. te[9] = -b * c;
  4091. te[2] = bf - ae * d;
  4092. te[6] = be + af * d;
  4093. te[10] = a * c;
  4094. } else if (euler.order === 'YXZ') {
  4095. const ce = c * e,
  4096. cf = c * f,
  4097. de = d * e,
  4098. df = d * f;
  4099. te[0] = ce + df * b;
  4100. te[4] = de * b - cf;
  4101. te[8] = a * d;
  4102. te[1] = a * f;
  4103. te[5] = a * e;
  4104. te[9] = -b;
  4105. te[2] = cf * b - de;
  4106. te[6] = df + ce * b;
  4107. te[10] = a * c;
  4108. } else if (euler.order === 'ZXY') {
  4109. const ce = c * e,
  4110. cf = c * f,
  4111. de = d * e,
  4112. df = d * f;
  4113. te[0] = ce - df * b;
  4114. te[4] = -a * f;
  4115. te[8] = de + cf * b;
  4116. te[1] = cf + de * b;
  4117. te[5] = a * e;
  4118. te[9] = df - ce * b;
  4119. te[2] = -a * d;
  4120. te[6] = b;
  4121. te[10] = a * c;
  4122. } else if (euler.order === 'ZYX') {
  4123. const ae = a * e,
  4124. af = a * f,
  4125. be = b * e,
  4126. bf = b * f;
  4127. te[0] = c * e;
  4128. te[4] = be * d - af;
  4129. te[8] = ae * d + bf;
  4130. te[1] = c * f;
  4131. te[5] = bf * d + ae;
  4132. te[9] = af * d - be;
  4133. te[2] = -d;
  4134. te[6] = b * c;
  4135. te[10] = a * c;
  4136. } else if (euler.order === 'YZX') {
  4137. const ac = a * c,
  4138. ad = a * d,
  4139. bc = b * c,
  4140. bd = b * d;
  4141. te[0] = c * e;
  4142. te[4] = bd - ac * f;
  4143. te[8] = bc * f + ad;
  4144. te[1] = f;
  4145. te[5] = a * e;
  4146. te[9] = -b * e;
  4147. te[2] = -d * e;
  4148. te[6] = ad * f + bc;
  4149. te[10] = ac - bd * f;
  4150. } else if (euler.order === 'XZY') {
  4151. const ac = a * c,
  4152. ad = a * d,
  4153. bc = b * c,
  4154. bd = b * d;
  4155. te[0] = c * e;
  4156. te[4] = -f;
  4157. te[8] = d * e;
  4158. te[1] = ac * f + bd;
  4159. te[5] = a * e;
  4160. te[9] = ad * f - bc;
  4161. te[2] = bc * f - ad;
  4162. te[6] = b * e;
  4163. te[10] = bd * f + ac;
  4164. }
  4165. // bottom row
  4166. te[3] = 0;
  4167. te[7] = 0;
  4168. te[11] = 0;
  4169. // last column
  4170. te[12] = 0;
  4171. te[13] = 0;
  4172. te[14] = 0;
  4173. te[15] = 1;
  4174. return this;
  4175. }
  4176. makeRotationFromQuaternion(q) {
  4177. return this.compose(_zero, q, _one);
  4178. }
  4179. lookAt(eye, target, up) {
  4180. const te = this.elements;
  4181. _z.subVectors(eye, target);
  4182. if (_z.lengthSq() === 0) {
  4183. // eye and target are in the same position
  4184. _z.z = 1;
  4185. }
  4186. _z.normalize();
  4187. _x.crossVectors(up, _z);
  4188. if (_x.lengthSq() === 0) {
  4189. // up and z are parallel
  4190. if (Math.abs(up.z) === 1) {
  4191. _z.x += 0.0001;
  4192. } else {
  4193. _z.z += 0.0001;
  4194. }
  4195. _z.normalize();
  4196. _x.crossVectors(up, _z);
  4197. }
  4198. _x.normalize();
  4199. _y.crossVectors(_z, _x);
  4200. te[0] = _x.x;
  4201. te[4] = _y.x;
  4202. te[8] = _z.x;
  4203. te[1] = _x.y;
  4204. te[5] = _y.y;
  4205. te[9] = _z.y;
  4206. te[2] = _x.z;
  4207. te[6] = _y.z;
  4208. te[10] = _z.z;
  4209. return this;
  4210. }
  4211. multiply(m) {
  4212. return this.multiplyMatrices(this, m);
  4213. }
  4214. premultiply(m) {
  4215. return this.multiplyMatrices(m, this);
  4216. }
  4217. multiplyMatrices(a, b) {
  4218. const ae = a.elements;
  4219. const be = b.elements;
  4220. const te = this.elements;
  4221. const a11 = ae[0],
  4222. a12 = ae[4],
  4223. a13 = ae[8],
  4224. a14 = ae[12];
  4225. const a21 = ae[1],
  4226. a22 = ae[5],
  4227. a23 = ae[9],
  4228. a24 = ae[13];
  4229. const a31 = ae[2],
  4230. a32 = ae[6],
  4231. a33 = ae[10],
  4232. a34 = ae[14];
  4233. const a41 = ae[3],
  4234. a42 = ae[7],
  4235. a43 = ae[11],
  4236. a44 = ae[15];
  4237. const b11 = be[0],
  4238. b12 = be[4],
  4239. b13 = be[8],
  4240. b14 = be[12];
  4241. const b21 = be[1],
  4242. b22 = be[5],
  4243. b23 = be[9],
  4244. b24 = be[13];
  4245. const b31 = be[2],
  4246. b32 = be[6],
  4247. b33 = be[10],
  4248. b34 = be[14];
  4249. const b41 = be[3],
  4250. b42 = be[7],
  4251. b43 = be[11],
  4252. b44 = be[15];
  4253. te[0] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  4254. te[4] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  4255. te[8] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  4256. te[12] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  4257. te[1] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  4258. te[5] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  4259. te[9] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  4260. te[13] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  4261. te[2] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  4262. te[6] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  4263. te[10] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  4264. te[14] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  4265. te[3] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  4266. te[7] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  4267. te[11] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  4268. te[15] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  4269. return this;
  4270. }
  4271. multiplyScalar(s) {
  4272. const te = this.elements;
  4273. te[0] *= s;
  4274. te[4] *= s;
  4275. te[8] *= s;
  4276. te[12] *= s;
  4277. te[1] *= s;
  4278. te[5] *= s;
  4279. te[9] *= s;
  4280. te[13] *= s;
  4281. te[2] *= s;
  4282. te[6] *= s;
  4283. te[10] *= s;
  4284. te[14] *= s;
  4285. te[3] *= s;
  4286. te[7] *= s;
  4287. te[11] *= s;
  4288. te[15] *= s;
  4289. return this;
  4290. }
  4291. determinant() {
  4292. const te = this.elements;
  4293. const n11 = te[0],
  4294. n12 = te[4],
  4295. n13 = te[8],
  4296. n14 = te[12];
  4297. const n21 = te[1],
  4298. n22 = te[5],
  4299. n23 = te[9],
  4300. n24 = te[13];
  4301. const n31 = te[2],
  4302. n32 = te[6],
  4303. n33 = te[10],
  4304. n34 = te[14];
  4305. const n41 = te[3],
  4306. n42 = te[7],
  4307. n43 = te[11],
  4308. n44 = te[15];
  4309. //TODO: make this more efficient
  4310. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  4311. 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);
  4312. }
  4313. transpose() {
  4314. const te = this.elements;
  4315. let tmp;
  4316. tmp = te[1];
  4317. te[1] = te[4];
  4318. te[4] = tmp;
  4319. tmp = te[2];
  4320. te[2] = te[8];
  4321. te[8] = tmp;
  4322. tmp = te[6];
  4323. te[6] = te[9];
  4324. te[9] = tmp;
  4325. tmp = te[3];
  4326. te[3] = te[12];
  4327. te[12] = tmp;
  4328. tmp = te[7];
  4329. te[7] = te[13];
  4330. te[13] = tmp;
  4331. tmp = te[11];
  4332. te[11] = te[14];
  4333. te[14] = tmp;
  4334. return this;
  4335. }
  4336. setPosition(x, y, z) {
  4337. const te = this.elements;
  4338. if (x.isVector3) {
  4339. te[12] = x.x;
  4340. te[13] = x.y;
  4341. te[14] = x.z;
  4342. } else {
  4343. te[12] = x;
  4344. te[13] = y;
  4345. te[14] = z;
  4346. }
  4347. return this;
  4348. }
  4349. invert() {
  4350. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  4351. const te = this.elements,
  4352. n11 = te[0],
  4353. n21 = te[1],
  4354. n31 = te[2],
  4355. n41 = te[3],
  4356. n12 = te[4],
  4357. n22 = te[5],
  4358. n32 = te[6],
  4359. n42 = te[7],
  4360. n13 = te[8],
  4361. n23 = te[9],
  4362. n33 = te[10],
  4363. n43 = te[11],
  4364. n14 = te[12],
  4365. n24 = te[13],
  4366. n34 = te[14],
  4367. n44 = te[15],
  4368. t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44,
  4369. t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44,
  4370. t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44,
  4371. t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34;
  4372. const det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14;
  4373. if (det === 0) return this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  4374. const detInv = 1 / det;
  4375. te[0] = t11 * detInv;
  4376. te[1] = (n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44) * detInv;
  4377. te[2] = (n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44) * detInv;
  4378. te[3] = (n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43) * detInv;
  4379. te[4] = t12 * detInv;
  4380. te[5] = (n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44) * detInv;
  4381. te[6] = (n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44) * detInv;
  4382. te[7] = (n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43) * detInv;
  4383. te[8] = t13 * detInv;
  4384. te[9] = (n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44) * detInv;
  4385. te[10] = (n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44) * detInv;
  4386. te[11] = (n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43) * detInv;
  4387. te[12] = t14 * detInv;
  4388. te[13] = (n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34) * detInv;
  4389. te[14] = (n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34) * detInv;
  4390. te[15] = (n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33) * detInv;
  4391. return this;
  4392. }
  4393. scale(v) {
  4394. const te = this.elements;
  4395. const x = v.x,
  4396. y = v.y,
  4397. z = v.z;
  4398. te[0] *= x;
  4399. te[4] *= y;
  4400. te[8] *= z;
  4401. te[1] *= x;
  4402. te[5] *= y;
  4403. te[9] *= z;
  4404. te[2] *= x;
  4405. te[6] *= y;
  4406. te[10] *= z;
  4407. te[3] *= x;
  4408. te[7] *= y;
  4409. te[11] *= z;
  4410. return this;
  4411. }
  4412. getMaxScaleOnAxis() {
  4413. const te = this.elements;
  4414. const scaleXSq = te[0] * te[0] + te[1] * te[1] + te[2] * te[2];
  4415. const scaleYSq = te[4] * te[4] + te[5] * te[5] + te[6] * te[6];
  4416. const scaleZSq = te[8] * te[8] + te[9] * te[9] + te[10] * te[10];
  4417. return Math.sqrt(Math.max(scaleXSq, scaleYSq, scaleZSq));
  4418. }
  4419. makeTranslation(x, y, z) {
  4420. this.set(1, 0, 0, x, 0, 1, 0, y, 0, 0, 1, z, 0, 0, 0, 1);
  4421. return this;
  4422. }
  4423. makeRotationX(theta) {
  4424. const c = Math.cos(theta),
  4425. s = Math.sin(theta);
  4426. this.set(1, 0, 0, 0, 0, c, -s, 0, 0, s, c, 0, 0, 0, 0, 1);
  4427. return this;
  4428. }
  4429. makeRotationY(theta) {
  4430. const c = Math.cos(theta),
  4431. s = Math.sin(theta);
  4432. this.set(c, 0, s, 0, 0, 1, 0, 0, -s, 0, c, 0, 0, 0, 0, 1);
  4433. return this;
  4434. }
  4435. makeRotationZ(theta) {
  4436. const c = Math.cos(theta),
  4437. s = Math.sin(theta);
  4438. this.set(c, -s, 0, 0, s, c, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1);
  4439. return this;
  4440. }
  4441. makeRotationAxis(axis, angle) {
  4442. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  4443. const c = Math.cos(angle);
  4444. const s = Math.sin(angle);
  4445. const t = 1 - c;
  4446. const x = axis.x,
  4447. y = axis.y,
  4448. z = axis.z;
  4449. const tx = t * x,
  4450. ty = t * y;
  4451. 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);
  4452. return this;
  4453. }
  4454. makeScale(x, y, z) {
  4455. this.set(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1);
  4456. return this;
  4457. }
  4458. makeShear(xy, xz, yx, yz, zx, zy) {
  4459. this.set(1, yx, zx, 0, xy, 1, zy, 0, xz, yz, 1, 0, 0, 0, 0, 1);
  4460. return this;
  4461. }
  4462. compose(position, quaternion, scale) {
  4463. const te = this.elements;
  4464. const x = quaternion._x,
  4465. y = quaternion._y,
  4466. z = quaternion._z,
  4467. w = quaternion._w;
  4468. const x2 = x + x,
  4469. y2 = y + y,
  4470. z2 = z + z;
  4471. const xx = x * x2,
  4472. xy = x * y2,
  4473. xz = x * z2;
  4474. const yy = y * y2,
  4475. yz = y * z2,
  4476. zz = z * z2;
  4477. const wx = w * x2,
  4478. wy = w * y2,
  4479. wz = w * z2;
  4480. const sx = scale.x,
  4481. sy = scale.y,
  4482. sz = scale.z;
  4483. te[0] = (1 - (yy + zz)) * sx;
  4484. te[1] = (xy + wz) * sx;
  4485. te[2] = (xz - wy) * sx;
  4486. te[3] = 0;
  4487. te[4] = (xy - wz) * sy;
  4488. te[5] = (1 - (xx + zz)) * sy;
  4489. te[6] = (yz + wx) * sy;
  4490. te[7] = 0;
  4491. te[8] = (xz + wy) * sz;
  4492. te[9] = (yz - wx) * sz;
  4493. te[10] = (1 - (xx + yy)) * sz;
  4494. te[11] = 0;
  4495. te[12] = position.x;
  4496. te[13] = position.y;
  4497. te[14] = position.z;
  4498. te[15] = 1;
  4499. return this;
  4500. }
  4501. decompose(position, quaternion, scale) {
  4502. const te = this.elements;
  4503. let sx = _v1$5.set(te[0], te[1], te[2]).length();
  4504. const sy = _v1$5.set(te[4], te[5], te[6]).length();
  4505. const sz = _v1$5.set(te[8], te[9], te[10]).length();
  4506. // if determine is negative, we need to invert one scale
  4507. const det = this.determinant();
  4508. if (det < 0) sx = -sx;
  4509. position.x = te[12];
  4510. position.y = te[13];
  4511. position.z = te[14];
  4512. // scale the rotation part
  4513. _m1$2.copy(this);
  4514. const invSX = 1 / sx;
  4515. const invSY = 1 / sy;
  4516. const invSZ = 1 / sz;
  4517. _m1$2.elements[0] *= invSX;
  4518. _m1$2.elements[1] *= invSX;
  4519. _m1$2.elements[2] *= invSX;
  4520. _m1$2.elements[4] *= invSY;
  4521. _m1$2.elements[5] *= invSY;
  4522. _m1$2.elements[6] *= invSY;
  4523. _m1$2.elements[8] *= invSZ;
  4524. _m1$2.elements[9] *= invSZ;
  4525. _m1$2.elements[10] *= invSZ;
  4526. quaternion.setFromRotationMatrix(_m1$2);
  4527. scale.x = sx;
  4528. scale.y = sy;
  4529. scale.z = sz;
  4530. return this;
  4531. }
  4532. makePerspective(left, right, top, bottom, near, far) {
  4533. const te = this.elements;
  4534. const x = 2 * near / (right - left);
  4535. const y = 2 * near / (top - bottom);
  4536. const a = (right + left) / (right - left);
  4537. const b = (top + bottom) / (top - bottom);
  4538. const c = -(far + near) / (far - near);
  4539. const d = -2 * far * near / (far - near);
  4540. te[0] = x;
  4541. te[4] = 0;
  4542. te[8] = a;
  4543. te[12] = 0;
  4544. te[1] = 0;
  4545. te[5] = y;
  4546. te[9] = b;
  4547. te[13] = 0;
  4548. te[2] = 0;
  4549. te[6] = 0;
  4550. te[10] = c;
  4551. te[14] = d;
  4552. te[3] = 0;
  4553. te[7] = 0;
  4554. te[11] = -1;
  4555. te[15] = 0;
  4556. return this;
  4557. }
  4558. makeOrthographic(left, right, top, bottom, near, far) {
  4559. const te = this.elements;
  4560. const w = 1.0 / (right - left);
  4561. const h = 1.0 / (top - bottom);
  4562. const p = 1.0 / (far - near);
  4563. const x = (right + left) * w;
  4564. const y = (top + bottom) * h;
  4565. const z = (far + near) * p;
  4566. te[0] = 2 * w;
  4567. te[4] = 0;
  4568. te[8] = 0;
  4569. te[12] = -x;
  4570. te[1] = 0;
  4571. te[5] = 2 * h;
  4572. te[9] = 0;
  4573. te[13] = -y;
  4574. te[2] = 0;
  4575. te[6] = 0;
  4576. te[10] = -2 * p;
  4577. te[14] = -z;
  4578. te[3] = 0;
  4579. te[7] = 0;
  4580. te[11] = 0;
  4581. te[15] = 1;
  4582. return this;
  4583. }
  4584. equals(matrix) {
  4585. const te = this.elements;
  4586. const me = matrix.elements;
  4587. for (let i = 0; i < 16; i++) {
  4588. if (te[i] !== me[i]) return false;
  4589. }
  4590. return true;
  4591. }
  4592. fromArray(array, offset = 0) {
  4593. for (let i = 0; i < 16; i++) {
  4594. this.elements[i] = array[i + offset];
  4595. }
  4596. return this;
  4597. }
  4598. toArray(array = [], offset = 0) {
  4599. const te = this.elements;
  4600. array[offset] = te[0];
  4601. array[offset + 1] = te[1];
  4602. array[offset + 2] = te[2];
  4603. array[offset + 3] = te[3];
  4604. array[offset + 4] = te[4];
  4605. array[offset + 5] = te[5];
  4606. array[offset + 6] = te[6];
  4607. array[offset + 7] = te[7];
  4608. array[offset + 8] = te[8];
  4609. array[offset + 9] = te[9];
  4610. array[offset + 10] = te[10];
  4611. array[offset + 11] = te[11];
  4612. array[offset + 12] = te[12];
  4613. array[offset + 13] = te[13];
  4614. array[offset + 14] = te[14];
  4615. array[offset + 15] = te[15];
  4616. return array;
  4617. }
  4618. }
  4619. const _v1$5 = /*@__PURE__*/new Vector3();
  4620. const _m1$2 = /*@__PURE__*/new Matrix4();
  4621. const _zero = /*@__PURE__*/new Vector3(0, 0, 0);
  4622. const _one = /*@__PURE__*/new Vector3(1, 1, 1);
  4623. const _x = /*@__PURE__*/new Vector3();
  4624. const _y = /*@__PURE__*/new Vector3();
  4625. const _z = /*@__PURE__*/new Vector3();
  4626. const _matrix$1 = /*@__PURE__*/new Matrix4();
  4627. const _quaternion$3 = /*@__PURE__*/new Quaternion();
  4628. class Euler {
  4629. constructor(x = 0, y = 0, z = 0, order = Euler.DefaultOrder) {
  4630. this.isEuler = true;
  4631. this._x = x;
  4632. this._y = y;
  4633. this._z = z;
  4634. this._order = order;
  4635. }
  4636. get x() {
  4637. return this._x;
  4638. }
  4639. set x(value) {
  4640. this._x = value;
  4641. this._onChangeCallback();
  4642. }
  4643. get y() {
  4644. return this._y;
  4645. }
  4646. set y(value) {
  4647. this._y = value;
  4648. this._onChangeCallback();
  4649. }
  4650. get z() {
  4651. return this._z;
  4652. }
  4653. set z(value) {
  4654. this._z = value;
  4655. this._onChangeCallback();
  4656. }
  4657. get order() {
  4658. return this._order;
  4659. }
  4660. set order(value) {
  4661. this._order = value;
  4662. this._onChangeCallback();
  4663. }
  4664. set(x, y, z, order = this._order) {
  4665. this._x = x;
  4666. this._y = y;
  4667. this._z = z;
  4668. this._order = order;
  4669. this._onChangeCallback();
  4670. return this;
  4671. }
  4672. clone() {
  4673. return new this.constructor(this._x, this._y, this._z, this._order);
  4674. }
  4675. copy(euler) {
  4676. this._x = euler._x;
  4677. this._y = euler._y;
  4678. this._z = euler._z;
  4679. this._order = euler._order;
  4680. this._onChangeCallback();
  4681. return this;
  4682. }
  4683. setFromRotationMatrix(m, order = this._order, update = true) {
  4684. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  4685. const te = m.elements;
  4686. const m11 = te[0],
  4687. m12 = te[4],
  4688. m13 = te[8];
  4689. const m21 = te[1],
  4690. m22 = te[5],
  4691. m23 = te[9];
  4692. const m31 = te[2],
  4693. m32 = te[6],
  4694. m33 = te[10];
  4695. switch (order) {
  4696. case 'XYZ':
  4697. this._y = Math.asin(clamp(m13, -1, 1));
  4698. if (Math.abs(m13) < 0.9999999) {
  4699. this._x = Math.atan2(-m23, m33);
  4700. this._z = Math.atan2(-m12, m11);
  4701. } else {
  4702. this._x = Math.atan2(m32, m22);
  4703. this._z = 0;
  4704. }
  4705. break;
  4706. case 'YXZ':
  4707. this._x = Math.asin(-clamp(m23, -1, 1));
  4708. if (Math.abs(m23) < 0.9999999) {
  4709. this._y = Math.atan2(m13, m33);
  4710. this._z = Math.atan2(m21, m22);
  4711. } else {
  4712. this._y = Math.atan2(-m31, m11);
  4713. this._z = 0;
  4714. }
  4715. break;
  4716. case 'ZXY':
  4717. this._x = Math.asin(clamp(m32, -1, 1));
  4718. if (Math.abs(m32) < 0.9999999) {
  4719. this._y = Math.atan2(-m31, m33);
  4720. this._z = Math.atan2(-m12, m22);
  4721. } else {
  4722. this._y = 0;
  4723. this._z = Math.atan2(m21, m11);
  4724. }
  4725. break;
  4726. case 'ZYX':
  4727. this._y = Math.asin(-clamp(m31, -1, 1));
  4728. if (Math.abs(m31) < 0.9999999) {
  4729. this._x = Math.atan2(m32, m33);
  4730. this._z = Math.atan2(m21, m11);
  4731. } else {
  4732. this._x = 0;
  4733. this._z = Math.atan2(-m12, m22);
  4734. }
  4735. break;
  4736. case 'YZX':
  4737. this._z = Math.asin(clamp(m21, -1, 1));
  4738. if (Math.abs(m21) < 0.9999999) {
  4739. this._x = Math.atan2(-m23, m22);
  4740. this._y = Math.atan2(-m31, m11);
  4741. } else {
  4742. this._x = 0;
  4743. this._y = Math.atan2(m13, m33);
  4744. }
  4745. break;
  4746. case 'XZY':
  4747. this._z = Math.asin(-clamp(m12, -1, 1));
  4748. if (Math.abs(m12) < 0.9999999) {
  4749. this._x = Math.atan2(m32, m22);
  4750. this._y = Math.atan2(m13, m11);
  4751. } else {
  4752. this._x = Math.atan2(-m23, m33);
  4753. this._y = 0;
  4754. }
  4755. break;
  4756. default:
  4757. console.warn('THREE.Euler: .setFromRotationMatrix() encountered an unknown order: ' + order);
  4758. }
  4759. this._order = order;
  4760. if (update === true) this._onChangeCallback();
  4761. return this;
  4762. }
  4763. setFromQuaternion(q, order, update) {
  4764. _matrix$1.makeRotationFromQuaternion(q);
  4765. return this.setFromRotationMatrix(_matrix$1, order, update);
  4766. }
  4767. setFromVector3(v, order = this._order) {
  4768. return this.set(v.x, v.y, v.z, order);
  4769. }
  4770. reorder(newOrder) {
  4771. // WARNING: this discards revolution information -bhouston
  4772. _quaternion$3.setFromEuler(this);
  4773. return this.setFromQuaternion(_quaternion$3, newOrder);
  4774. }
  4775. equals(euler) {
  4776. return euler._x === this._x && euler._y === this._y && euler._z === this._z && euler._order === this._order;
  4777. }
  4778. fromArray(array) {
  4779. this._x = array[0];
  4780. this._y = array[1];
  4781. this._z = array[2];
  4782. if (array[3] !== undefined) this._order = array[3];
  4783. this._onChangeCallback();
  4784. return this;
  4785. }
  4786. toArray(array = [], offset = 0) {
  4787. array[offset] = this._x;
  4788. array[offset + 1] = this._y;
  4789. array[offset + 2] = this._z;
  4790. array[offset + 3] = this._order;
  4791. return array;
  4792. }
  4793. _onChange(callback) {
  4794. this._onChangeCallback = callback;
  4795. return this;
  4796. }
  4797. _onChangeCallback() {}
  4798. *[Symbol.iterator]() {
  4799. yield this._x;
  4800. yield this._y;
  4801. yield this._z;
  4802. yield this._order;
  4803. }
  4804. // @deprecated since r138, 02cf0df1cb4575d5842fef9c85bb5a89fe020d53
  4805. toVector3() {
  4806. console.error('THREE.Euler: .toVector3() has been removed. Use Vector3.setFromEuler() instead');
  4807. }
  4808. }
  4809. Euler.DefaultOrder = 'XYZ';
  4810. Euler.RotationOrders = ['XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX'];
  4811. class Layers {
  4812. constructor() {
  4813. this.mask = 1 | 0;
  4814. }
  4815. set(channel) {
  4816. this.mask = (1 << channel | 0) >>> 0;
  4817. }
  4818. enable(channel) {
  4819. this.mask |= 1 << channel | 0;
  4820. }
  4821. enableAll() {
  4822. this.mask = 0xffffffff | 0;
  4823. }
  4824. toggle(channel) {
  4825. this.mask ^= 1 << channel | 0;
  4826. }
  4827. disable(channel) {
  4828. this.mask &= ~(1 << channel | 0);
  4829. }
  4830. disableAll() {
  4831. this.mask = 0;
  4832. }
  4833. test(layers) {
  4834. return (this.mask & layers.mask) !== 0;
  4835. }
  4836. isEnabled(channel) {
  4837. return (this.mask & (1 << channel | 0)) !== 0;
  4838. }
  4839. }
  4840. let _object3DId = 0;
  4841. const _v1$4 = /*@__PURE__*/new Vector3();
  4842. const _q1 = /*@__PURE__*/new Quaternion();
  4843. const _m1$1 = /*@__PURE__*/new Matrix4();
  4844. const _target = /*@__PURE__*/new Vector3();
  4845. const _position$3 = /*@__PURE__*/new Vector3();
  4846. const _scale$2 = /*@__PURE__*/new Vector3();
  4847. const _quaternion$2 = /*@__PURE__*/new Quaternion();
  4848. const _xAxis = /*@__PURE__*/new Vector3(1, 0, 0);
  4849. const _yAxis = /*@__PURE__*/new Vector3(0, 1, 0);
  4850. const _zAxis = /*@__PURE__*/new Vector3(0, 0, 1);
  4851. const _addedEvent = {
  4852. type: 'added'
  4853. };
  4854. const _removedEvent = {
  4855. type: 'removed'
  4856. };
  4857. class Object3D extends EventDispatcher {
  4858. constructor() {
  4859. super();
  4860. this.isObject3D = true;
  4861. Object.defineProperty(this, 'id', {
  4862. value: _object3DId++
  4863. });
  4864. this.uuid = generateUUID();
  4865. this.name = '';
  4866. this.type = 'Object3D';
  4867. this.parent = null;
  4868. this.children = [];
  4869. this.up = Object3D.DefaultUp.clone();
  4870. const position = new Vector3();
  4871. const rotation = new Euler();
  4872. const quaternion = new Quaternion();
  4873. const scale = new Vector3(1, 1, 1);
  4874. function onRotationChange() {
  4875. quaternion.setFromEuler(rotation, false);
  4876. }
  4877. function onQuaternionChange() {
  4878. rotation.setFromQuaternion(quaternion, undefined, false);
  4879. }
  4880. rotation._onChange(onRotationChange);
  4881. quaternion._onChange(onQuaternionChange);
  4882. Object.defineProperties(this, {
  4883. position: {
  4884. configurable: true,
  4885. enumerable: true,
  4886. value: position
  4887. },
  4888. rotation: {
  4889. configurable: true,
  4890. enumerable: true,
  4891. value: rotation
  4892. },
  4893. quaternion: {
  4894. configurable: true,
  4895. enumerable: true,
  4896. value: quaternion
  4897. },
  4898. scale: {
  4899. configurable: true,
  4900. enumerable: true,
  4901. value: scale
  4902. },
  4903. modelViewMatrix: {
  4904. value: new Matrix4()
  4905. },
  4906. normalMatrix: {
  4907. value: new Matrix3()
  4908. }
  4909. });
  4910. this.matrix = new Matrix4();
  4911. this.matrixWorld = new Matrix4();
  4912. this.matrixAutoUpdate = Object3D.DefaultMatrixAutoUpdate;
  4913. this.matrixWorldNeedsUpdate = false;
  4914. this.matrixWorldAutoUpdate = Object3D.DefaultMatrixWorldAutoUpdate; // checked by the renderer
  4915. this.layers = new Layers();
  4916. this.visible = true;
  4917. this.castShadow = false;
  4918. this.receiveShadow = false;
  4919. this.frustumCulled = true;
  4920. this.renderOrder = 0;
  4921. this.animations = [];
  4922. this.userData = {};
  4923. }
  4924. onBeforeRender( /* renderer, scene, camera, geometry, material, group */) {}
  4925. onAfterRender( /* renderer, scene, camera, geometry, material, group */) {}
  4926. applyMatrix4(matrix) {
  4927. if (this.matrixAutoUpdate) this.updateMatrix();
  4928. this.matrix.premultiply(matrix);
  4929. this.matrix.decompose(this.position, this.quaternion, this.scale);
  4930. }
  4931. applyQuaternion(q) {
  4932. this.quaternion.premultiply(q);
  4933. return this;
  4934. }
  4935. setRotationFromAxisAngle(axis, angle) {
  4936. // assumes axis is normalized
  4937. this.quaternion.setFromAxisAngle(axis, angle);
  4938. }
  4939. setRotationFromEuler(euler) {
  4940. this.quaternion.setFromEuler(euler, true);
  4941. }
  4942. setRotationFromMatrix(m) {
  4943. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  4944. this.quaternion.setFromRotationMatrix(m);
  4945. }
  4946. setRotationFromQuaternion(q) {
  4947. // assumes q is normalized
  4948. this.quaternion.copy(q);
  4949. }
  4950. rotateOnAxis(axis, angle) {
  4951. // rotate object on axis in object space
  4952. // axis is assumed to be normalized
  4953. _q1.setFromAxisAngle(axis, angle);
  4954. this.quaternion.multiply(_q1);
  4955. return this;
  4956. }
  4957. rotateOnWorldAxis(axis, angle) {
  4958. // rotate object on axis in world space
  4959. // axis is assumed to be normalized
  4960. // method assumes no rotated parent
  4961. _q1.setFromAxisAngle(axis, angle);
  4962. this.quaternion.premultiply(_q1);
  4963. return this;
  4964. }
  4965. rotateX(angle) {
  4966. return this.rotateOnAxis(_xAxis, angle);
  4967. }
  4968. rotateY(angle) {
  4969. return this.rotateOnAxis(_yAxis, angle);
  4970. }
  4971. rotateZ(angle) {
  4972. return this.rotateOnAxis(_zAxis, angle);
  4973. }
  4974. translateOnAxis(axis, distance) {
  4975. // translate object by distance along axis in object space
  4976. // axis is assumed to be normalized
  4977. _v1$4.copy(axis).applyQuaternion(this.quaternion);
  4978. this.position.add(_v1$4.multiplyScalar(distance));
  4979. return this;
  4980. }
  4981. translateX(distance) {
  4982. return this.translateOnAxis(_xAxis, distance);
  4983. }
  4984. translateY(distance) {
  4985. return this.translateOnAxis(_yAxis, distance);
  4986. }
  4987. translateZ(distance) {
  4988. return this.translateOnAxis(_zAxis, distance);
  4989. }
  4990. localToWorld(vector) {
  4991. this.updateWorldMatrix(true, false);
  4992. return vector.applyMatrix4(this.matrixWorld);
  4993. }
  4994. worldToLocal(vector) {
  4995. this.updateWorldMatrix(true, false);
  4996. return vector.applyMatrix4(_m1$1.copy(this.matrixWorld).invert());
  4997. }
  4998. lookAt(x, y, z) {
  4999. // This method does not support objects having non-uniformly-scaled parent(s)
  5000. if (x.isVector3) {
  5001. _target.copy(x);
  5002. } else {
  5003. _target.set(x, y, z);
  5004. }
  5005. const parent = this.parent;
  5006. this.updateWorldMatrix(true, false);
  5007. _position$3.setFromMatrixPosition(this.matrixWorld);
  5008. if (this.isCamera || this.isLight) {
  5009. _m1$1.lookAt(_position$3, _target, this.up);
  5010. } else {
  5011. _m1$1.lookAt(_target, _position$3, this.up);
  5012. }
  5013. this.quaternion.setFromRotationMatrix(_m1$1);
  5014. if (parent) {
  5015. _m1$1.extractRotation(parent.matrixWorld);
  5016. _q1.setFromRotationMatrix(_m1$1);
  5017. this.quaternion.premultiply(_q1.invert());
  5018. }
  5019. }
  5020. add(object) {
  5021. if (arguments.length > 1) {
  5022. for (let i = 0; i < arguments.length; i++) {
  5023. this.add(arguments[i]);
  5024. }
  5025. return this;
  5026. }
  5027. if (object === this) {
  5028. console.error('THREE.Object3D.add: object can\'t be added as a child of itself.', object);
  5029. return this;
  5030. }
  5031. if (object && object.isObject3D) {
  5032. if (object.parent !== null) {
  5033. object.parent.remove(object);
  5034. }
  5035. object.parent = this;
  5036. this.children.push(object);
  5037. object.dispatchEvent(_addedEvent);
  5038. } else {
  5039. console.error('THREE.Object3D.add: object not an instance of THREE.Object3D.', object);
  5040. }
  5041. return this;
  5042. }
  5043. remove(object) {
  5044. if (arguments.length > 1) {
  5045. for (let i = 0; i < arguments.length; i++) {
  5046. this.remove(arguments[i]);
  5047. }
  5048. return this;
  5049. }
  5050. const index = this.children.indexOf(object);
  5051. if (index !== -1) {
  5052. object.parent = null;
  5053. this.children.splice(index, 1);
  5054. object.dispatchEvent(_removedEvent);
  5055. }
  5056. return this;
  5057. }
  5058. removeFromParent() {
  5059. const parent = this.parent;
  5060. if (parent !== null) {
  5061. parent.remove(this);
  5062. }
  5063. return this;
  5064. }
  5065. clear() {
  5066. for (let i = 0; i < this.children.length; i++) {
  5067. const object = this.children[i];
  5068. object.parent = null;
  5069. object.dispatchEvent(_removedEvent);
  5070. }
  5071. this.children.length = 0;
  5072. return this;
  5073. }
  5074. attach(object) {
  5075. // adds object as a child of this, while maintaining the object's world transform
  5076. // Note: This method does not support scene graphs having non-uniformly-scaled nodes(s)
  5077. this.updateWorldMatrix(true, false);
  5078. _m1$1.copy(this.matrixWorld).invert();
  5079. if (object.parent !== null) {
  5080. object.parent.updateWorldMatrix(true, false);
  5081. _m1$1.multiply(object.parent.matrixWorld);
  5082. }
  5083. object.applyMatrix4(_m1$1);
  5084. this.add(object);
  5085. object.updateWorldMatrix(false, true);
  5086. return this;
  5087. }
  5088. getObjectById(id) {
  5089. return this.getObjectByProperty('id', id);
  5090. }
  5091. getObjectByName(name) {
  5092. return this.getObjectByProperty('name', name);
  5093. }
  5094. getObjectByProperty(name, value) {
  5095. if (this[name] === value) return this;
  5096. for (let i = 0, l = this.children.length; i < l; i++) {
  5097. const child = this.children[i];
  5098. const object = child.getObjectByProperty(name, value);
  5099. if (object !== undefined) {
  5100. return object;
  5101. }
  5102. }
  5103. return undefined;
  5104. }
  5105. getWorldPosition(target) {
  5106. this.updateWorldMatrix(true, false);
  5107. return target.setFromMatrixPosition(this.matrixWorld);
  5108. }
  5109. getWorldQuaternion(target) {
  5110. this.updateWorldMatrix(true, false);
  5111. this.matrixWorld.decompose(_position$3, target, _scale$2);
  5112. return target;
  5113. }
  5114. getWorldScale(target) {
  5115. this.updateWorldMatrix(true, false);
  5116. this.matrixWorld.decompose(_position$3, _quaternion$2, target);
  5117. return target;
  5118. }
  5119. getWorldDirection(target) {
  5120. this.updateWorldMatrix(true, false);
  5121. const e = this.matrixWorld.elements;
  5122. return target.set(e[8], e[9], e[10]).normalize();
  5123. }
  5124. raycast( /* raycaster, intersects */) {}
  5125. traverse(callback) {
  5126. callback(this);
  5127. const children = this.children;
  5128. for (let i = 0, l = children.length; i < l; i++) {
  5129. children[i].traverse(callback);
  5130. }
  5131. }
  5132. traverseVisible(callback) {
  5133. if (this.visible === false) return;
  5134. callback(this);
  5135. const children = this.children;
  5136. for (let i = 0, l = children.length; i < l; i++) {
  5137. children[i].traverseVisible(callback);
  5138. }
  5139. }
  5140. traverseAncestors(callback) {
  5141. const parent = this.parent;
  5142. if (parent !== null) {
  5143. callback(parent);
  5144. parent.traverseAncestors(callback);
  5145. }
  5146. }
  5147. updateMatrix() {
  5148. this.matrix.compose(this.position, this.quaternion, this.scale);
  5149. this.matrixWorldNeedsUpdate = true;
  5150. }
  5151. updateMatrixWorld(force) {
  5152. if (this.matrixAutoUpdate) this.updateMatrix();
  5153. if (this.matrixWorldNeedsUpdate || force) {
  5154. if (this.parent === null) {
  5155. this.matrixWorld.copy(this.matrix);
  5156. } else {
  5157. this.matrixWorld.multiplyMatrices(this.parent.matrixWorld, this.matrix);
  5158. }
  5159. this.matrixWorldNeedsUpdate = false;
  5160. force = true;
  5161. }
  5162. // update children
  5163. const children = this.children;
  5164. for (let i = 0, l = children.length; i < l; i++) {
  5165. const child = children[i];
  5166. if (child.matrixWorldAutoUpdate === true || force === true) {
  5167. child.updateMatrixWorld(force);
  5168. }
  5169. }
  5170. }
  5171. updateWorldMatrix(updateParents, updateChildren) {
  5172. const parent = this.parent;
  5173. if (updateParents === true && parent !== null && parent.matrixWorldAutoUpdate === true) {
  5174. parent.updateWorldMatrix(true, false);
  5175. }
  5176. if (this.matrixAutoUpdate) this.updateMatrix();
  5177. if (this.parent === null) {
  5178. this.matrixWorld.copy(this.matrix);
  5179. } else {
  5180. this.matrixWorld.multiplyMatrices(this.parent.matrixWorld, this.matrix);
  5181. }
  5182. // update children
  5183. if (updateChildren === true) {
  5184. const children = this.children;
  5185. for (let i = 0, l = children.length; i < l; i++) {
  5186. const child = children[i];
  5187. if (child.matrixWorldAutoUpdate === true) {
  5188. child.updateWorldMatrix(false, true);
  5189. }
  5190. }
  5191. }
  5192. }
  5193. toJSON(meta) {
  5194. // meta is a string when called from JSON.stringify
  5195. const isRootObject = meta === undefined || typeof meta === 'string';
  5196. const output = {};
  5197. // meta is a hash used to collect geometries, materials.
  5198. // not providing it implies that this is the root object
  5199. // being serialized.
  5200. if (isRootObject) {
  5201. // initialize meta obj
  5202. meta = {
  5203. geometries: {},
  5204. materials: {},
  5205. textures: {},
  5206. images: {},
  5207. shapes: {},
  5208. skeletons: {},
  5209. animations: {},
  5210. nodes: {}
  5211. };
  5212. output.metadata = {
  5213. version: 4.5,
  5214. type: 'Object',
  5215. generator: 'Object3D.toJSON'
  5216. };
  5217. }
  5218. // standard Object3D serialization
  5219. const object = {};
  5220. object.uuid = this.uuid;
  5221. object.type = this.type;
  5222. if (this.name !== '') object.name = this.name;
  5223. if (this.castShadow === true) object.castShadow = true;
  5224. if (this.receiveShadow === true) object.receiveShadow = true;
  5225. if (this.visible === false) object.visible = false;
  5226. if (this.frustumCulled === false) object.frustumCulled = false;
  5227. if (this.renderOrder !== 0) object.renderOrder = this.renderOrder;
  5228. if (Object.keys(this.userData).length > 0) object.userData = this.userData;
  5229. object.layers = this.layers.mask;
  5230. object.matrix = this.matrix.toArray();
  5231. if (this.matrixAutoUpdate === false) object.matrixAutoUpdate = false;
  5232. // object specific properties
  5233. if (this.isInstancedMesh) {
  5234. object.type = 'InstancedMesh';
  5235. object.count = this.count;
  5236. object.instanceMatrix = this.instanceMatrix.toJSON();
  5237. if (this.instanceColor !== null) object.instanceColor = this.instanceColor.toJSON();
  5238. }
  5239. //
  5240. function serialize(library, element) {
  5241. if (library[element.uuid] === undefined) {
  5242. library[element.uuid] = element.toJSON(meta);
  5243. }
  5244. return element.uuid;
  5245. }
  5246. if (this.isScene) {
  5247. if (this.background) {
  5248. if (this.background.isColor) {
  5249. object.background = this.background.toJSON();
  5250. } else if (this.background.isTexture) {
  5251. object.background = this.background.toJSON(meta).uuid;
  5252. }
  5253. }
  5254. if (this.environment && this.environment.isTexture && this.environment.isRenderTargetTexture !== true) {
  5255. object.environment = this.environment.toJSON(meta).uuid;
  5256. }
  5257. } else if (this.isMesh || this.isLine || this.isPoints) {
  5258. object.geometry = serialize(meta.geometries, this.geometry);
  5259. const parameters = this.geometry.parameters;
  5260. if (parameters !== undefined && parameters.shapes !== undefined) {
  5261. const shapes = parameters.shapes;
  5262. if (Array.isArray(shapes)) {
  5263. for (let i = 0, l = shapes.length; i < l; i++) {
  5264. const shape = shapes[i];
  5265. serialize(meta.shapes, shape);
  5266. }
  5267. } else {
  5268. serialize(meta.shapes, shapes);
  5269. }
  5270. }
  5271. }
  5272. if (this.isSkinnedMesh) {
  5273. object.bindMode = this.bindMode;
  5274. object.bindMatrix = this.bindMatrix.toArray();
  5275. if (this.skeleton !== undefined) {
  5276. serialize(meta.skeletons, this.skeleton);
  5277. object.skeleton = this.skeleton.uuid;
  5278. }
  5279. }
  5280. if (this.material !== undefined) {
  5281. if (Array.isArray(this.material)) {
  5282. const uuids = [];
  5283. for (let i = 0, l = this.material.length; i < l; i++) {
  5284. uuids.push(serialize(meta.materials, this.material[i]));
  5285. }
  5286. object.material = uuids;
  5287. } else {
  5288. object.material = serialize(meta.materials, this.material);
  5289. }
  5290. }
  5291. //
  5292. if (this.children.length > 0) {
  5293. object.children = [];
  5294. for (let i = 0; i < this.children.length; i++) {
  5295. object.children.push(this.children[i].toJSON(meta).object);
  5296. }
  5297. }
  5298. //
  5299. if (this.animations.length > 0) {
  5300. object.animations = [];
  5301. for (let i = 0; i < this.animations.length; i++) {
  5302. const animation = this.animations[i];
  5303. object.animations.push(serialize(meta.animations, animation));
  5304. }
  5305. }
  5306. if (isRootObject) {
  5307. const geometries = extractFromCache(meta.geometries);
  5308. const materials = extractFromCache(meta.materials);
  5309. const textures = extractFromCache(meta.textures);
  5310. const images = extractFromCache(meta.images);
  5311. const shapes = extractFromCache(meta.shapes);
  5312. const skeletons = extractFromCache(meta.skeletons);
  5313. const animations = extractFromCache(meta.animations);
  5314. const nodes = extractFromCache(meta.nodes);
  5315. if (geometries.length > 0) output.geometries = geometries;
  5316. if (materials.length > 0) output.materials = materials;
  5317. if (textures.length > 0) output.textures = textures;
  5318. if (images.length > 0) output.images = images;
  5319. if (shapes.length > 0) output.shapes = shapes;
  5320. if (skeletons.length > 0) output.skeletons = skeletons;
  5321. if (animations.length > 0) output.animations = animations;
  5322. if (nodes.length > 0) output.nodes = nodes;
  5323. }
  5324. output.object = object;
  5325. return output;
  5326. // extract data from the cache hash
  5327. // remove metadata on each item
  5328. // and return as array
  5329. function extractFromCache(cache) {
  5330. const values = [];
  5331. for (const key in cache) {
  5332. const data = cache[key];
  5333. delete data.metadata;
  5334. values.push(data);
  5335. }
  5336. return values;
  5337. }
  5338. }
  5339. clone(recursive) {
  5340. return new this.constructor().copy(this, recursive);
  5341. }
  5342. copy(source, recursive = true) {
  5343. this.name = source.name;
  5344. this.up.copy(source.up);
  5345. this.position.copy(source.position);
  5346. this.rotation.order = source.rotation.order;
  5347. this.quaternion.copy(source.quaternion);
  5348. this.scale.copy(source.scale);
  5349. this.matrix.copy(source.matrix);
  5350. this.matrixWorld.copy(source.matrixWorld);
  5351. this.matrixAutoUpdate = source.matrixAutoUpdate;
  5352. this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;
  5353. this.matrixWorldAutoUpdate = source.matrixWorldAutoUpdate;
  5354. this.layers.mask = source.layers.mask;
  5355. this.visible = source.visible;
  5356. this.castShadow = source.castShadow;
  5357. this.receiveShadow = source.receiveShadow;
  5358. this.frustumCulled = source.frustumCulled;
  5359. this.renderOrder = source.renderOrder;
  5360. this.userData = JSON.parse(JSON.stringify(source.userData));
  5361. if (recursive === true) {
  5362. for (let i = 0; i < source.children.length; i++) {
  5363. const child = source.children[i];
  5364. this.add(child.clone());
  5365. }
  5366. }
  5367. return this;
  5368. }
  5369. }
  5370. Object3D.DefaultUp = /*@__PURE__*/new Vector3(0, 1, 0);
  5371. Object3D.DefaultMatrixAutoUpdate = true;
  5372. Object3D.DefaultMatrixWorldAutoUpdate = true;
  5373. const _v0$1 = /*@__PURE__*/new Vector3();
  5374. const _v1$3 = /*@__PURE__*/new Vector3();
  5375. const _v2$2 = /*@__PURE__*/new Vector3();
  5376. const _v3$1 = /*@__PURE__*/new Vector3();
  5377. const _vab = /*@__PURE__*/new Vector3();
  5378. const _vac = /*@__PURE__*/new Vector3();
  5379. const _vbc = /*@__PURE__*/new Vector3();
  5380. const _vap = /*@__PURE__*/new Vector3();
  5381. const _vbp = /*@__PURE__*/new Vector3();
  5382. const _vcp = /*@__PURE__*/new Vector3();
  5383. class Triangle {
  5384. constructor(a = new Vector3(), b = new Vector3(), c = new Vector3()) {
  5385. this.a = a;
  5386. this.b = b;
  5387. this.c = c;
  5388. }
  5389. static getNormal(a, b, c, target) {
  5390. target.subVectors(c, b);
  5391. _v0$1.subVectors(a, b);
  5392. target.cross(_v0$1);
  5393. const targetLengthSq = target.lengthSq();
  5394. if (targetLengthSq > 0) {
  5395. return target.multiplyScalar(1 / Math.sqrt(targetLengthSq));
  5396. }
  5397. return target.set(0, 0, 0);
  5398. }
  5399. // static/instance method to calculate barycentric coordinates
  5400. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  5401. static getBarycoord(point, a, b, c, target) {
  5402. _v0$1.subVectors(c, a);
  5403. _v1$3.subVectors(b, a);
  5404. _v2$2.subVectors(point, a);
  5405. const dot00 = _v0$1.dot(_v0$1);
  5406. const dot01 = _v0$1.dot(_v1$3);
  5407. const dot02 = _v0$1.dot(_v2$2);
  5408. const dot11 = _v1$3.dot(_v1$3);
  5409. const dot12 = _v1$3.dot(_v2$2);
  5410. const denom = dot00 * dot11 - dot01 * dot01;
  5411. // collinear or singular triangle
  5412. if (denom === 0) {
  5413. // arbitrary location outside of triangle?
  5414. // not sure if this is the best idea, maybe should be returning undefined
  5415. return target.set(-2, -1, -1);
  5416. }
  5417. const invDenom = 1 / denom;
  5418. const u = (dot11 * dot02 - dot01 * dot12) * invDenom;
  5419. const v = (dot00 * dot12 - dot01 * dot02) * invDenom;
  5420. // barycentric coordinates must always sum to 1
  5421. return target.set(1 - u - v, v, u);
  5422. }
  5423. static containsPoint(point, a, b, c) {
  5424. this.getBarycoord(point, a, b, c, _v3$1);
  5425. return _v3$1.x >= 0 && _v3$1.y >= 0 && _v3$1.x + _v3$1.y <= 1;
  5426. }
  5427. static getUV(point, p1, p2, p3, uv1, uv2, uv3, target) {
  5428. this.getBarycoord(point, p1, p2, p3, _v3$1);
  5429. target.set(0, 0);
  5430. target.addScaledVector(uv1, _v3$1.x);
  5431. target.addScaledVector(uv2, _v3$1.y);
  5432. target.addScaledVector(uv3, _v3$1.z);
  5433. return target;
  5434. }
  5435. static isFrontFacing(a, b, c, direction) {
  5436. _v0$1.subVectors(c, b);
  5437. _v1$3.subVectors(a, b);
  5438. // strictly front facing
  5439. return _v0$1.cross(_v1$3).dot(direction) < 0 ? true : false;
  5440. }
  5441. set(a, b, c) {
  5442. this.a.copy(a);
  5443. this.b.copy(b);
  5444. this.c.copy(c);
  5445. return this;
  5446. }
  5447. setFromPointsAndIndices(points, i0, i1, i2) {
  5448. this.a.copy(points[i0]);
  5449. this.b.copy(points[i1]);
  5450. this.c.copy(points[i2]);
  5451. return this;
  5452. }
  5453. setFromAttributeAndIndices(attribute, i0, i1, i2) {
  5454. this.a.fromBufferAttribute(attribute, i0);
  5455. this.b.fromBufferAttribute(attribute, i1);
  5456. this.c.fromBufferAttribute(attribute, i2);
  5457. return this;
  5458. }
  5459. clone() {
  5460. return new this.constructor().copy(this);
  5461. }
  5462. copy(triangle) {
  5463. this.a.copy(triangle.a);
  5464. this.b.copy(triangle.b);
  5465. this.c.copy(triangle.c);
  5466. return this;
  5467. }
  5468. getArea() {
  5469. _v0$1.subVectors(this.c, this.b);
  5470. _v1$3.subVectors(this.a, this.b);
  5471. return _v0$1.cross(_v1$3).length() * 0.5;
  5472. }
  5473. getMidpoint(target) {
  5474. return target.addVectors(this.a, this.b).add(this.c).multiplyScalar(1 / 3);
  5475. }
  5476. getNormal(target) {
  5477. return Triangle.getNormal(this.a, this.b, this.c, target);
  5478. }
  5479. getPlane(target) {
  5480. return target.setFromCoplanarPoints(this.a, this.b, this.c);
  5481. }
  5482. getBarycoord(point, target) {
  5483. return Triangle.getBarycoord(point, this.a, this.b, this.c, target);
  5484. }
  5485. getUV(point, uv1, uv2, uv3, target) {
  5486. return Triangle.getUV(point, this.a, this.b, this.c, uv1, uv2, uv3, target);
  5487. }
  5488. containsPoint(point) {
  5489. return Triangle.containsPoint(point, this.a, this.b, this.c);
  5490. }
  5491. isFrontFacing(direction) {
  5492. return Triangle.isFrontFacing(this.a, this.b, this.c, direction);
  5493. }
  5494. intersectsBox(box) {
  5495. return box.intersectsTriangle(this);
  5496. }
  5497. closestPointToPoint(p, target) {
  5498. const a = this.a,
  5499. b = this.b,
  5500. c = this.c;
  5501. let v, w;
  5502. // algorithm thanks to Real-Time Collision Detection by Christer Ericson,
  5503. // published by Morgan Kaufmann Publishers, (c) 2005 Elsevier Inc.,
  5504. // under the accompanying license; see chapter 5.1.5 for detailed explanation.
  5505. // basically, we're distinguishing which of the voronoi regions of the triangle
  5506. // the point lies in with the minimum amount of redundant computation.
  5507. _vab.subVectors(b, a);
  5508. _vac.subVectors(c, a);
  5509. _vap.subVectors(p, a);
  5510. const d1 = _vab.dot(_vap);
  5511. const d2 = _vac.dot(_vap);
  5512. if (d1 <= 0 && d2 <= 0) {
  5513. // vertex region of A; barycentric coords (1, 0, 0)
  5514. return target.copy(a);
  5515. }
  5516. _vbp.subVectors(p, b);
  5517. const d3 = _vab.dot(_vbp);
  5518. const d4 = _vac.dot(_vbp);
  5519. if (d3 >= 0 && d4 <= d3) {
  5520. // vertex region of B; barycentric coords (0, 1, 0)
  5521. return target.copy(b);
  5522. }
  5523. const vc = d1 * d4 - d3 * d2;
  5524. if (vc <= 0 && d1 >= 0 && d3 <= 0) {
  5525. v = d1 / (d1 - d3);
  5526. // edge region of AB; barycentric coords (1-v, v, 0)
  5527. return target.copy(a).addScaledVector(_vab, v);
  5528. }
  5529. _vcp.subVectors(p, c);
  5530. const d5 = _vab.dot(_vcp);
  5531. const d6 = _vac.dot(_vcp);
  5532. if (d6 >= 0 && d5 <= d6) {
  5533. // vertex region of C; barycentric coords (0, 0, 1)
  5534. return target.copy(c);
  5535. }
  5536. const vb = d5 * d2 - d1 * d6;
  5537. if (vb <= 0 && d2 >= 0 && d6 <= 0) {
  5538. w = d2 / (d2 - d6);
  5539. // edge region of AC; barycentric coords (1-w, 0, w)
  5540. return target.copy(a).addScaledVector(_vac, w);
  5541. }
  5542. const va = d3 * d6 - d5 * d4;
  5543. if (va <= 0 && d4 - d3 >= 0 && d5 - d6 >= 0) {
  5544. _vbc.subVectors(c, b);
  5545. w = (d4 - d3) / (d4 - d3 + (d5 - d6));
  5546. // edge region of BC; barycentric coords (0, 1-w, w)
  5547. return target.copy(b).addScaledVector(_vbc, w); // edge region of BC
  5548. }
  5549. // face region
  5550. const denom = 1 / (va + vb + vc);
  5551. // u = va * denom
  5552. v = vb * denom;
  5553. w = vc * denom;
  5554. return target.copy(a).addScaledVector(_vab, v).addScaledVector(_vac, w);
  5555. }
  5556. equals(triangle) {
  5557. return triangle.a.equals(this.a) && triangle.b.equals(this.b) && triangle.c.equals(this.c);
  5558. }
  5559. }
  5560. let materialId = 0;
  5561. class Material extends EventDispatcher {
  5562. constructor() {
  5563. super();
  5564. this.isMaterial = true;
  5565. Object.defineProperty(this, 'id', {
  5566. value: materialId++
  5567. });
  5568. this.uuid = generateUUID();
  5569. this.name = '';
  5570. this.type = 'Material';
  5571. this.blending = NormalBlending;
  5572. this.side = FrontSide;
  5573. this.vertexColors = false;
  5574. this.opacity = 1;
  5575. this.transparent = false;
  5576. this.blendSrc = SrcAlphaFactor;
  5577. this.blendDst = OneMinusSrcAlphaFactor;
  5578. this.blendEquation = AddEquation;
  5579. this.blendSrcAlpha = null;
  5580. this.blendDstAlpha = null;
  5581. this.blendEquationAlpha = null;
  5582. this.depthFunc = LessEqualDepth;
  5583. this.depthTest = true;
  5584. this.depthWrite = true;
  5585. this.stencilWriteMask = 0xff;
  5586. this.stencilFunc = AlwaysStencilFunc;
  5587. this.stencilRef = 0;
  5588. this.stencilFuncMask = 0xff;
  5589. this.stencilFail = KeepStencilOp;
  5590. this.stencilZFail = KeepStencilOp;
  5591. this.stencilZPass = KeepStencilOp;
  5592. this.stencilWrite = false;
  5593. this.clippingPlanes = null;
  5594. this.clipIntersection = false;
  5595. this.clipShadows = false;
  5596. this.shadowSide = null;
  5597. this.colorWrite = true;
  5598. this.precision = null; // override the renderer's default precision for this material
  5599. this.polygonOffset = false;
  5600. this.polygonOffsetFactor = 0;
  5601. this.polygonOffsetUnits = 0;
  5602. this.dithering = false;
  5603. this.alphaToCoverage = false;
  5604. this.premultipliedAlpha = false;
  5605. this.visible = true;
  5606. this.toneMapped = true;
  5607. this.userData = {};
  5608. this.version = 0;
  5609. this._alphaTest = 0;
  5610. }
  5611. get alphaTest() {
  5612. return this._alphaTest;
  5613. }
  5614. set alphaTest(value) {
  5615. if (this._alphaTest > 0 !== value > 0) {
  5616. this.version++;
  5617. }
  5618. this._alphaTest = value;
  5619. }
  5620. onBuild( /* shaderobject, renderer */) {}
  5621. onBeforeRender( /* renderer, scene, camera, geometry, object, group */) {}
  5622. onBeforeCompile( /* shaderobject, renderer */) {}
  5623. customProgramCacheKey() {
  5624. return this.onBeforeCompile.toString();
  5625. }
  5626. setValues(values) {
  5627. if (values === undefined) return;
  5628. for (const key in values) {
  5629. const newValue = values[key];
  5630. if (newValue === undefined) {
  5631. console.warn('THREE.Material: \'' + key + '\' parameter is undefined.');
  5632. continue;
  5633. }
  5634. const currentValue = this[key];
  5635. if (currentValue === undefined) {
  5636. console.warn('THREE.' + this.type + ': \'' + key + '\' is not a property of this material.');
  5637. continue;
  5638. }
  5639. if (currentValue && currentValue.isColor) {
  5640. currentValue.set(newValue);
  5641. } else if (currentValue && currentValue.isVector3 && newValue && newValue.isVector3) {
  5642. currentValue.copy(newValue);
  5643. } else {
  5644. this[key] = newValue;
  5645. }
  5646. }
  5647. }
  5648. toJSON(meta) {
  5649. const isRootObject = meta === undefined || typeof meta === 'string';
  5650. if (isRootObject) {
  5651. meta = {
  5652. textures: {},
  5653. images: {}
  5654. };
  5655. }
  5656. const data = {
  5657. metadata: {
  5658. version: 4.5,
  5659. type: 'Material',
  5660. generator: 'Material.toJSON'
  5661. }
  5662. };
  5663. // standard Material serialization
  5664. data.uuid = this.uuid;
  5665. data.type = this.type;
  5666. if (this.name !== '') data.name = this.name;
  5667. if (this.color && this.color.isColor) data.color = this.color.getHex();
  5668. if (this.roughness !== undefined) data.roughness = this.roughness;
  5669. if (this.metalness !== undefined) data.metalness = this.metalness;
  5670. if (this.sheen !== undefined) data.sheen = this.sheen;
  5671. if (this.sheenColor && this.sheenColor.isColor) data.sheenColor = this.sheenColor.getHex();
  5672. if (this.sheenRoughness !== undefined) data.sheenRoughness = this.sheenRoughness;
  5673. if (this.emissive && this.emissive.isColor) data.emissive = this.emissive.getHex();
  5674. if (this.emissiveIntensity && this.emissiveIntensity !== 1) data.emissiveIntensity = this.emissiveIntensity;
  5675. if (this.specular && this.specular.isColor) data.specular = this.specular.getHex();
  5676. if (this.specularIntensity !== undefined) data.specularIntensity = this.specularIntensity;
  5677. if (this.specularColor && this.specularColor.isColor) data.specularColor = this.specularColor.getHex();
  5678. if (this.shininess !== undefined) data.shininess = this.shininess;
  5679. if (this.clearcoat !== undefined) data.clearcoat = this.clearcoat;
  5680. if (this.clearcoatRoughness !== undefined) data.clearcoatRoughness = this.clearcoatRoughness;
  5681. if (this.clearcoatMap && this.clearcoatMap.isTexture) {
  5682. data.clearcoatMap = this.clearcoatMap.toJSON(meta).uuid;
  5683. }
  5684. if (this.clearcoatRoughnessMap && this.clearcoatRoughnessMap.isTexture) {
  5685. data.clearcoatRoughnessMap = this.clearcoatRoughnessMap.toJSON(meta).uuid;
  5686. }
  5687. if (this.clearcoatNormalMap && this.clearcoatNormalMap.isTexture) {
  5688. data.clearcoatNormalMap = this.clearcoatNormalMap.toJSON(meta).uuid;
  5689. data.clearcoatNormalScale = this.clearcoatNormalScale.toArray();
  5690. }
  5691. if (this.iridescence !== undefined) data.iridescence = this.iridescence;
  5692. if (this.iridescenceIOR !== undefined) data.iridescenceIOR = this.iridescenceIOR;
  5693. if (this.iridescenceThicknessRange !== undefined) data.iridescenceThicknessRange = this.iridescenceThicknessRange;
  5694. if (this.iridescenceMap && this.iridescenceMap.isTexture) {
  5695. data.iridescenceMap = this.iridescenceMap.toJSON(meta).uuid;
  5696. }
  5697. if (this.iridescenceThicknessMap && this.iridescenceThicknessMap.isTexture) {
  5698. data.iridescenceThicknessMap = this.iridescenceThicknessMap.toJSON(meta).uuid;
  5699. }
  5700. if (this.map && this.map.isTexture) data.map = this.map.toJSON(meta).uuid;
  5701. if (this.matcap && this.matcap.isTexture) data.matcap = this.matcap.toJSON(meta).uuid;
  5702. if (this.alphaMap && this.alphaMap.isTexture) data.alphaMap = this.alphaMap.toJSON(meta).uuid;
  5703. if (this.lightMap && this.lightMap.isTexture) {
  5704. data.lightMap = this.lightMap.toJSON(meta).uuid;
  5705. data.lightMapIntensity = this.lightMapIntensity;
  5706. }
  5707. if (this.aoMap && this.aoMap.isTexture) {
  5708. data.aoMap = this.aoMap.toJSON(meta).uuid;
  5709. data.aoMapIntensity = this.aoMapIntensity;
  5710. }
  5711. if (this.bumpMap && this.bumpMap.isTexture) {
  5712. data.bumpMap = this.bumpMap.toJSON(meta).uuid;
  5713. data.bumpScale = this.bumpScale;
  5714. }
  5715. if (this.normalMap && this.normalMap.isTexture) {
  5716. data.normalMap = this.normalMap.toJSON(meta).uuid;
  5717. data.normalMapType = this.normalMapType;
  5718. data.normalScale = this.normalScale.toArray();
  5719. }
  5720. if (this.displacementMap && this.displacementMap.isTexture) {
  5721. data.displacementMap = this.displacementMap.toJSON(meta).uuid;
  5722. data.displacementScale = this.displacementScale;
  5723. data.displacementBias = this.displacementBias;
  5724. }
  5725. if (this.roughnessMap && this.roughnessMap.isTexture) data.roughnessMap = this.roughnessMap.toJSON(meta).uuid;
  5726. if (this.metalnessMap && this.metalnessMap.isTexture) data.metalnessMap = this.metalnessMap.toJSON(meta).uuid;
  5727. if (this.emissiveMap && this.emissiveMap.isTexture) data.emissiveMap = this.emissiveMap.toJSON(meta).uuid;
  5728. if (this.specularMap && this.specularMap.isTexture) data.specularMap = this.specularMap.toJSON(meta).uuid;
  5729. if (this.specularIntensityMap && this.specularIntensityMap.isTexture) data.specularIntensityMap = this.specularIntensityMap.toJSON(meta).uuid;
  5730. if (this.specularColorMap && this.specularColorMap.isTexture) data.specularColorMap = this.specularColorMap.toJSON(meta).uuid;
  5731. if (this.envMap && this.envMap.isTexture) {
  5732. data.envMap = this.envMap.toJSON(meta).uuid;
  5733. if (this.combine !== undefined) data.combine = this.combine;
  5734. }
  5735. if (this.envMapIntensity !== undefined) data.envMapIntensity = this.envMapIntensity;
  5736. if (this.reflectivity !== undefined) data.reflectivity = this.reflectivity;
  5737. if (this.refractionRatio !== undefined) data.refractionRatio = this.refractionRatio;
  5738. if (this.gradientMap && this.gradientMap.isTexture) {
  5739. data.gradientMap = this.gradientMap.toJSON(meta).uuid;
  5740. }
  5741. if (this.transmission !== undefined) data.transmission = this.transmission;
  5742. if (this.transmissionMap && this.transmissionMap.isTexture) data.transmissionMap = this.transmissionMap.toJSON(meta).uuid;
  5743. if (this.thickness !== undefined) data.thickness = this.thickness;
  5744. if (this.thicknessMap && this.thicknessMap.isTexture) data.thicknessMap = this.thicknessMap.toJSON(meta).uuid;
  5745. if (this.attenuationDistance !== undefined && this.attenuationDistance !== Infinity) data.attenuationDistance = this.attenuationDistance;
  5746. if (this.attenuationColor !== undefined) data.attenuationColor = this.attenuationColor.getHex();
  5747. if (this.size !== undefined) data.size = this.size;
  5748. if (this.shadowSide !== null) data.shadowSide = this.shadowSide;
  5749. if (this.sizeAttenuation !== undefined) data.sizeAttenuation = this.sizeAttenuation;
  5750. if (this.blending !== NormalBlending) data.blending = this.blending;
  5751. if (this.side !== FrontSide) data.side = this.side;
  5752. if (this.vertexColors) data.vertexColors = true;
  5753. if (this.opacity < 1) data.opacity = this.opacity;
  5754. if (this.transparent === true) data.transparent = this.transparent;
  5755. data.depthFunc = this.depthFunc;
  5756. data.depthTest = this.depthTest;
  5757. data.depthWrite = this.depthWrite;
  5758. data.colorWrite = this.colorWrite;
  5759. data.stencilWrite = this.stencilWrite;
  5760. data.stencilWriteMask = this.stencilWriteMask;
  5761. data.stencilFunc = this.stencilFunc;
  5762. data.stencilRef = this.stencilRef;
  5763. data.stencilFuncMask = this.stencilFuncMask;
  5764. data.stencilFail = this.stencilFail;
  5765. data.stencilZFail = this.stencilZFail;
  5766. data.stencilZPass = this.stencilZPass;
  5767. // rotation (SpriteMaterial)
  5768. if (this.rotation !== undefined && this.rotation !== 0) data.rotation = this.rotation;
  5769. if (this.polygonOffset === true) data.polygonOffset = true;
  5770. if (this.polygonOffsetFactor !== 0) data.polygonOffsetFactor = this.polygonOffsetFactor;
  5771. if (this.polygonOffsetUnits !== 0) data.polygonOffsetUnits = this.polygonOffsetUnits;
  5772. if (this.linewidth !== undefined && this.linewidth !== 1) data.linewidth = this.linewidth;
  5773. if (this.dashSize !== undefined) data.dashSize = this.dashSize;
  5774. if (this.gapSize !== undefined) data.gapSize = this.gapSize;
  5775. if (this.scale !== undefined) data.scale = this.scale;
  5776. if (this.dithering === true) data.dithering = true;
  5777. if (this.alphaTest > 0) data.alphaTest = this.alphaTest;
  5778. if (this.alphaToCoverage === true) data.alphaToCoverage = this.alphaToCoverage;
  5779. if (this.premultipliedAlpha === true) data.premultipliedAlpha = this.premultipliedAlpha;
  5780. if (this.wireframe === true) data.wireframe = this.wireframe;
  5781. if (this.wireframeLinewidth > 1) data.wireframeLinewidth = this.wireframeLinewidth;
  5782. if (this.wireframeLinecap !== 'round') data.wireframeLinecap = this.wireframeLinecap;
  5783. if (this.wireframeLinejoin !== 'round') data.wireframeLinejoin = this.wireframeLinejoin;
  5784. if (this.flatShading === true) data.flatShading = this.flatShading;
  5785. if (this.visible === false) data.visible = false;
  5786. if (this.toneMapped === false) data.toneMapped = false;
  5787. if (this.fog === false) data.fog = false;
  5788. if (Object.keys(this.userData).length > 0) data.userData = this.userData;
  5789. // TODO: Copied from Object3D.toJSON
  5790. function extractFromCache(cache) {
  5791. const values = [];
  5792. for (const key in cache) {
  5793. const data = cache[key];
  5794. delete data.metadata;
  5795. values.push(data);
  5796. }
  5797. return values;
  5798. }
  5799. if (isRootObject) {
  5800. const textures = extractFromCache(meta.textures);
  5801. const images = extractFromCache(meta.images);
  5802. if (textures.length > 0) data.textures = textures;
  5803. if (images.length > 0) data.images = images;
  5804. }
  5805. return data;
  5806. }
  5807. clone() {
  5808. return new this.constructor().copy(this);
  5809. }
  5810. copy(source) {
  5811. this.name = source.name;
  5812. this.blending = source.blending;
  5813. this.side = source.side;
  5814. this.vertexColors = source.vertexColors;
  5815. this.opacity = source.opacity;
  5816. this.transparent = source.transparent;
  5817. this.blendSrc = source.blendSrc;
  5818. this.blendDst = source.blendDst;
  5819. this.blendEquation = source.blendEquation;
  5820. this.blendSrcAlpha = source.blendSrcAlpha;
  5821. this.blendDstAlpha = source.blendDstAlpha;
  5822. this.blendEquationAlpha = source.blendEquationAlpha;
  5823. this.depthFunc = source.depthFunc;
  5824. this.depthTest = source.depthTest;
  5825. this.depthWrite = source.depthWrite;
  5826. this.stencilWriteMask = source.stencilWriteMask;
  5827. this.stencilFunc = source.stencilFunc;
  5828. this.stencilRef = source.stencilRef;
  5829. this.stencilFuncMask = source.stencilFuncMask;
  5830. this.stencilFail = source.stencilFail;
  5831. this.stencilZFail = source.stencilZFail;
  5832. this.stencilZPass = source.stencilZPass;
  5833. this.stencilWrite = source.stencilWrite;
  5834. const srcPlanes = source.clippingPlanes;
  5835. let dstPlanes = null;
  5836. if (srcPlanes !== null) {
  5837. const n = srcPlanes.length;
  5838. dstPlanes = new Array(n);
  5839. for (let i = 0; i !== n; ++i) {
  5840. dstPlanes[i] = srcPlanes[i].clone();
  5841. }
  5842. }
  5843. this.clippingPlanes = dstPlanes;
  5844. this.clipIntersection = source.clipIntersection;
  5845. this.clipShadows = source.clipShadows;
  5846. this.shadowSide = source.shadowSide;
  5847. this.colorWrite = source.colorWrite;
  5848. this.precision = source.precision;
  5849. this.polygonOffset = source.polygonOffset;
  5850. this.polygonOffsetFactor = source.polygonOffsetFactor;
  5851. this.polygonOffsetUnits = source.polygonOffsetUnits;
  5852. this.dithering = source.dithering;
  5853. this.alphaTest = source.alphaTest;
  5854. this.alphaToCoverage = source.alphaToCoverage;
  5855. this.premultipliedAlpha = source.premultipliedAlpha;
  5856. this.visible = source.visible;
  5857. this.toneMapped = source.toneMapped;
  5858. this.userData = JSON.parse(JSON.stringify(source.userData));
  5859. return this;
  5860. }
  5861. dispose() {
  5862. this.dispatchEvent({
  5863. type: 'dispose'
  5864. });
  5865. }
  5866. set needsUpdate(value) {
  5867. if (value === true) this.version++;
  5868. }
  5869. }
  5870. class MeshBasicMaterial extends Material {
  5871. constructor(parameters) {
  5872. super();
  5873. this.isMeshBasicMaterial = true;
  5874. this.type = 'MeshBasicMaterial';
  5875. this.color = new Color(0xffffff); // emissive
  5876. this.map = null;
  5877. this.lightMap = null;
  5878. this.lightMapIntensity = 1.0;
  5879. this.aoMap = null;
  5880. this.aoMapIntensity = 1.0;
  5881. this.specularMap = null;
  5882. this.alphaMap = null;
  5883. this.envMap = null;
  5884. this.combine = MultiplyOperation;
  5885. this.reflectivity = 1;
  5886. this.refractionRatio = 0.98;
  5887. this.wireframe = false;
  5888. this.wireframeLinewidth = 1;
  5889. this.wireframeLinecap = 'round';
  5890. this.wireframeLinejoin = 'round';
  5891. this.fog = true;
  5892. this.setValues(parameters);
  5893. }
  5894. copy(source) {
  5895. super.copy(source);
  5896. this.color.copy(source.color);
  5897. this.map = source.map;
  5898. this.lightMap = source.lightMap;
  5899. this.lightMapIntensity = source.lightMapIntensity;
  5900. this.aoMap = source.aoMap;
  5901. this.aoMapIntensity = source.aoMapIntensity;
  5902. this.specularMap = source.specularMap;
  5903. this.alphaMap = source.alphaMap;
  5904. this.envMap = source.envMap;
  5905. this.combine = source.combine;
  5906. this.reflectivity = source.reflectivity;
  5907. this.refractionRatio = source.refractionRatio;
  5908. this.wireframe = source.wireframe;
  5909. this.wireframeLinewidth = source.wireframeLinewidth;
  5910. this.wireframeLinecap = source.wireframeLinecap;
  5911. this.wireframeLinejoin = source.wireframeLinejoin;
  5912. this.fog = source.fog;
  5913. return this;
  5914. }
  5915. }
  5916. const _vector$9 = /*@__PURE__*/new Vector3();
  5917. const _vector2$1 = /*@__PURE__*/new Vector2();
  5918. class BufferAttribute {
  5919. constructor(array, itemSize, normalized = false) {
  5920. if (Array.isArray(array)) {
  5921. throw new TypeError('THREE.BufferAttribute: array should be a Typed Array.');
  5922. }
  5923. this.isBufferAttribute = true;
  5924. this.name = '';
  5925. this.array = array;
  5926. this.itemSize = itemSize;
  5927. this.count = array !== undefined ? array.length / itemSize : 0;
  5928. this.normalized = normalized;
  5929. this.usage = StaticDrawUsage;
  5930. this.updateRange = {
  5931. offset: 0,
  5932. count: -1
  5933. };
  5934. this.version = 0;
  5935. }
  5936. onUploadCallback() {}
  5937. set needsUpdate(value) {
  5938. if (value === true) this.version++;
  5939. }
  5940. setUsage(value) {
  5941. this.usage = value;
  5942. return this;
  5943. }
  5944. copy(source) {
  5945. this.name = source.name;
  5946. this.array = new source.array.constructor(source.array);
  5947. this.itemSize = source.itemSize;
  5948. this.count = source.count;
  5949. this.normalized = source.normalized;
  5950. this.usage = source.usage;
  5951. return this;
  5952. }
  5953. copyAt(index1, attribute, index2) {
  5954. index1 *= this.itemSize;
  5955. index2 *= attribute.itemSize;
  5956. for (let i = 0, l = this.itemSize; i < l; i++) {
  5957. this.array[index1 + i] = attribute.array[index2 + i];
  5958. }
  5959. return this;
  5960. }
  5961. copyArray(array) {
  5962. this.array.set(array);
  5963. return this;
  5964. }
  5965. applyMatrix3(m) {
  5966. if (this.itemSize === 2) {
  5967. for (let i = 0, l = this.count; i < l; i++) {
  5968. _vector2$1.fromBufferAttribute(this, i);
  5969. _vector2$1.applyMatrix3(m);
  5970. this.setXY(i, _vector2$1.x, _vector2$1.y);
  5971. }
  5972. } else if (this.itemSize === 3) {
  5973. for (let i = 0, l = this.count; i < l; i++) {
  5974. _vector$9.fromBufferAttribute(this, i);
  5975. _vector$9.applyMatrix3(m);
  5976. this.setXYZ(i, _vector$9.x, _vector$9.y, _vector$9.z);
  5977. }
  5978. }
  5979. return this;
  5980. }
  5981. applyMatrix4(m) {
  5982. for (let i = 0, l = this.count; i < l; i++) {
  5983. _vector$9.fromBufferAttribute(this, i);
  5984. _vector$9.applyMatrix4(m);
  5985. this.setXYZ(i, _vector$9.x, _vector$9.y, _vector$9.z);
  5986. }
  5987. return this;
  5988. }
  5989. applyNormalMatrix(m) {
  5990. for (let i = 0, l = this.count; i < l; i++) {
  5991. _vector$9.fromBufferAttribute(this, i);
  5992. _vector$9.applyNormalMatrix(m);
  5993. this.setXYZ(i, _vector$9.x, _vector$9.y, _vector$9.z);
  5994. }
  5995. return this;
  5996. }
  5997. transformDirection(m) {
  5998. for (let i = 0, l = this.count; i < l; i++) {
  5999. _vector$9.fromBufferAttribute(this, i);
  6000. _vector$9.transformDirection(m);
  6001. this.setXYZ(i, _vector$9.x, _vector$9.y, _vector$9.z);
  6002. }
  6003. return this;
  6004. }
  6005. set(value, offset = 0) {
  6006. // Matching BufferAttribute constructor, do not normalize the array.
  6007. this.array.set(value, offset);
  6008. return this;
  6009. }
  6010. getX(index) {
  6011. let x = this.array[index * this.itemSize];
  6012. if (this.normalized) x = denormalize(x, this.array);
  6013. return x;
  6014. }
  6015. setX(index, x) {
  6016. if (this.normalized) x = normalize(x, this.array);
  6017. this.array[index * this.itemSize] = x;
  6018. return this;
  6019. }
  6020. getY(index) {
  6021. let y = this.array[index * this.itemSize + 1];
  6022. if (this.normalized) y = denormalize(y, this.array);
  6023. return y;
  6024. }
  6025. setY(index, y) {
  6026. if (this.normalized) y = normalize(y, this.array);
  6027. this.array[index * this.itemSize + 1] = y;
  6028. return this;
  6029. }
  6030. getZ(index) {
  6031. let z = this.array[index * this.itemSize + 2];
  6032. if (this.normalized) z = denormalize(z, this.array);
  6033. return z;
  6034. }
  6035. setZ(index, z) {
  6036. if (this.normalized) z = normalize(z, this.array);
  6037. this.array[index * this.itemSize + 2] = z;
  6038. return this;
  6039. }
  6040. getW(index) {
  6041. let w = this.array[index * this.itemSize + 3];
  6042. if (this.normalized) w = denormalize(w, this.array);
  6043. return w;
  6044. }
  6045. setW(index, w) {
  6046. if (this.normalized) w = normalize(w, this.array);
  6047. this.array[index * this.itemSize + 3] = w;
  6048. return this;
  6049. }
  6050. setXY(index, x, y) {
  6051. index *= this.itemSize;
  6052. if (this.normalized) {
  6053. x = normalize(x, this.array);
  6054. y = normalize(y, this.array);
  6055. }
  6056. this.array[index + 0] = x;
  6057. this.array[index + 1] = y;
  6058. return this;
  6059. }
  6060. setXYZ(index, x, y, z) {
  6061. index *= this.itemSize;
  6062. if (this.normalized) {
  6063. x = normalize(x, this.array);
  6064. y = normalize(y, this.array);
  6065. z = normalize(z, this.array);
  6066. }
  6067. this.array[index + 0] = x;
  6068. this.array[index + 1] = y;
  6069. this.array[index + 2] = z;
  6070. return this;
  6071. }
  6072. setXYZW(index, x, y, z, w) {
  6073. index *= this.itemSize;
  6074. if (this.normalized) {
  6075. x = normalize(x, this.array);
  6076. y = normalize(y, this.array);
  6077. z = normalize(z, this.array);
  6078. w = normalize(w, this.array);
  6079. }
  6080. this.array[index + 0] = x;
  6081. this.array[index + 1] = y;
  6082. this.array[index + 2] = z;
  6083. this.array[index + 3] = w;
  6084. return this;
  6085. }
  6086. onUpload(callback) {
  6087. this.onUploadCallback = callback;
  6088. return this;
  6089. }
  6090. clone() {
  6091. return new this.constructor(this.array, this.itemSize).copy(this);
  6092. }
  6093. toJSON() {
  6094. const data = {
  6095. itemSize: this.itemSize,
  6096. type: this.array.constructor.name,
  6097. array: Array.from(this.array),
  6098. normalized: this.normalized
  6099. };
  6100. if (this.name !== '') data.name = this.name;
  6101. if (this.usage !== StaticDrawUsage) data.usage = this.usage;
  6102. if (this.updateRange.offset !== 0 || this.updateRange.count !== -1) data.updateRange = this.updateRange;
  6103. return data;
  6104. }
  6105. // @deprecated
  6106. copyColorsArray() {
  6107. console.error('THREE.BufferAttribute: copyColorsArray() was removed in r144.');
  6108. }
  6109. copyVector2sArray() {
  6110. console.error('THREE.BufferAttribute: copyVector2sArray() was removed in r144.');
  6111. }
  6112. copyVector3sArray() {
  6113. console.error('THREE.BufferAttribute: copyVector3sArray() was removed in r144.');
  6114. }
  6115. copyVector4sArray() {
  6116. console.error('THREE.BufferAttribute: copyVector4sArray() was removed in r144.');
  6117. }
  6118. }
  6119. //
  6120. class Int8BufferAttribute extends BufferAttribute {
  6121. constructor(array, itemSize, normalized) {
  6122. super(new Int8Array(array), itemSize, normalized);
  6123. }
  6124. }
  6125. class Uint8BufferAttribute extends BufferAttribute {
  6126. constructor(array, itemSize, normalized) {
  6127. super(new Uint8Array(array), itemSize, normalized);
  6128. }
  6129. }
  6130. class Uint8ClampedBufferAttribute extends BufferAttribute {
  6131. constructor(array, itemSize, normalized) {
  6132. super(new Uint8ClampedArray(array), itemSize, normalized);
  6133. }
  6134. }
  6135. class Int16BufferAttribute extends BufferAttribute {
  6136. constructor(array, itemSize, normalized) {
  6137. super(new Int16Array(array), itemSize, normalized);
  6138. }
  6139. }
  6140. class Uint16BufferAttribute extends BufferAttribute {
  6141. constructor(array, itemSize, normalized) {
  6142. super(new Uint16Array(array), itemSize, normalized);
  6143. }
  6144. }
  6145. class Int32BufferAttribute extends BufferAttribute {
  6146. constructor(array, itemSize, normalized) {
  6147. super(new Int32Array(array), itemSize, normalized);
  6148. }
  6149. }
  6150. class Uint32BufferAttribute extends BufferAttribute {
  6151. constructor(array, itemSize, normalized) {
  6152. super(new Uint32Array(array), itemSize, normalized);
  6153. }
  6154. }
  6155. class Float16BufferAttribute extends BufferAttribute {
  6156. constructor(array, itemSize, normalized) {
  6157. super(new Uint16Array(array), itemSize, normalized);
  6158. this.isFloat16BufferAttribute = true;
  6159. }
  6160. }
  6161. class Float32BufferAttribute extends BufferAttribute {
  6162. constructor(array, itemSize, normalized) {
  6163. super(new Float32Array(array), itemSize, normalized);
  6164. }
  6165. }
  6166. class Float64BufferAttribute extends BufferAttribute {
  6167. constructor(array, itemSize, normalized) {
  6168. super(new Float64Array(array), itemSize, normalized);
  6169. }
  6170. }
  6171. let _id$1 = 0;
  6172. const _m1 = /*@__PURE__*/new Matrix4();
  6173. const _obj = /*@__PURE__*/new Object3D();
  6174. const _offset = /*@__PURE__*/new Vector3();
  6175. const _box$1 = /*@__PURE__*/new Box3();
  6176. const _boxMorphTargets = /*@__PURE__*/new Box3();
  6177. const _vector$8 = /*@__PURE__*/new Vector3();
  6178. class BufferGeometry extends EventDispatcher {
  6179. constructor() {
  6180. super();
  6181. this.isBufferGeometry = true;
  6182. Object.defineProperty(this, 'id', {
  6183. value: _id$1++
  6184. });
  6185. this.uuid = generateUUID();
  6186. this.name = '';
  6187. this.type = 'BufferGeometry';
  6188. this.index = null;
  6189. this.attributes = {};
  6190. this.morphAttributes = {};
  6191. this.morphTargetsRelative = false;
  6192. this.groups = [];
  6193. this.boundingBox = null;
  6194. this.boundingSphere = null;
  6195. this.drawRange = {
  6196. start: 0,
  6197. count: Infinity
  6198. };
  6199. this.userData = {};
  6200. }
  6201. getIndex() {
  6202. return this.index;
  6203. }
  6204. setIndex(index) {
  6205. if (Array.isArray(index)) {
  6206. this.index = new (arrayNeedsUint32(index) ? Uint32BufferAttribute : Uint16BufferAttribute)(index, 1);
  6207. } else {
  6208. this.index = index;
  6209. }
  6210. return this;
  6211. }
  6212. getAttribute(name) {
  6213. return this.attributes[name];
  6214. }
  6215. setAttribute(name, attribute) {
  6216. this.attributes[name] = attribute;
  6217. return this;
  6218. }
  6219. deleteAttribute(name) {
  6220. delete this.attributes[name];
  6221. return this;
  6222. }
  6223. hasAttribute(name) {
  6224. return this.attributes[name] !== undefined;
  6225. }
  6226. addGroup(start, count, materialIndex = 0) {
  6227. this.groups.push({
  6228. start: start,
  6229. count: count,
  6230. materialIndex: materialIndex
  6231. });
  6232. }
  6233. clearGroups() {
  6234. this.groups = [];
  6235. }
  6236. setDrawRange(start, count) {
  6237. this.drawRange.start = start;
  6238. this.drawRange.count = count;
  6239. }
  6240. applyMatrix4(matrix) {
  6241. const position = this.attributes.position;
  6242. if (position !== undefined) {
  6243. position.applyMatrix4(matrix);
  6244. position.needsUpdate = true;
  6245. }
  6246. const normal = this.attributes.normal;
  6247. if (normal !== undefined) {
  6248. const normalMatrix = new Matrix3().getNormalMatrix(matrix);
  6249. normal.applyNormalMatrix(normalMatrix);
  6250. normal.needsUpdate = true;
  6251. }
  6252. const tangent = this.attributes.tangent;
  6253. if (tangent !== undefined) {
  6254. tangent.transformDirection(matrix);
  6255. tangent.needsUpdate = true;
  6256. }
  6257. if (this.boundingBox !== null) {
  6258. this.computeBoundingBox();
  6259. }
  6260. if (this.boundingSphere !== null) {
  6261. this.computeBoundingSphere();
  6262. }
  6263. return this;
  6264. }
  6265. applyQuaternion(q) {
  6266. _m1.makeRotationFromQuaternion(q);
  6267. this.applyMatrix4(_m1);
  6268. return this;
  6269. }
  6270. rotateX(angle) {
  6271. // rotate geometry around world x-axis
  6272. _m1.makeRotationX(angle);
  6273. this.applyMatrix4(_m1);
  6274. return this;
  6275. }
  6276. rotateY(angle) {
  6277. // rotate geometry around world y-axis
  6278. _m1.makeRotationY(angle);
  6279. this.applyMatrix4(_m1);
  6280. return this;
  6281. }
  6282. rotateZ(angle) {
  6283. // rotate geometry around world z-axis
  6284. _m1.makeRotationZ(angle);
  6285. this.applyMatrix4(_m1);
  6286. return this;
  6287. }
  6288. translate(x, y, z) {
  6289. // translate geometry
  6290. _m1.makeTranslation(x, y, z);
  6291. this.applyMatrix4(_m1);
  6292. return this;
  6293. }
  6294. scale(x, y, z) {
  6295. // scale geometry
  6296. _m1.makeScale(x, y, z);
  6297. this.applyMatrix4(_m1);
  6298. return this;
  6299. }
  6300. lookAt(vector) {
  6301. _obj.lookAt(vector);
  6302. _obj.updateMatrix();
  6303. this.applyMatrix4(_obj.matrix);
  6304. return this;
  6305. }
  6306. center() {
  6307. this.computeBoundingBox();
  6308. this.boundingBox.getCenter(_offset).negate();
  6309. this.translate(_offset.x, _offset.y, _offset.z);
  6310. return this;
  6311. }
  6312. setFromPoints(points) {
  6313. const position = [];
  6314. for (let i = 0, l = points.length; i < l; i++) {
  6315. const point = points[i];
  6316. position.push(point.x, point.y, point.z || 0);
  6317. }
  6318. this.setAttribute('position', new Float32BufferAttribute(position, 3));
  6319. return this;
  6320. }
  6321. computeBoundingBox() {
  6322. if (this.boundingBox === null) {
  6323. this.boundingBox = new Box3();
  6324. }
  6325. const position = this.attributes.position;
  6326. const morphAttributesPosition = this.morphAttributes.position;
  6327. if (position && position.isGLBufferAttribute) {
  6328. console.error('THREE.BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box. Alternatively set "mesh.frustumCulled" to "false".', this);
  6329. this.boundingBox.set(new Vector3(-Infinity, -Infinity, -Infinity), new Vector3(+Infinity, +Infinity, +Infinity));
  6330. return;
  6331. }
  6332. if (position !== undefined) {
  6333. this.boundingBox.setFromBufferAttribute(position);
  6334. // process morph attributes if present
  6335. if (morphAttributesPosition) {
  6336. for (let i = 0, il = morphAttributesPosition.length; i < il; i++) {
  6337. const morphAttribute = morphAttributesPosition[i];
  6338. _box$1.setFromBufferAttribute(morphAttribute);
  6339. if (this.morphTargetsRelative) {
  6340. _vector$8.addVectors(this.boundingBox.min, _box$1.min);
  6341. this.boundingBox.expandByPoint(_vector$8);
  6342. _vector$8.addVectors(this.boundingBox.max, _box$1.max);
  6343. this.boundingBox.expandByPoint(_vector$8);
  6344. } else {
  6345. this.boundingBox.expandByPoint(_box$1.min);
  6346. this.boundingBox.expandByPoint(_box$1.max);
  6347. }
  6348. }
  6349. }
  6350. } else {
  6351. this.boundingBox.makeEmpty();
  6352. }
  6353. if (isNaN(this.boundingBox.min.x) || isNaN(this.boundingBox.min.y) || isNaN(this.boundingBox.min.z)) {
  6354. console.error('THREE.BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this);
  6355. }
  6356. }
  6357. computeBoundingSphere() {
  6358. if (this.boundingSphere === null) {
  6359. this.boundingSphere = new Sphere();
  6360. }
  6361. const position = this.attributes.position;
  6362. const morphAttributesPosition = this.morphAttributes.position;
  6363. if (position && position.isGLBufferAttribute) {
  6364. console.error('THREE.BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere. Alternatively set "mesh.frustumCulled" to "false".', this);
  6365. this.boundingSphere.set(new Vector3(), Infinity);
  6366. return;
  6367. }
  6368. if (position) {
  6369. // first, find the center of the bounding sphere
  6370. const center = this.boundingSphere.center;
  6371. _box$1.setFromBufferAttribute(position);
  6372. // process morph attributes if present
  6373. if (morphAttributesPosition) {
  6374. for (let i = 0, il = morphAttributesPosition.length; i < il; i++) {
  6375. const morphAttribute = morphAttributesPosition[i];
  6376. _boxMorphTargets.setFromBufferAttribute(morphAttribute);
  6377. if (this.morphTargetsRelative) {
  6378. _vector$8.addVectors(_box$1.min, _boxMorphTargets.min);
  6379. _box$1.expandByPoint(_vector$8);
  6380. _vector$8.addVectors(_box$1.max, _boxMorphTargets.max);
  6381. _box$1.expandByPoint(_vector$8);
  6382. } else {
  6383. _box$1.expandByPoint(_boxMorphTargets.min);
  6384. _box$1.expandByPoint(_boxMorphTargets.max);
  6385. }
  6386. }
  6387. }
  6388. _box$1.getCenter(center);
  6389. // second, try to find a boundingSphere with a radius smaller than the
  6390. // boundingSphere of the boundingBox: sqrt(3) smaller in the best case
  6391. let maxRadiusSq = 0;
  6392. for (let i = 0, il = position.count; i < il; i++) {
  6393. _vector$8.fromBufferAttribute(position, i);
  6394. maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(_vector$8));
  6395. }
  6396. // process morph attributes if present
  6397. if (morphAttributesPosition) {
  6398. for (let i = 0, il = morphAttributesPosition.length; i < il; i++) {
  6399. const morphAttribute = morphAttributesPosition[i];
  6400. const morphTargetsRelative = this.morphTargetsRelative;
  6401. for (let j = 0, jl = morphAttribute.count; j < jl; j++) {
  6402. _vector$8.fromBufferAttribute(morphAttribute, j);
  6403. if (morphTargetsRelative) {
  6404. _offset.fromBufferAttribute(position, j);
  6405. _vector$8.add(_offset);
  6406. }
  6407. maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(_vector$8));
  6408. }
  6409. }
  6410. }
  6411. this.boundingSphere.radius = Math.sqrt(maxRadiusSq);
  6412. if (isNaN(this.boundingSphere.radius)) {
  6413. console.error('THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this);
  6414. }
  6415. }
  6416. }
  6417. computeTangents() {
  6418. const index = this.index;
  6419. const attributes = this.attributes;
  6420. // based on http://www.terathon.com/code/tangent.html
  6421. // (per vertex tangents)
  6422. if (index === null || attributes.position === undefined || attributes.normal === undefined || attributes.uv === undefined) {
  6423. console.error('THREE.BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)');
  6424. return;
  6425. }
  6426. const indices = index.array;
  6427. const positions = attributes.position.array;
  6428. const normals = attributes.normal.array;
  6429. const uvs = attributes.uv.array;
  6430. const nVertices = positions.length / 3;
  6431. if (this.hasAttribute('tangent') === false) {
  6432. this.setAttribute('tangent', new BufferAttribute(new Float32Array(4 * nVertices), 4));
  6433. }
  6434. const tangents = this.getAttribute('tangent').array;
  6435. const tan1 = [],
  6436. tan2 = [];
  6437. for (let i = 0; i < nVertices; i++) {
  6438. tan1[i] = new Vector3();
  6439. tan2[i] = new Vector3();
  6440. }
  6441. const vA = new Vector3(),
  6442. vB = new Vector3(),
  6443. vC = new Vector3(),
  6444. uvA = new Vector2(),
  6445. uvB = new Vector2(),
  6446. uvC = new Vector2(),
  6447. sdir = new Vector3(),
  6448. tdir = new Vector3();
  6449. function handleTriangle(a, b, c) {
  6450. vA.fromArray(positions, a * 3);
  6451. vB.fromArray(positions, b * 3);
  6452. vC.fromArray(positions, c * 3);
  6453. uvA.fromArray(uvs, a * 2);
  6454. uvB.fromArray(uvs, b * 2);
  6455. uvC.fromArray(uvs, c * 2);
  6456. vB.sub(vA);
  6457. vC.sub(vA);
  6458. uvB.sub(uvA);
  6459. uvC.sub(uvA);
  6460. const r = 1.0 / (uvB.x * uvC.y - uvC.x * uvB.y);
  6461. // silently ignore degenerate uv triangles having coincident or colinear vertices
  6462. if (!isFinite(r)) return;
  6463. sdir.copy(vB).multiplyScalar(uvC.y).addScaledVector(vC, -uvB.y).multiplyScalar(r);
  6464. tdir.copy(vC).multiplyScalar(uvB.x).addScaledVector(vB, -uvC.x).multiplyScalar(r);
  6465. tan1[a].add(sdir);
  6466. tan1[b].add(sdir);
  6467. tan1[c].add(sdir);
  6468. tan2[a].add(tdir);
  6469. tan2[b].add(tdir);
  6470. tan2[c].add(tdir);
  6471. }
  6472. let groups = this.groups;
  6473. if (groups.length === 0) {
  6474. groups = [{
  6475. start: 0,
  6476. count: indices.length
  6477. }];
  6478. }
  6479. for (let i = 0, il = groups.length; i < il; ++i) {
  6480. const group = groups[i];
  6481. const start = group.start;
  6482. const count = group.count;
  6483. for (let j = start, jl = start + count; j < jl; j += 3) {
  6484. handleTriangle(indices[j + 0], indices[j + 1], indices[j + 2]);
  6485. }
  6486. }
  6487. const tmp = new Vector3(),
  6488. tmp2 = new Vector3();
  6489. const n = new Vector3(),
  6490. n2 = new Vector3();
  6491. function handleVertex(v) {
  6492. n.fromArray(normals, v * 3);
  6493. n2.copy(n);
  6494. const t = tan1[v];
  6495. // Gram-Schmidt orthogonalize
  6496. tmp.copy(t);
  6497. tmp.sub(n.multiplyScalar(n.dot(t))).normalize();
  6498. // Calculate handedness
  6499. tmp2.crossVectors(n2, t);
  6500. const test = tmp2.dot(tan2[v]);
  6501. const w = test < 0.0 ? -1.0 : 1.0;
  6502. tangents[v * 4] = tmp.x;
  6503. tangents[v * 4 + 1] = tmp.y;
  6504. tangents[v * 4 + 2] = tmp.z;
  6505. tangents[v * 4 + 3] = w;
  6506. }
  6507. for (let i = 0, il = groups.length; i < il; ++i) {
  6508. const group = groups[i];
  6509. const start = group.start;
  6510. const count = group.count;
  6511. for (let j = start, jl = start + count; j < jl; j += 3) {
  6512. handleVertex(indices[j + 0]);
  6513. handleVertex(indices[j + 1]);
  6514. handleVertex(indices[j + 2]);
  6515. }
  6516. }
  6517. }
  6518. computeVertexNormals() {
  6519. const index = this.index;
  6520. const positionAttribute = this.getAttribute('position');
  6521. if (positionAttribute !== undefined) {
  6522. let normalAttribute = this.getAttribute('normal');
  6523. if (normalAttribute === undefined) {
  6524. normalAttribute = new BufferAttribute(new Float32Array(positionAttribute.count * 3), 3);
  6525. this.setAttribute('normal', normalAttribute);
  6526. } else {
  6527. // reset existing normals to zero
  6528. for (let i = 0, il = normalAttribute.count; i < il; i++) {
  6529. normalAttribute.setXYZ(i, 0, 0, 0);
  6530. }
  6531. }
  6532. const pA = new Vector3(),
  6533. pB = new Vector3(),
  6534. pC = new Vector3();
  6535. const nA = new Vector3(),
  6536. nB = new Vector3(),
  6537. nC = new Vector3();
  6538. const cb = new Vector3(),
  6539. ab = new Vector3();
  6540. // indexed elements
  6541. if (index) {
  6542. for (let i = 0, il = index.count; i < il; i += 3) {
  6543. const vA = index.getX(i + 0);
  6544. const vB = index.getX(i + 1);
  6545. const vC = index.getX(i + 2);
  6546. pA.fromBufferAttribute(positionAttribute, vA);
  6547. pB.fromBufferAttribute(positionAttribute, vB);
  6548. pC.fromBufferAttribute(positionAttribute, vC);
  6549. cb.subVectors(pC, pB);
  6550. ab.subVectors(pA, pB);
  6551. cb.cross(ab);
  6552. nA.fromBufferAttribute(normalAttribute, vA);
  6553. nB.fromBufferAttribute(normalAttribute, vB);
  6554. nC.fromBufferAttribute(normalAttribute, vC);
  6555. nA.add(cb);
  6556. nB.add(cb);
  6557. nC.add(cb);
  6558. normalAttribute.setXYZ(vA, nA.x, nA.y, nA.z);
  6559. normalAttribute.setXYZ(vB, nB.x, nB.y, nB.z);
  6560. normalAttribute.setXYZ(vC, nC.x, nC.y, nC.z);
  6561. }
  6562. } else {
  6563. // non-indexed elements (unconnected triangle soup)
  6564. for (let i = 0, il = positionAttribute.count; i < il; i += 3) {
  6565. pA.fromBufferAttribute(positionAttribute, i + 0);
  6566. pB.fromBufferAttribute(positionAttribute, i + 1);
  6567. pC.fromBufferAttribute(positionAttribute, i + 2);
  6568. cb.subVectors(pC, pB);
  6569. ab.subVectors(pA, pB);
  6570. cb.cross(ab);
  6571. normalAttribute.setXYZ(i + 0, cb.x, cb.y, cb.z);
  6572. normalAttribute.setXYZ(i + 1, cb.x, cb.y, cb.z);
  6573. normalAttribute.setXYZ(i + 2, cb.x, cb.y, cb.z);
  6574. }
  6575. }
  6576. this.normalizeNormals();
  6577. normalAttribute.needsUpdate = true;
  6578. }
  6579. }
  6580. // @deprecated since r144
  6581. merge() {
  6582. console.error('THREE.BufferGeometry.merge() has been removed. Use THREE.BufferGeometryUtils.mergeBufferGeometries() instead.');
  6583. return this;
  6584. }
  6585. normalizeNormals() {
  6586. const normals = this.attributes.normal;
  6587. for (let i = 0, il = normals.count; i < il; i++) {
  6588. _vector$8.fromBufferAttribute(normals, i);
  6589. _vector$8.normalize();
  6590. normals.setXYZ(i, _vector$8.x, _vector$8.y, _vector$8.z);
  6591. }
  6592. }
  6593. toNonIndexed() {
  6594. function convertBufferAttribute(attribute, indices) {
  6595. const array = attribute.array;
  6596. const itemSize = attribute.itemSize;
  6597. const normalized = attribute.normalized;
  6598. const array2 = new array.constructor(indices.length * itemSize);
  6599. let index = 0,
  6600. index2 = 0;
  6601. for (let i = 0, l = indices.length; i < l; i++) {
  6602. if (attribute.isInterleavedBufferAttribute) {
  6603. index = indices[i] * attribute.data.stride + attribute.offset;
  6604. } else {
  6605. index = indices[i] * itemSize;
  6606. }
  6607. for (let j = 0; j < itemSize; j++) {
  6608. array2[index2++] = array[index++];
  6609. }
  6610. }
  6611. return new BufferAttribute(array2, itemSize, normalized);
  6612. }
  6613. //
  6614. if (this.index === null) {
  6615. console.warn('THREE.BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed.');
  6616. return this;
  6617. }
  6618. const geometry2 = new BufferGeometry();
  6619. const indices = this.index.array;
  6620. const attributes = this.attributes;
  6621. // attributes
  6622. for (const name in attributes) {
  6623. const attribute = attributes[name];
  6624. const newAttribute = convertBufferAttribute(attribute, indices);
  6625. geometry2.setAttribute(name, newAttribute);
  6626. }
  6627. // morph attributes
  6628. const morphAttributes = this.morphAttributes;
  6629. for (const name in morphAttributes) {
  6630. const morphArray = [];
  6631. const morphAttribute = morphAttributes[name]; // morphAttribute: array of Float32BufferAttributes
  6632. for (let i = 0, il = morphAttribute.length; i < il; i++) {
  6633. const attribute = morphAttribute[i];
  6634. const newAttribute = convertBufferAttribute(attribute, indices);
  6635. morphArray.push(newAttribute);
  6636. }
  6637. geometry2.morphAttributes[name] = morphArray;
  6638. }
  6639. geometry2.morphTargetsRelative = this.morphTargetsRelative;
  6640. // groups
  6641. const groups = this.groups;
  6642. for (let i = 0, l = groups.length; i < l; i++) {
  6643. const group = groups[i];
  6644. geometry2.addGroup(group.start, group.count, group.materialIndex);
  6645. }
  6646. return geometry2;
  6647. }
  6648. toJSON() {
  6649. const data = {
  6650. metadata: {
  6651. version: 4.5,
  6652. type: 'BufferGeometry',
  6653. generator: 'BufferGeometry.toJSON'
  6654. }
  6655. };
  6656. // standard BufferGeometry serialization
  6657. data.uuid = this.uuid;
  6658. data.type = this.type;
  6659. if (this.name !== '') data.name = this.name;
  6660. if (Object.keys(this.userData).length > 0) data.userData = this.userData;
  6661. if (this.parameters !== undefined) {
  6662. const parameters = this.parameters;
  6663. for (const key in parameters) {
  6664. if (parameters[key] !== undefined) data[key] = parameters[key];
  6665. }
  6666. return data;
  6667. }
  6668. // for simplicity the code assumes attributes are not shared across geometries, see #15811
  6669. data.data = {
  6670. attributes: {}
  6671. };
  6672. const index = this.index;
  6673. if (index !== null) {
  6674. data.data.index = {
  6675. type: index.array.constructor.name,
  6676. array: Array.prototype.slice.call(index.array)
  6677. };
  6678. }
  6679. const attributes = this.attributes;
  6680. for (const key in attributes) {
  6681. const attribute = attributes[key];
  6682. data.data.attributes[key] = attribute.toJSON(data.data);
  6683. }
  6684. const morphAttributes = {};
  6685. let hasMorphAttributes = false;
  6686. for (const key in this.morphAttributes) {
  6687. const attributeArray = this.morphAttributes[key];
  6688. const array = [];
  6689. for (let i = 0, il = attributeArray.length; i < il; i++) {
  6690. const attribute = attributeArray[i];
  6691. array.push(attribute.toJSON(data.data));
  6692. }
  6693. if (array.length > 0) {
  6694. morphAttributes[key] = array;
  6695. hasMorphAttributes = true;
  6696. }
  6697. }
  6698. if (hasMorphAttributes) {
  6699. data.data.morphAttributes = morphAttributes;
  6700. data.data.morphTargetsRelative = this.morphTargetsRelative;
  6701. }
  6702. const groups = this.groups;
  6703. if (groups.length > 0) {
  6704. data.data.groups = JSON.parse(JSON.stringify(groups));
  6705. }
  6706. const boundingSphere = this.boundingSphere;
  6707. if (boundingSphere !== null) {
  6708. data.data.boundingSphere = {
  6709. center: boundingSphere.center.toArray(),
  6710. radius: boundingSphere.radius
  6711. };
  6712. }
  6713. return data;
  6714. }
  6715. clone() {
  6716. return new this.constructor().copy(this);
  6717. }
  6718. copy(source) {
  6719. // reset
  6720. this.index = null;
  6721. this.attributes = {};
  6722. this.morphAttributes = {};
  6723. this.groups = [];
  6724. this.boundingBox = null;
  6725. this.boundingSphere = null;
  6726. // used for storing cloned, shared data
  6727. const data = {};
  6728. // name
  6729. this.name = source.name;
  6730. // index
  6731. const index = source.index;
  6732. if (index !== null) {
  6733. this.setIndex(index.clone(data));
  6734. }
  6735. // attributes
  6736. const attributes = source.attributes;
  6737. for (const name in attributes) {
  6738. const attribute = attributes[name];
  6739. this.setAttribute(name, attribute.clone(data));
  6740. }
  6741. // morph attributes
  6742. const morphAttributes = source.morphAttributes;
  6743. for (const name in morphAttributes) {
  6744. const array = [];
  6745. const morphAttribute = morphAttributes[name]; // morphAttribute: array of Float32BufferAttributes
  6746. for (let i = 0, l = morphAttribute.length; i < l; i++) {
  6747. array.push(morphAttribute[i].clone(data));
  6748. }
  6749. this.morphAttributes[name] = array;
  6750. }
  6751. this.morphTargetsRelative = source.morphTargetsRelative;
  6752. // groups
  6753. const groups = source.groups;
  6754. for (let i = 0, l = groups.length; i < l; i++) {
  6755. const group = groups[i];
  6756. this.addGroup(group.start, group.count, group.materialIndex);
  6757. }
  6758. // bounding box
  6759. const boundingBox = source.boundingBox;
  6760. if (boundingBox !== null) {
  6761. this.boundingBox = boundingBox.clone();
  6762. }
  6763. // bounding sphere
  6764. const boundingSphere = source.boundingSphere;
  6765. if (boundingSphere !== null) {
  6766. this.boundingSphere = boundingSphere.clone();
  6767. }
  6768. // draw range
  6769. this.drawRange.start = source.drawRange.start;
  6770. this.drawRange.count = source.drawRange.count;
  6771. // user data
  6772. this.userData = source.userData;
  6773. // geometry generator parameters
  6774. if (source.parameters !== undefined) this.parameters = Object.assign({}, source.parameters);
  6775. return this;
  6776. }
  6777. dispose() {
  6778. this.dispatchEvent({
  6779. type: 'dispose'
  6780. });
  6781. }
  6782. }
  6783. const _inverseMatrix$2 = /*@__PURE__*/new Matrix4();
  6784. const _ray$2 = /*@__PURE__*/new Ray();
  6785. const _sphere$3 = /*@__PURE__*/new Sphere();
  6786. const _vA$1 = /*@__PURE__*/new Vector3();
  6787. const _vB$1 = /*@__PURE__*/new Vector3();
  6788. const _vC$1 = /*@__PURE__*/new Vector3();
  6789. const _tempA = /*@__PURE__*/new Vector3();
  6790. const _tempB = /*@__PURE__*/new Vector3();
  6791. const _tempC = /*@__PURE__*/new Vector3();
  6792. const _morphA = /*@__PURE__*/new Vector3();
  6793. const _morphB = /*@__PURE__*/new Vector3();
  6794. const _morphC = /*@__PURE__*/new Vector3();
  6795. const _uvA$1 = /*@__PURE__*/new Vector2();
  6796. const _uvB$1 = /*@__PURE__*/new Vector2();
  6797. const _uvC$1 = /*@__PURE__*/new Vector2();
  6798. const _intersectionPoint = /*@__PURE__*/new Vector3();
  6799. const _intersectionPointWorld = /*@__PURE__*/new Vector3();
  6800. class Mesh extends Object3D {
  6801. constructor(geometry = new BufferGeometry(), material = new MeshBasicMaterial()) {
  6802. super();
  6803. this.isMesh = true;
  6804. this.type = 'Mesh';
  6805. this.geometry = geometry;
  6806. this.material = material;
  6807. this.updateMorphTargets();
  6808. }
  6809. copy(source, recursive) {
  6810. super.copy(source, recursive);
  6811. if (source.morphTargetInfluences !== undefined) {
  6812. this.morphTargetInfluences = source.morphTargetInfluences.slice();
  6813. }
  6814. if (source.morphTargetDictionary !== undefined) {
  6815. this.morphTargetDictionary = Object.assign({}, source.morphTargetDictionary);
  6816. }
  6817. this.material = source.material;
  6818. this.geometry = source.geometry;
  6819. return this;
  6820. }
  6821. updateMorphTargets() {
  6822. const geometry = this.geometry;
  6823. const morphAttributes = geometry.morphAttributes;
  6824. const keys = Object.keys(morphAttributes);
  6825. if (keys.length > 0) {
  6826. const morphAttribute = morphAttributes[keys[0]];
  6827. if (morphAttribute !== undefined) {
  6828. this.morphTargetInfluences = [];
  6829. this.morphTargetDictionary = {};
  6830. for (let m = 0, ml = morphAttribute.length; m < ml; m++) {
  6831. const name = morphAttribute[m].name || String(m);
  6832. this.morphTargetInfluences.push(0);
  6833. this.morphTargetDictionary[name] = m;
  6834. }
  6835. }
  6836. }
  6837. }
  6838. raycast(raycaster, intersects) {
  6839. const geometry = this.geometry;
  6840. const material = this.material;
  6841. const matrixWorld = this.matrixWorld;
  6842. if (material === undefined) return;
  6843. // Checking boundingSphere distance to ray
  6844. if (geometry.boundingSphere === null) geometry.computeBoundingSphere();
  6845. _sphere$3.copy(geometry.boundingSphere);
  6846. _sphere$3.applyMatrix4(matrixWorld);
  6847. if (raycaster.ray.intersectsSphere(_sphere$3) === false) return;
  6848. //
  6849. _inverseMatrix$2.copy(matrixWorld).invert();
  6850. _ray$2.copy(raycaster.ray).applyMatrix4(_inverseMatrix$2);
  6851. // Check boundingBox before continuing
  6852. if (geometry.boundingBox !== null) {
  6853. if (_ray$2.intersectsBox(geometry.boundingBox) === false) return;
  6854. }
  6855. let intersection;
  6856. const index = geometry.index;
  6857. const position = geometry.attributes.position;
  6858. const morphPosition = geometry.morphAttributes.position;
  6859. const morphTargetsRelative = geometry.morphTargetsRelative;
  6860. const uv = geometry.attributes.uv;
  6861. const uv2 = geometry.attributes.uv2;
  6862. const groups = geometry.groups;
  6863. const drawRange = geometry.drawRange;
  6864. if (index !== null) {
  6865. // indexed buffer geometry
  6866. if (Array.isArray(material)) {
  6867. for (let i = 0, il = groups.length; i < il; i++) {
  6868. const group = groups[i];
  6869. const groupMaterial = material[group.materialIndex];
  6870. const start = Math.max(group.start, drawRange.start);
  6871. const end = Math.min(index.count, Math.min(group.start + group.count, drawRange.start + drawRange.count));
  6872. for (let j = start, jl = end; j < jl; j += 3) {
  6873. const a = index.getX(j);
  6874. const b = index.getX(j + 1);
  6875. const c = index.getX(j + 2);
  6876. intersection = checkBufferGeometryIntersection(this, groupMaterial, raycaster, _ray$2, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c);
  6877. if (intersection) {
  6878. intersection.faceIndex = Math.floor(j / 3); // triangle number in indexed buffer semantics
  6879. intersection.face.materialIndex = group.materialIndex;
  6880. intersects.push(intersection);
  6881. }
  6882. }
  6883. }
  6884. } else {
  6885. const start = Math.max(0, drawRange.start);
  6886. const end = Math.min(index.count, drawRange.start + drawRange.count);
  6887. for (let i = start, il = end; i < il; i += 3) {
  6888. const a = index.getX(i);
  6889. const b = index.getX(i + 1);
  6890. const c = index.getX(i + 2);
  6891. intersection = checkBufferGeometryIntersection(this, material, raycaster, _ray$2, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c);
  6892. if (intersection) {
  6893. intersection.faceIndex = Math.floor(i / 3); // triangle number in indexed buffer semantics
  6894. intersects.push(intersection);
  6895. }
  6896. }
  6897. }
  6898. } else if (position !== undefined) {
  6899. // non-indexed buffer geometry
  6900. if (Array.isArray(material)) {
  6901. for (let i = 0, il = groups.length; i < il; i++) {
  6902. const group = groups[i];
  6903. const groupMaterial = material[group.materialIndex];
  6904. const start = Math.max(group.start, drawRange.start);
  6905. const end = Math.min(position.count, Math.min(group.start + group.count, drawRange.start + drawRange.count));
  6906. for (let j = start, jl = end; j < jl; j += 3) {
  6907. const a = j;
  6908. const b = j + 1;
  6909. const c = j + 2;
  6910. intersection = checkBufferGeometryIntersection(this, groupMaterial, raycaster, _ray$2, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c);
  6911. if (intersection) {
  6912. intersection.faceIndex = Math.floor(j / 3); // triangle number in non-indexed buffer semantics
  6913. intersection.face.materialIndex = group.materialIndex;
  6914. intersects.push(intersection);
  6915. }
  6916. }
  6917. }
  6918. } else {
  6919. const start = Math.max(0, drawRange.start);
  6920. const end = Math.min(position.count, drawRange.start + drawRange.count);
  6921. for (let i = start, il = end; i < il; i += 3) {
  6922. const a = i;
  6923. const b = i + 1;
  6924. const c = i + 2;
  6925. intersection = checkBufferGeometryIntersection(this, material, raycaster, _ray$2, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c);
  6926. if (intersection) {
  6927. intersection.faceIndex = Math.floor(i / 3); // triangle number in non-indexed buffer semantics
  6928. intersects.push(intersection);
  6929. }
  6930. }
  6931. }
  6932. }
  6933. }
  6934. }
  6935. function checkIntersection(object, material, raycaster, ray, pA, pB, pC, point) {
  6936. let intersect;
  6937. if (material.side === BackSide) {
  6938. intersect = ray.intersectTriangle(pC, pB, pA, true, point);
  6939. } else {
  6940. intersect = ray.intersectTriangle(pA, pB, pC, material.side !== DoubleSide, point);
  6941. }
  6942. if (intersect === null) return null;
  6943. _intersectionPointWorld.copy(point);
  6944. _intersectionPointWorld.applyMatrix4(object.matrixWorld);
  6945. const distance = raycaster.ray.origin.distanceTo(_intersectionPointWorld);
  6946. if (distance < raycaster.near || distance > raycaster.far) return null;
  6947. return {
  6948. distance: distance,
  6949. point: _intersectionPointWorld.clone(),
  6950. object: object
  6951. };
  6952. }
  6953. function checkBufferGeometryIntersection(object, material, raycaster, ray, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c) {
  6954. _vA$1.fromBufferAttribute(position, a);
  6955. _vB$1.fromBufferAttribute(position, b);
  6956. _vC$1.fromBufferAttribute(position, c);
  6957. const morphInfluences = object.morphTargetInfluences;
  6958. if (morphPosition && morphInfluences) {
  6959. _morphA.set(0, 0, 0);
  6960. _morphB.set(0, 0, 0);
  6961. _morphC.set(0, 0, 0);
  6962. for (let i = 0, il = morphPosition.length; i < il; i++) {
  6963. const influence = morphInfluences[i];
  6964. const morphAttribute = morphPosition[i];
  6965. if (influence === 0) continue;
  6966. _tempA.fromBufferAttribute(morphAttribute, a);
  6967. _tempB.fromBufferAttribute(morphAttribute, b);
  6968. _tempC.fromBufferAttribute(morphAttribute, c);
  6969. if (morphTargetsRelative) {
  6970. _morphA.addScaledVector(_tempA, influence);
  6971. _morphB.addScaledVector(_tempB, influence);
  6972. _morphC.addScaledVector(_tempC, influence);
  6973. } else {
  6974. _morphA.addScaledVector(_tempA.sub(_vA$1), influence);
  6975. _morphB.addScaledVector(_tempB.sub(_vB$1), influence);
  6976. _morphC.addScaledVector(_tempC.sub(_vC$1), influence);
  6977. }
  6978. }
  6979. _vA$1.add(_morphA);
  6980. _vB$1.add(_morphB);
  6981. _vC$1.add(_morphC);
  6982. }
  6983. if (object.isSkinnedMesh) {
  6984. object.boneTransform(a, _vA$1);
  6985. object.boneTransform(b, _vB$1);
  6986. object.boneTransform(c, _vC$1);
  6987. }
  6988. const intersection = checkIntersection(object, material, raycaster, ray, _vA$1, _vB$1, _vC$1, _intersectionPoint);
  6989. if (intersection) {
  6990. if (uv) {
  6991. _uvA$1.fromBufferAttribute(uv, a);
  6992. _uvB$1.fromBufferAttribute(uv, b);
  6993. _uvC$1.fromBufferAttribute(uv, c);
  6994. intersection.uv = Triangle.getUV(_intersectionPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2());
  6995. }
  6996. if (uv2) {
  6997. _uvA$1.fromBufferAttribute(uv2, a);
  6998. _uvB$1.fromBufferAttribute(uv2, b);
  6999. _uvC$1.fromBufferAttribute(uv2, c);
  7000. intersection.uv2 = Triangle.getUV(_intersectionPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2());
  7001. }
  7002. const face = {
  7003. a: a,
  7004. b: b,
  7005. c: c,
  7006. normal: new Vector3(),
  7007. materialIndex: 0
  7008. };
  7009. Triangle.getNormal(_vA$1, _vB$1, _vC$1, face.normal);
  7010. intersection.face = face;
  7011. }
  7012. return intersection;
  7013. }
  7014. class BoxGeometry extends BufferGeometry {
  7015. constructor(width = 1, height = 1, depth = 1, widthSegments = 1, heightSegments = 1, depthSegments = 1) {
  7016. super();
  7017. this.type = 'BoxGeometry';
  7018. this.parameters = {
  7019. width: width,
  7020. height: height,
  7021. depth: depth,
  7022. widthSegments: widthSegments,
  7023. heightSegments: heightSegments,
  7024. depthSegments: depthSegments
  7025. };
  7026. const scope = this;
  7027. // segments
  7028. widthSegments = Math.floor(widthSegments);
  7029. heightSegments = Math.floor(heightSegments);
  7030. depthSegments = Math.floor(depthSegments);
  7031. // buffers
  7032. const indices = [];
  7033. const vertices = [];
  7034. const normals = [];
  7035. const uvs = [];
  7036. // helper variables
  7037. let numberOfVertices = 0;
  7038. let groupStart = 0;
  7039. // build each side of the box geometry
  7040. buildPlane('z', 'y', 'x', -1, -1, depth, height, width, depthSegments, heightSegments, 0); // px
  7041. buildPlane('z', 'y', 'x', 1, -1, depth, height, -width, depthSegments, heightSegments, 1); // nx
  7042. buildPlane('x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2); // py
  7043. buildPlane('x', 'z', 'y', 1, -1, width, depth, -height, widthSegments, depthSegments, 3); // ny
  7044. buildPlane('x', 'y', 'z', 1, -1, width, height, depth, widthSegments, heightSegments, 4); // pz
  7045. buildPlane('x', 'y', 'z', -1, -1, width, height, -depth, widthSegments, heightSegments, 5); // nz
  7046. // build geometry
  7047. this.setIndex(indices);
  7048. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  7049. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  7050. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  7051. function buildPlane(u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex) {
  7052. const segmentWidth = width / gridX;
  7053. const segmentHeight = height / gridY;
  7054. const widthHalf = width / 2;
  7055. const heightHalf = height / 2;
  7056. const depthHalf = depth / 2;
  7057. const gridX1 = gridX + 1;
  7058. const gridY1 = gridY + 1;
  7059. let vertexCounter = 0;
  7060. let groupCount = 0;
  7061. const vector = new Vector3();
  7062. // generate vertices, normals and uvs
  7063. for (let iy = 0; iy < gridY1; iy++) {
  7064. const y = iy * segmentHeight - heightHalf;
  7065. for (let ix = 0; ix < gridX1; ix++) {
  7066. const x = ix * segmentWidth - widthHalf;
  7067. // set values to correct vector component
  7068. vector[u] = x * udir;
  7069. vector[v] = y * vdir;
  7070. vector[w] = depthHalf;
  7071. // now apply vector to vertex buffer
  7072. vertices.push(vector.x, vector.y, vector.z);
  7073. // set values to correct vector component
  7074. vector[u] = 0;
  7075. vector[v] = 0;
  7076. vector[w] = depth > 0 ? 1 : -1;
  7077. // now apply vector to normal buffer
  7078. normals.push(vector.x, vector.y, vector.z);
  7079. // uvs
  7080. uvs.push(ix / gridX);
  7081. uvs.push(1 - iy / gridY);
  7082. // counters
  7083. vertexCounter += 1;
  7084. }
  7085. }
  7086. // indices
  7087. // 1. you need three indices to draw a single face
  7088. // 2. a single segment consists of two faces
  7089. // 3. so we need to generate six (2*3) indices per segment
  7090. for (let iy = 0; iy < gridY; iy++) {
  7091. for (let ix = 0; ix < gridX; ix++) {
  7092. const a = numberOfVertices + ix + gridX1 * iy;
  7093. const b = numberOfVertices + ix + gridX1 * (iy + 1);
  7094. const c = numberOfVertices + (ix + 1) + gridX1 * (iy + 1);
  7095. const d = numberOfVertices + (ix + 1) + gridX1 * iy;
  7096. // faces
  7097. indices.push(a, b, d);
  7098. indices.push(b, c, d);
  7099. // increase counter
  7100. groupCount += 6;
  7101. }
  7102. }
  7103. // add a group to the geometry. this will ensure multi material support
  7104. scope.addGroup(groupStart, groupCount, materialIndex);
  7105. // calculate new start value for groups
  7106. groupStart += groupCount;
  7107. // update total number of vertices
  7108. numberOfVertices += vertexCounter;
  7109. }
  7110. }
  7111. static fromJSON(data) {
  7112. return new BoxGeometry(data.width, data.height, data.depth, data.widthSegments, data.heightSegments, data.depthSegments);
  7113. }
  7114. }
  7115. /**
  7116. * Uniform Utilities
  7117. */
  7118. function cloneUniforms(src) {
  7119. const dst = {};
  7120. for (const u in src) {
  7121. dst[u] = {};
  7122. for (const p in src[u]) {
  7123. const property = src[u][p];
  7124. if (property && (property.isColor || property.isMatrix3 || property.isMatrix4 || property.isVector2 || property.isVector3 || property.isVector4 || property.isTexture || property.isQuaternion)) {
  7125. dst[u][p] = property.clone();
  7126. } else if (Array.isArray(property)) {
  7127. dst[u][p] = property.slice();
  7128. } else {
  7129. dst[u][p] = property;
  7130. }
  7131. }
  7132. }
  7133. return dst;
  7134. }
  7135. function mergeUniforms(uniforms) {
  7136. const merged = {};
  7137. for (let u = 0; u < uniforms.length; u++) {
  7138. const tmp = cloneUniforms(uniforms[u]);
  7139. for (const p in tmp) {
  7140. merged[p] = tmp[p];
  7141. }
  7142. }
  7143. return merged;
  7144. }
  7145. function cloneUniformsGroups(src) {
  7146. const dst = [];
  7147. for (let u = 0; u < src.length; u++) {
  7148. dst.push(src[u].clone());
  7149. }
  7150. return dst;
  7151. }
  7152. function getUnlitUniformColorSpace(renderer) {
  7153. if (renderer.getRenderTarget() === null) {
  7154. // https://github.com/mrdoob/three.js/pull/23937#issuecomment-1111067398
  7155. return renderer.outputEncoding === sRGBEncoding ? SRGBColorSpace : LinearSRGBColorSpace;
  7156. }
  7157. return LinearSRGBColorSpace;
  7158. }
  7159. // Legacy
  7160. const UniformsUtils = {
  7161. clone: cloneUniforms,
  7162. merge: mergeUniforms
  7163. };
  7164. var default_vertex = "void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}";
  7165. var default_fragment = "void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}";
  7166. class ShaderMaterial extends Material {
  7167. constructor(parameters) {
  7168. super();
  7169. this.isShaderMaterial = true;
  7170. this.type = 'ShaderMaterial';
  7171. this.defines = {};
  7172. this.uniforms = {};
  7173. this.uniformsGroups = [];
  7174. this.vertexShader = default_vertex;
  7175. this.fragmentShader = default_fragment;
  7176. this.linewidth = 1;
  7177. this.wireframe = false;
  7178. this.wireframeLinewidth = 1;
  7179. this.fog = false; // set to use scene fog
  7180. this.lights = false; // set to use scene lights
  7181. this.clipping = false; // set to use user-defined clipping planes
  7182. this.extensions = {
  7183. derivatives: false,
  7184. // set to use derivatives
  7185. fragDepth: false,
  7186. // set to use fragment depth values
  7187. drawBuffers: false,
  7188. // set to use draw buffers
  7189. shaderTextureLOD: false // set to use shader texture LOD
  7190. };
  7191. // When rendered geometry doesn't include these attributes but the material does,
  7192. // use these default values in WebGL. This avoids errors when buffer data is missing.
  7193. this.defaultAttributeValues = {
  7194. 'color': [1, 1, 1],
  7195. 'uv': [0, 0],
  7196. 'uv2': [0, 0]
  7197. };
  7198. this.index0AttributeName = undefined;
  7199. this.uniformsNeedUpdate = false;
  7200. this.glslVersion = null;
  7201. if (parameters !== undefined) {
  7202. this.setValues(parameters);
  7203. }
  7204. }
  7205. copy(source) {
  7206. super.copy(source);
  7207. this.fragmentShader = source.fragmentShader;
  7208. this.vertexShader = source.vertexShader;
  7209. this.uniforms = cloneUniforms(source.uniforms);
  7210. this.uniformsGroups = cloneUniformsGroups(source.uniformsGroups);
  7211. this.defines = Object.assign({}, source.defines);
  7212. this.wireframe = source.wireframe;
  7213. this.wireframeLinewidth = source.wireframeLinewidth;
  7214. this.fog = source.fog;
  7215. this.lights = source.lights;
  7216. this.clipping = source.clipping;
  7217. this.extensions = Object.assign({}, source.extensions);
  7218. this.glslVersion = source.glslVersion;
  7219. return this;
  7220. }
  7221. toJSON(meta) {
  7222. const data = super.toJSON(meta);
  7223. data.glslVersion = this.glslVersion;
  7224. data.uniforms = {};
  7225. for (const name in this.uniforms) {
  7226. const uniform = this.uniforms[name];
  7227. const value = uniform.value;
  7228. if (value && value.isTexture) {
  7229. data.uniforms[name] = {
  7230. type: 't',
  7231. value: value.toJSON(meta).uuid
  7232. };
  7233. } else if (value && value.isColor) {
  7234. data.uniforms[name] = {
  7235. type: 'c',
  7236. value: value.getHex()
  7237. };
  7238. } else if (value && value.isVector2) {
  7239. data.uniforms[name] = {
  7240. type: 'v2',
  7241. value: value.toArray()
  7242. };
  7243. } else if (value && value.isVector3) {
  7244. data.uniforms[name] = {
  7245. type: 'v3',
  7246. value: value.toArray()
  7247. };
  7248. } else if (value && value.isVector4) {
  7249. data.uniforms[name] = {
  7250. type: 'v4',
  7251. value: value.toArray()
  7252. };
  7253. } else if (value && value.isMatrix3) {
  7254. data.uniforms[name] = {
  7255. type: 'm3',
  7256. value: value.toArray()
  7257. };
  7258. } else if (value && value.isMatrix4) {
  7259. data.uniforms[name] = {
  7260. type: 'm4',
  7261. value: value.toArray()
  7262. };
  7263. } else {
  7264. data.uniforms[name] = {
  7265. value: value
  7266. };
  7267. // note: the array variants v2v, v3v, v4v, m4v and tv are not supported so far
  7268. }
  7269. }
  7270. if (Object.keys(this.defines).length > 0) data.defines = this.defines;
  7271. data.vertexShader = this.vertexShader;
  7272. data.fragmentShader = this.fragmentShader;
  7273. const extensions = {};
  7274. for (const key in this.extensions) {
  7275. if (this.extensions[key] === true) extensions[key] = true;
  7276. }
  7277. if (Object.keys(extensions).length > 0) data.extensions = extensions;
  7278. return data;
  7279. }
  7280. }
  7281. class Camera extends Object3D {
  7282. constructor() {
  7283. super();
  7284. this.isCamera = true;
  7285. this.type = 'Camera';
  7286. this.matrixWorldInverse = new Matrix4();
  7287. this.projectionMatrix = new Matrix4();
  7288. this.projectionMatrixInverse = new Matrix4();
  7289. }
  7290. copy(source, recursive) {
  7291. super.copy(source, recursive);
  7292. this.matrixWorldInverse.copy(source.matrixWorldInverse);
  7293. this.projectionMatrix.copy(source.projectionMatrix);
  7294. this.projectionMatrixInverse.copy(source.projectionMatrixInverse);
  7295. return this;
  7296. }
  7297. getWorldDirection(target) {
  7298. this.updateWorldMatrix(true, false);
  7299. const e = this.matrixWorld.elements;
  7300. return target.set(-e[8], -e[9], -e[10]).normalize();
  7301. }
  7302. updateMatrixWorld(force) {
  7303. super.updateMatrixWorld(force);
  7304. this.matrixWorldInverse.copy(this.matrixWorld).invert();
  7305. }
  7306. updateWorldMatrix(updateParents, updateChildren) {
  7307. super.updateWorldMatrix(updateParents, updateChildren);
  7308. this.matrixWorldInverse.copy(this.matrixWorld).invert();
  7309. }
  7310. clone() {
  7311. return new this.constructor().copy(this);
  7312. }
  7313. }
  7314. class PerspectiveCamera extends Camera {
  7315. constructor(fov = 50, aspect = 1, near = 0.1, far = 2000) {
  7316. super();
  7317. this.isPerspectiveCamera = true;
  7318. this.type = 'PerspectiveCamera';
  7319. this.fov = fov;
  7320. this.zoom = 1;
  7321. this.near = near;
  7322. this.far = far;
  7323. this.focus = 10;
  7324. this.aspect = aspect;
  7325. this.view = null;
  7326. this.filmGauge = 35; // width of the film (default in millimeters)
  7327. this.filmOffset = 0; // horizontal film offset (same unit as gauge)
  7328. this.updateProjectionMatrix();
  7329. }
  7330. copy(source, recursive) {
  7331. super.copy(source, recursive);
  7332. this.fov = source.fov;
  7333. this.zoom = source.zoom;
  7334. this.near = source.near;
  7335. this.far = source.far;
  7336. this.focus = source.focus;
  7337. this.aspect = source.aspect;
  7338. this.view = source.view === null ? null : Object.assign({}, source.view);
  7339. this.filmGauge = source.filmGauge;
  7340. this.filmOffset = source.filmOffset;
  7341. return this;
  7342. }
  7343. /**
  7344. * Sets the FOV by focal length in respect to the current .filmGauge.
  7345. *
  7346. * The default film gauge is 35, so that the focal length can be specified for
  7347. * a 35mm (full frame) camera.
  7348. *
  7349. * Values for focal length and film gauge must have the same unit.
  7350. */
  7351. setFocalLength(focalLength) {
  7352. /** see {@link http://www.bobatkins.com/photography/technical/field_of_view.html} */
  7353. const vExtentSlope = 0.5 * this.getFilmHeight() / focalLength;
  7354. this.fov = RAD2DEG * 2 * Math.atan(vExtentSlope);
  7355. this.updateProjectionMatrix();
  7356. }
  7357. /**
  7358. * Calculates the focal length from the current .fov and .filmGauge.
  7359. */
  7360. getFocalLength() {
  7361. const vExtentSlope = Math.tan(DEG2RAD * 0.5 * this.fov);
  7362. return 0.5 * this.getFilmHeight() / vExtentSlope;
  7363. }
  7364. getEffectiveFOV() {
  7365. return RAD2DEG * 2 * Math.atan(Math.tan(DEG2RAD * 0.5 * this.fov) / this.zoom);
  7366. }
  7367. getFilmWidth() {
  7368. // film not completely covered in portrait format (aspect < 1)
  7369. return this.filmGauge * Math.min(this.aspect, 1);
  7370. }
  7371. getFilmHeight() {
  7372. // film not completely covered in landscape format (aspect > 1)
  7373. return this.filmGauge / Math.max(this.aspect, 1);
  7374. }
  7375. /**
  7376. * Sets an offset in a larger frustum. This is useful for multi-window or
  7377. * multi-monitor/multi-machine setups.
  7378. *
  7379. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  7380. * the monitors are in grid like this
  7381. *
  7382. * +---+---+---+
  7383. * | A | B | C |
  7384. * +---+---+---+
  7385. * | D | E | F |
  7386. * +---+---+---+
  7387. *
  7388. * then for each monitor you would call it like this
  7389. *
  7390. * const w = 1920;
  7391. * const h = 1080;
  7392. * const fullWidth = w * 3;
  7393. * const fullHeight = h * 2;
  7394. *
  7395. * --A--
  7396. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  7397. * --B--
  7398. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  7399. * --C--
  7400. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  7401. * --D--
  7402. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  7403. * --E--
  7404. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  7405. * --F--
  7406. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  7407. *
  7408. * Note there is no reason monitors have to be the same size or in a grid.
  7409. */
  7410. setViewOffset(fullWidth, fullHeight, x, y, width, height) {
  7411. this.aspect = fullWidth / fullHeight;
  7412. if (this.view === null) {
  7413. this.view = {
  7414. enabled: true,
  7415. fullWidth: 1,
  7416. fullHeight: 1,
  7417. offsetX: 0,
  7418. offsetY: 0,
  7419. width: 1,
  7420. height: 1
  7421. };
  7422. }
  7423. this.view.enabled = true;
  7424. this.view.fullWidth = fullWidth;
  7425. this.view.fullHeight = fullHeight;
  7426. this.view.offsetX = x;
  7427. this.view.offsetY = y;
  7428. this.view.width = width;
  7429. this.view.height = height;
  7430. this.updateProjectionMatrix();
  7431. }
  7432. clearViewOffset() {
  7433. if (this.view !== null) {
  7434. this.view.enabled = false;
  7435. }
  7436. this.updateProjectionMatrix();
  7437. }
  7438. updateProjectionMatrix() {
  7439. const near = this.near;
  7440. let top = near * Math.tan(DEG2RAD * 0.5 * this.fov) / this.zoom;
  7441. let height = 2 * top;
  7442. let width = this.aspect * height;
  7443. let left = -0.5 * width;
  7444. const view = this.view;
  7445. if (this.view !== null && this.view.enabled) {
  7446. const fullWidth = view.fullWidth,
  7447. fullHeight = view.fullHeight;
  7448. left += view.offsetX * width / fullWidth;
  7449. top -= view.offsetY * height / fullHeight;
  7450. width *= view.width / fullWidth;
  7451. height *= view.height / fullHeight;
  7452. }
  7453. const skew = this.filmOffset;
  7454. if (skew !== 0) left += near * skew / this.getFilmWidth();
  7455. this.projectionMatrix.makePerspective(left, left + width, top, top - height, near, this.far);
  7456. this.projectionMatrixInverse.copy(this.projectionMatrix).invert();
  7457. }
  7458. toJSON(meta) {
  7459. const data = super.toJSON(meta);
  7460. data.object.fov = this.fov;
  7461. data.object.zoom = this.zoom;
  7462. data.object.near = this.near;
  7463. data.object.far = this.far;
  7464. data.object.focus = this.focus;
  7465. data.object.aspect = this.aspect;
  7466. if (this.view !== null) data.object.view = Object.assign({}, this.view);
  7467. data.object.filmGauge = this.filmGauge;
  7468. data.object.filmOffset = this.filmOffset;
  7469. return data;
  7470. }
  7471. }
  7472. const fov = -90; // negative fov is not an error
  7473. const aspect = 1;
  7474. class CubeCamera extends Object3D {
  7475. constructor(near, far, renderTarget) {
  7476. super();
  7477. this.type = 'CubeCamera';
  7478. this.renderTarget = renderTarget;
  7479. const cameraPX = new PerspectiveCamera(fov, aspect, near, far);
  7480. cameraPX.layers = this.layers;
  7481. cameraPX.up.set(0, 1, 0);
  7482. cameraPX.lookAt(1, 0, 0);
  7483. this.add(cameraPX);
  7484. const cameraNX = new PerspectiveCamera(fov, aspect, near, far);
  7485. cameraNX.layers = this.layers;
  7486. cameraNX.up.set(0, 1, 0);
  7487. cameraNX.lookAt(-1, 0, 0);
  7488. this.add(cameraNX);
  7489. const cameraPY = new PerspectiveCamera(fov, aspect, near, far);
  7490. cameraPY.layers = this.layers;
  7491. cameraPY.up.set(0, 0, -1);
  7492. cameraPY.lookAt(0, 1, 0);
  7493. this.add(cameraPY);
  7494. const cameraNY = new PerspectiveCamera(fov, aspect, near, far);
  7495. cameraNY.layers = this.layers;
  7496. cameraNY.up.set(0, 0, 1);
  7497. cameraNY.lookAt(0, -1, 0);
  7498. this.add(cameraNY);
  7499. const cameraPZ = new PerspectiveCamera(fov, aspect, near, far);
  7500. cameraPZ.layers = this.layers;
  7501. cameraPZ.up.set(0, 1, 0);
  7502. cameraPZ.lookAt(0, 0, 1);
  7503. this.add(cameraPZ);
  7504. const cameraNZ = new PerspectiveCamera(fov, aspect, near, far);
  7505. cameraNZ.layers = this.layers;
  7506. cameraNZ.up.set(0, 1, 0);
  7507. cameraNZ.lookAt(0, 0, -1);
  7508. this.add(cameraNZ);
  7509. }
  7510. update(renderer, scene) {
  7511. if (this.parent === null) this.updateMatrixWorld();
  7512. const renderTarget = this.renderTarget;
  7513. const [cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ] = this.children;
  7514. const currentRenderTarget = renderer.getRenderTarget();
  7515. const currentToneMapping = renderer.toneMapping;
  7516. const currentXrEnabled = renderer.xr.enabled;
  7517. renderer.toneMapping = NoToneMapping;
  7518. renderer.xr.enabled = false;
  7519. const generateMipmaps = renderTarget.texture.generateMipmaps;
  7520. renderTarget.texture.generateMipmaps = false;
  7521. renderer.setRenderTarget(renderTarget, 0);
  7522. renderer.render(scene, cameraPX);
  7523. renderer.setRenderTarget(renderTarget, 1);
  7524. renderer.render(scene, cameraNX);
  7525. renderer.setRenderTarget(renderTarget, 2);
  7526. renderer.render(scene, cameraPY);
  7527. renderer.setRenderTarget(renderTarget, 3);
  7528. renderer.render(scene, cameraNY);
  7529. renderer.setRenderTarget(renderTarget, 4);
  7530. renderer.render(scene, cameraPZ);
  7531. renderTarget.texture.generateMipmaps = generateMipmaps;
  7532. renderer.setRenderTarget(renderTarget, 5);
  7533. renderer.render(scene, cameraNZ);
  7534. renderer.setRenderTarget(currentRenderTarget);
  7535. renderer.toneMapping = currentToneMapping;
  7536. renderer.xr.enabled = currentXrEnabled;
  7537. renderTarget.texture.needsPMREMUpdate = true;
  7538. }
  7539. }
  7540. class CubeTexture extends Texture {
  7541. constructor(images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding) {
  7542. images = images !== undefined ? images : [];
  7543. mapping = mapping !== undefined ? mapping : CubeReflectionMapping;
  7544. super(images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding);
  7545. this.isCubeTexture = true;
  7546. this.flipY = false;
  7547. }
  7548. get images() {
  7549. return this.image;
  7550. }
  7551. set images(value) {
  7552. this.image = value;
  7553. }
  7554. }
  7555. class WebGLCubeRenderTarget extends WebGLRenderTarget {
  7556. constructor(size = 1, options = {}) {
  7557. super(size, size, options);
  7558. this.isWebGLCubeRenderTarget = true;
  7559. const image = {
  7560. width: size,
  7561. height: size,
  7562. depth: 1
  7563. };
  7564. const images = [image, image, image, image, image, image];
  7565. this.texture = new CubeTexture(images, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding);
  7566. // By convention -- likely based on the RenderMan spec from the 1990's -- cube maps are specified by WebGL (and three.js)
  7567. // in a coordinate system in which positive-x is to the right when looking up the positive-z axis -- in other words,
  7568. // in a left-handed coordinate system. By continuing this convention, preexisting cube maps continued to render correctly.
  7569. // three.js uses a right-handed coordinate system. So environment maps used in three.js appear to have px and nx swapped
  7570. // and the flag isRenderTargetTexture controls this conversion. The flip is not required when using WebGLCubeRenderTarget.texture
  7571. // as a cube texture (this is detected when isRenderTargetTexture is set to true for cube textures).
  7572. this.texture.isRenderTargetTexture = true;
  7573. this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false;
  7574. this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter;
  7575. }
  7576. fromEquirectangularTexture(renderer, texture) {
  7577. this.texture.type = texture.type;
  7578. this.texture.encoding = texture.encoding;
  7579. this.texture.generateMipmaps = texture.generateMipmaps;
  7580. this.texture.minFilter = texture.minFilter;
  7581. this.texture.magFilter = texture.magFilter;
  7582. const shader = {
  7583. uniforms: {
  7584. tEquirect: {
  7585. value: null
  7586. }
  7587. },
  7588. vertexShader: /* glsl */`
  7589. varying vec3 vWorldDirection;
  7590. vec3 transformDirection( in vec3 dir, in mat4 matrix ) {
  7591. return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );
  7592. }
  7593. void main() {
  7594. vWorldDirection = transformDirection( position, modelMatrix );
  7595. #include <begin_vertex>
  7596. #include <project_vertex>
  7597. }
  7598. `,
  7599. fragmentShader: /* glsl */`
  7600. uniform sampler2D tEquirect;
  7601. varying vec3 vWorldDirection;
  7602. #include <common>
  7603. void main() {
  7604. vec3 direction = normalize( vWorldDirection );
  7605. vec2 sampleUV = equirectUv( direction );
  7606. gl_FragColor = texture2D( tEquirect, sampleUV );
  7607. }
  7608. `
  7609. };
  7610. const geometry = new BoxGeometry(5, 5, 5);
  7611. const material = new ShaderMaterial({
  7612. name: 'CubemapFromEquirect',
  7613. uniforms: cloneUniforms(shader.uniforms),
  7614. vertexShader: shader.vertexShader,
  7615. fragmentShader: shader.fragmentShader,
  7616. side: BackSide,
  7617. blending: NoBlending
  7618. });
  7619. material.uniforms.tEquirect.value = texture;
  7620. const mesh = new Mesh(geometry, material);
  7621. const currentMinFilter = texture.minFilter;
  7622. // Avoid blurred poles
  7623. if (texture.minFilter === LinearMipmapLinearFilter) texture.minFilter = LinearFilter;
  7624. const camera = new CubeCamera(1, 10, this);
  7625. camera.update(renderer, mesh);
  7626. texture.minFilter = currentMinFilter;
  7627. mesh.geometry.dispose();
  7628. mesh.material.dispose();
  7629. return this;
  7630. }
  7631. clear(renderer, color, depth, stencil) {
  7632. const currentRenderTarget = renderer.getRenderTarget();
  7633. for (let i = 0; i < 6; i++) {
  7634. renderer.setRenderTarget(this, i);
  7635. renderer.clear(color, depth, stencil);
  7636. }
  7637. renderer.setRenderTarget(currentRenderTarget);
  7638. }
  7639. }
  7640. const _vector1 = /*@__PURE__*/new Vector3();
  7641. const _vector2 = /*@__PURE__*/new Vector3();
  7642. const _normalMatrix = /*@__PURE__*/new Matrix3();
  7643. class Plane {
  7644. constructor(normal = new Vector3(1, 0, 0), constant = 0) {
  7645. this.isPlane = true;
  7646. // normal is assumed to be normalized
  7647. this.normal = normal;
  7648. this.constant = constant;
  7649. }
  7650. set(normal, constant) {
  7651. this.normal.copy(normal);
  7652. this.constant = constant;
  7653. return this;
  7654. }
  7655. setComponents(x, y, z, w) {
  7656. this.normal.set(x, y, z);
  7657. this.constant = w;
  7658. return this;
  7659. }
  7660. setFromNormalAndCoplanarPoint(normal, point) {
  7661. this.normal.copy(normal);
  7662. this.constant = -point.dot(this.normal);
  7663. return this;
  7664. }
  7665. setFromCoplanarPoints(a, b, c) {
  7666. const normal = _vector1.subVectors(c, b).cross(_vector2.subVectors(a, b)).normalize();
  7667. // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  7668. this.setFromNormalAndCoplanarPoint(normal, a);
  7669. return this;
  7670. }
  7671. copy(plane) {
  7672. this.normal.copy(plane.normal);
  7673. this.constant = plane.constant;
  7674. return this;
  7675. }
  7676. normalize() {
  7677. // Note: will lead to a divide by zero if the plane is invalid.
  7678. const inverseNormalLength = 1.0 / this.normal.length();
  7679. this.normal.multiplyScalar(inverseNormalLength);
  7680. this.constant *= inverseNormalLength;
  7681. return this;
  7682. }
  7683. negate() {
  7684. this.constant *= -1;
  7685. this.normal.negate();
  7686. return this;
  7687. }
  7688. distanceToPoint(point) {
  7689. return this.normal.dot(point) + this.constant;
  7690. }
  7691. distanceToSphere(sphere) {
  7692. return this.distanceToPoint(sphere.center) - sphere.radius;
  7693. }
  7694. projectPoint(point, target) {
  7695. return target.copy(this.normal).multiplyScalar(-this.distanceToPoint(point)).add(point);
  7696. }
  7697. intersectLine(line, target) {
  7698. const direction = line.delta(_vector1);
  7699. const denominator = this.normal.dot(direction);
  7700. if (denominator === 0) {
  7701. // line is coplanar, return origin
  7702. if (this.distanceToPoint(line.start) === 0) {
  7703. return target.copy(line.start);
  7704. }
  7705. // Unsure if this is the correct method to handle this case.
  7706. return null;
  7707. }
  7708. const t = -(line.start.dot(this.normal) + this.constant) / denominator;
  7709. if (t < 0 || t > 1) {
  7710. return null;
  7711. }
  7712. return target.copy(direction).multiplyScalar(t).add(line.start);
  7713. }
  7714. intersectsLine(line) {
  7715. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  7716. const startSign = this.distanceToPoint(line.start);
  7717. const endSign = this.distanceToPoint(line.end);
  7718. return startSign < 0 && endSign > 0 || endSign < 0 && startSign > 0;
  7719. }
  7720. intersectsBox(box) {
  7721. return box.intersectsPlane(this);
  7722. }
  7723. intersectsSphere(sphere) {
  7724. return sphere.intersectsPlane(this);
  7725. }
  7726. coplanarPoint(target) {
  7727. return target.copy(this.normal).multiplyScalar(-this.constant);
  7728. }
  7729. applyMatrix4(matrix, optionalNormalMatrix) {
  7730. const normalMatrix = optionalNormalMatrix || _normalMatrix.getNormalMatrix(matrix);
  7731. const referencePoint = this.coplanarPoint(_vector1).applyMatrix4(matrix);
  7732. const normal = this.normal.applyMatrix3(normalMatrix).normalize();
  7733. this.constant = -referencePoint.dot(normal);
  7734. return this;
  7735. }
  7736. translate(offset) {
  7737. this.constant -= offset.dot(this.normal);
  7738. return this;
  7739. }
  7740. equals(plane) {
  7741. return plane.normal.equals(this.normal) && plane.constant === this.constant;
  7742. }
  7743. clone() {
  7744. return new this.constructor().copy(this);
  7745. }
  7746. }
  7747. const _sphere$2 = /*@__PURE__*/new Sphere();
  7748. const _vector$7 = /*@__PURE__*/new Vector3();
  7749. class Frustum {
  7750. constructor(p0 = new Plane(), p1 = new Plane(), p2 = new Plane(), p3 = new Plane(), p4 = new Plane(), p5 = new Plane()) {
  7751. this.planes = [p0, p1, p2, p3, p4, p5];
  7752. }
  7753. set(p0, p1, p2, p3, p4, p5) {
  7754. const planes = this.planes;
  7755. planes[0].copy(p0);
  7756. planes[1].copy(p1);
  7757. planes[2].copy(p2);
  7758. planes[3].copy(p3);
  7759. planes[4].copy(p4);
  7760. planes[5].copy(p5);
  7761. return this;
  7762. }
  7763. copy(frustum) {
  7764. const planes = this.planes;
  7765. for (let i = 0; i < 6; i++) {
  7766. planes[i].copy(frustum.planes[i]);
  7767. }
  7768. return this;
  7769. }
  7770. setFromProjectionMatrix(m) {
  7771. const planes = this.planes;
  7772. const me = m.elements;
  7773. const me0 = me[0],
  7774. me1 = me[1],
  7775. me2 = me[2],
  7776. me3 = me[3];
  7777. const me4 = me[4],
  7778. me5 = me[5],
  7779. me6 = me[6],
  7780. me7 = me[7];
  7781. const me8 = me[8],
  7782. me9 = me[9],
  7783. me10 = me[10],
  7784. me11 = me[11];
  7785. const me12 = me[12],
  7786. me13 = me[13],
  7787. me14 = me[14],
  7788. me15 = me[15];
  7789. planes[0].setComponents(me3 - me0, me7 - me4, me11 - me8, me15 - me12).normalize();
  7790. planes[1].setComponents(me3 + me0, me7 + me4, me11 + me8, me15 + me12).normalize();
  7791. planes[2].setComponents(me3 + me1, me7 + me5, me11 + me9, me15 + me13).normalize();
  7792. planes[3].setComponents(me3 - me1, me7 - me5, me11 - me9, me15 - me13).normalize();
  7793. planes[4].setComponents(me3 - me2, me7 - me6, me11 - me10, me15 - me14).normalize();
  7794. planes[5].setComponents(me3 + me2, me7 + me6, me11 + me10, me15 + me14).normalize();
  7795. return this;
  7796. }
  7797. intersectsObject(object) {
  7798. const geometry = object.geometry;
  7799. if (geometry.boundingSphere === null) geometry.computeBoundingSphere();
  7800. _sphere$2.copy(geometry.boundingSphere).applyMatrix4(object.matrixWorld);
  7801. return this.intersectsSphere(_sphere$2);
  7802. }
  7803. intersectsSprite(sprite) {
  7804. _sphere$2.center.set(0, 0, 0);
  7805. _sphere$2.radius = 0.7071067811865476;
  7806. _sphere$2.applyMatrix4(sprite.matrixWorld);
  7807. return this.intersectsSphere(_sphere$2);
  7808. }
  7809. intersectsSphere(sphere) {
  7810. const planes = this.planes;
  7811. const center = sphere.center;
  7812. const negRadius = -sphere.radius;
  7813. for (let i = 0; i < 6; i++) {
  7814. const distance = planes[i].distanceToPoint(center);
  7815. if (distance < negRadius) {
  7816. return false;
  7817. }
  7818. }
  7819. return true;
  7820. }
  7821. intersectsBox(box) {
  7822. const planes = this.planes;
  7823. for (let i = 0; i < 6; i++) {
  7824. const plane = planes[i];
  7825. // corner at max distance
  7826. _vector$7.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  7827. _vector$7.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  7828. _vector$7.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  7829. if (plane.distanceToPoint(_vector$7) < 0) {
  7830. return false;
  7831. }
  7832. }
  7833. return true;
  7834. }
  7835. containsPoint(point) {
  7836. const planes = this.planes;
  7837. for (let i = 0; i < 6; i++) {
  7838. if (planes[i].distanceToPoint(point) < 0) {
  7839. return false;
  7840. }
  7841. }
  7842. return true;
  7843. }
  7844. clone() {
  7845. return new this.constructor().copy(this);
  7846. }
  7847. }
  7848. function WebGLAnimation() {
  7849. let context = null;
  7850. let isAnimating = false;
  7851. let animationLoop = null;
  7852. let requestId = null;
  7853. function onAnimationFrame(time, frame) {
  7854. animationLoop(time, frame);
  7855. requestId = context.requestAnimationFrame(onAnimationFrame);
  7856. }
  7857. return {
  7858. start: function () {
  7859. if (isAnimating === true) return;
  7860. if (animationLoop === null) return;
  7861. requestId = context.requestAnimationFrame(onAnimationFrame);
  7862. isAnimating = true;
  7863. },
  7864. stop: function () {
  7865. context.cancelAnimationFrame(requestId);
  7866. isAnimating = false;
  7867. },
  7868. setAnimationLoop: function (callback) {
  7869. animationLoop = callback;
  7870. },
  7871. setContext: function (value) {
  7872. context = value;
  7873. }
  7874. };
  7875. }
  7876. function WebGLAttributes(gl, capabilities) {
  7877. const isWebGL2 = capabilities.isWebGL2;
  7878. const buffers = new WeakMap();
  7879. function createBuffer(attribute, bufferType) {
  7880. const array = attribute.array;
  7881. const usage = attribute.usage;
  7882. const buffer = gl.createBuffer();
  7883. gl.bindBuffer(bufferType, buffer);
  7884. gl.bufferData(bufferType, array, usage);
  7885. attribute.onUploadCallback();
  7886. let type;
  7887. if (array instanceof Float32Array) {
  7888. type = gl.FLOAT;
  7889. } else if (array instanceof Uint16Array) {
  7890. if (attribute.isFloat16BufferAttribute) {
  7891. if (isWebGL2) {
  7892. type = gl.HALF_FLOAT;
  7893. } else {
  7894. throw new Error('THREE.WebGLAttributes: Usage of Float16BufferAttribute requires WebGL2.');
  7895. }
  7896. } else {
  7897. type = gl.UNSIGNED_SHORT;
  7898. }
  7899. } else if (array instanceof Int16Array) {
  7900. type = gl.SHORT;
  7901. } else if (array instanceof Uint32Array) {
  7902. type = gl.UNSIGNED_INT;
  7903. } else if (array instanceof Int32Array) {
  7904. type = gl.INT;
  7905. } else if (array instanceof Int8Array) {
  7906. type = gl.BYTE;
  7907. } else if (array instanceof Uint8Array) {
  7908. type = gl.UNSIGNED_BYTE;
  7909. } else if (array instanceof Uint8ClampedArray) {
  7910. type = gl.UNSIGNED_BYTE;
  7911. } else {
  7912. throw new Error('THREE.WebGLAttributes: Unsupported buffer data format: ' + array);
  7913. }
  7914. return {
  7915. buffer: buffer,
  7916. type: type,
  7917. bytesPerElement: array.BYTES_PER_ELEMENT,
  7918. version: attribute.version
  7919. };
  7920. }
  7921. function updateBuffer(buffer, attribute, bufferType) {
  7922. const array = attribute.array;
  7923. const updateRange = attribute.updateRange;
  7924. gl.bindBuffer(bufferType, buffer);
  7925. if (updateRange.count === -1) {
  7926. // Not using update ranges
  7927. gl.bufferSubData(bufferType, 0, array);
  7928. } else {
  7929. if (isWebGL2) {
  7930. gl.bufferSubData(bufferType, updateRange.offset * array.BYTES_PER_ELEMENT, array, updateRange.offset, updateRange.count);
  7931. } else {
  7932. gl.bufferSubData(bufferType, updateRange.offset * array.BYTES_PER_ELEMENT, array.subarray(updateRange.offset, updateRange.offset + updateRange.count));
  7933. }
  7934. updateRange.count = -1; // reset range
  7935. }
  7936. attribute.onUploadCallback();
  7937. }
  7938. //
  7939. function get(attribute) {
  7940. if (attribute.isInterleavedBufferAttribute) attribute = attribute.data;
  7941. return buffers.get(attribute);
  7942. }
  7943. function remove(attribute) {
  7944. if (attribute.isInterleavedBufferAttribute) attribute = attribute.data;
  7945. const data = buffers.get(attribute);
  7946. if (data) {
  7947. gl.deleteBuffer(data.buffer);
  7948. buffers.delete(attribute);
  7949. }
  7950. }
  7951. function update(attribute, bufferType) {
  7952. if (attribute.isGLBufferAttribute) {
  7953. const cached = buffers.get(attribute);
  7954. if (!cached || cached.version < attribute.version) {
  7955. buffers.set(attribute, {
  7956. buffer: attribute.buffer,
  7957. type: attribute.type,
  7958. bytesPerElement: attribute.elementSize,
  7959. version: attribute.version
  7960. });
  7961. }
  7962. return;
  7963. }
  7964. if (attribute.isInterleavedBufferAttribute) attribute = attribute.data;
  7965. const data = buffers.get(attribute);
  7966. if (data === undefined) {
  7967. buffers.set(attribute, createBuffer(attribute, bufferType));
  7968. } else if (data.version < attribute.version) {
  7969. updateBuffer(data.buffer, attribute, bufferType);
  7970. data.version = attribute.version;
  7971. }
  7972. }
  7973. return {
  7974. get: get,
  7975. remove: remove,
  7976. update: update
  7977. };
  7978. }
  7979. class PlaneGeometry extends BufferGeometry {
  7980. constructor(width = 1, height = 1, widthSegments = 1, heightSegments = 1) {
  7981. super();
  7982. this.type = 'PlaneGeometry';
  7983. this.parameters = {
  7984. width: width,
  7985. height: height,
  7986. widthSegments: widthSegments,
  7987. heightSegments: heightSegments
  7988. };
  7989. const width_half = width / 2;
  7990. const height_half = height / 2;
  7991. const gridX = Math.floor(widthSegments);
  7992. const gridY = Math.floor(heightSegments);
  7993. const gridX1 = gridX + 1;
  7994. const gridY1 = gridY + 1;
  7995. const segment_width = width / gridX;
  7996. const segment_height = height / gridY;
  7997. //
  7998. const indices = [];
  7999. const vertices = [];
  8000. const normals = [];
  8001. const uvs = [];
  8002. for (let iy = 0; iy < gridY1; iy++) {
  8003. const y = iy * segment_height - height_half;
  8004. for (let ix = 0; ix < gridX1; ix++) {
  8005. const x = ix * segment_width - width_half;
  8006. vertices.push(x, -y, 0);
  8007. normals.push(0, 0, 1);
  8008. uvs.push(ix / gridX);
  8009. uvs.push(1 - iy / gridY);
  8010. }
  8011. }
  8012. for (let iy = 0; iy < gridY; iy++) {
  8013. for (let ix = 0; ix < gridX; ix++) {
  8014. const a = ix + gridX1 * iy;
  8015. const b = ix + gridX1 * (iy + 1);
  8016. const c = ix + 1 + gridX1 * (iy + 1);
  8017. const d = ix + 1 + gridX1 * iy;
  8018. indices.push(a, b, d);
  8019. indices.push(b, c, d);
  8020. }
  8021. }
  8022. this.setIndex(indices);
  8023. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  8024. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  8025. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  8026. }
  8027. static fromJSON(data) {
  8028. return new PlaneGeometry(data.width, data.height, data.widthSegments, data.heightSegments);
  8029. }
  8030. }
  8031. var alphamap_fragment = "#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, vUv ).g;\n#endif";
  8032. var alphamap_pars_fragment = "#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif";
  8033. var alphatest_fragment = "#ifdef USE_ALPHATEST\n\tif ( diffuseColor.a < alphaTest ) discard;\n#endif";
  8034. var alphatest_pars_fragment = "#ifdef USE_ALPHATEST\n\tuniform float alphaTest;\n#endif";
  8035. 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";
  8036. var aomap_pars_fragment = "#ifdef USE_AOMAP\n\tuniform sampler2D aoMap;\n\tuniform float aoMapIntensity;\n#endif";
  8037. var begin_vertex = "vec3 transformed = vec3( position );";
  8038. var beginnormal_vertex = "vec3 objectNormal = vec3( normal );\n#ifdef USE_TANGENT\n\tvec3 objectTangent = vec3( tangent.xyz );\n#endif";
  8039. 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";
  8040. 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";
  8041. 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";
  8042. 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";
  8043. var clipping_planes_pars_fragment = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n\tuniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];\n#endif";
  8044. var clipping_planes_pars_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n#endif";
  8045. var clipping_planes_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvClipPosition = - mvPosition.xyz;\n#endif";
  8046. var color_fragment = "#if defined( USE_COLOR_ALPHA )\n\tdiffuseColor *= vColor;\n#elif defined( USE_COLOR )\n\tdiffuseColor.rgb *= vColor;\n#endif";
  8047. var color_pars_fragment = "#if defined( USE_COLOR_ALPHA )\n\tvarying vec4 vColor;\n#elif defined( USE_COLOR )\n\tvarying vec3 vColor;\n#endif";
  8048. 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";
  8049. 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";
  8050. 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}";
  8051. 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\thighp vec2 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";
  8052. 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";
  8053. var displacementmap_pars_vertex = "#ifdef USE_DISPLACEMENTMAP\n\tuniform sampler2D displacementMap;\n\tuniform float displacementScale;\n\tuniform float displacementBias;\n#endif";
  8054. var displacementmap_vertex = "#ifdef USE_DISPLACEMENTMAP\n\ttransformed += normalize( objectNormal ) * ( texture2D( displacementMap, vUv ).x * displacementScale + displacementBias );\n#endif";
  8055. var emissivemap_fragment = "#ifdef USE_EMISSIVEMAP\n\tvec4 emissiveColor = texture2D( emissiveMap, vUv );\n\ttotalEmissiveRadiance *= emissiveColor.rgb;\n#endif";
  8056. var emissivemap_pars_fragment = "#ifdef USE_EMISSIVEMAP\n\tuniform sampler2D emissiveMap;\n#endif";
  8057. var encodings_fragment = "gl_FragColor = linearToOutputTexel( gl_FragColor );";
  8058. 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}";
  8059. 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#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";
  8060. 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";
  8061. 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";
  8062. 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";
  8063. 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";
  8064. var fog_vertex = "#ifdef USE_FOG\n\tvFogDepth = - mvPosition.z;\n#endif";
  8065. var fog_pars_vertex = "#ifdef USE_FOG\n\tvarying float vFogDepth;\n#endif";
  8066. 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";
  8067. 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";
  8068. 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}";
  8069. var lightmap_fragment = "#ifdef USE_LIGHTMAP\n\tvec4 lightMapTexel = texture2D( lightMap, vUv2 );\n\tvec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity;\n\treflectedLight.indirectDiffuse += lightMapIrradiance;\n#endif";
  8070. var lightmap_pars_fragment = "#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif";
  8071. var lights_lambert_fragment = "LambertMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularStrength = specularStrength;";
  8072. 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";
  8073. 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";
  8074. 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";
  8075. var lights_toon_fragment = "ToonMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;";
  8076. 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";
  8077. var lights_phong_fragment = "BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;";
  8078. 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";
  8079. 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";
  8080. 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}";
  8081. 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";
  8082. 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";
  8083. 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";
  8084. 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";
  8085. 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";
  8086. 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";
  8087. 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";
  8088. 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";
  8089. var map_pars_fragment = "#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif";
  8090. 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";
  8091. 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";
  8092. var metalnessmap_fragment = "float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n\tvec4 texelMetalness = texture2D( metalnessMap, vUv );\n\tmetalnessFactor *= texelMetalness.b;\n#endif";
  8093. var metalnessmap_pars_fragment = "#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif";
  8094. 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";
  8095. 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";
  8096. 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";
  8097. 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";
  8098. 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;";
  8099. 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";
  8100. 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";
  8101. 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";
  8102. 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";
  8103. 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";
  8104. var clearcoat_normal_fragment_begin = "#ifdef USE_CLEARCOAT\n\tvec3 clearcoatNormal = geometryNormal;\n#endif";
  8105. 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";
  8106. 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";
  8107. var iridescence_pars_fragment = "#ifdef USE_IRIDESCENCEMAP\n\tuniform sampler2D iridescenceMap;\n#endif\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\tuniform sampler2D iridescenceThicknessMap;\n#endif";
  8108. 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 );";
  8109. 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}\nvec2 packDepthToRG( in highp float v ) {\n\treturn packDepthToRGBA( v ).yx;\n}\nfloat unpackRGToDepth( const in highp vec2 v ) {\n\treturn unpackRGBAToDepth( vec4( v.xy, 0.0, 0.0 ) );\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}";
  8110. var premultiplied_alpha_fragment = "#ifdef PREMULTIPLIED_ALPHA\n\tgl_FragColor.rgb *= gl_FragColor.a;\n#endif";
  8111. 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;";
  8112. var dithering_fragment = "#ifdef DITHERING\n\tgl_FragColor.rgb = dithering( gl_FragColor.rgb );\n#endif";
  8113. 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";
  8114. var roughnessmap_fragment = "float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n\tvec4 texelRoughness = texture2D( roughnessMap, vUv );\n\troughnessFactor *= texelRoughness.g;\n#endif";
  8115. var roughnessmap_pars_fragment = "#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif";
  8116. 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";
  8117. 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";
  8118. 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";
  8119. 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}";
  8120. 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";
  8121. 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";
  8122. 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";
  8123. 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";
  8124. 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";
  8125. var specularmap_pars_fragment = "#ifdef USE_SPECULARMAP\n\tuniform sampler2D specularMap;\n#endif";
  8126. var tonemapping_fragment = "#if defined( TONE_MAPPING )\n\tgl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif";
  8127. 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; }";
  8128. 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";
  8129. 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";
  8130. var uv_pars_fragment = "#if ( defined( USE_UV ) && ! defined( UVS_VERTEX_ONLY ) )\n\tvarying vec2 vUv;\n#endif";
  8131. 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";
  8132. var uv_vertex = "#ifdef USE_UV\n\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n#endif";
  8133. var uv2_pars_fragment = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvarying vec2 vUv2;\n#endif";
  8134. 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";
  8135. var uv2_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvUv2 = ( uv2Transform * vec3( uv2, 1 ) ).xy;\n#endif";
  8136. 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";
  8137. const vertex$h = "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}";
  8138. const fragment$h = "uniform sampler2D t2D;\nuniform float backgroundIntensity;\nvarying vec2 vUv;\nvoid main() {\n\tvec4 texColor = texture2D( t2D, vUv );\n\t#ifdef DECODE_VIDEO_TEXTURE\n\t\ttexColor = vec4( mix( pow( texColor.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), texColor.rgb * 0.0773993808, vec3( lessThanEqual( texColor.rgb, vec3( 0.04045 ) ) ) ), texColor.w );\n\t#endif\n\ttexColor.rgb *= backgroundIntensity;\n\tgl_FragColor = texColor;\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n}";
  8139. const vertex$g = "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}";
  8140. const fragment$g = "#ifdef ENVMAP_TYPE_CUBE\n\tuniform samplerCube envMap;\n#elif defined( ENVMAP_TYPE_CUBE_UV )\n\tuniform sampler2D envMap;\n#endif\nuniform float flipEnvMap;\nuniform float backgroundBlurriness;\nuniform float backgroundIntensity;\nvarying vec3 vWorldDirection;\n#include <cube_uv_reflection_fragment>\nvoid main() {\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tvec4 texColor = textureCube( envMap, vec3( flipEnvMap * vWorldDirection.x, vWorldDirection.yz ) );\n\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\tvec4 texColor = textureCubeUV( envMap, vWorldDirection, backgroundBlurriness );\n\t#else\n\t\tvec4 texColor = vec4( 0.0, 0.0, 0.0, 1.0 );\n\t#endif\n\ttexColor.rgb *= backgroundIntensity;\n\tgl_FragColor = texColor;\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n}";
  8141. 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}";
  8142. const fragment$f = "uniform samplerCube tCube;\nuniform float tFlip;\nuniform float opacity;\nvarying vec3 vWorldDirection;\nvoid main() {\n\tvec4 texColor = textureCube( tCube, vec3( tFlip * vWorldDirection.x, vWorldDirection.yz ) );\n\tgl_FragColor = texColor;\n\tgl_FragColor.a *= opacity;\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n}";
  8143. 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}";
  8144. 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}";
  8145. 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}";
  8146. 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}";
  8147. 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}";
  8148. 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}";
  8149. 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}";
  8150. 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}";
  8151. 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}";
  8152. 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}";
  8153. 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}";
  8154. 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}";
  8155. 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}";
  8156. 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}";
  8157. 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}";
  8158. 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}";
  8159. 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}";
  8160. 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}";
  8161. 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}";
  8162. 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}";
  8163. 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}";
  8164. 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}";
  8165. 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}";
  8166. 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}";
  8167. 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}";
  8168. 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}";
  8169. 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}";
  8170. 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}";
  8171. const ShaderChunk = {
  8172. alphamap_fragment: alphamap_fragment,
  8173. alphamap_pars_fragment: alphamap_pars_fragment,
  8174. alphatest_fragment: alphatest_fragment,
  8175. alphatest_pars_fragment: alphatest_pars_fragment,
  8176. aomap_fragment: aomap_fragment,
  8177. aomap_pars_fragment: aomap_pars_fragment,
  8178. begin_vertex: begin_vertex,
  8179. beginnormal_vertex: beginnormal_vertex,
  8180. bsdfs: bsdfs,
  8181. iridescence_fragment: iridescence_fragment,
  8182. bumpmap_pars_fragment: bumpmap_pars_fragment,
  8183. clipping_planes_fragment: clipping_planes_fragment,
  8184. clipping_planes_pars_fragment: clipping_planes_pars_fragment,
  8185. clipping_planes_pars_vertex: clipping_planes_pars_vertex,
  8186. clipping_planes_vertex: clipping_planes_vertex,
  8187. color_fragment: color_fragment,
  8188. color_pars_fragment: color_pars_fragment,
  8189. color_pars_vertex: color_pars_vertex,
  8190. color_vertex: color_vertex,
  8191. common: common,
  8192. cube_uv_reflection_fragment: cube_uv_reflection_fragment,
  8193. defaultnormal_vertex: defaultnormal_vertex,
  8194. displacementmap_pars_vertex: displacementmap_pars_vertex,
  8195. displacementmap_vertex: displacementmap_vertex,
  8196. emissivemap_fragment: emissivemap_fragment,
  8197. emissivemap_pars_fragment: emissivemap_pars_fragment,
  8198. encodings_fragment: encodings_fragment,
  8199. encodings_pars_fragment: encodings_pars_fragment,
  8200. envmap_fragment: envmap_fragment,
  8201. envmap_common_pars_fragment: envmap_common_pars_fragment,
  8202. envmap_pars_fragment: envmap_pars_fragment,
  8203. envmap_pars_vertex: envmap_pars_vertex,
  8204. envmap_physical_pars_fragment: envmap_physical_pars_fragment,
  8205. envmap_vertex: envmap_vertex,
  8206. fog_vertex: fog_vertex,
  8207. fog_pars_vertex: fog_pars_vertex,
  8208. fog_fragment: fog_fragment,
  8209. fog_pars_fragment: fog_pars_fragment,
  8210. gradientmap_pars_fragment: gradientmap_pars_fragment,
  8211. lightmap_fragment: lightmap_fragment,
  8212. lightmap_pars_fragment: lightmap_pars_fragment,
  8213. lights_lambert_fragment: lights_lambert_fragment,
  8214. lights_lambert_pars_fragment: lights_lambert_pars_fragment,
  8215. lights_pars_begin: lights_pars_begin,
  8216. lights_toon_fragment: lights_toon_fragment,
  8217. lights_toon_pars_fragment: lights_toon_pars_fragment,
  8218. lights_phong_fragment: lights_phong_fragment,
  8219. lights_phong_pars_fragment: lights_phong_pars_fragment,
  8220. lights_physical_fragment: lights_physical_fragment,
  8221. lights_physical_pars_fragment: lights_physical_pars_fragment,
  8222. lights_fragment_begin: lights_fragment_begin,
  8223. lights_fragment_maps: lights_fragment_maps,
  8224. lights_fragment_end: lights_fragment_end,
  8225. logdepthbuf_fragment: logdepthbuf_fragment,
  8226. logdepthbuf_pars_fragment: logdepthbuf_pars_fragment,
  8227. logdepthbuf_pars_vertex: logdepthbuf_pars_vertex,
  8228. logdepthbuf_vertex: logdepthbuf_vertex,
  8229. map_fragment: map_fragment,
  8230. map_pars_fragment: map_pars_fragment,
  8231. map_particle_fragment: map_particle_fragment,
  8232. map_particle_pars_fragment: map_particle_pars_fragment,
  8233. metalnessmap_fragment: metalnessmap_fragment,
  8234. metalnessmap_pars_fragment: metalnessmap_pars_fragment,
  8235. morphcolor_vertex: morphcolor_vertex,
  8236. morphnormal_vertex: morphnormal_vertex,
  8237. morphtarget_pars_vertex: morphtarget_pars_vertex,
  8238. morphtarget_vertex: morphtarget_vertex,
  8239. normal_fragment_begin: normal_fragment_begin,
  8240. normal_fragment_maps: normal_fragment_maps,
  8241. normal_pars_fragment: normal_pars_fragment,
  8242. normal_pars_vertex: normal_pars_vertex,
  8243. normal_vertex: normal_vertex,
  8244. normalmap_pars_fragment: normalmap_pars_fragment,
  8245. clearcoat_normal_fragment_begin: clearcoat_normal_fragment_begin,
  8246. clearcoat_normal_fragment_maps: clearcoat_normal_fragment_maps,
  8247. clearcoat_pars_fragment: clearcoat_pars_fragment,
  8248. iridescence_pars_fragment: iridescence_pars_fragment,
  8249. output_fragment: output_fragment,
  8250. packing: packing,
  8251. premultiplied_alpha_fragment: premultiplied_alpha_fragment,
  8252. project_vertex: project_vertex,
  8253. dithering_fragment: dithering_fragment,
  8254. dithering_pars_fragment: dithering_pars_fragment,
  8255. roughnessmap_fragment: roughnessmap_fragment,
  8256. roughnessmap_pars_fragment: roughnessmap_pars_fragment,
  8257. shadowmap_pars_fragment: shadowmap_pars_fragment,
  8258. shadowmap_pars_vertex: shadowmap_pars_vertex,
  8259. shadowmap_vertex: shadowmap_vertex,
  8260. shadowmask_pars_fragment: shadowmask_pars_fragment,
  8261. skinbase_vertex: skinbase_vertex,
  8262. skinning_pars_vertex: skinning_pars_vertex,
  8263. skinning_vertex: skinning_vertex,
  8264. skinnormal_vertex: skinnormal_vertex,
  8265. specularmap_fragment: specularmap_fragment,
  8266. specularmap_pars_fragment: specularmap_pars_fragment,
  8267. tonemapping_fragment: tonemapping_fragment,
  8268. tonemapping_pars_fragment: tonemapping_pars_fragment,
  8269. transmission_fragment: transmission_fragment,
  8270. transmission_pars_fragment: transmission_pars_fragment,
  8271. uv_pars_fragment: uv_pars_fragment,
  8272. uv_pars_vertex: uv_pars_vertex,
  8273. uv_vertex: uv_vertex,
  8274. uv2_pars_fragment: uv2_pars_fragment,
  8275. uv2_pars_vertex: uv2_pars_vertex,
  8276. uv2_vertex: uv2_vertex,
  8277. worldpos_vertex: worldpos_vertex,
  8278. background_vert: vertex$h,
  8279. background_frag: fragment$h,
  8280. backgroundCube_vert: vertex$g,
  8281. backgroundCube_frag: fragment$g,
  8282. cube_vert: vertex$f,
  8283. cube_frag: fragment$f,
  8284. depth_vert: vertex$e,
  8285. depth_frag: fragment$e,
  8286. distanceRGBA_vert: vertex$d,
  8287. distanceRGBA_frag: fragment$d,
  8288. equirect_vert: vertex$c,
  8289. equirect_frag: fragment$c,
  8290. linedashed_vert: vertex$b,
  8291. linedashed_frag: fragment$b,
  8292. meshbasic_vert: vertex$a,
  8293. meshbasic_frag: fragment$a,
  8294. meshlambert_vert: vertex$9,
  8295. meshlambert_frag: fragment$9,
  8296. meshmatcap_vert: vertex$8,
  8297. meshmatcap_frag: fragment$8,
  8298. meshnormal_vert: vertex$7,
  8299. meshnormal_frag: fragment$7,
  8300. meshphong_vert: vertex$6,
  8301. meshphong_frag: fragment$6,
  8302. meshphysical_vert: vertex$5,
  8303. meshphysical_frag: fragment$5,
  8304. meshtoon_vert: vertex$4,
  8305. meshtoon_frag: fragment$4,
  8306. points_vert: vertex$3,
  8307. points_frag: fragment$3,
  8308. shadow_vert: vertex$2,
  8309. shadow_frag: fragment$2,
  8310. sprite_vert: vertex$1,
  8311. sprite_frag: fragment$1
  8312. };
  8313. /**
  8314. * Uniforms library for shared webgl shaders
  8315. */
  8316. const UniformsLib = {
  8317. common: {
  8318. diffuse: {
  8319. value: /*@__PURE__*/new Color(0xffffff)
  8320. },
  8321. opacity: {
  8322. value: 1.0
  8323. },
  8324. map: {
  8325. value: null
  8326. },
  8327. uvTransform: {
  8328. value: /*@__PURE__*/new Matrix3()
  8329. },
  8330. uv2Transform: {
  8331. value: /*@__PURE__*/new Matrix3()
  8332. },
  8333. alphaMap: {
  8334. value: null
  8335. },
  8336. alphaTest: {
  8337. value: 0
  8338. }
  8339. },
  8340. specularmap: {
  8341. specularMap: {
  8342. value: null
  8343. }
  8344. },
  8345. envmap: {
  8346. envMap: {
  8347. value: null
  8348. },
  8349. flipEnvMap: {
  8350. value: -1
  8351. },
  8352. reflectivity: {
  8353. value: 1.0
  8354. },
  8355. // basic, lambert, phong
  8356. ior: {
  8357. value: 1.5
  8358. },
  8359. // physical
  8360. refractionRatio: {
  8361. value: 0.98
  8362. } // basic, lambert, phong
  8363. },
  8364. aomap: {
  8365. aoMap: {
  8366. value: null
  8367. },
  8368. aoMapIntensity: {
  8369. value: 1
  8370. }
  8371. },
  8372. lightmap: {
  8373. lightMap: {
  8374. value: null
  8375. },
  8376. lightMapIntensity: {
  8377. value: 1
  8378. }
  8379. },
  8380. emissivemap: {
  8381. emissiveMap: {
  8382. value: null
  8383. }
  8384. },
  8385. bumpmap: {
  8386. bumpMap: {
  8387. value: null
  8388. },
  8389. bumpScale: {
  8390. value: 1
  8391. }
  8392. },
  8393. normalmap: {
  8394. normalMap: {
  8395. value: null
  8396. },
  8397. normalScale: {
  8398. value: /*@__PURE__*/new Vector2(1, 1)
  8399. }
  8400. },
  8401. displacementmap: {
  8402. displacementMap: {
  8403. value: null
  8404. },
  8405. displacementScale: {
  8406. value: 1
  8407. },
  8408. displacementBias: {
  8409. value: 0
  8410. }
  8411. },
  8412. roughnessmap: {
  8413. roughnessMap: {
  8414. value: null
  8415. }
  8416. },
  8417. metalnessmap: {
  8418. metalnessMap: {
  8419. value: null
  8420. }
  8421. },
  8422. gradientmap: {
  8423. gradientMap: {
  8424. value: null
  8425. }
  8426. },
  8427. fog: {
  8428. fogDensity: {
  8429. value: 0.00025
  8430. },
  8431. fogNear: {
  8432. value: 1
  8433. },
  8434. fogFar: {
  8435. value: 2000
  8436. },
  8437. fogColor: {
  8438. value: /*@__PURE__*/new Color(0xffffff)
  8439. }
  8440. },
  8441. lights: {
  8442. ambientLightColor: {
  8443. value: []
  8444. },
  8445. lightProbe: {
  8446. value: []
  8447. },
  8448. directionalLights: {
  8449. value: [],
  8450. properties: {
  8451. direction: {},
  8452. color: {}
  8453. }
  8454. },
  8455. directionalLightShadows: {
  8456. value: [],
  8457. properties: {
  8458. shadowBias: {},
  8459. shadowNormalBias: {},
  8460. shadowRadius: {},
  8461. shadowMapSize: {}
  8462. }
  8463. },
  8464. directionalShadowMap: {
  8465. value: []
  8466. },
  8467. directionalShadowMatrix: {
  8468. value: []
  8469. },
  8470. spotLights: {
  8471. value: [],
  8472. properties: {
  8473. color: {},
  8474. position: {},
  8475. direction: {},
  8476. distance: {},
  8477. coneCos: {},
  8478. penumbraCos: {},
  8479. decay: {}
  8480. }
  8481. },
  8482. spotLightShadows: {
  8483. value: [],
  8484. properties: {
  8485. shadowBias: {},
  8486. shadowNormalBias: {},
  8487. shadowRadius: {},
  8488. shadowMapSize: {}
  8489. }
  8490. },
  8491. spotLightMap: {
  8492. value: []
  8493. },
  8494. spotShadowMap: {
  8495. value: []
  8496. },
  8497. spotLightMatrix: {
  8498. value: []
  8499. },
  8500. pointLights: {
  8501. value: [],
  8502. properties: {
  8503. color: {},
  8504. position: {},
  8505. decay: {},
  8506. distance: {}
  8507. }
  8508. },
  8509. pointLightShadows: {
  8510. value: [],
  8511. properties: {
  8512. shadowBias: {},
  8513. shadowNormalBias: {},
  8514. shadowRadius: {},
  8515. shadowMapSize: {},
  8516. shadowCameraNear: {},
  8517. shadowCameraFar: {}
  8518. }
  8519. },
  8520. pointShadowMap: {
  8521. value: []
  8522. },
  8523. pointShadowMatrix: {
  8524. value: []
  8525. },
  8526. hemisphereLights: {
  8527. value: [],
  8528. properties: {
  8529. direction: {},
  8530. skyColor: {},
  8531. groundColor: {}
  8532. }
  8533. },
  8534. // TODO (abelnation): RectAreaLight BRDF data needs to be moved from example to main src
  8535. rectAreaLights: {
  8536. value: [],
  8537. properties: {
  8538. color: {},
  8539. position: {},
  8540. width: {},
  8541. height: {}
  8542. }
  8543. },
  8544. ltc_1: {
  8545. value: null
  8546. },
  8547. ltc_2: {
  8548. value: null
  8549. }
  8550. },
  8551. points: {
  8552. diffuse: {
  8553. value: /*@__PURE__*/new Color(0xffffff)
  8554. },
  8555. opacity: {
  8556. value: 1.0
  8557. },
  8558. size: {
  8559. value: 1.0
  8560. },
  8561. scale: {
  8562. value: 1.0
  8563. },
  8564. map: {
  8565. value: null
  8566. },
  8567. alphaMap: {
  8568. value: null
  8569. },
  8570. alphaTest: {
  8571. value: 0
  8572. },
  8573. uvTransform: {
  8574. value: /*@__PURE__*/new Matrix3()
  8575. }
  8576. },
  8577. sprite: {
  8578. diffuse: {
  8579. value: /*@__PURE__*/new Color(0xffffff)
  8580. },
  8581. opacity: {
  8582. value: 1.0
  8583. },
  8584. center: {
  8585. value: /*@__PURE__*/new Vector2(0.5, 0.5)
  8586. },
  8587. rotation: {
  8588. value: 0.0
  8589. },
  8590. map: {
  8591. value: null
  8592. },
  8593. alphaMap: {
  8594. value: null
  8595. },
  8596. alphaTest: {
  8597. value: 0
  8598. },
  8599. uvTransform: {
  8600. value: /*@__PURE__*/new Matrix3()
  8601. }
  8602. }
  8603. };
  8604. const ShaderLib = {
  8605. basic: {
  8606. uniforms: /*@__PURE__*/mergeUniforms([UniformsLib.common, UniformsLib.specularmap, UniformsLib.envmap, UniformsLib.aomap, UniformsLib.lightmap, UniformsLib.fog]),
  8607. vertexShader: ShaderChunk.meshbasic_vert,
  8608. fragmentShader: ShaderChunk.meshbasic_frag
  8609. },
  8610. lambert: {
  8611. 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, {
  8612. emissive: {
  8613. value: /*@__PURE__*/new Color(0x000000)
  8614. }
  8615. }]),
  8616. vertexShader: ShaderChunk.meshlambert_vert,
  8617. fragmentShader: ShaderChunk.meshlambert_frag
  8618. },
  8619. phong: {
  8620. 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, {
  8621. emissive: {
  8622. value: /*@__PURE__*/new Color(0x000000)
  8623. },
  8624. specular: {
  8625. value: /*@__PURE__*/new Color(0x111111)
  8626. },
  8627. shininess: {
  8628. value: 30
  8629. }
  8630. }]),
  8631. vertexShader: ShaderChunk.meshphong_vert,
  8632. fragmentShader: ShaderChunk.meshphong_frag
  8633. },
  8634. standard: {
  8635. 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, {
  8636. emissive: {
  8637. value: /*@__PURE__*/new Color(0x000000)
  8638. },
  8639. roughness: {
  8640. value: 1.0
  8641. },
  8642. metalness: {
  8643. value: 0.0
  8644. },
  8645. envMapIntensity: {
  8646. value: 1
  8647. } // temporary
  8648. }]),
  8649. vertexShader: ShaderChunk.meshphysical_vert,
  8650. fragmentShader: ShaderChunk.meshphysical_frag
  8651. },
  8652. toon: {
  8653. uniforms: /*@__PURE__*/mergeUniforms([UniformsLib.common, UniformsLib.aomap, UniformsLib.lightmap, UniformsLib.emissivemap, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, UniformsLib.gradientmap, UniformsLib.fog, UniformsLib.lights, {
  8654. emissive: {
  8655. value: /*@__PURE__*/new Color(0x000000)
  8656. }
  8657. }]),
  8658. vertexShader: ShaderChunk.meshtoon_vert,
  8659. fragmentShader: ShaderChunk.meshtoon_frag
  8660. },
  8661. matcap: {
  8662. uniforms: /*@__PURE__*/mergeUniforms([UniformsLib.common, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, UniformsLib.fog, {
  8663. matcap: {
  8664. value: null
  8665. }
  8666. }]),
  8667. vertexShader: ShaderChunk.meshmatcap_vert,
  8668. fragmentShader: ShaderChunk.meshmatcap_frag
  8669. },
  8670. points: {
  8671. uniforms: /*@__PURE__*/mergeUniforms([UniformsLib.points, UniformsLib.fog]),
  8672. vertexShader: ShaderChunk.points_vert,
  8673. fragmentShader: ShaderChunk.points_frag
  8674. },
  8675. dashed: {
  8676. uniforms: /*@__PURE__*/mergeUniforms([UniformsLib.common, UniformsLib.fog, {
  8677. scale: {
  8678. value: 1
  8679. },
  8680. dashSize: {
  8681. value: 1
  8682. },
  8683. totalSize: {
  8684. value: 2
  8685. }
  8686. }]),
  8687. vertexShader: ShaderChunk.linedashed_vert,
  8688. fragmentShader: ShaderChunk.linedashed_frag
  8689. },
  8690. depth: {
  8691. uniforms: /*@__PURE__*/mergeUniforms([UniformsLib.common, UniformsLib.displacementmap]),
  8692. vertexShader: ShaderChunk.depth_vert,
  8693. fragmentShader: ShaderChunk.depth_frag
  8694. },
  8695. normal: {
  8696. uniforms: /*@__PURE__*/mergeUniforms([UniformsLib.common, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, {
  8697. opacity: {
  8698. value: 1.0
  8699. }
  8700. }]),
  8701. vertexShader: ShaderChunk.meshnormal_vert,
  8702. fragmentShader: ShaderChunk.meshnormal_frag
  8703. },
  8704. sprite: {
  8705. uniforms: /*@__PURE__*/mergeUniforms([UniformsLib.sprite, UniformsLib.fog]),
  8706. vertexShader: ShaderChunk.sprite_vert,
  8707. fragmentShader: ShaderChunk.sprite_frag
  8708. },
  8709. background: {
  8710. uniforms: {
  8711. uvTransform: {
  8712. value: /*@__PURE__*/new Matrix3()
  8713. },
  8714. t2D: {
  8715. value: null
  8716. },
  8717. backgroundIntensity: {
  8718. value: 1
  8719. }
  8720. },
  8721. vertexShader: ShaderChunk.background_vert,
  8722. fragmentShader: ShaderChunk.background_frag
  8723. },
  8724. backgroundCube: {
  8725. uniforms: {
  8726. envMap: {
  8727. value: null
  8728. },
  8729. flipEnvMap: {
  8730. value: -1
  8731. },
  8732. backgroundBlurriness: {
  8733. value: 0
  8734. },
  8735. backgroundIntensity: {
  8736. value: 1
  8737. }
  8738. },
  8739. vertexShader: ShaderChunk.backgroundCube_vert,
  8740. fragmentShader: ShaderChunk.backgroundCube_frag
  8741. },
  8742. cube: {
  8743. uniforms: {
  8744. tCube: {
  8745. value: null
  8746. },
  8747. tFlip: {
  8748. value: -1
  8749. },
  8750. opacity: {
  8751. value: 1.0
  8752. }
  8753. },
  8754. vertexShader: ShaderChunk.cube_vert,
  8755. fragmentShader: ShaderChunk.cube_frag
  8756. },
  8757. equirect: {
  8758. uniforms: {
  8759. tEquirect: {
  8760. value: null
  8761. }
  8762. },
  8763. vertexShader: ShaderChunk.equirect_vert,
  8764. fragmentShader: ShaderChunk.equirect_frag
  8765. },
  8766. distanceRGBA: {
  8767. uniforms: /*@__PURE__*/mergeUniforms([UniformsLib.common, UniformsLib.displacementmap, {
  8768. referencePosition: {
  8769. value: /*@__PURE__*/new Vector3()
  8770. },
  8771. nearDistance: {
  8772. value: 1
  8773. },
  8774. farDistance: {
  8775. value: 1000
  8776. }
  8777. }]),
  8778. vertexShader: ShaderChunk.distanceRGBA_vert,
  8779. fragmentShader: ShaderChunk.distanceRGBA_frag
  8780. },
  8781. shadow: {
  8782. uniforms: /*@__PURE__*/mergeUniforms([UniformsLib.lights, UniformsLib.fog, {
  8783. color: {
  8784. value: /*@__PURE__*/new Color(0x00000)
  8785. },
  8786. opacity: {
  8787. value: 1.0
  8788. }
  8789. }]),
  8790. vertexShader: ShaderChunk.shadow_vert,
  8791. fragmentShader: ShaderChunk.shadow_frag
  8792. }
  8793. };
  8794. ShaderLib.physical = {
  8795. uniforms: /*@__PURE__*/mergeUniforms([ShaderLib.standard.uniforms, {
  8796. clearcoat: {
  8797. value: 0
  8798. },
  8799. clearcoatMap: {
  8800. value: null
  8801. },
  8802. clearcoatRoughness: {
  8803. value: 0
  8804. },
  8805. clearcoatRoughnessMap: {
  8806. value: null
  8807. },
  8808. clearcoatNormalScale: {
  8809. value: /*@__PURE__*/new Vector2(1, 1)
  8810. },
  8811. clearcoatNormalMap: {
  8812. value: null
  8813. },
  8814. iridescence: {
  8815. value: 0
  8816. },
  8817. iridescenceMap: {
  8818. value: null
  8819. },
  8820. iridescenceIOR: {
  8821. value: 1.3
  8822. },
  8823. iridescenceThicknessMinimum: {
  8824. value: 100
  8825. },
  8826. iridescenceThicknessMaximum: {
  8827. value: 400
  8828. },
  8829. iridescenceThicknessMap: {
  8830. value: null
  8831. },
  8832. sheen: {
  8833. value: 0
  8834. },
  8835. sheenColor: {
  8836. value: /*@__PURE__*/new Color(0x000000)
  8837. },
  8838. sheenColorMap: {
  8839. value: null
  8840. },
  8841. sheenRoughness: {
  8842. value: 1
  8843. },
  8844. sheenRoughnessMap: {
  8845. value: null
  8846. },
  8847. transmission: {
  8848. value: 0
  8849. },
  8850. transmissionMap: {
  8851. value: null
  8852. },
  8853. transmissionSamplerSize: {
  8854. value: /*@__PURE__*/new Vector2()
  8855. },
  8856. transmissionSamplerMap: {
  8857. value: null
  8858. },
  8859. thickness: {
  8860. value: 0
  8861. },
  8862. thicknessMap: {
  8863. value: null
  8864. },
  8865. attenuationDistance: {
  8866. value: 0
  8867. },
  8868. attenuationColor: {
  8869. value: /*@__PURE__*/new Color(0x000000)
  8870. },
  8871. specularIntensity: {
  8872. value: 1
  8873. },
  8874. specularIntensityMap: {
  8875. value: null
  8876. },
  8877. specularColor: {
  8878. value: /*@__PURE__*/new Color(1, 1, 1)
  8879. },
  8880. specularColorMap: {
  8881. value: null
  8882. }
  8883. }]),
  8884. vertexShader: ShaderChunk.meshphysical_vert,
  8885. fragmentShader: ShaderChunk.meshphysical_frag
  8886. };
  8887. const _rgb = {
  8888. r: 0,
  8889. b: 0,
  8890. g: 0
  8891. };
  8892. function WebGLBackground(renderer, cubemaps, cubeuvmaps, state, objects, alpha, premultipliedAlpha) {
  8893. const clearColor = new Color(0x000000);
  8894. let clearAlpha = alpha === true ? 0 : 1;
  8895. let planeMesh;
  8896. let boxMesh;
  8897. let currentBackground = null;
  8898. let currentBackgroundVersion = 0;
  8899. let currentTonemapping = null;
  8900. function render(renderList, scene) {
  8901. let forceClear = false;
  8902. let background = scene.isScene === true ? scene.background : null;
  8903. if (background && background.isTexture) {
  8904. const usePMREM = scene.backgroundBlurriness > 0; // use PMREM if the user wants to blur the background
  8905. background = (usePMREM ? cubeuvmaps : cubemaps).get(background);
  8906. }
  8907. // Ignore background in AR
  8908. // TODO: Reconsider this.
  8909. const xr = renderer.xr;
  8910. const session = xr.getSession && xr.getSession();
  8911. if (session && session.environmentBlendMode === 'additive') {
  8912. background = null;
  8913. }
  8914. if (background === null) {
  8915. setClear(clearColor, clearAlpha);
  8916. } else if (background && background.isColor) {
  8917. setClear(background, 1);
  8918. forceClear = true;
  8919. }
  8920. if (renderer.autoClear || forceClear) {
  8921. renderer.clear(renderer.autoClearColor, renderer.autoClearDepth, renderer.autoClearStencil);
  8922. }
  8923. if (background && (background.isCubeTexture || background.mapping === CubeUVReflectionMapping)) {
  8924. if (boxMesh === undefined) {
  8925. boxMesh = new Mesh(new BoxGeometry(1, 1, 1), new ShaderMaterial({
  8926. name: 'BackgroundCubeMaterial',
  8927. uniforms: cloneUniforms(ShaderLib.backgroundCube.uniforms),
  8928. vertexShader: ShaderLib.backgroundCube.vertexShader,
  8929. fragmentShader: ShaderLib.backgroundCube.fragmentShader,
  8930. side: BackSide,
  8931. depthTest: false,
  8932. depthWrite: false,
  8933. fog: false
  8934. }));
  8935. boxMesh.geometry.deleteAttribute('normal');
  8936. boxMesh.geometry.deleteAttribute('uv');
  8937. boxMesh.onBeforeRender = function (renderer, scene, camera) {
  8938. this.matrixWorld.copyPosition(camera.matrixWorld);
  8939. };
  8940. // add "envMap" material property so the renderer can evaluate it like for built-in materials
  8941. Object.defineProperty(boxMesh.material, 'envMap', {
  8942. get: function () {
  8943. return this.uniforms.envMap.value;
  8944. }
  8945. });
  8946. objects.update(boxMesh);
  8947. }
  8948. boxMesh.material.uniforms.envMap.value = background;
  8949. boxMesh.material.uniforms.flipEnvMap.value = background.isCubeTexture && background.isRenderTargetTexture === false ? -1 : 1;
  8950. boxMesh.material.uniforms.backgroundBlurriness.value = scene.backgroundBlurriness;
  8951. boxMesh.material.uniforms.backgroundIntensity.value = scene.backgroundIntensity;
  8952. if (currentBackground !== background || currentBackgroundVersion !== background.version || currentTonemapping !== renderer.toneMapping) {
  8953. boxMesh.material.needsUpdate = true;
  8954. currentBackground = background;
  8955. currentBackgroundVersion = background.version;
  8956. currentTonemapping = renderer.toneMapping;
  8957. }
  8958. boxMesh.layers.enableAll();
  8959. // push to the pre-sorted opaque render list
  8960. renderList.unshift(boxMesh, boxMesh.geometry, boxMesh.material, 0, 0, null);
  8961. } else if (background && background.isTexture) {
  8962. if (planeMesh === undefined) {
  8963. planeMesh = new Mesh(new PlaneGeometry(2, 2), new ShaderMaterial({
  8964. name: 'BackgroundMaterial',
  8965. uniforms: cloneUniforms(ShaderLib.background.uniforms),
  8966. vertexShader: ShaderLib.background.vertexShader,
  8967. fragmentShader: ShaderLib.background.fragmentShader,
  8968. side: FrontSide,
  8969. depthTest: false,
  8970. depthWrite: false,
  8971. fog: false
  8972. }));
  8973. planeMesh.geometry.deleteAttribute('normal');
  8974. // add "map" material property so the renderer can evaluate it like for built-in materials
  8975. Object.defineProperty(planeMesh.material, 'map', {
  8976. get: function () {
  8977. return this.uniforms.t2D.value;
  8978. }
  8979. });
  8980. objects.update(planeMesh);
  8981. }
  8982. planeMesh.material.uniforms.t2D.value = background;
  8983. planeMesh.material.uniforms.backgroundIntensity.value = scene.backgroundIntensity;
  8984. if (background.matrixAutoUpdate === true) {
  8985. background.updateMatrix();
  8986. }
  8987. planeMesh.material.uniforms.uvTransform.value.copy(background.matrix);
  8988. if (currentBackground !== background || currentBackgroundVersion !== background.version || currentTonemapping !== renderer.toneMapping) {
  8989. planeMesh.material.needsUpdate = true;
  8990. currentBackground = background;
  8991. currentBackgroundVersion = background.version;
  8992. currentTonemapping = renderer.toneMapping;
  8993. }
  8994. planeMesh.layers.enableAll();
  8995. // push to the pre-sorted opaque render list
  8996. renderList.unshift(planeMesh, planeMesh.geometry, planeMesh.material, 0, 0, null);
  8997. }
  8998. }
  8999. function setClear(color, alpha) {
  9000. color.getRGB(_rgb, getUnlitUniformColorSpace(renderer));
  9001. state.buffers.color.setClear(_rgb.r, _rgb.g, _rgb.b, alpha, premultipliedAlpha);
  9002. }
  9003. return {
  9004. getClearColor: function () {
  9005. return clearColor;
  9006. },
  9007. setClearColor: function (color, alpha = 1) {
  9008. clearColor.set(color);
  9009. clearAlpha = alpha;
  9010. setClear(clearColor, clearAlpha);
  9011. },
  9012. getClearAlpha: function () {
  9013. return clearAlpha;
  9014. },
  9015. setClearAlpha: function (alpha) {
  9016. clearAlpha = alpha;
  9017. setClear(clearColor, clearAlpha);
  9018. },
  9019. render: render
  9020. };
  9021. }
  9022. function WebGLBindingStates(gl, extensions, attributes, capabilities) {
  9023. const maxVertexAttributes = gl.getParameter(gl.MAX_VERTEX_ATTRIBS);
  9024. const extension = capabilities.isWebGL2 ? null : extensions.get('OES_vertex_array_object');
  9025. const vaoAvailable = capabilities.isWebGL2 || extension !== null;
  9026. const bindingStates = {};
  9027. const defaultState = createBindingState(null);
  9028. let currentState = defaultState;
  9029. let forceUpdate = false;
  9030. function setup(object, material, program, geometry, index) {
  9031. let updateBuffers = false;
  9032. if (vaoAvailable) {
  9033. const state = getBindingState(geometry, program, material);
  9034. if (currentState !== state) {
  9035. currentState = state;
  9036. bindVertexArrayObject(currentState.object);
  9037. }
  9038. updateBuffers = needsUpdate(object, geometry, program, index);
  9039. if (updateBuffers) saveCache(object, geometry, program, index);
  9040. } else {
  9041. const wireframe = material.wireframe === true;
  9042. if (currentState.geometry !== geometry.id || currentState.program !== program.id || currentState.wireframe !== wireframe) {
  9043. currentState.geometry = geometry.id;
  9044. currentState.program = program.id;
  9045. currentState.wireframe = wireframe;
  9046. updateBuffers = true;
  9047. }
  9048. }
  9049. if (index !== null) {
  9050. attributes.update(index, gl.ELEMENT_ARRAY_BUFFER);
  9051. }
  9052. if (updateBuffers || forceUpdate) {
  9053. forceUpdate = false;
  9054. setupVertexAttributes(object, material, program, geometry);
  9055. if (index !== null) {
  9056. gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, attributes.get(index).buffer);
  9057. }
  9058. }
  9059. }
  9060. function createVertexArrayObject() {
  9061. if (capabilities.isWebGL2) return gl.createVertexArray();
  9062. return extension.createVertexArrayOES();
  9063. }
  9064. function bindVertexArrayObject(vao) {
  9065. if (capabilities.isWebGL2) return gl.bindVertexArray(vao);
  9066. return extension.bindVertexArrayOES(vao);
  9067. }
  9068. function deleteVertexArrayObject(vao) {
  9069. if (capabilities.isWebGL2) return gl.deleteVertexArray(vao);
  9070. return extension.deleteVertexArrayOES(vao);
  9071. }
  9072. function getBindingState(geometry, program, material) {
  9073. const wireframe = material.wireframe === true;
  9074. let programMap = bindingStates[geometry.id];
  9075. if (programMap === undefined) {
  9076. programMap = {};
  9077. bindingStates[geometry.id] = programMap;
  9078. }
  9079. let stateMap = programMap[program.id];
  9080. if (stateMap === undefined) {
  9081. stateMap = {};
  9082. programMap[program.id] = stateMap;
  9083. }
  9084. let state = stateMap[wireframe];
  9085. if (state === undefined) {
  9086. state = createBindingState(createVertexArrayObject());
  9087. stateMap[wireframe] = state;
  9088. }
  9089. return state;
  9090. }
  9091. function createBindingState(vao) {
  9092. const newAttributes = [];
  9093. const enabledAttributes = [];
  9094. const attributeDivisors = [];
  9095. for (let i = 0; i < maxVertexAttributes; i++) {
  9096. newAttributes[i] = 0;
  9097. enabledAttributes[i] = 0;
  9098. attributeDivisors[i] = 0;
  9099. }
  9100. return {
  9101. // for backward compatibility on non-VAO support browser
  9102. geometry: null,
  9103. program: null,
  9104. wireframe: false,
  9105. newAttributes: newAttributes,
  9106. enabledAttributes: enabledAttributes,
  9107. attributeDivisors: attributeDivisors,
  9108. object: vao,
  9109. attributes: {},
  9110. index: null
  9111. };
  9112. }
  9113. function needsUpdate(object, geometry, program, index) {
  9114. const cachedAttributes = currentState.attributes;
  9115. const geometryAttributes = geometry.attributes;
  9116. let attributesNum = 0;
  9117. const programAttributes = program.getAttributes();
  9118. for (const name in programAttributes) {
  9119. const programAttribute = programAttributes[name];
  9120. if (programAttribute.location >= 0) {
  9121. const cachedAttribute = cachedAttributes[name];
  9122. let geometryAttribute = geometryAttributes[name];
  9123. if (geometryAttribute === undefined) {
  9124. if (name === 'instanceMatrix' && object.instanceMatrix) geometryAttribute = object.instanceMatrix;
  9125. if (name === 'instanceColor' && object.instanceColor) geometryAttribute = object.instanceColor;
  9126. }
  9127. if (cachedAttribute === undefined) return true;
  9128. if (cachedAttribute.attribute !== geometryAttribute) return true;
  9129. if (geometryAttribute && cachedAttribute.data !== geometryAttribute.data) return true;
  9130. attributesNum++;
  9131. }
  9132. }
  9133. if (currentState.attributesNum !== attributesNum) return true;
  9134. if (currentState.index !== index) return true;
  9135. return false;
  9136. }
  9137. function saveCache(object, geometry, program, index) {
  9138. const cache = {};
  9139. const attributes = geometry.attributes;
  9140. let attributesNum = 0;
  9141. const programAttributes = program.getAttributes();
  9142. for (const name in programAttributes) {
  9143. const programAttribute = programAttributes[name];
  9144. if (programAttribute.location >= 0) {
  9145. let attribute = attributes[name];
  9146. if (attribute === undefined) {
  9147. if (name === 'instanceMatrix' && object.instanceMatrix) attribute = object.instanceMatrix;
  9148. if (name === 'instanceColor' && object.instanceColor) attribute = object.instanceColor;
  9149. }
  9150. const data = {};
  9151. data.attribute = attribute;
  9152. if (attribute && attribute.data) {
  9153. data.data = attribute.data;
  9154. }
  9155. cache[name] = data;
  9156. attributesNum++;
  9157. }
  9158. }
  9159. currentState.attributes = cache;
  9160. currentState.attributesNum = attributesNum;
  9161. currentState.index = index;
  9162. }
  9163. function initAttributes() {
  9164. const newAttributes = currentState.newAttributes;
  9165. for (let i = 0, il = newAttributes.length; i < il; i++) {
  9166. newAttributes[i] = 0;
  9167. }
  9168. }
  9169. function enableAttribute(attribute) {
  9170. enableAttributeAndDivisor(attribute, 0);
  9171. }
  9172. function enableAttributeAndDivisor(attribute, meshPerAttribute) {
  9173. const newAttributes = currentState.newAttributes;
  9174. const enabledAttributes = currentState.enabledAttributes;
  9175. const attributeDivisors = currentState.attributeDivisors;
  9176. newAttributes[attribute] = 1;
  9177. if (enabledAttributes[attribute] === 0) {
  9178. gl.enableVertexAttribArray(attribute);
  9179. enabledAttributes[attribute] = 1;
  9180. }
  9181. if (attributeDivisors[attribute] !== meshPerAttribute) {
  9182. const extension = capabilities.isWebGL2 ? gl : extensions.get('ANGLE_instanced_arrays');
  9183. extension[capabilities.isWebGL2 ? 'vertexAttribDivisor' : 'vertexAttribDivisorANGLE'](attribute, meshPerAttribute);
  9184. attributeDivisors[attribute] = meshPerAttribute;
  9185. }
  9186. }
  9187. function disableUnusedAttributes() {
  9188. const newAttributes = currentState.newAttributes;
  9189. const enabledAttributes = currentState.enabledAttributes;
  9190. for (let i = 0, il = enabledAttributes.length; i < il; i++) {
  9191. if (enabledAttributes[i] !== newAttributes[i]) {
  9192. gl.disableVertexAttribArray(i);
  9193. enabledAttributes[i] = 0;
  9194. }
  9195. }
  9196. }
  9197. function vertexAttribPointer(index, size, type, normalized, stride, offset) {
  9198. if (capabilities.isWebGL2 === true && (type === gl.INT || type === gl.UNSIGNED_INT)) {
  9199. gl.vertexAttribIPointer(index, size, type, stride, offset);
  9200. } else {
  9201. gl.vertexAttribPointer(index, size, type, normalized, stride, offset);
  9202. }
  9203. }
  9204. function setupVertexAttributes(object, material, program, geometry) {
  9205. if (capabilities.isWebGL2 === false && (object.isInstancedMesh || geometry.isInstancedBufferGeometry)) {
  9206. if (extensions.get('ANGLE_instanced_arrays') === null) return;
  9207. }
  9208. initAttributes();
  9209. const geometryAttributes = geometry.attributes;
  9210. const programAttributes = program.getAttributes();
  9211. const materialDefaultAttributeValues = material.defaultAttributeValues;
  9212. for (const name in programAttributes) {
  9213. const programAttribute = programAttributes[name];
  9214. if (programAttribute.location >= 0) {
  9215. let geometryAttribute = geometryAttributes[name];
  9216. if (geometryAttribute === undefined) {
  9217. if (name === 'instanceMatrix' && object.instanceMatrix) geometryAttribute = object.instanceMatrix;
  9218. if (name === 'instanceColor' && object.instanceColor) geometryAttribute = object.instanceColor;
  9219. }
  9220. if (geometryAttribute !== undefined) {
  9221. const normalized = geometryAttribute.normalized;
  9222. const size = geometryAttribute.itemSize;
  9223. const attribute = attributes.get(geometryAttribute);
  9224. // TODO Attribute may not be available on context restore
  9225. if (attribute === undefined) continue;
  9226. const buffer = attribute.buffer;
  9227. const type = attribute.type;
  9228. const bytesPerElement = attribute.bytesPerElement;
  9229. if (geometryAttribute.isInterleavedBufferAttribute) {
  9230. const data = geometryAttribute.data;
  9231. const stride = data.stride;
  9232. const offset = geometryAttribute.offset;
  9233. if (data.isInstancedInterleavedBuffer) {
  9234. for (let i = 0; i < programAttribute.locationSize; i++) {
  9235. enableAttributeAndDivisor(programAttribute.location + i, data.meshPerAttribute);
  9236. }
  9237. if (object.isInstancedMesh !== true && geometry._maxInstanceCount === undefined) {
  9238. geometry._maxInstanceCount = data.meshPerAttribute * data.count;
  9239. }
  9240. } else {
  9241. for (let i = 0; i < programAttribute.locationSize; i++) {
  9242. enableAttribute(programAttribute.location + i);
  9243. }
  9244. }
  9245. gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
  9246. for (let i = 0; i < programAttribute.locationSize; i++) {
  9247. vertexAttribPointer(programAttribute.location + i, size / programAttribute.locationSize, type, normalized, stride * bytesPerElement, (offset + size / programAttribute.locationSize * i) * bytesPerElement);
  9248. }
  9249. } else {
  9250. if (geometryAttribute.isInstancedBufferAttribute) {
  9251. for (let i = 0; i < programAttribute.locationSize; i++) {
  9252. enableAttributeAndDivisor(programAttribute.location + i, geometryAttribute.meshPerAttribute);
  9253. }
  9254. if (object.isInstancedMesh !== true && geometry._maxInstanceCount === undefined) {
  9255. geometry._maxInstanceCount = geometryAttribute.meshPerAttribute * geometryAttribute.count;
  9256. }
  9257. } else {
  9258. for (let i = 0; i < programAttribute.locationSize; i++) {
  9259. enableAttribute(programAttribute.location + i);
  9260. }
  9261. }
  9262. gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
  9263. for (let i = 0; i < programAttribute.locationSize; i++) {
  9264. vertexAttribPointer(programAttribute.location + i, size / programAttribute.locationSize, type, normalized, size * bytesPerElement, size / programAttribute.locationSize * i * bytesPerElement);
  9265. }
  9266. }
  9267. } else if (materialDefaultAttributeValues !== undefined) {
  9268. const value = materialDefaultAttributeValues[name];
  9269. if (value !== undefined) {
  9270. switch (value.length) {
  9271. case 2:
  9272. gl.vertexAttrib2fv(programAttribute.location, value);
  9273. break;
  9274. case 3:
  9275. gl.vertexAttrib3fv(programAttribute.location, value);
  9276. break;
  9277. case 4:
  9278. gl.vertexAttrib4fv(programAttribute.location, value);
  9279. break;
  9280. default:
  9281. gl.vertexAttrib1fv(programAttribute.location, value);
  9282. }
  9283. }
  9284. }
  9285. }
  9286. }
  9287. disableUnusedAttributes();
  9288. }
  9289. function dispose() {
  9290. reset();
  9291. for (const geometryId in bindingStates) {
  9292. const programMap = bindingStates[geometryId];
  9293. for (const programId in programMap) {
  9294. const stateMap = programMap[programId];
  9295. for (const wireframe in stateMap) {
  9296. deleteVertexArrayObject(stateMap[wireframe].object);
  9297. delete stateMap[wireframe];
  9298. }
  9299. delete programMap[programId];
  9300. }
  9301. delete bindingStates[geometryId];
  9302. }
  9303. }
  9304. function releaseStatesOfGeometry(geometry) {
  9305. if (bindingStates[geometry.id] === undefined) return;
  9306. const programMap = bindingStates[geometry.id];
  9307. for (const programId in programMap) {
  9308. const stateMap = programMap[programId];
  9309. for (const wireframe in stateMap) {
  9310. deleteVertexArrayObject(stateMap[wireframe].object);
  9311. delete stateMap[wireframe];
  9312. }
  9313. delete programMap[programId];
  9314. }
  9315. delete bindingStates[geometry.id];
  9316. }
  9317. function releaseStatesOfProgram(program) {
  9318. for (const geometryId in bindingStates) {
  9319. const programMap = bindingStates[geometryId];
  9320. if (programMap[program.id] === undefined) continue;
  9321. const stateMap = programMap[program.id];
  9322. for (const wireframe in stateMap) {
  9323. deleteVertexArrayObject(stateMap[wireframe].object);
  9324. delete stateMap[wireframe];
  9325. }
  9326. delete programMap[program.id];
  9327. }
  9328. }
  9329. function reset() {
  9330. resetDefaultState();
  9331. forceUpdate = true;
  9332. if (currentState === defaultState) return;
  9333. currentState = defaultState;
  9334. bindVertexArrayObject(currentState.object);
  9335. }
  9336. // for backward-compatibility
  9337. function resetDefaultState() {
  9338. defaultState.geometry = null;
  9339. defaultState.program = null;
  9340. defaultState.wireframe = false;
  9341. }
  9342. return {
  9343. setup: setup,
  9344. reset: reset,
  9345. resetDefaultState: resetDefaultState,
  9346. dispose: dispose,
  9347. releaseStatesOfGeometry: releaseStatesOfGeometry,
  9348. releaseStatesOfProgram: releaseStatesOfProgram,
  9349. initAttributes: initAttributes,
  9350. enableAttribute: enableAttribute,
  9351. disableUnusedAttributes: disableUnusedAttributes
  9352. };
  9353. }
  9354. function WebGLBufferRenderer(gl, extensions, info, capabilities) {
  9355. const isWebGL2 = capabilities.isWebGL2;
  9356. let mode;
  9357. function setMode(value) {
  9358. mode = value;
  9359. }
  9360. function render(start, count) {
  9361. gl.drawArrays(mode, start, count);
  9362. info.update(count, mode, 1);
  9363. }
  9364. function renderInstances(start, count, primcount) {
  9365. if (primcount === 0) return;
  9366. let extension, methodName;
  9367. if (isWebGL2) {
  9368. extension = gl;
  9369. methodName = 'drawArraysInstanced';
  9370. } else {
  9371. extension = extensions.get('ANGLE_instanced_arrays');
  9372. methodName = 'drawArraysInstancedANGLE';
  9373. if (extension === null) {
  9374. console.error('THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.');
  9375. return;
  9376. }
  9377. }
  9378. extension[methodName](mode, start, count, primcount);
  9379. info.update(count, mode, primcount);
  9380. }
  9381. //
  9382. this.setMode = setMode;
  9383. this.render = render;
  9384. this.renderInstances = renderInstances;
  9385. }
  9386. function WebGLCapabilities(gl, extensions, parameters) {
  9387. let maxAnisotropy;
  9388. function getMaxAnisotropy() {
  9389. if (maxAnisotropy !== undefined) return maxAnisotropy;
  9390. if (extensions.has('EXT_texture_filter_anisotropic') === true) {
  9391. const extension = extensions.get('EXT_texture_filter_anisotropic');
  9392. maxAnisotropy = gl.getParameter(extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT);
  9393. } else {
  9394. maxAnisotropy = 0;
  9395. }
  9396. return maxAnisotropy;
  9397. }
  9398. function getMaxPrecision(precision) {
  9399. if (precision === 'highp') {
  9400. if (gl.getShaderPrecisionFormat(gl.VERTEX_SHADER, gl.HIGH_FLOAT).precision > 0 && gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.HIGH_FLOAT).precision > 0) {
  9401. return 'highp';
  9402. }
  9403. precision = 'mediump';
  9404. }
  9405. if (precision === 'mediump') {
  9406. if (gl.getShaderPrecisionFormat(gl.VERTEX_SHADER, gl.MEDIUM_FLOAT).precision > 0 && gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.MEDIUM_FLOAT).precision > 0) {
  9407. return 'mediump';
  9408. }
  9409. }
  9410. return 'lowp';
  9411. }
  9412. const isWebGL2 = typeof WebGL2RenderingContext !== 'undefined' && gl instanceof WebGL2RenderingContext || typeof WebGL2ComputeRenderingContext !== 'undefined' && gl instanceof WebGL2ComputeRenderingContext;
  9413. let precision = parameters.precision !== undefined ? parameters.precision : 'highp';
  9414. const maxPrecision = getMaxPrecision(precision);
  9415. if (maxPrecision !== precision) {
  9416. console.warn('THREE.WebGLRenderer:', precision, 'not supported, using', maxPrecision, 'instead.');
  9417. precision = maxPrecision;
  9418. }
  9419. const drawBuffers = isWebGL2 || extensions.has('WEBGL_draw_buffers');
  9420. const logarithmicDepthBuffer = parameters.logarithmicDepthBuffer === true;
  9421. const maxTextures = gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS);
  9422. const maxVertexTextures = gl.getParameter(gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  9423. const maxTextureSize = gl.getParameter(gl.MAX_TEXTURE_SIZE);
  9424. const maxCubemapSize = gl.getParameter(gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  9425. const maxAttributes = gl.getParameter(gl.MAX_VERTEX_ATTRIBS);
  9426. const maxVertexUniforms = gl.getParameter(gl.MAX_VERTEX_UNIFORM_VECTORS);
  9427. const maxVaryings = gl.getParameter(gl.MAX_VARYING_VECTORS);
  9428. const maxFragmentUniforms = gl.getParameter(gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  9429. const vertexTextures = maxVertexTextures > 0;
  9430. const floatFragmentTextures = isWebGL2 || extensions.has('OES_texture_float');
  9431. const floatVertexTextures = vertexTextures && floatFragmentTextures;
  9432. const maxSamples = isWebGL2 ? gl.getParameter(gl.MAX_SAMPLES) : 0;
  9433. return {
  9434. isWebGL2: isWebGL2,
  9435. drawBuffers: drawBuffers,
  9436. getMaxAnisotropy: getMaxAnisotropy,
  9437. getMaxPrecision: getMaxPrecision,
  9438. precision: precision,
  9439. logarithmicDepthBuffer: logarithmicDepthBuffer,
  9440. maxTextures: maxTextures,
  9441. maxVertexTextures: maxVertexTextures,
  9442. maxTextureSize: maxTextureSize,
  9443. maxCubemapSize: maxCubemapSize,
  9444. maxAttributes: maxAttributes,
  9445. maxVertexUniforms: maxVertexUniforms,
  9446. maxVaryings: maxVaryings,
  9447. maxFragmentUniforms: maxFragmentUniforms,
  9448. vertexTextures: vertexTextures,
  9449. floatFragmentTextures: floatFragmentTextures,
  9450. floatVertexTextures: floatVertexTextures,
  9451. maxSamples: maxSamples
  9452. };
  9453. }
  9454. function WebGLClipping(properties) {
  9455. const scope = this;
  9456. let globalState = null,
  9457. numGlobalPlanes = 0,
  9458. localClippingEnabled = false,
  9459. renderingShadows = false;
  9460. const plane = new Plane(),
  9461. viewNormalMatrix = new Matrix3(),
  9462. uniform = {
  9463. value: null,
  9464. needsUpdate: false
  9465. };
  9466. this.uniform = uniform;
  9467. this.numPlanes = 0;
  9468. this.numIntersection = 0;
  9469. this.init = function (planes, enableLocalClipping, camera) {
  9470. const enabled = planes.length !== 0 || enableLocalClipping ||
  9471. // enable state of previous frame - the clipping code has to
  9472. // run another frame in order to reset the state:
  9473. numGlobalPlanes !== 0 || localClippingEnabled;
  9474. localClippingEnabled = enableLocalClipping;
  9475. globalState = projectPlanes(planes, camera, 0);
  9476. numGlobalPlanes = planes.length;
  9477. return enabled;
  9478. };
  9479. this.beginShadows = function () {
  9480. renderingShadows = true;
  9481. projectPlanes(null);
  9482. };
  9483. this.endShadows = function () {
  9484. renderingShadows = false;
  9485. resetGlobalState();
  9486. };
  9487. this.setState = function (material, camera, useCache) {
  9488. const planes = material.clippingPlanes,
  9489. clipIntersection = material.clipIntersection,
  9490. clipShadows = material.clipShadows;
  9491. const materialProperties = properties.get(material);
  9492. if (!localClippingEnabled || planes === null || planes.length === 0 || renderingShadows && !clipShadows) {
  9493. // there's no local clipping
  9494. if (renderingShadows) {
  9495. // there's no global clipping
  9496. projectPlanes(null);
  9497. } else {
  9498. resetGlobalState();
  9499. }
  9500. } else {
  9501. const nGlobal = renderingShadows ? 0 : numGlobalPlanes,
  9502. lGlobal = nGlobal * 4;
  9503. let dstArray = materialProperties.clippingState || null;
  9504. uniform.value = dstArray; // ensure unique state
  9505. dstArray = projectPlanes(planes, camera, lGlobal, useCache);
  9506. for (let i = 0; i !== lGlobal; ++i) {
  9507. dstArray[i] = globalState[i];
  9508. }
  9509. materialProperties.clippingState = dstArray;
  9510. this.numIntersection = clipIntersection ? this.numPlanes : 0;
  9511. this.numPlanes += nGlobal;
  9512. }
  9513. };
  9514. function resetGlobalState() {
  9515. if (uniform.value !== globalState) {
  9516. uniform.value = globalState;
  9517. uniform.needsUpdate = numGlobalPlanes > 0;
  9518. }
  9519. scope.numPlanes = numGlobalPlanes;
  9520. scope.numIntersection = 0;
  9521. }
  9522. function projectPlanes(planes, camera, dstOffset, skipTransform) {
  9523. const nPlanes = planes !== null ? planes.length : 0;
  9524. let dstArray = null;
  9525. if (nPlanes !== 0) {
  9526. dstArray = uniform.value;
  9527. if (skipTransform !== true || dstArray === null) {
  9528. const flatSize = dstOffset + nPlanes * 4,
  9529. viewMatrix = camera.matrixWorldInverse;
  9530. viewNormalMatrix.getNormalMatrix(viewMatrix);
  9531. if (dstArray === null || dstArray.length < flatSize) {
  9532. dstArray = new Float32Array(flatSize);
  9533. }
  9534. for (let i = 0, i4 = dstOffset; i !== nPlanes; ++i, i4 += 4) {
  9535. plane.copy(planes[i]).applyMatrix4(viewMatrix, viewNormalMatrix);
  9536. plane.normal.toArray(dstArray, i4);
  9537. dstArray[i4 + 3] = plane.constant;
  9538. }
  9539. }
  9540. uniform.value = dstArray;
  9541. uniform.needsUpdate = true;
  9542. }
  9543. scope.numPlanes = nPlanes;
  9544. scope.numIntersection = 0;
  9545. return dstArray;
  9546. }
  9547. }
  9548. function WebGLCubeMaps(renderer) {
  9549. let cubemaps = new WeakMap();
  9550. function mapTextureMapping(texture, mapping) {
  9551. if (mapping === EquirectangularReflectionMapping) {
  9552. texture.mapping = CubeReflectionMapping;
  9553. } else if (mapping === EquirectangularRefractionMapping) {
  9554. texture.mapping = CubeRefractionMapping;
  9555. }
  9556. return texture;
  9557. }
  9558. function get(texture) {
  9559. if (texture && texture.isTexture && texture.isRenderTargetTexture === false) {
  9560. const mapping = texture.mapping;
  9561. if (mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping) {
  9562. if (cubemaps.has(texture)) {
  9563. const cubemap = cubemaps.get(texture).texture;
  9564. return mapTextureMapping(cubemap, texture.mapping);
  9565. } else {
  9566. const image = texture.image;
  9567. if (image && image.height > 0) {
  9568. const renderTarget = new WebGLCubeRenderTarget(image.height / 2);
  9569. renderTarget.fromEquirectangularTexture(renderer, texture);
  9570. cubemaps.set(texture, renderTarget);
  9571. texture.addEventListener('dispose', onTextureDispose);
  9572. return mapTextureMapping(renderTarget.texture, texture.mapping);
  9573. } else {
  9574. // image not yet ready. try the conversion next frame
  9575. return null;
  9576. }
  9577. }
  9578. }
  9579. }
  9580. return texture;
  9581. }
  9582. function onTextureDispose(event) {
  9583. const texture = event.target;
  9584. texture.removeEventListener('dispose', onTextureDispose);
  9585. const cubemap = cubemaps.get(texture);
  9586. if (cubemap !== undefined) {
  9587. cubemaps.delete(texture);
  9588. cubemap.dispose();
  9589. }
  9590. }
  9591. function dispose() {
  9592. cubemaps = new WeakMap();
  9593. }
  9594. return {
  9595. get: get,
  9596. dispose: dispose
  9597. };
  9598. }
  9599. class OrthographicCamera extends Camera {
  9600. constructor(left = -1, right = 1, top = 1, bottom = -1, near = 0.1, far = 2000) {
  9601. super();
  9602. this.isOrthographicCamera = true;
  9603. this.type = 'OrthographicCamera';
  9604. this.zoom = 1;
  9605. this.view = null;
  9606. this.left = left;
  9607. this.right = right;
  9608. this.top = top;
  9609. this.bottom = bottom;
  9610. this.near = near;
  9611. this.far = far;
  9612. this.updateProjectionMatrix();
  9613. }
  9614. copy(source, recursive) {
  9615. super.copy(source, recursive);
  9616. this.left = source.left;
  9617. this.right = source.right;
  9618. this.top = source.top;
  9619. this.bottom = source.bottom;
  9620. this.near = source.near;
  9621. this.far = source.far;
  9622. this.zoom = source.zoom;
  9623. this.view = source.view === null ? null : Object.assign({}, source.view);
  9624. return this;
  9625. }
  9626. setViewOffset(fullWidth, fullHeight, x, y, width, height) {
  9627. if (this.view === null) {
  9628. this.view = {
  9629. enabled: true,
  9630. fullWidth: 1,
  9631. fullHeight: 1,
  9632. offsetX: 0,
  9633. offsetY: 0,
  9634. width: 1,
  9635. height: 1
  9636. };
  9637. }
  9638. this.view.enabled = true;
  9639. this.view.fullWidth = fullWidth;
  9640. this.view.fullHeight = fullHeight;
  9641. this.view.offsetX = x;
  9642. this.view.offsetY = y;
  9643. this.view.width = width;
  9644. this.view.height = height;
  9645. this.updateProjectionMatrix();
  9646. }
  9647. clearViewOffset() {
  9648. if (this.view !== null) {
  9649. this.view.enabled = false;
  9650. }
  9651. this.updateProjectionMatrix();
  9652. }
  9653. updateProjectionMatrix() {
  9654. const dx = (this.right - this.left) / (2 * this.zoom);
  9655. const dy = (this.top - this.bottom) / (2 * this.zoom);
  9656. const cx = (this.right + this.left) / 2;
  9657. const cy = (this.top + this.bottom) / 2;
  9658. let left = cx - dx;
  9659. let right = cx + dx;
  9660. let top = cy + dy;
  9661. let bottom = cy - dy;
  9662. if (this.view !== null && this.view.enabled) {
  9663. const scaleW = (this.right - this.left) / this.view.fullWidth / this.zoom;
  9664. const scaleH = (this.top - this.bottom) / this.view.fullHeight / this.zoom;
  9665. left += scaleW * this.view.offsetX;
  9666. right = left + scaleW * this.view.width;
  9667. top -= scaleH * this.view.offsetY;
  9668. bottom = top - scaleH * this.view.height;
  9669. }
  9670. this.projectionMatrix.makeOrthographic(left, right, top, bottom, this.near, this.far);
  9671. this.projectionMatrixInverse.copy(this.projectionMatrix).invert();
  9672. }
  9673. toJSON(meta) {
  9674. const data = super.toJSON(meta);
  9675. data.object.zoom = this.zoom;
  9676. data.object.left = this.left;
  9677. data.object.right = this.right;
  9678. data.object.top = this.top;
  9679. data.object.bottom = this.bottom;
  9680. data.object.near = this.near;
  9681. data.object.far = this.far;
  9682. if (this.view !== null) data.object.view = Object.assign({}, this.view);
  9683. return data;
  9684. }
  9685. }
  9686. const LOD_MIN = 4;
  9687. // The standard deviations (radians) associated with the extra mips. These are
  9688. // chosen to approximate a Trowbridge-Reitz distribution function times the
  9689. // geometric shadowing function. These sigma values squared must match the
  9690. // variance #defines in cube_uv_reflection_fragment.glsl.js.
  9691. const EXTRA_LOD_SIGMA = [0.125, 0.215, 0.35, 0.446, 0.526, 0.582];
  9692. // The maximum length of the blur for loop. Smaller sigmas will use fewer
  9693. // samples and exit early, but not recompile the shader.
  9694. const MAX_SAMPLES = 20;
  9695. const _flatCamera = /*@__PURE__*/new OrthographicCamera();
  9696. const _clearColor = /*@__PURE__*/new Color();
  9697. let _oldTarget = null;
  9698. // Golden Ratio
  9699. const PHI = (1 + Math.sqrt(5)) / 2;
  9700. const INV_PHI = 1 / PHI;
  9701. // Vertices of a dodecahedron (except the opposites, which represent the
  9702. // same axis), used as axis directions evenly spread on a sphere.
  9703. 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)];
  9704. /**
  9705. * This class generates a Prefiltered, Mipmapped Radiance Environment Map
  9706. * (PMREM) from a cubeMap environment texture. This allows different levels of
  9707. * blur to be quickly accessed based on material roughness. It is packed into a
  9708. * special CubeUV format that allows us to perform custom interpolation so that
  9709. * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap
  9710. * chain, it only goes down to the LOD_MIN level (above), and then creates extra
  9711. * even more filtered 'mips' at the same LOD_MIN resolution, associated with
  9712. * higher roughness levels. In this way we maintain resolution to smoothly
  9713. * interpolate diffuse lighting while limiting sampling computation.
  9714. *
  9715. * Paper: Fast, Accurate Image-Based Lighting
  9716. * https://drive.google.com/file/d/15y8r_UpKlU9SvV4ILb0C3qCPecS8pvLz/view
  9717. */
  9718. class PMREMGenerator {
  9719. constructor(renderer) {
  9720. this._renderer = renderer;
  9721. this._pingPongRenderTarget = null;
  9722. this._lodMax = 0;
  9723. this._cubeSize = 0;
  9724. this._lodPlanes = [];
  9725. this._sizeLods = [];
  9726. this._sigmas = [];
  9727. this._blurMaterial = null;
  9728. this._cubemapMaterial = null;
  9729. this._equirectMaterial = null;
  9730. this._compileMaterial(this._blurMaterial);
  9731. }
  9732. /**
  9733. * Generates a PMREM from a supplied Scene, which can be faster than using an
  9734. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  9735. * in radians to be applied to the scene before PMREM generation. Optional near
  9736. * and far planes ensure the scene is rendered in its entirety (the cubeCamera
  9737. * is placed at the origin).
  9738. */
  9739. fromScene(scene, sigma = 0, near = 0.1, far = 100) {
  9740. _oldTarget = this._renderer.getRenderTarget();
  9741. this._setSize(256);
  9742. const cubeUVRenderTarget = this._allocateTargets();
  9743. cubeUVRenderTarget.depthBuffer = true;
  9744. this._sceneToCubeUV(scene, near, far, cubeUVRenderTarget);
  9745. if (sigma > 0) {
  9746. this._blur(cubeUVRenderTarget, 0, 0, sigma);
  9747. }
  9748. this._applyPMREM(cubeUVRenderTarget);
  9749. this._cleanup(cubeUVRenderTarget);
  9750. return cubeUVRenderTarget;
  9751. }
  9752. /**
  9753. * Generates a PMREM from an equirectangular texture, which can be either LDR
  9754. * or HDR. The ideal input image size is 1k (1024 x 512),
  9755. * as this matches best with the 256 x 256 cubemap output.
  9756. */
  9757. fromEquirectangular(equirectangular, renderTarget = null) {
  9758. return this._fromTexture(equirectangular, renderTarget);
  9759. }
  9760. /**
  9761. * Generates a PMREM from an cubemap texture, which can be either LDR
  9762. * or HDR. The ideal input cube size is 256 x 256,
  9763. * as this matches best with the 256 x 256 cubemap output.
  9764. */
  9765. fromCubemap(cubemap, renderTarget = null) {
  9766. return this._fromTexture(cubemap, renderTarget);
  9767. }
  9768. /**
  9769. * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during
  9770. * your texture's network fetch for increased concurrency.
  9771. */
  9772. compileCubemapShader() {
  9773. if (this._cubemapMaterial === null) {
  9774. this._cubemapMaterial = _getCubemapMaterial();
  9775. this._compileMaterial(this._cubemapMaterial);
  9776. }
  9777. }
  9778. /**
  9779. * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during
  9780. * your texture's network fetch for increased concurrency.
  9781. */
  9782. compileEquirectangularShader() {
  9783. if (this._equirectMaterial === null) {
  9784. this._equirectMaterial = _getEquirectMaterial();
  9785. this._compileMaterial(this._equirectMaterial);
  9786. }
  9787. }
  9788. /**
  9789. * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class,
  9790. * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on
  9791. * one of them will cause any others to also become unusable.
  9792. */
  9793. dispose() {
  9794. this._dispose();
  9795. if (this._cubemapMaterial !== null) this._cubemapMaterial.dispose();
  9796. if (this._equirectMaterial !== null) this._equirectMaterial.dispose();
  9797. }
  9798. // private interface
  9799. _setSize(cubeSize) {
  9800. this._lodMax = Math.floor(Math.log2(cubeSize));
  9801. this._cubeSize = Math.pow(2, this._lodMax);
  9802. }
  9803. _dispose() {
  9804. if (this._blurMaterial !== null) this._blurMaterial.dispose();
  9805. if (this._pingPongRenderTarget !== null) this._pingPongRenderTarget.dispose();
  9806. for (let i = 0; i < this._lodPlanes.length; i++) {
  9807. this._lodPlanes[i].dispose();
  9808. }
  9809. }
  9810. _cleanup(outputTarget) {
  9811. this._renderer.setRenderTarget(_oldTarget);
  9812. outputTarget.scissorTest = false;
  9813. _setViewport(outputTarget, 0, 0, outputTarget.width, outputTarget.height);
  9814. }
  9815. _fromTexture(texture, renderTarget) {
  9816. if (texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping) {
  9817. this._setSize(texture.image.length === 0 ? 16 : texture.image[0].width || texture.image[0].image.width);
  9818. } else {
  9819. // Equirectangular
  9820. this._setSize(texture.image.width / 4);
  9821. }
  9822. _oldTarget = this._renderer.getRenderTarget();
  9823. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  9824. this._textureToCubeUV(texture, cubeUVRenderTarget);
  9825. this._applyPMREM(cubeUVRenderTarget);
  9826. this._cleanup(cubeUVRenderTarget);
  9827. return cubeUVRenderTarget;
  9828. }
  9829. _allocateTargets() {
  9830. const width = 3 * Math.max(this._cubeSize, 16 * 7);
  9831. const height = 4 * this._cubeSize;
  9832. const params = {
  9833. magFilter: LinearFilter,
  9834. minFilter: LinearFilter,
  9835. generateMipmaps: false,
  9836. type: HalfFloatType,
  9837. format: RGBAFormat,
  9838. encoding: LinearEncoding,
  9839. depthBuffer: false
  9840. };
  9841. const cubeUVRenderTarget = _createRenderTarget(width, height, params);
  9842. if (this._pingPongRenderTarget === null || this._pingPongRenderTarget.width !== width) {
  9843. if (this._pingPongRenderTarget !== null) {
  9844. this._dispose();
  9845. }
  9846. this._pingPongRenderTarget = _createRenderTarget(width, height, params);
  9847. const {
  9848. _lodMax
  9849. } = this;
  9850. ({
  9851. sizeLods: this._sizeLods,
  9852. lodPlanes: this._lodPlanes,
  9853. sigmas: this._sigmas
  9854. } = _createPlanes(_lodMax));
  9855. this._blurMaterial = _getBlurShader(_lodMax, width, height);
  9856. }
  9857. return cubeUVRenderTarget;
  9858. }
  9859. _compileMaterial(material) {
  9860. const tmpMesh = new Mesh(this._lodPlanes[0], material);
  9861. this._renderer.compile(tmpMesh, _flatCamera);
  9862. }
  9863. _sceneToCubeUV(scene, near, far, cubeUVRenderTarget) {
  9864. const fov = 90;
  9865. const aspect = 1;
  9866. const cubeCamera = new PerspectiveCamera(fov, aspect, near, far);
  9867. const upSign = [1, -1, 1, 1, 1, 1];
  9868. const forwardSign = [1, 1, 1, -1, -1, -1];
  9869. const renderer = this._renderer;
  9870. const originalAutoClear = renderer.autoClear;
  9871. const toneMapping = renderer.toneMapping;
  9872. renderer.getClearColor(_clearColor);
  9873. renderer.toneMapping = NoToneMapping;
  9874. renderer.autoClear = false;
  9875. const backgroundMaterial = new MeshBasicMaterial({
  9876. name: 'PMREM.Background',
  9877. side: BackSide,
  9878. depthWrite: false,
  9879. depthTest: false
  9880. });
  9881. const backgroundBox = new Mesh(new BoxGeometry(), backgroundMaterial);
  9882. let useSolidColor = false;
  9883. const background = scene.background;
  9884. if (background) {
  9885. if (background.isColor) {
  9886. backgroundMaterial.color.copy(background);
  9887. scene.background = null;
  9888. useSolidColor = true;
  9889. }
  9890. } else {
  9891. backgroundMaterial.color.copy(_clearColor);
  9892. useSolidColor = true;
  9893. }
  9894. for (let i = 0; i < 6; i++) {
  9895. const col = i % 3;
  9896. if (col === 0) {
  9897. cubeCamera.up.set(0, upSign[i], 0);
  9898. cubeCamera.lookAt(forwardSign[i], 0, 0);
  9899. } else if (col === 1) {
  9900. cubeCamera.up.set(0, 0, upSign[i]);
  9901. cubeCamera.lookAt(0, forwardSign[i], 0);
  9902. } else {
  9903. cubeCamera.up.set(0, upSign[i], 0);
  9904. cubeCamera.lookAt(0, 0, forwardSign[i]);
  9905. }
  9906. const size = this._cubeSize;
  9907. _setViewport(cubeUVRenderTarget, col * size, i > 2 ? size : 0, size, size);
  9908. renderer.setRenderTarget(cubeUVRenderTarget);
  9909. if (useSolidColor) {
  9910. renderer.render(backgroundBox, cubeCamera);
  9911. }
  9912. renderer.render(scene, cubeCamera);
  9913. }
  9914. backgroundBox.geometry.dispose();
  9915. backgroundBox.material.dispose();
  9916. renderer.toneMapping = toneMapping;
  9917. renderer.autoClear = originalAutoClear;
  9918. scene.background = background;
  9919. }
  9920. _textureToCubeUV(texture, cubeUVRenderTarget) {
  9921. const renderer = this._renderer;
  9922. const isCubeTexture = texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping;
  9923. if (isCubeTexture) {
  9924. if (this._cubemapMaterial === null) {
  9925. this._cubemapMaterial = _getCubemapMaterial();
  9926. }
  9927. this._cubemapMaterial.uniforms.flipEnvMap.value = texture.isRenderTargetTexture === false ? -1 : 1;
  9928. } else {
  9929. if (this._equirectMaterial === null) {
  9930. this._equirectMaterial = _getEquirectMaterial();
  9931. }
  9932. }
  9933. const material = isCubeTexture ? this._cubemapMaterial : this._equirectMaterial;
  9934. const mesh = new Mesh(this._lodPlanes[0], material);
  9935. const uniforms = material.uniforms;
  9936. uniforms['envMap'].value = texture;
  9937. const size = this._cubeSize;
  9938. _setViewport(cubeUVRenderTarget, 0, 0, 3 * size, 2 * size);
  9939. renderer.setRenderTarget(cubeUVRenderTarget);
  9940. renderer.render(mesh, _flatCamera);
  9941. }
  9942. _applyPMREM(cubeUVRenderTarget) {
  9943. const renderer = this._renderer;
  9944. const autoClear = renderer.autoClear;
  9945. renderer.autoClear = false;
  9946. for (let i = 1; i < this._lodPlanes.length; i++) {
  9947. const sigma = Math.sqrt(this._sigmas[i] * this._sigmas[i] - this._sigmas[i - 1] * this._sigmas[i - 1]);
  9948. const poleAxis = _axisDirections[(i - 1) % _axisDirections.length];
  9949. this._blur(cubeUVRenderTarget, i - 1, i, sigma, poleAxis);
  9950. }
  9951. renderer.autoClear = autoClear;
  9952. }
  9953. /**
  9954. * This is a two-pass Gaussian blur for a cubemap. Normally this is done
  9955. * vertically and horizontally, but this breaks down on a cube. Here we apply
  9956. * the blur latitudinally (around the poles), and then longitudinally (towards
  9957. * the poles) to approximate the orthogonally-separable blur. It is least
  9958. * accurate at the poles, but still does a decent job.
  9959. */
  9960. _blur(cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis) {
  9961. const pingPongRenderTarget = this._pingPongRenderTarget;
  9962. this._halfBlur(cubeUVRenderTarget, pingPongRenderTarget, lodIn, lodOut, sigma, 'latitudinal', poleAxis);
  9963. this._halfBlur(pingPongRenderTarget, cubeUVRenderTarget, lodOut, lodOut, sigma, 'longitudinal', poleAxis);
  9964. }
  9965. _halfBlur(targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis) {
  9966. const renderer = this._renderer;
  9967. const blurMaterial = this._blurMaterial;
  9968. if (direction !== 'latitudinal' && direction !== 'longitudinal') {
  9969. console.error('blur direction must be either latitudinal or longitudinal!');
  9970. }
  9971. // Number of standard deviations at which to cut off the discrete approximation.
  9972. const STANDARD_DEVIATIONS = 3;
  9973. const blurMesh = new Mesh(this._lodPlanes[lodOut], blurMaterial);
  9974. const blurUniforms = blurMaterial.uniforms;
  9975. const pixels = this._sizeLods[lodIn] - 1;
  9976. const radiansPerPixel = isFinite(sigmaRadians) ? Math.PI / (2 * pixels) : 2 * Math.PI / (2 * MAX_SAMPLES - 1);
  9977. const sigmaPixels = sigmaRadians / radiansPerPixel;
  9978. const samples = isFinite(sigmaRadians) ? 1 + Math.floor(STANDARD_DEVIATIONS * sigmaPixels) : MAX_SAMPLES;
  9979. if (samples > MAX_SAMPLES) {
  9980. console.warn(`sigmaRadians, ${sigmaRadians}, is too large and will clip, as it requested ${samples} samples when the maximum is set to ${MAX_SAMPLES}`);
  9981. }
  9982. const weights = [];
  9983. let sum = 0;
  9984. for (let i = 0; i < MAX_SAMPLES; ++i) {
  9985. const x = i / sigmaPixels;
  9986. const weight = Math.exp(-x * x / 2);
  9987. weights.push(weight);
  9988. if (i === 0) {
  9989. sum += weight;
  9990. } else if (i < samples) {
  9991. sum += 2 * weight;
  9992. }
  9993. }
  9994. for (let i = 0; i < weights.length; i++) {
  9995. weights[i] = weights[i] / sum;
  9996. }
  9997. blurUniforms['envMap'].value = targetIn.texture;
  9998. blurUniforms['samples'].value = samples;
  9999. blurUniforms['weights'].value = weights;
  10000. blurUniforms['latitudinal'].value = direction === 'latitudinal';
  10001. if (poleAxis) {
  10002. blurUniforms['poleAxis'].value = poleAxis;
  10003. }
  10004. const {
  10005. _lodMax
  10006. } = this;
  10007. blurUniforms['dTheta'].value = radiansPerPixel;
  10008. blurUniforms['mipInt'].value = _lodMax - lodIn;
  10009. const outputSize = this._sizeLods[lodOut];
  10010. const x = 3 * outputSize * (lodOut > _lodMax - LOD_MIN ? lodOut - _lodMax + LOD_MIN : 0);
  10011. const y = 4 * (this._cubeSize - outputSize);
  10012. _setViewport(targetOut, x, y, 3 * outputSize, 2 * outputSize);
  10013. renderer.setRenderTarget(targetOut);
  10014. renderer.render(blurMesh, _flatCamera);
  10015. }
  10016. }
  10017. function _createPlanes(lodMax) {
  10018. const lodPlanes = [];
  10019. const sizeLods = [];
  10020. const sigmas = [];
  10021. let lod = lodMax;
  10022. const totalLods = lodMax - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length;
  10023. for (let i = 0; i < totalLods; i++) {
  10024. const sizeLod = Math.pow(2, lod);
  10025. sizeLods.push(sizeLod);
  10026. let sigma = 1.0 / sizeLod;
  10027. if (i > lodMax - LOD_MIN) {
  10028. sigma = EXTRA_LOD_SIGMA[i - lodMax + LOD_MIN - 1];
  10029. } else if (i === 0) {
  10030. sigma = 0;
  10031. }
  10032. sigmas.push(sigma);
  10033. const texelSize = 1.0 / (sizeLod - 2);
  10034. const min = -texelSize;
  10035. const max = 1 + texelSize;
  10036. const uv1 = [min, min, max, min, max, max, min, min, max, max, min, max];
  10037. const cubeFaces = 6;
  10038. const vertices = 6;
  10039. const positionSize = 3;
  10040. const uvSize = 2;
  10041. const faceIndexSize = 1;
  10042. const position = new Float32Array(positionSize * vertices * cubeFaces);
  10043. const uv = new Float32Array(uvSize * vertices * cubeFaces);
  10044. const faceIndex = new Float32Array(faceIndexSize * vertices * cubeFaces);
  10045. for (let face = 0; face < cubeFaces; face++) {
  10046. const x = face % 3 * 2 / 3 - 1;
  10047. const y = face > 2 ? 0 : -1;
  10048. 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];
  10049. position.set(coordinates, positionSize * vertices * face);
  10050. uv.set(uv1, uvSize * vertices * face);
  10051. const fill = [face, face, face, face, face, face];
  10052. faceIndex.set(fill, faceIndexSize * vertices * face);
  10053. }
  10054. const planes = new BufferGeometry();
  10055. planes.setAttribute('position', new BufferAttribute(position, positionSize));
  10056. planes.setAttribute('uv', new BufferAttribute(uv, uvSize));
  10057. planes.setAttribute('faceIndex', new BufferAttribute(faceIndex, faceIndexSize));
  10058. lodPlanes.push(planes);
  10059. if (lod > LOD_MIN) {
  10060. lod--;
  10061. }
  10062. }
  10063. return {
  10064. lodPlanes,
  10065. sizeLods,
  10066. sigmas
  10067. };
  10068. }
  10069. function _createRenderTarget(width, height, params) {
  10070. const cubeUVRenderTarget = new WebGLRenderTarget(width, height, params);
  10071. cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping;
  10072. cubeUVRenderTarget.texture.name = 'PMREM.cubeUv';
  10073. cubeUVRenderTarget.scissorTest = true;
  10074. return cubeUVRenderTarget;
  10075. }
  10076. function _setViewport(target, x, y, width, height) {
  10077. target.viewport.set(x, y, width, height);
  10078. target.scissor.set(x, y, width, height);
  10079. }
  10080. function _getBlurShader(lodMax, width, height) {
  10081. const weights = new Float32Array(MAX_SAMPLES);
  10082. const poleAxis = new Vector3(0, 1, 0);
  10083. const shaderMaterial = new ShaderMaterial({
  10084. name: 'SphericalGaussianBlur',
  10085. defines: {
  10086. 'n': MAX_SAMPLES,
  10087. 'CUBEUV_TEXEL_WIDTH': 1.0 / width,
  10088. 'CUBEUV_TEXEL_HEIGHT': 1.0 / height,
  10089. 'CUBEUV_MAX_MIP': `${lodMax}.0`
  10090. },
  10091. uniforms: {
  10092. 'envMap': {
  10093. value: null
  10094. },
  10095. 'samples': {
  10096. value: 1
  10097. },
  10098. 'weights': {
  10099. value: weights
  10100. },
  10101. 'latitudinal': {
  10102. value: false
  10103. },
  10104. 'dTheta': {
  10105. value: 0
  10106. },
  10107. 'mipInt': {
  10108. value: 0
  10109. },
  10110. 'poleAxis': {
  10111. value: poleAxis
  10112. }
  10113. },
  10114. vertexShader: _getCommonVertexShader(),
  10115. fragmentShader: /* glsl */`
  10116. precision mediump float;
  10117. precision mediump int;
  10118. varying vec3 vOutputDirection;
  10119. uniform sampler2D envMap;
  10120. uniform int samples;
  10121. uniform float weights[ n ];
  10122. uniform bool latitudinal;
  10123. uniform float dTheta;
  10124. uniform float mipInt;
  10125. uniform vec3 poleAxis;
  10126. #define ENVMAP_TYPE_CUBE_UV
  10127. #include <cube_uv_reflection_fragment>
  10128. vec3 getSample( float theta, vec3 axis ) {
  10129. float cosTheta = cos( theta );
  10130. // Rodrigues' axis-angle rotation
  10131. vec3 sampleDirection = vOutputDirection * cosTheta
  10132. + cross( axis, vOutputDirection ) * sin( theta )
  10133. + axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta );
  10134. return bilinearCubeUV( envMap, sampleDirection, mipInt );
  10135. }
  10136. void main() {
  10137. vec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection );
  10138. if ( all( equal( axis, vec3( 0.0 ) ) ) ) {
  10139. axis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x );
  10140. }
  10141. axis = normalize( axis );
  10142. gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );
  10143. gl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis );
  10144. for ( int i = 1; i < n; i++ ) {
  10145. if ( i >= samples ) {
  10146. break;
  10147. }
  10148. float theta = dTheta * float( i );
  10149. gl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis );
  10150. gl_FragColor.rgb += weights[ i ] * getSample( theta, axis );
  10151. }
  10152. }
  10153. `,
  10154. blending: NoBlending,
  10155. depthTest: false,
  10156. depthWrite: false
  10157. });
  10158. return shaderMaterial;
  10159. }
  10160. function _getEquirectMaterial() {
  10161. return new ShaderMaterial({
  10162. name: 'EquirectangularToCubeUV',
  10163. uniforms: {
  10164. 'envMap': {
  10165. value: null
  10166. }
  10167. },
  10168. vertexShader: _getCommonVertexShader(),
  10169. fragmentShader: /* glsl */`
  10170. precision mediump float;
  10171. precision mediump int;
  10172. varying vec3 vOutputDirection;
  10173. uniform sampler2D envMap;
  10174. #include <common>
  10175. void main() {
  10176. vec3 outputDirection = normalize( vOutputDirection );
  10177. vec2 uv = equirectUv( outputDirection );
  10178. gl_FragColor = vec4( texture2D ( envMap, uv ).rgb, 1.0 );
  10179. }
  10180. `,
  10181. blending: NoBlending,
  10182. depthTest: false,
  10183. depthWrite: false
  10184. });
  10185. }
  10186. function _getCubemapMaterial() {
  10187. return new ShaderMaterial({
  10188. name: 'CubemapToCubeUV',
  10189. uniforms: {
  10190. 'envMap': {
  10191. value: null
  10192. },
  10193. 'flipEnvMap': {
  10194. value: -1
  10195. }
  10196. },
  10197. vertexShader: _getCommonVertexShader(),
  10198. fragmentShader: /* glsl */`
  10199. precision mediump float;
  10200. precision mediump int;
  10201. uniform float flipEnvMap;
  10202. varying vec3 vOutputDirection;
  10203. uniform samplerCube envMap;
  10204. void main() {
  10205. gl_FragColor = textureCube( envMap, vec3( flipEnvMap * vOutputDirection.x, vOutputDirection.yz ) );
  10206. }
  10207. `,
  10208. blending: NoBlending,
  10209. depthTest: false,
  10210. depthWrite: false
  10211. });
  10212. }
  10213. function _getCommonVertexShader() {
  10214. return (/* glsl */`
  10215. precision mediump float;
  10216. precision mediump int;
  10217. attribute float faceIndex;
  10218. varying vec3 vOutputDirection;
  10219. // RH coordinate system; PMREM face-indexing convention
  10220. vec3 getDirection( vec2 uv, float face ) {
  10221. uv = 2.0 * uv - 1.0;
  10222. vec3 direction = vec3( uv, 1.0 );
  10223. if ( face == 0.0 ) {
  10224. direction = direction.zyx; // ( 1, v, u ) pos x
  10225. } else if ( face == 1.0 ) {
  10226. direction = direction.xzy;
  10227. direction.xz *= -1.0; // ( -u, 1, -v ) pos y
  10228. } else if ( face == 2.0 ) {
  10229. direction.x *= -1.0; // ( -u, v, 1 ) pos z
  10230. } else if ( face == 3.0 ) {
  10231. direction = direction.zyx;
  10232. direction.xz *= -1.0; // ( -1, v, -u ) neg x
  10233. } else if ( face == 4.0 ) {
  10234. direction = direction.xzy;
  10235. direction.xy *= -1.0; // ( -u, -1, v ) neg y
  10236. } else if ( face == 5.0 ) {
  10237. direction.z *= -1.0; // ( u, v, -1 ) neg z
  10238. }
  10239. return direction;
  10240. }
  10241. void main() {
  10242. vOutputDirection = getDirection( uv, faceIndex );
  10243. gl_Position = vec4( position, 1.0 );
  10244. }
  10245. `
  10246. );
  10247. }
  10248. function WebGLCubeUVMaps(renderer) {
  10249. let cubeUVmaps = new WeakMap();
  10250. let pmremGenerator = null;
  10251. function get(texture) {
  10252. if (texture && texture.isTexture) {
  10253. const mapping = texture.mapping;
  10254. const isEquirectMap = mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping;
  10255. const isCubeMap = mapping === CubeReflectionMapping || mapping === CubeRefractionMapping;
  10256. // equirect/cube map to cubeUV conversion
  10257. if (isEquirectMap || isCubeMap) {
  10258. if (texture.isRenderTargetTexture && texture.needsPMREMUpdate === true) {
  10259. texture.needsPMREMUpdate = false;
  10260. let renderTarget = cubeUVmaps.get(texture);
  10261. if (pmremGenerator === null) pmremGenerator = new PMREMGenerator(renderer);
  10262. renderTarget = isEquirectMap ? pmremGenerator.fromEquirectangular(texture, renderTarget) : pmremGenerator.fromCubemap(texture, renderTarget);
  10263. cubeUVmaps.set(texture, renderTarget);
  10264. return renderTarget.texture;
  10265. } else {
  10266. if (cubeUVmaps.has(texture)) {
  10267. return cubeUVmaps.get(texture).texture;
  10268. } else {
  10269. const image = texture.image;
  10270. if (isEquirectMap && image && image.height > 0 || isCubeMap && image && isCubeTextureComplete(image)) {
  10271. if (pmremGenerator === null) pmremGenerator = new PMREMGenerator(renderer);
  10272. const renderTarget = isEquirectMap ? pmremGenerator.fromEquirectangular(texture) : pmremGenerator.fromCubemap(texture);
  10273. cubeUVmaps.set(texture, renderTarget);
  10274. texture.addEventListener('dispose', onTextureDispose);
  10275. return renderTarget.texture;
  10276. } else {
  10277. // image not yet ready. try the conversion next frame
  10278. return null;
  10279. }
  10280. }
  10281. }
  10282. }
  10283. }
  10284. return texture;
  10285. }
  10286. function isCubeTextureComplete(image) {
  10287. let count = 0;
  10288. const length = 6;
  10289. for (let i = 0; i < length; i++) {
  10290. if (image[i] !== undefined) count++;
  10291. }
  10292. return count === length;
  10293. }
  10294. function onTextureDispose(event) {
  10295. const texture = event.target;
  10296. texture.removeEventListener('dispose', onTextureDispose);
  10297. const cubemapUV = cubeUVmaps.get(texture);
  10298. if (cubemapUV !== undefined) {
  10299. cubeUVmaps.delete(texture);
  10300. cubemapUV.dispose();
  10301. }
  10302. }
  10303. function dispose() {
  10304. cubeUVmaps = new WeakMap();
  10305. if (pmremGenerator !== null) {
  10306. pmremGenerator.dispose();
  10307. pmremGenerator = null;
  10308. }
  10309. }
  10310. return {
  10311. get: get,
  10312. dispose: dispose
  10313. };
  10314. }
  10315. function WebGLExtensions(gl) {
  10316. const extensions = {};
  10317. function getExtension(name) {
  10318. if (extensions[name] !== undefined) {
  10319. return extensions[name];
  10320. }
  10321. let extension;
  10322. switch (name) {
  10323. case 'WEBGL_depth_texture':
  10324. extension = gl.getExtension('WEBGL_depth_texture') || gl.getExtension('MOZ_WEBGL_depth_texture') || gl.getExtension('WEBKIT_WEBGL_depth_texture');
  10325. break;
  10326. case 'EXT_texture_filter_anisotropic':
  10327. extension = gl.getExtension('EXT_texture_filter_anisotropic') || gl.getExtension('MOZ_EXT_texture_filter_anisotropic') || gl.getExtension('WEBKIT_EXT_texture_filter_anisotropic');
  10328. break;
  10329. case 'WEBGL_compressed_texture_s3tc':
  10330. extension = gl.getExtension('WEBGL_compressed_texture_s3tc') || gl.getExtension('MOZ_WEBGL_compressed_texture_s3tc') || gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  10331. break;
  10332. case 'WEBGL_compressed_texture_pvrtc':
  10333. extension = gl.getExtension('WEBGL_compressed_texture_pvrtc') || gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  10334. break;
  10335. default:
  10336. extension = gl.getExtension(name);
  10337. }
  10338. extensions[name] = extension;
  10339. return extension;
  10340. }
  10341. return {
  10342. has: function (name) {
  10343. return getExtension(name) !== null;
  10344. },
  10345. init: function (capabilities) {
  10346. if (capabilities.isWebGL2) {
  10347. getExtension('EXT_color_buffer_float');
  10348. } else {
  10349. getExtension('WEBGL_depth_texture');
  10350. getExtension('OES_texture_float');
  10351. getExtension('OES_texture_half_float');
  10352. getExtension('OES_texture_half_float_linear');
  10353. getExtension('OES_standard_derivatives');
  10354. getExtension('OES_element_index_uint');
  10355. getExtension('OES_vertex_array_object');
  10356. getExtension('ANGLE_instanced_arrays');
  10357. }
  10358. getExtension('OES_texture_float_linear');
  10359. getExtension('EXT_color_buffer_half_float');
  10360. getExtension('WEBGL_multisampled_render_to_texture');
  10361. },
  10362. get: function (name) {
  10363. const extension = getExtension(name);
  10364. if (extension === null) {
  10365. console.warn('THREE.WebGLRenderer: ' + name + ' extension not supported.');
  10366. }
  10367. return extension;
  10368. }
  10369. };
  10370. }
  10371. function WebGLGeometries(gl, attributes, info, bindingStates) {
  10372. const geometries = {};
  10373. const wireframeAttributes = new WeakMap();
  10374. function onGeometryDispose(event) {
  10375. const geometry = event.target;
  10376. if (geometry.index !== null) {
  10377. attributes.remove(geometry.index);
  10378. }
  10379. for (const name in geometry.attributes) {
  10380. attributes.remove(geometry.attributes[name]);
  10381. }
  10382. geometry.removeEventListener('dispose', onGeometryDispose);
  10383. delete geometries[geometry.id];
  10384. const attribute = wireframeAttributes.get(geometry);
  10385. if (attribute) {
  10386. attributes.remove(attribute);
  10387. wireframeAttributes.delete(geometry);
  10388. }
  10389. bindingStates.releaseStatesOfGeometry(geometry);
  10390. if (geometry.isInstancedBufferGeometry === true) {
  10391. delete geometry._maxInstanceCount;
  10392. }
  10393. //
  10394. info.memory.geometries--;
  10395. }
  10396. function get(object, geometry) {
  10397. if (geometries[geometry.id] === true) return geometry;
  10398. geometry.addEventListener('dispose', onGeometryDispose);
  10399. geometries[geometry.id] = true;
  10400. info.memory.geometries++;
  10401. return geometry;
  10402. }
  10403. function update(geometry) {
  10404. const geometryAttributes = geometry.attributes;
  10405. // Updating index buffer in VAO now. See WebGLBindingStates.
  10406. for (const name in geometryAttributes) {
  10407. attributes.update(geometryAttributes[name], gl.ARRAY_BUFFER);
  10408. }
  10409. // morph targets
  10410. const morphAttributes = geometry.morphAttributes;
  10411. for (const name in morphAttributes) {
  10412. const array = morphAttributes[name];
  10413. for (let i = 0, l = array.length; i < l; i++) {
  10414. attributes.update(array[i], gl.ARRAY_BUFFER);
  10415. }
  10416. }
  10417. }
  10418. function updateWireframeAttribute(geometry) {
  10419. const indices = [];
  10420. const geometryIndex = geometry.index;
  10421. const geometryPosition = geometry.attributes.position;
  10422. let version = 0;
  10423. if (geometryIndex !== null) {
  10424. const array = geometryIndex.array;
  10425. version = geometryIndex.version;
  10426. for (let i = 0, l = array.length; i < l; i += 3) {
  10427. const a = array[i + 0];
  10428. const b = array[i + 1];
  10429. const c = array[i + 2];
  10430. indices.push(a, b, b, c, c, a);
  10431. }
  10432. } else {
  10433. const array = geometryPosition.array;
  10434. version = geometryPosition.version;
  10435. for (let i = 0, l = array.length / 3 - 1; i < l; i += 3) {
  10436. const a = i + 0;
  10437. const b = i + 1;
  10438. const c = i + 2;
  10439. indices.push(a, b, b, c, c, a);
  10440. }
  10441. }
  10442. const attribute = new (arrayNeedsUint32(indices) ? Uint32BufferAttribute : Uint16BufferAttribute)(indices, 1);
  10443. attribute.version = version;
  10444. // Updating index buffer in VAO now. See WebGLBindingStates
  10445. //
  10446. const previousAttribute = wireframeAttributes.get(geometry);
  10447. if (previousAttribute) attributes.remove(previousAttribute);
  10448. //
  10449. wireframeAttributes.set(geometry, attribute);
  10450. }
  10451. function getWireframeAttribute(geometry) {
  10452. const currentAttribute = wireframeAttributes.get(geometry);
  10453. if (currentAttribute) {
  10454. const geometryIndex = geometry.index;
  10455. if (geometryIndex !== null) {
  10456. // if the attribute is obsolete, create a new one
  10457. if (currentAttribute.version < geometryIndex.version) {
  10458. updateWireframeAttribute(geometry);
  10459. }
  10460. }
  10461. } else {
  10462. updateWireframeAttribute(geometry);
  10463. }
  10464. return wireframeAttributes.get(geometry);
  10465. }
  10466. return {
  10467. get: get,
  10468. update: update,
  10469. getWireframeAttribute: getWireframeAttribute
  10470. };
  10471. }
  10472. function WebGLIndexedBufferRenderer(gl, extensions, info, capabilities) {
  10473. const isWebGL2 = capabilities.isWebGL2;
  10474. let mode;
  10475. function setMode(value) {
  10476. mode = value;
  10477. }
  10478. let type, bytesPerElement;
  10479. function setIndex(value) {
  10480. type = value.type;
  10481. bytesPerElement = value.bytesPerElement;
  10482. }
  10483. function render(start, count) {
  10484. gl.drawElements(mode, count, type, start * bytesPerElement);
  10485. info.update(count, mode, 1);
  10486. }
  10487. function renderInstances(start, count, primcount) {
  10488. if (primcount === 0) return;
  10489. let extension, methodName;
  10490. if (isWebGL2) {
  10491. extension = gl;
  10492. methodName = 'drawElementsInstanced';
  10493. } else {
  10494. extension = extensions.get('ANGLE_instanced_arrays');
  10495. methodName = 'drawElementsInstancedANGLE';
  10496. if (extension === null) {
  10497. console.error('THREE.WebGLIndexedBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.');
  10498. return;
  10499. }
  10500. }
  10501. extension[methodName](mode, count, type, start * bytesPerElement, primcount);
  10502. info.update(count, mode, primcount);
  10503. }
  10504. //
  10505. this.setMode = setMode;
  10506. this.setIndex = setIndex;
  10507. this.render = render;
  10508. this.renderInstances = renderInstances;
  10509. }
  10510. function WebGLInfo(gl) {
  10511. const memory = {
  10512. geometries: 0,
  10513. textures: 0
  10514. };
  10515. const render = {
  10516. frame: 0,
  10517. calls: 0,
  10518. triangles: 0,
  10519. points: 0,
  10520. lines: 0
  10521. };
  10522. function update(count, mode, instanceCount) {
  10523. render.calls++;
  10524. switch (mode) {
  10525. case gl.TRIANGLES:
  10526. render.triangles += instanceCount * (count / 3);
  10527. break;
  10528. case gl.LINES:
  10529. render.lines += instanceCount * (count / 2);
  10530. break;
  10531. case gl.LINE_STRIP:
  10532. render.lines += instanceCount * (count - 1);
  10533. break;
  10534. case gl.LINE_LOOP:
  10535. render.lines += instanceCount * count;
  10536. break;
  10537. case gl.POINTS:
  10538. render.points += instanceCount * count;
  10539. break;
  10540. default:
  10541. console.error('THREE.WebGLInfo: Unknown draw mode:', mode);
  10542. break;
  10543. }
  10544. }
  10545. function reset() {
  10546. render.frame++;
  10547. render.calls = 0;
  10548. render.triangles = 0;
  10549. render.points = 0;
  10550. render.lines = 0;
  10551. }
  10552. return {
  10553. memory: memory,
  10554. render: render,
  10555. programs: null,
  10556. autoReset: true,
  10557. reset: reset,
  10558. update: update
  10559. };
  10560. }
  10561. function numericalSort(a, b) {
  10562. return a[0] - b[0];
  10563. }
  10564. function absNumericalSort(a, b) {
  10565. return Math.abs(b[1]) - Math.abs(a[1]);
  10566. }
  10567. function WebGLMorphtargets(gl, capabilities, textures) {
  10568. const influencesList = {};
  10569. const morphInfluences = new Float32Array(8);
  10570. const morphTextures = new WeakMap();
  10571. const morph = new Vector4();
  10572. const workInfluences = [];
  10573. for (let i = 0; i < 8; i++) {
  10574. workInfluences[i] = [i, 0];
  10575. }
  10576. function update(object, geometry, material, program) {
  10577. const objectInfluences = object.morphTargetInfluences;
  10578. if (capabilities.isWebGL2 === true) {
  10579. // instead of using attributes, the WebGL 2 code path encodes morph targets
  10580. // into an array of data textures. Each layer represents a single morph target.
  10581. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  10582. const morphTargetsCount = morphAttribute !== undefined ? morphAttribute.length : 0;
  10583. let entry = morphTextures.get(geometry);
  10584. if (entry === undefined || entry.count !== morphTargetsCount) {
  10585. if (entry !== undefined) entry.texture.dispose();
  10586. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  10587. const hasMorphNormals = geometry.morphAttributes.normal !== undefined;
  10588. const hasMorphColors = geometry.morphAttributes.color !== undefined;
  10589. const morphTargets = geometry.morphAttributes.position || [];
  10590. const morphNormals = geometry.morphAttributes.normal || [];
  10591. const morphColors = geometry.morphAttributes.color || [];
  10592. let vertexDataCount = 0;
  10593. if (hasMorphPosition === true) vertexDataCount = 1;
  10594. if (hasMorphNormals === true) vertexDataCount = 2;
  10595. if (hasMorphColors === true) vertexDataCount = 3;
  10596. let width = geometry.attributes.position.count * vertexDataCount;
  10597. let height = 1;
  10598. if (width > capabilities.maxTextureSize) {
  10599. height = Math.ceil(width / capabilities.maxTextureSize);
  10600. width = capabilities.maxTextureSize;
  10601. }
  10602. const buffer = new Float32Array(width * height * 4 * morphTargetsCount);
  10603. const texture = new DataArrayTexture(buffer, width, height, morphTargetsCount);
  10604. texture.type = FloatType;
  10605. texture.needsUpdate = true;
  10606. // fill buffer
  10607. const vertexDataStride = vertexDataCount * 4;
  10608. for (let i = 0; i < morphTargetsCount; i++) {
  10609. const morphTarget = morphTargets[i];
  10610. const morphNormal = morphNormals[i];
  10611. const morphColor = morphColors[i];
  10612. const offset = width * height * 4 * i;
  10613. for (let j = 0; j < morphTarget.count; j++) {
  10614. const stride = j * vertexDataStride;
  10615. if (hasMorphPosition === true) {
  10616. morph.fromBufferAttribute(morphTarget, j);
  10617. buffer[offset + stride + 0] = morph.x;
  10618. buffer[offset + stride + 1] = morph.y;
  10619. buffer[offset + stride + 2] = morph.z;
  10620. buffer[offset + stride + 3] = 0;
  10621. }
  10622. if (hasMorphNormals === true) {
  10623. morph.fromBufferAttribute(morphNormal, j);
  10624. buffer[offset + stride + 4] = morph.x;
  10625. buffer[offset + stride + 5] = morph.y;
  10626. buffer[offset + stride + 6] = morph.z;
  10627. buffer[offset + stride + 7] = 0;
  10628. }
  10629. if (hasMorphColors === true) {
  10630. morph.fromBufferAttribute(morphColor, j);
  10631. buffer[offset + stride + 8] = morph.x;
  10632. buffer[offset + stride + 9] = morph.y;
  10633. buffer[offset + stride + 10] = morph.z;
  10634. buffer[offset + stride + 11] = morphColor.itemSize === 4 ? morph.w : 1;
  10635. }
  10636. }
  10637. }
  10638. entry = {
  10639. count: morphTargetsCount,
  10640. texture: texture,
  10641. size: new Vector2(width, height)
  10642. };
  10643. morphTextures.set(geometry, entry);
  10644. function disposeTexture() {
  10645. texture.dispose();
  10646. morphTextures.delete(geometry);
  10647. geometry.removeEventListener('dispose', disposeTexture);
  10648. }
  10649. geometry.addEventListener('dispose', disposeTexture);
  10650. }
  10651. //
  10652. let morphInfluencesSum = 0;
  10653. for (let i = 0; i < objectInfluences.length; i++) {
  10654. morphInfluencesSum += objectInfluences[i];
  10655. }
  10656. const morphBaseInfluence = geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
  10657. program.getUniforms().setValue(gl, 'morphTargetBaseInfluence', morphBaseInfluence);
  10658. program.getUniforms().setValue(gl, 'morphTargetInfluences', objectInfluences);
  10659. program.getUniforms().setValue(gl, 'morphTargetsTexture', entry.texture, textures);
  10660. program.getUniforms().setValue(gl, 'morphTargetsTextureSize', entry.size);
  10661. } else {
  10662. // When object doesn't have morph target influences defined, we treat it as a 0-length array
  10663. // This is important to make sure we set up morphTargetBaseInfluence / morphTargetInfluences
  10664. const length = objectInfluences === undefined ? 0 : objectInfluences.length;
  10665. let influences = influencesList[geometry.id];
  10666. if (influences === undefined || influences.length !== length) {
  10667. // initialise list
  10668. influences = [];
  10669. for (let i = 0; i < length; i++) {
  10670. influences[i] = [i, 0];
  10671. }
  10672. influencesList[geometry.id] = influences;
  10673. }
  10674. // Collect influences
  10675. for (let i = 0; i < length; i++) {
  10676. const influence = influences[i];
  10677. influence[0] = i;
  10678. influence[1] = objectInfluences[i];
  10679. }
  10680. influences.sort(absNumericalSort);
  10681. for (let i = 0; i < 8; i++) {
  10682. if (i < length && influences[i][1]) {
  10683. workInfluences[i][0] = influences[i][0];
  10684. workInfluences[i][1] = influences[i][1];
  10685. } else {
  10686. workInfluences[i][0] = Number.MAX_SAFE_INTEGER;
  10687. workInfluences[i][1] = 0;
  10688. }
  10689. }
  10690. workInfluences.sort(numericalSort);
  10691. const morphTargets = geometry.morphAttributes.position;
  10692. const morphNormals = geometry.morphAttributes.normal;
  10693. let morphInfluencesSum = 0;
  10694. for (let i = 0; i < 8; i++) {
  10695. const influence = workInfluences[i];
  10696. const index = influence[0];
  10697. const value = influence[1];
  10698. if (index !== Number.MAX_SAFE_INTEGER && value) {
  10699. if (morphTargets && geometry.getAttribute('morphTarget' + i) !== morphTargets[index]) {
  10700. geometry.setAttribute('morphTarget' + i, morphTargets[index]);
  10701. }
  10702. if (morphNormals && geometry.getAttribute('morphNormal' + i) !== morphNormals[index]) {
  10703. geometry.setAttribute('morphNormal' + i, morphNormals[index]);
  10704. }
  10705. morphInfluences[i] = value;
  10706. morphInfluencesSum += value;
  10707. } else {
  10708. if (morphTargets && geometry.hasAttribute('morphTarget' + i) === true) {
  10709. geometry.deleteAttribute('morphTarget' + i);
  10710. }
  10711. if (morphNormals && geometry.hasAttribute('morphNormal' + i) === true) {
  10712. geometry.deleteAttribute('morphNormal' + i);
  10713. }
  10714. morphInfluences[i] = 0;
  10715. }
  10716. }
  10717. // GLSL shader uses formula baseinfluence * base + sum(target * influence)
  10718. // This allows us to switch between absolute morphs and relative morphs without changing shader code
  10719. // When baseinfluence = 1 - sum(influence), the above is equivalent to sum((target - base) * influence)
  10720. const morphBaseInfluence = geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
  10721. program.getUniforms().setValue(gl, 'morphTargetBaseInfluence', morphBaseInfluence);
  10722. program.getUniforms().setValue(gl, 'morphTargetInfluences', morphInfluences);
  10723. }
  10724. }
  10725. return {
  10726. update: update
  10727. };
  10728. }
  10729. function WebGLObjects(gl, geometries, attributes, info) {
  10730. let updateMap = new WeakMap();
  10731. function update(object) {
  10732. const frame = info.render.frame;
  10733. const geometry = object.geometry;
  10734. const buffergeometry = geometries.get(object, geometry);
  10735. // Update once per frame
  10736. if (updateMap.get(buffergeometry) !== frame) {
  10737. geometries.update(buffergeometry);
  10738. updateMap.set(buffergeometry, frame);
  10739. }
  10740. if (object.isInstancedMesh) {
  10741. if (object.hasEventListener('dispose', onInstancedMeshDispose) === false) {
  10742. object.addEventListener('dispose', onInstancedMeshDispose);
  10743. }
  10744. attributes.update(object.instanceMatrix, gl.ARRAY_BUFFER);
  10745. if (object.instanceColor !== null) {
  10746. attributes.update(object.instanceColor, gl.ARRAY_BUFFER);
  10747. }
  10748. }
  10749. return buffergeometry;
  10750. }
  10751. function dispose() {
  10752. updateMap = new WeakMap();
  10753. }
  10754. function onInstancedMeshDispose(event) {
  10755. const instancedMesh = event.target;
  10756. instancedMesh.removeEventListener('dispose', onInstancedMeshDispose);
  10757. attributes.remove(instancedMesh.instanceMatrix);
  10758. if (instancedMesh.instanceColor !== null) attributes.remove(instancedMesh.instanceColor);
  10759. }
  10760. return {
  10761. update: update,
  10762. dispose: dispose
  10763. };
  10764. }
  10765. /**
  10766. * Uniforms of a program.
  10767. * Those form a tree structure with a special top-level container for the root,
  10768. * which you get by calling 'new WebGLUniforms( gl, program )'.
  10769. *
  10770. *
  10771. * Properties of inner nodes including the top-level container:
  10772. *
  10773. * .seq - array of nested uniforms
  10774. * .map - nested uniforms by name
  10775. *
  10776. *
  10777. * Methods of all nodes except the top-level container:
  10778. *
  10779. * .setValue( gl, value, [textures] )
  10780. *
  10781. * uploads a uniform value(s)
  10782. * the 'textures' parameter is needed for sampler uniforms
  10783. *
  10784. *
  10785. * Static methods of the top-level container (textures factorizations):
  10786. *
  10787. * .upload( gl, seq, values, textures )
  10788. *
  10789. * sets uniforms in 'seq' to 'values[id].value'
  10790. *
  10791. * .seqWithValue( seq, values ) : filteredSeq
  10792. *
  10793. * filters 'seq' entries with corresponding entry in values
  10794. *
  10795. *
  10796. * Methods of the top-level container (textures factorizations):
  10797. *
  10798. * .setValue( gl, name, value, textures )
  10799. *
  10800. * sets uniform with name 'name' to 'value'
  10801. *
  10802. * .setOptional( gl, obj, prop )
  10803. *
  10804. * like .set for an optional property of the object
  10805. *
  10806. */
  10807. const emptyTexture = /*@__PURE__*/new Texture();
  10808. const emptyArrayTexture = /*@__PURE__*/new DataArrayTexture();
  10809. const empty3dTexture = /*@__PURE__*/new Data3DTexture();
  10810. const emptyCubeTexture = /*@__PURE__*/new CubeTexture();
  10811. // --- Utilities ---
  10812. // Array Caches (provide typed arrays for temporary by size)
  10813. const arrayCacheF32 = [];
  10814. const arrayCacheI32 = [];
  10815. // Float32Array caches used for uploading Matrix uniforms
  10816. const mat4array = new Float32Array(16);
  10817. const mat3array = new Float32Array(9);
  10818. const mat2array = new Float32Array(4);
  10819. // Flattening for arrays of vectors and matrices
  10820. function flatten(array, nBlocks, blockSize) {
  10821. const firstElem = array[0];
  10822. if (firstElem <= 0 || firstElem > 0) return array;
  10823. // unoptimized: ! isNaN( firstElem )
  10824. // see http://jacksondunstan.com/articles/983
  10825. const n = nBlocks * blockSize;
  10826. let r = arrayCacheF32[n];
  10827. if (r === undefined) {
  10828. r = new Float32Array(n);
  10829. arrayCacheF32[n] = r;
  10830. }
  10831. if (nBlocks !== 0) {
  10832. firstElem.toArray(r, 0);
  10833. for (let i = 1, offset = 0; i !== nBlocks; ++i) {
  10834. offset += blockSize;
  10835. array[i].toArray(r, offset);
  10836. }
  10837. }
  10838. return r;
  10839. }
  10840. function arraysEqual(a, b) {
  10841. if (a.length !== b.length) return false;
  10842. for (let i = 0, l = a.length; i < l; i++) {
  10843. if (a[i] !== b[i]) return false;
  10844. }
  10845. return true;
  10846. }
  10847. function copyArray(a, b) {
  10848. for (let i = 0, l = b.length; i < l; i++) {
  10849. a[i] = b[i];
  10850. }
  10851. }
  10852. // Texture unit allocation
  10853. function allocTexUnits(textures, n) {
  10854. let r = arrayCacheI32[n];
  10855. if (r === undefined) {
  10856. r = new Int32Array(n);
  10857. arrayCacheI32[n] = r;
  10858. }
  10859. for (let i = 0; i !== n; ++i) {
  10860. r[i] = textures.allocateTextureUnit();
  10861. }
  10862. return r;
  10863. }
  10864. // --- Setters ---
  10865. // Note: Defining these methods externally, because they come in a bunch
  10866. // and this way their names minify.
  10867. // Single scalar
  10868. function setValueV1f(gl, v) {
  10869. const cache = this.cache;
  10870. if (cache[0] === v) return;
  10871. gl.uniform1f(this.addr, v);
  10872. cache[0] = v;
  10873. }
  10874. // Single float vector (from flat array or THREE.VectorN)
  10875. function setValueV2f(gl, v) {
  10876. const cache = this.cache;
  10877. if (v.x !== undefined) {
  10878. if (cache[0] !== v.x || cache[1] !== v.y) {
  10879. gl.uniform2f(this.addr, v.x, v.y);
  10880. cache[0] = v.x;
  10881. cache[1] = v.y;
  10882. }
  10883. } else {
  10884. if (arraysEqual(cache, v)) return;
  10885. gl.uniform2fv(this.addr, v);
  10886. copyArray(cache, v);
  10887. }
  10888. }
  10889. function setValueV3f(gl, v) {
  10890. const cache = this.cache;
  10891. if (v.x !== undefined) {
  10892. if (cache[0] !== v.x || cache[1] !== v.y || cache[2] !== v.z) {
  10893. gl.uniform3f(this.addr, v.x, v.y, v.z);
  10894. cache[0] = v.x;
  10895. cache[1] = v.y;
  10896. cache[2] = v.z;
  10897. }
  10898. } else if (v.r !== undefined) {
  10899. if (cache[0] !== v.r || cache[1] !== v.g || cache[2] !== v.b) {
  10900. gl.uniform3f(this.addr, v.r, v.g, v.b);
  10901. cache[0] = v.r;
  10902. cache[1] = v.g;
  10903. cache[2] = v.b;
  10904. }
  10905. } else {
  10906. if (arraysEqual(cache, v)) return;
  10907. gl.uniform3fv(this.addr, v);
  10908. copyArray(cache, v);
  10909. }
  10910. }
  10911. function setValueV4f(gl, v) {
  10912. const cache = this.cache;
  10913. if (v.x !== undefined) {
  10914. if (cache[0] !== v.x || cache[1] !== v.y || cache[2] !== v.z || cache[3] !== v.w) {
  10915. gl.uniform4f(this.addr, v.x, v.y, v.z, v.w);
  10916. cache[0] = v.x;
  10917. cache[1] = v.y;
  10918. cache[2] = v.z;
  10919. cache[3] = v.w;
  10920. }
  10921. } else {
  10922. if (arraysEqual(cache, v)) return;
  10923. gl.uniform4fv(this.addr, v);
  10924. copyArray(cache, v);
  10925. }
  10926. }
  10927. // Single matrix (from flat array or THREE.MatrixN)
  10928. function setValueM2(gl, v) {
  10929. const cache = this.cache;
  10930. const elements = v.elements;
  10931. if (elements === undefined) {
  10932. if (arraysEqual(cache, v)) return;
  10933. gl.uniformMatrix2fv(this.addr, false, v);
  10934. copyArray(cache, v);
  10935. } else {
  10936. if (arraysEqual(cache, elements)) return;
  10937. mat2array.set(elements);
  10938. gl.uniformMatrix2fv(this.addr, false, mat2array);
  10939. copyArray(cache, elements);
  10940. }
  10941. }
  10942. function setValueM3(gl, v) {
  10943. const cache = this.cache;
  10944. const elements = v.elements;
  10945. if (elements === undefined) {
  10946. if (arraysEqual(cache, v)) return;
  10947. gl.uniformMatrix3fv(this.addr, false, v);
  10948. copyArray(cache, v);
  10949. } else {
  10950. if (arraysEqual(cache, elements)) return;
  10951. mat3array.set(elements);
  10952. gl.uniformMatrix3fv(this.addr, false, mat3array);
  10953. copyArray(cache, elements);
  10954. }
  10955. }
  10956. function setValueM4(gl, v) {
  10957. const cache = this.cache;
  10958. const elements = v.elements;
  10959. if (elements === undefined) {
  10960. if (arraysEqual(cache, v)) return;
  10961. gl.uniformMatrix4fv(this.addr, false, v);
  10962. copyArray(cache, v);
  10963. } else {
  10964. if (arraysEqual(cache, elements)) return;
  10965. mat4array.set(elements);
  10966. gl.uniformMatrix4fv(this.addr, false, mat4array);
  10967. copyArray(cache, elements);
  10968. }
  10969. }
  10970. // Single integer / boolean
  10971. function setValueV1i(gl, v) {
  10972. const cache = this.cache;
  10973. if (cache[0] === v) return;
  10974. gl.uniform1i(this.addr, v);
  10975. cache[0] = v;
  10976. }
  10977. // Single integer / boolean vector (from flat array or THREE.VectorN)
  10978. function setValueV2i(gl, v) {
  10979. const cache = this.cache;
  10980. if (v.x !== undefined) {
  10981. if (cache[0] !== v.x || cache[1] !== v.y) {
  10982. gl.uniform2i(this.addr, v.x, v.y);
  10983. cache[0] = v.x;
  10984. cache[1] = v.y;
  10985. }
  10986. } else {
  10987. if (arraysEqual(cache, v)) return;
  10988. gl.uniform2iv(this.addr, v);
  10989. copyArray(cache, v);
  10990. }
  10991. }
  10992. function setValueV3i(gl, v) {
  10993. const cache = this.cache;
  10994. if (v.x !== undefined) {
  10995. if (cache[0] !== v.x || cache[1] !== v.y || cache[2] !== v.z) {
  10996. gl.uniform3i(this.addr, v.x, v.y, v.z);
  10997. cache[0] = v.x;
  10998. cache[1] = v.y;
  10999. cache[2] = v.z;
  11000. }
  11001. } else {
  11002. if (arraysEqual(cache, v)) return;
  11003. gl.uniform3iv(this.addr, v);
  11004. copyArray(cache, v);
  11005. }
  11006. }
  11007. function setValueV4i(gl, v) {
  11008. const cache = this.cache;
  11009. if (v.x !== undefined) {
  11010. if (cache[0] !== v.x || cache[1] !== v.y || cache[2] !== v.z || cache[3] !== v.w) {
  11011. gl.uniform4i(this.addr, v.x, v.y, v.z, v.w);
  11012. cache[0] = v.x;
  11013. cache[1] = v.y;
  11014. cache[2] = v.z;
  11015. cache[3] = v.w;
  11016. }
  11017. } else {
  11018. if (arraysEqual(cache, v)) return;
  11019. gl.uniform4iv(this.addr, v);
  11020. copyArray(cache, v);
  11021. }
  11022. }
  11023. // Single unsigned integer
  11024. function setValueV1ui(gl, v) {
  11025. const cache = this.cache;
  11026. if (cache[0] === v) return;
  11027. gl.uniform1ui(this.addr, v);
  11028. cache[0] = v;
  11029. }
  11030. // Single unsigned integer vector (from flat array or THREE.VectorN)
  11031. function setValueV2ui(gl, v) {
  11032. const cache = this.cache;
  11033. if (v.x !== undefined) {
  11034. if (cache[0] !== v.x || cache[1] !== v.y) {
  11035. gl.uniform2ui(this.addr, v.x, v.y);
  11036. cache[0] = v.x;
  11037. cache[1] = v.y;
  11038. }
  11039. } else {
  11040. if (arraysEqual(cache, v)) return;
  11041. gl.uniform2uiv(this.addr, v);
  11042. copyArray(cache, v);
  11043. }
  11044. }
  11045. function setValueV3ui(gl, v) {
  11046. const cache = this.cache;
  11047. if (v.x !== undefined) {
  11048. if (cache[0] !== v.x || cache[1] !== v.y || cache[2] !== v.z) {
  11049. gl.uniform3ui(this.addr, v.x, v.y, v.z);
  11050. cache[0] = v.x;
  11051. cache[1] = v.y;
  11052. cache[2] = v.z;
  11053. }
  11054. } else {
  11055. if (arraysEqual(cache, v)) return;
  11056. gl.uniform3uiv(this.addr, v);
  11057. copyArray(cache, v);
  11058. }
  11059. }
  11060. function setValueV4ui(gl, v) {
  11061. const cache = this.cache;
  11062. if (v.x !== undefined) {
  11063. if (cache[0] !== v.x || cache[1] !== v.y || cache[2] !== v.z || cache[3] !== v.w) {
  11064. gl.uniform4ui(this.addr, v.x, v.y, v.z, v.w);
  11065. cache[0] = v.x;
  11066. cache[1] = v.y;
  11067. cache[2] = v.z;
  11068. cache[3] = v.w;
  11069. }
  11070. } else {
  11071. if (arraysEqual(cache, v)) return;
  11072. gl.uniform4uiv(this.addr, v);
  11073. copyArray(cache, v);
  11074. }
  11075. }
  11076. // Single texture (2D / Cube)
  11077. function setValueT1(gl, v, textures) {
  11078. const cache = this.cache;
  11079. const unit = textures.allocateTextureUnit();
  11080. if (cache[0] !== unit) {
  11081. gl.uniform1i(this.addr, unit);
  11082. cache[0] = unit;
  11083. }
  11084. textures.setTexture2D(v || emptyTexture, unit);
  11085. }
  11086. function setValueT3D1(gl, v, textures) {
  11087. const cache = this.cache;
  11088. const unit = textures.allocateTextureUnit();
  11089. if (cache[0] !== unit) {
  11090. gl.uniform1i(this.addr, unit);
  11091. cache[0] = unit;
  11092. }
  11093. textures.setTexture3D(v || empty3dTexture, unit);
  11094. }
  11095. function setValueT6(gl, v, textures) {
  11096. const cache = this.cache;
  11097. const unit = textures.allocateTextureUnit();
  11098. if (cache[0] !== unit) {
  11099. gl.uniform1i(this.addr, unit);
  11100. cache[0] = unit;
  11101. }
  11102. textures.setTextureCube(v || emptyCubeTexture, unit);
  11103. }
  11104. function setValueT2DArray1(gl, v, textures) {
  11105. const cache = this.cache;
  11106. const unit = textures.allocateTextureUnit();
  11107. if (cache[0] !== unit) {
  11108. gl.uniform1i(this.addr, unit);
  11109. cache[0] = unit;
  11110. }
  11111. textures.setTexture2DArray(v || emptyArrayTexture, unit);
  11112. }
  11113. // Helper to pick the right setter for the singular case
  11114. function getSingularSetter(type) {
  11115. switch (type) {
  11116. case 0x1406:
  11117. return setValueV1f;
  11118. // FLOAT
  11119. case 0x8b50:
  11120. return setValueV2f;
  11121. // _VEC2
  11122. case 0x8b51:
  11123. return setValueV3f;
  11124. // _VEC3
  11125. case 0x8b52:
  11126. return setValueV4f;
  11127. // _VEC4
  11128. case 0x8b5a:
  11129. return setValueM2;
  11130. // _MAT2
  11131. case 0x8b5b:
  11132. return setValueM3;
  11133. // _MAT3
  11134. case 0x8b5c:
  11135. return setValueM4;
  11136. // _MAT4
  11137. case 0x1404:
  11138. case 0x8b56:
  11139. return setValueV1i;
  11140. // INT, BOOL
  11141. case 0x8b53:
  11142. case 0x8b57:
  11143. return setValueV2i;
  11144. // _VEC2
  11145. case 0x8b54:
  11146. case 0x8b58:
  11147. return setValueV3i;
  11148. // _VEC3
  11149. case 0x8b55:
  11150. case 0x8b59:
  11151. return setValueV4i;
  11152. // _VEC4
  11153. case 0x1405:
  11154. return setValueV1ui;
  11155. // UINT
  11156. case 0x8dc6:
  11157. return setValueV2ui;
  11158. // _VEC2
  11159. case 0x8dc7:
  11160. return setValueV3ui;
  11161. // _VEC3
  11162. case 0x8dc8:
  11163. return setValueV4ui;
  11164. // _VEC4
  11165. case 0x8b5e: // SAMPLER_2D
  11166. case 0x8d66: // SAMPLER_EXTERNAL_OES
  11167. case 0x8dca: // INT_SAMPLER_2D
  11168. case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
  11169. case 0x8b62:
  11170. // SAMPLER_2D_SHADOW
  11171. return setValueT1;
  11172. case 0x8b5f: // SAMPLER_3D
  11173. case 0x8dcb: // INT_SAMPLER_3D
  11174. case 0x8dd3:
  11175. // UNSIGNED_INT_SAMPLER_3D
  11176. return setValueT3D1;
  11177. case 0x8b60: // SAMPLER_CUBE
  11178. case 0x8dcc: // INT_SAMPLER_CUBE
  11179. case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
  11180. case 0x8dc5:
  11181. // SAMPLER_CUBE_SHADOW
  11182. return setValueT6;
  11183. case 0x8dc1: // SAMPLER_2D_ARRAY
  11184. case 0x8dcf: // INT_SAMPLER_2D_ARRAY
  11185. case 0x8dd7: // UNSIGNED_INT_SAMPLER_2D_ARRAY
  11186. case 0x8dc4:
  11187. // SAMPLER_2D_ARRAY_SHADOW
  11188. return setValueT2DArray1;
  11189. }
  11190. }
  11191. // Array of scalars
  11192. function setValueV1fArray(gl, v) {
  11193. gl.uniform1fv(this.addr, v);
  11194. }
  11195. // Array of vectors (from flat array or array of THREE.VectorN)
  11196. function setValueV2fArray(gl, v) {
  11197. const data = flatten(v, this.size, 2);
  11198. gl.uniform2fv(this.addr, data);
  11199. }
  11200. function setValueV3fArray(gl, v) {
  11201. const data = flatten(v, this.size, 3);
  11202. gl.uniform3fv(this.addr, data);
  11203. }
  11204. function setValueV4fArray(gl, v) {
  11205. const data = flatten(v, this.size, 4);
  11206. gl.uniform4fv(this.addr, data);
  11207. }
  11208. // Array of matrices (from flat array or array of THREE.MatrixN)
  11209. function setValueM2Array(gl, v) {
  11210. const data = flatten(v, this.size, 4);
  11211. gl.uniformMatrix2fv(this.addr, false, data);
  11212. }
  11213. function setValueM3Array(gl, v) {
  11214. const data = flatten(v, this.size, 9);
  11215. gl.uniformMatrix3fv(this.addr, false, data);
  11216. }
  11217. function setValueM4Array(gl, v) {
  11218. const data = flatten(v, this.size, 16);
  11219. gl.uniformMatrix4fv(this.addr, false, data);
  11220. }
  11221. // Array of integer / boolean
  11222. function setValueV1iArray(gl, v) {
  11223. gl.uniform1iv(this.addr, v);
  11224. }
  11225. // Array of integer / boolean vectors (from flat array)
  11226. function setValueV2iArray(gl, v) {
  11227. gl.uniform2iv(this.addr, v);
  11228. }
  11229. function setValueV3iArray(gl, v) {
  11230. gl.uniform3iv(this.addr, v);
  11231. }
  11232. function setValueV4iArray(gl, v) {
  11233. gl.uniform4iv(this.addr, v);
  11234. }
  11235. // Array of unsigned integer
  11236. function setValueV1uiArray(gl, v) {
  11237. gl.uniform1uiv(this.addr, v);
  11238. }
  11239. // Array of unsigned integer vectors (from flat array)
  11240. function setValueV2uiArray(gl, v) {
  11241. gl.uniform2uiv(this.addr, v);
  11242. }
  11243. function setValueV3uiArray(gl, v) {
  11244. gl.uniform3uiv(this.addr, v);
  11245. }
  11246. function setValueV4uiArray(gl, v) {
  11247. gl.uniform4uiv(this.addr, v);
  11248. }
  11249. // Array of textures (2D / 3D / Cube / 2DArray)
  11250. function setValueT1Array(gl, v, textures) {
  11251. const cache = this.cache;
  11252. const n = v.length;
  11253. const units = allocTexUnits(textures, n);
  11254. if (!arraysEqual(cache, units)) {
  11255. gl.uniform1iv(this.addr, units);
  11256. copyArray(cache, units);
  11257. }
  11258. for (let i = 0; i !== n; ++i) {
  11259. textures.setTexture2D(v[i] || emptyTexture, units[i]);
  11260. }
  11261. }
  11262. function setValueT3DArray(gl, v, textures) {
  11263. const cache = this.cache;
  11264. const n = v.length;
  11265. const units = allocTexUnits(textures, n);
  11266. if (!arraysEqual(cache, units)) {
  11267. gl.uniform1iv(this.addr, units);
  11268. copyArray(cache, units);
  11269. }
  11270. for (let i = 0; i !== n; ++i) {
  11271. textures.setTexture3D(v[i] || empty3dTexture, units[i]);
  11272. }
  11273. }
  11274. function setValueT6Array(gl, v, textures) {
  11275. const cache = this.cache;
  11276. const n = v.length;
  11277. const units = allocTexUnits(textures, n);
  11278. if (!arraysEqual(cache, units)) {
  11279. gl.uniform1iv(this.addr, units);
  11280. copyArray(cache, units);
  11281. }
  11282. for (let i = 0; i !== n; ++i) {
  11283. textures.setTextureCube(v[i] || emptyCubeTexture, units[i]);
  11284. }
  11285. }
  11286. function setValueT2DArrayArray(gl, v, textures) {
  11287. const cache = this.cache;
  11288. const n = v.length;
  11289. const units = allocTexUnits(textures, n);
  11290. if (!arraysEqual(cache, units)) {
  11291. gl.uniform1iv(this.addr, units);
  11292. copyArray(cache, units);
  11293. }
  11294. for (let i = 0; i !== n; ++i) {
  11295. textures.setTexture2DArray(v[i] || emptyArrayTexture, units[i]);
  11296. }
  11297. }
  11298. // Helper to pick the right setter for a pure (bottom-level) array
  11299. function getPureArraySetter(type) {
  11300. switch (type) {
  11301. case 0x1406:
  11302. return setValueV1fArray;
  11303. // FLOAT
  11304. case 0x8b50:
  11305. return setValueV2fArray;
  11306. // _VEC2
  11307. case 0x8b51:
  11308. return setValueV3fArray;
  11309. // _VEC3
  11310. case 0x8b52:
  11311. return setValueV4fArray;
  11312. // _VEC4
  11313. case 0x8b5a:
  11314. return setValueM2Array;
  11315. // _MAT2
  11316. case 0x8b5b:
  11317. return setValueM3Array;
  11318. // _MAT3
  11319. case 0x8b5c:
  11320. return setValueM4Array;
  11321. // _MAT4
  11322. case 0x1404:
  11323. case 0x8b56:
  11324. return setValueV1iArray;
  11325. // INT, BOOL
  11326. case 0x8b53:
  11327. case 0x8b57:
  11328. return setValueV2iArray;
  11329. // _VEC2
  11330. case 0x8b54:
  11331. case 0x8b58:
  11332. return setValueV3iArray;
  11333. // _VEC3
  11334. case 0x8b55:
  11335. case 0x8b59:
  11336. return setValueV4iArray;
  11337. // _VEC4
  11338. case 0x1405:
  11339. return setValueV1uiArray;
  11340. // UINT
  11341. case 0x8dc6:
  11342. return setValueV2uiArray;
  11343. // _VEC2
  11344. case 0x8dc7:
  11345. return setValueV3uiArray;
  11346. // _VEC3
  11347. case 0x8dc8:
  11348. return setValueV4uiArray;
  11349. // _VEC4
  11350. case 0x8b5e: // SAMPLER_2D
  11351. case 0x8d66: // SAMPLER_EXTERNAL_OES
  11352. case 0x8dca: // INT_SAMPLER_2D
  11353. case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
  11354. case 0x8b62:
  11355. // SAMPLER_2D_SHADOW
  11356. return setValueT1Array;
  11357. case 0x8b5f: // SAMPLER_3D
  11358. case 0x8dcb: // INT_SAMPLER_3D
  11359. case 0x8dd3:
  11360. // UNSIGNED_INT_SAMPLER_3D
  11361. return setValueT3DArray;
  11362. case 0x8b60: // SAMPLER_CUBE
  11363. case 0x8dcc: // INT_SAMPLER_CUBE
  11364. case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
  11365. case 0x8dc5:
  11366. // SAMPLER_CUBE_SHADOW
  11367. return setValueT6Array;
  11368. case 0x8dc1: // SAMPLER_2D_ARRAY
  11369. case 0x8dcf: // INT_SAMPLER_2D_ARRAY
  11370. case 0x8dd7: // UNSIGNED_INT_SAMPLER_2D_ARRAY
  11371. case 0x8dc4:
  11372. // SAMPLER_2D_ARRAY_SHADOW
  11373. return setValueT2DArrayArray;
  11374. }
  11375. }
  11376. // --- Uniform Classes ---
  11377. class SingleUniform {
  11378. constructor(id, activeInfo, addr) {
  11379. this.id = id;
  11380. this.addr = addr;
  11381. this.cache = [];
  11382. this.setValue = getSingularSetter(activeInfo.type);
  11383. // this.path = activeInfo.name; // DEBUG
  11384. }
  11385. }
  11386. class PureArrayUniform {
  11387. constructor(id, activeInfo, addr) {
  11388. this.id = id;
  11389. this.addr = addr;
  11390. this.cache = [];
  11391. this.size = activeInfo.size;
  11392. this.setValue = getPureArraySetter(activeInfo.type);
  11393. // this.path = activeInfo.name; // DEBUG
  11394. }
  11395. }
  11396. class StructuredUniform {
  11397. constructor(id) {
  11398. this.id = id;
  11399. this.seq = [];
  11400. this.map = {};
  11401. }
  11402. setValue(gl, value, textures) {
  11403. const seq = this.seq;
  11404. for (let i = 0, n = seq.length; i !== n; ++i) {
  11405. const u = seq[i];
  11406. u.setValue(gl, value[u.id], textures);
  11407. }
  11408. }
  11409. }
  11410. // --- Top-level ---
  11411. // Parser - builds up the property tree from the path strings
  11412. const RePathPart = /(\w+)(\])?(\[|\.)?/g;
  11413. // extracts
  11414. // - the identifier (member name or array index)
  11415. // - followed by an optional right bracket (found when array index)
  11416. // - followed by an optional left bracket or dot (type of subscript)
  11417. //
  11418. // Note: These portions can be read in a non-overlapping fashion and
  11419. // allow straightforward parsing of the hierarchy that WebGL encodes
  11420. // in the uniform names.
  11421. function addUniform(container, uniformObject) {
  11422. container.seq.push(uniformObject);
  11423. container.map[uniformObject.id] = uniformObject;
  11424. }
  11425. function parseUniform(activeInfo, addr, container) {
  11426. const path = activeInfo.name,
  11427. pathLength = path.length;
  11428. // reset RegExp object, because of the early exit of a previous run
  11429. RePathPart.lastIndex = 0;
  11430. while (true) {
  11431. const match = RePathPart.exec(path),
  11432. matchEnd = RePathPart.lastIndex;
  11433. let id = match[1];
  11434. const idIsIndex = match[2] === ']',
  11435. subscript = match[3];
  11436. if (idIsIndex) id = id | 0; // convert to integer
  11437. if (subscript === undefined || subscript === '[' && matchEnd + 2 === pathLength) {
  11438. // bare name or "pure" bottom-level array "[0]" suffix
  11439. addUniform(container, subscript === undefined ? new SingleUniform(id, activeInfo, addr) : new PureArrayUniform(id, activeInfo, addr));
  11440. break;
  11441. } else {
  11442. // step into inner node / create it in case it doesn't exist
  11443. const map = container.map;
  11444. let next = map[id];
  11445. if (next === undefined) {
  11446. next = new StructuredUniform(id);
  11447. addUniform(container, next);
  11448. }
  11449. container = next;
  11450. }
  11451. }
  11452. }
  11453. // Root Container
  11454. class WebGLUniforms {
  11455. constructor(gl, program) {
  11456. this.seq = [];
  11457. this.map = {};
  11458. const n = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS);
  11459. for (let i = 0; i < n; ++i) {
  11460. const info = gl.getActiveUniform(program, i),
  11461. addr = gl.getUniformLocation(program, info.name);
  11462. parseUniform(info, addr, this);
  11463. }
  11464. }
  11465. setValue(gl, name, value, textures) {
  11466. const u = this.map[name];
  11467. if (u !== undefined) u.setValue(gl, value, textures);
  11468. }
  11469. setOptional(gl, object, name) {
  11470. const v = object[name];
  11471. if (v !== undefined) this.setValue(gl, name, v);
  11472. }
  11473. static upload(gl, seq, values, textures) {
  11474. for (let i = 0, n = seq.length; i !== n; ++i) {
  11475. const u = seq[i],
  11476. v = values[u.id];
  11477. if (v.needsUpdate !== false) {
  11478. // note: always updating when .needsUpdate is undefined
  11479. u.setValue(gl, v.value, textures);
  11480. }
  11481. }
  11482. }
  11483. static seqWithValue(seq, values) {
  11484. const r = [];
  11485. for (let i = 0, n = seq.length; i !== n; ++i) {
  11486. const u = seq[i];
  11487. if (u.id in values) r.push(u);
  11488. }
  11489. return r;
  11490. }
  11491. }
  11492. function WebGLShader(gl, type, string) {
  11493. const shader = gl.createShader(type);
  11494. gl.shaderSource(shader, string);
  11495. gl.compileShader(shader);
  11496. return shader;
  11497. }
  11498. let programIdCount = 0;
  11499. function handleSource(string, errorLine) {
  11500. const lines = string.split('\n');
  11501. const lines2 = [];
  11502. const from = Math.max(errorLine - 6, 0);
  11503. const to = Math.min(errorLine + 6, lines.length);
  11504. for (let i = from; i < to; i++) {
  11505. const line = i + 1;
  11506. lines2.push(`${line === errorLine ? '>' : ' '} ${line}: ${lines[i]}`);
  11507. }
  11508. return lines2.join('\n');
  11509. }
  11510. function getEncodingComponents(encoding) {
  11511. switch (encoding) {
  11512. case LinearEncoding:
  11513. return ['Linear', '( value )'];
  11514. case sRGBEncoding:
  11515. return ['sRGB', '( value )'];
  11516. default:
  11517. console.warn('THREE.WebGLProgram: Unsupported encoding:', encoding);
  11518. return ['Linear', '( value )'];
  11519. }
  11520. }
  11521. function getShaderErrors(gl, shader, type) {
  11522. const status = gl.getShaderParameter(shader, gl.COMPILE_STATUS);
  11523. const errors = gl.getShaderInfoLog(shader).trim();
  11524. if (status && errors === '') return '';
  11525. const errorMatches = /ERROR: 0:(\d+)/.exec(errors);
  11526. if (errorMatches) {
  11527. // --enable-privileged-webgl-extension
  11528. // console.log( '**' + type + '**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) );
  11529. const errorLine = parseInt(errorMatches[1]);
  11530. return type.toUpperCase() + '\n\n' + errors + '\n\n' + handleSource(gl.getShaderSource(shader), errorLine);
  11531. } else {
  11532. return errors;
  11533. }
  11534. }
  11535. function getTexelEncodingFunction(functionName, encoding) {
  11536. const components = getEncodingComponents(encoding);
  11537. return 'vec4 ' + functionName + '( vec4 value ) { return LinearTo' + components[0] + components[1] + '; }';
  11538. }
  11539. function getToneMappingFunction(functionName, toneMapping) {
  11540. let toneMappingName;
  11541. switch (toneMapping) {
  11542. case LinearToneMapping:
  11543. toneMappingName = 'Linear';
  11544. break;
  11545. case ReinhardToneMapping:
  11546. toneMappingName = 'Reinhard';
  11547. break;
  11548. case CineonToneMapping:
  11549. toneMappingName = 'OptimizedCineon';
  11550. break;
  11551. case ACESFilmicToneMapping:
  11552. toneMappingName = 'ACESFilmic';
  11553. break;
  11554. case CustomToneMapping:
  11555. toneMappingName = 'Custom';
  11556. break;
  11557. default:
  11558. console.warn('THREE.WebGLProgram: Unsupported toneMapping:', toneMapping);
  11559. toneMappingName = 'Linear';
  11560. }
  11561. return 'vec3 ' + functionName + '( vec3 color ) { return ' + toneMappingName + 'ToneMapping( color ); }';
  11562. }
  11563. function generateExtensions(parameters) {
  11564. 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' : ''];
  11565. return chunks.filter(filterEmptyLine).join('\n');
  11566. }
  11567. function generateDefines(defines) {
  11568. const chunks = [];
  11569. for (const name in defines) {
  11570. const value = defines[name];
  11571. if (value === false) continue;
  11572. chunks.push('#define ' + name + ' ' + value);
  11573. }
  11574. return chunks.join('\n');
  11575. }
  11576. function fetchAttributeLocations(gl, program) {
  11577. const attributes = {};
  11578. const n = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES);
  11579. for (let i = 0; i < n; i++) {
  11580. const info = gl.getActiveAttrib(program, i);
  11581. const name = info.name;
  11582. let locationSize = 1;
  11583. if (info.type === gl.FLOAT_MAT2) locationSize = 2;
  11584. if (info.type === gl.FLOAT_MAT3) locationSize = 3;
  11585. if (info.type === gl.FLOAT_MAT4) locationSize = 4;
  11586. // console.log( 'THREE.WebGLProgram: ACTIVE VERTEX ATTRIBUTE:', name, i );
  11587. attributes[name] = {
  11588. type: info.type,
  11589. location: gl.getAttribLocation(program, name),
  11590. locationSize: locationSize
  11591. };
  11592. }
  11593. return attributes;
  11594. }
  11595. function filterEmptyLine(string) {
  11596. return string !== '';
  11597. }
  11598. function replaceLightNums(string, parameters) {
  11599. const numSpotLightCoords = parameters.numSpotLightShadows + parameters.numSpotLightMaps - parameters.numSpotLightShadowsWithMaps;
  11600. 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);
  11601. }
  11602. function replaceClippingPlaneNums(string, parameters) {
  11603. return string.replace(/NUM_CLIPPING_PLANES/g, parameters.numClippingPlanes).replace(/UNION_CLIPPING_PLANES/g, parameters.numClippingPlanes - parameters.numClipIntersection);
  11604. }
  11605. // Resolve Includes
  11606. const includePattern = /^[ \t]*#include +<([\w\d./]+)>/gm;
  11607. function resolveIncludes(string) {
  11608. return string.replace(includePattern, includeReplacer);
  11609. }
  11610. function includeReplacer(match, include) {
  11611. const string = ShaderChunk[include];
  11612. if (string === undefined) {
  11613. throw new Error('Can not resolve #include <' + include + '>');
  11614. }
  11615. return resolveIncludes(string);
  11616. }
  11617. // Unroll Loops
  11618. 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;
  11619. function unrollLoops(string) {
  11620. return string.replace(unrollLoopPattern, loopReplacer);
  11621. }
  11622. function loopReplacer(match, start, end, snippet) {
  11623. let string = '';
  11624. for (let i = parseInt(start); i < parseInt(end); i++) {
  11625. string += snippet.replace(/\[\s*i\s*\]/g, '[ ' + i + ' ]').replace(/UNROLLED_LOOP_INDEX/g, i);
  11626. }
  11627. return string;
  11628. }
  11629. //
  11630. function generatePrecision(parameters) {
  11631. let precisionstring = 'precision ' + parameters.precision + ' float;\nprecision ' + parameters.precision + ' int;';
  11632. if (parameters.precision === 'highp') {
  11633. precisionstring += '\n#define HIGH_PRECISION';
  11634. } else if (parameters.precision === 'mediump') {
  11635. precisionstring += '\n#define MEDIUM_PRECISION';
  11636. } else if (parameters.precision === 'lowp') {
  11637. precisionstring += '\n#define LOW_PRECISION';
  11638. }
  11639. return precisionstring;
  11640. }
  11641. function generateShadowMapTypeDefine(parameters) {
  11642. let shadowMapTypeDefine = 'SHADOWMAP_TYPE_BASIC';
  11643. if (parameters.shadowMapType === PCFShadowMap) {
  11644. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF';
  11645. } else if (parameters.shadowMapType === PCFSoftShadowMap) {
  11646. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF_SOFT';
  11647. } else if (parameters.shadowMapType === VSMShadowMap) {
  11648. shadowMapTypeDefine = 'SHADOWMAP_TYPE_VSM';
  11649. }
  11650. return shadowMapTypeDefine;
  11651. }
  11652. function generateEnvMapTypeDefine(parameters) {
  11653. let envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  11654. if (parameters.envMap) {
  11655. switch (parameters.envMapMode) {
  11656. case CubeReflectionMapping:
  11657. case CubeRefractionMapping:
  11658. envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  11659. break;
  11660. case CubeUVReflectionMapping:
  11661. envMapTypeDefine = 'ENVMAP_TYPE_CUBE_UV';
  11662. break;
  11663. }
  11664. }
  11665. return envMapTypeDefine;
  11666. }
  11667. function generateEnvMapModeDefine(parameters) {
  11668. let envMapModeDefine = 'ENVMAP_MODE_REFLECTION';
  11669. if (parameters.envMap) {
  11670. switch (parameters.envMapMode) {
  11671. case CubeRefractionMapping:
  11672. envMapModeDefine = 'ENVMAP_MODE_REFRACTION';
  11673. break;
  11674. }
  11675. }
  11676. return envMapModeDefine;
  11677. }
  11678. function generateEnvMapBlendingDefine(parameters) {
  11679. let envMapBlendingDefine = 'ENVMAP_BLENDING_NONE';
  11680. if (parameters.envMap) {
  11681. switch (parameters.combine) {
  11682. case MultiplyOperation:
  11683. envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  11684. break;
  11685. case MixOperation:
  11686. envMapBlendingDefine = 'ENVMAP_BLENDING_MIX';
  11687. break;
  11688. case AddOperation:
  11689. envMapBlendingDefine = 'ENVMAP_BLENDING_ADD';
  11690. break;
  11691. }
  11692. }
  11693. return envMapBlendingDefine;
  11694. }
  11695. function generateCubeUVSize(parameters) {
  11696. const imageHeight = parameters.envMapCubeUVHeight;
  11697. if (imageHeight === null) return null;
  11698. const maxMip = Math.log2(imageHeight) - 2;
  11699. const texelHeight = 1.0 / imageHeight;
  11700. const texelWidth = 1.0 / (3 * Math.max(Math.pow(2, maxMip), 7 * 16));
  11701. return {
  11702. texelWidth,
  11703. texelHeight,
  11704. maxMip
  11705. };
  11706. }
  11707. function WebGLProgram(renderer, cacheKey, parameters, bindingStates) {
  11708. // TODO Send this event to Three.js DevTools
  11709. // console.log( 'WebGLProgram', cacheKey );
  11710. const gl = renderer.getContext();
  11711. const defines = parameters.defines;
  11712. let vertexShader = parameters.vertexShader;
  11713. let fragmentShader = parameters.fragmentShader;
  11714. const shadowMapTypeDefine = generateShadowMapTypeDefine(parameters);
  11715. const envMapTypeDefine = generateEnvMapTypeDefine(parameters);
  11716. const envMapModeDefine = generateEnvMapModeDefine(parameters);
  11717. const envMapBlendingDefine = generateEnvMapBlendingDefine(parameters);
  11718. const envMapCubeUVSize = generateCubeUVSize(parameters);
  11719. const customExtensions = parameters.isWebGL2 ? '' : generateExtensions(parameters);
  11720. const customDefines = generateDefines(defines);
  11721. const program = gl.createProgram();
  11722. let prefixVertex, prefixFragment;
  11723. let versionString = parameters.glslVersion ? '#version ' + parameters.glslVersion + '\n' : '';
  11724. if (parameters.isRawShaderMaterial) {
  11725. prefixVertex = [customDefines].filter(filterEmptyLine).join('\n');
  11726. if (prefixVertex.length > 0) {
  11727. prefixVertex += '\n';
  11728. }
  11729. prefixFragment = [customExtensions, customDefines].filter(filterEmptyLine).join('\n');
  11730. if (prefixFragment.length > 0) {
  11731. prefixFragment += '\n';
  11732. }
  11733. } else {
  11734. 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');
  11735. 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'] : '',
  11736. // this code is required here because it is used by the toneMapping() function defined below
  11737. parameters.toneMapping !== NoToneMapping ? getToneMappingFunction('toneMapping', parameters.toneMapping) : '', parameters.dithering ? '#define DITHERING' : '', parameters.opaque ? '#define OPAQUE' : '', ShaderChunk['encodings_pars_fragment'],
  11738. // this code is required here because it is used by the various encoding/decoding function defined below
  11739. getTexelEncodingFunction('linearToOutputTexel', parameters.outputEncoding), parameters.useDepthPacking ? '#define DEPTH_PACKING ' + parameters.depthPacking : '', '\n'].filter(filterEmptyLine).join('\n');
  11740. }
  11741. vertexShader = resolveIncludes(vertexShader);
  11742. vertexShader = replaceLightNums(vertexShader, parameters);
  11743. vertexShader = replaceClippingPlaneNums(vertexShader, parameters);
  11744. fragmentShader = resolveIncludes(fragmentShader);
  11745. fragmentShader = replaceLightNums(fragmentShader, parameters);
  11746. fragmentShader = replaceClippingPlaneNums(fragmentShader, parameters);
  11747. vertexShader = unrollLoops(vertexShader);
  11748. fragmentShader = unrollLoops(fragmentShader);
  11749. if (parameters.isWebGL2 && parameters.isRawShaderMaterial !== true) {
  11750. // GLSL 3.0 conversion for built-in materials and ShaderMaterial
  11751. versionString = '#version 300 es\n';
  11752. prefixVertex = ['precision mediump sampler2DArray;', '#define attribute in', '#define varying out', '#define texture2D texture'].join('\n') + '\n' + prefixVertex;
  11753. 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;
  11754. }
  11755. const vertexGlsl = versionString + prefixVertex + vertexShader;
  11756. const fragmentGlsl = versionString + prefixFragment + fragmentShader;
  11757. // console.log( '*VERTEX*', vertexGlsl );
  11758. // console.log( '*FRAGMENT*', fragmentGlsl );
  11759. const glVertexShader = WebGLShader(gl, gl.VERTEX_SHADER, vertexGlsl);
  11760. const glFragmentShader = WebGLShader(gl, gl.FRAGMENT_SHADER, fragmentGlsl);
  11761. gl.attachShader(program, glVertexShader);
  11762. gl.attachShader(program, glFragmentShader);
  11763. // Force a particular attribute to index 0.
  11764. if (parameters.index0AttributeName !== undefined) {
  11765. gl.bindAttribLocation(program, 0, parameters.index0AttributeName);
  11766. } else if (parameters.morphTargets === true) {
  11767. // programs with morphTargets displace position out of attribute 0
  11768. gl.bindAttribLocation(program, 0, 'position');
  11769. }
  11770. gl.linkProgram(program);
  11771. // check for link errors
  11772. if (renderer.debug.checkShaderErrors) {
  11773. const programLog = gl.getProgramInfoLog(program).trim();
  11774. const vertexLog = gl.getShaderInfoLog(glVertexShader).trim();
  11775. const fragmentLog = gl.getShaderInfoLog(glFragmentShader).trim();
  11776. let runnable = true;
  11777. let haveDiagnostics = true;
  11778. if (gl.getProgramParameter(program, gl.LINK_STATUS) === false) {
  11779. runnable = false;
  11780. const vertexErrors = getShaderErrors(gl, glVertexShader, 'vertex');
  11781. const fragmentErrors = getShaderErrors(gl, glFragmentShader, 'fragment');
  11782. 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);
  11783. } else if (programLog !== '') {
  11784. console.warn('THREE.WebGLProgram: Program Info Log:', programLog);
  11785. } else if (vertexLog === '' || fragmentLog === '') {
  11786. haveDiagnostics = false;
  11787. }
  11788. if (haveDiagnostics) {
  11789. this.diagnostics = {
  11790. runnable: runnable,
  11791. programLog: programLog,
  11792. vertexShader: {
  11793. log: vertexLog,
  11794. prefix: prefixVertex
  11795. },
  11796. fragmentShader: {
  11797. log: fragmentLog,
  11798. prefix: prefixFragment
  11799. }
  11800. };
  11801. }
  11802. }
  11803. // Clean up
  11804. // Crashes in iOS9 and iOS10. #18402
  11805. // gl.detachShader( program, glVertexShader );
  11806. // gl.detachShader( program, glFragmentShader );
  11807. gl.deleteShader(glVertexShader);
  11808. gl.deleteShader(glFragmentShader);
  11809. // set up caching for uniform locations
  11810. let cachedUniforms;
  11811. this.getUniforms = function () {
  11812. if (cachedUniforms === undefined) {
  11813. cachedUniforms = new WebGLUniforms(gl, program);
  11814. }
  11815. return cachedUniforms;
  11816. };
  11817. // set up caching for attribute locations
  11818. let cachedAttributes;
  11819. this.getAttributes = function () {
  11820. if (cachedAttributes === undefined) {
  11821. cachedAttributes = fetchAttributeLocations(gl, program);
  11822. }
  11823. return cachedAttributes;
  11824. };
  11825. // free resource
  11826. this.destroy = function () {
  11827. bindingStates.releaseStatesOfProgram(this);
  11828. gl.deleteProgram(program);
  11829. this.program = undefined;
  11830. };
  11831. //
  11832. this.name = parameters.shaderName;
  11833. this.id = programIdCount++;
  11834. this.cacheKey = cacheKey;
  11835. this.usedTimes = 1;
  11836. this.program = program;
  11837. this.vertexShader = glVertexShader;
  11838. this.fragmentShader = glFragmentShader;
  11839. return this;
  11840. }
  11841. let _id = 0;
  11842. class WebGLShaderCache {
  11843. constructor() {
  11844. this.shaderCache = new Map();
  11845. this.materialCache = new Map();
  11846. }
  11847. update(material) {
  11848. const vertexShader = material.vertexShader;
  11849. const fragmentShader = material.fragmentShader;
  11850. const vertexShaderStage = this._getShaderStage(vertexShader);
  11851. const fragmentShaderStage = this._getShaderStage(fragmentShader);
  11852. const materialShaders = this._getShaderCacheForMaterial(material);
  11853. if (materialShaders.has(vertexShaderStage) === false) {
  11854. materialShaders.add(vertexShaderStage);
  11855. vertexShaderStage.usedTimes++;
  11856. }
  11857. if (materialShaders.has(fragmentShaderStage) === false) {
  11858. materialShaders.add(fragmentShaderStage);
  11859. fragmentShaderStage.usedTimes++;
  11860. }
  11861. return this;
  11862. }
  11863. remove(material) {
  11864. const materialShaders = this.materialCache.get(material);
  11865. for (const shaderStage of materialShaders) {
  11866. shaderStage.usedTimes--;
  11867. if (shaderStage.usedTimes === 0) this.shaderCache.delete(shaderStage.code);
  11868. }
  11869. this.materialCache.delete(material);
  11870. return this;
  11871. }
  11872. getVertexShaderID(material) {
  11873. return this._getShaderStage(material.vertexShader).id;
  11874. }
  11875. getFragmentShaderID(material) {
  11876. return this._getShaderStage(material.fragmentShader).id;
  11877. }
  11878. dispose() {
  11879. this.shaderCache.clear();
  11880. this.materialCache.clear();
  11881. }
  11882. _getShaderCacheForMaterial(material) {
  11883. const cache = this.materialCache;
  11884. let set = cache.get(material);
  11885. if (set === undefined) {
  11886. set = new Set();
  11887. cache.set(material, set);
  11888. }
  11889. return set;
  11890. }
  11891. _getShaderStage(code) {
  11892. const cache = this.shaderCache;
  11893. let stage = cache.get(code);
  11894. if (stage === undefined) {
  11895. stage = new WebGLShaderStage(code);
  11896. cache.set(code, stage);
  11897. }
  11898. return stage;
  11899. }
  11900. }
  11901. class WebGLShaderStage {
  11902. constructor(code) {
  11903. this.id = _id++;
  11904. this.code = code;
  11905. this.usedTimes = 0;
  11906. }
  11907. }
  11908. function WebGLPrograms(renderer, cubemaps, cubeuvmaps, extensions, capabilities, bindingStates, clipping) {
  11909. const _programLayers = new Layers();
  11910. const _customShaders = new WebGLShaderCache();
  11911. const programs = [];
  11912. const isWebGL2 = capabilities.isWebGL2;
  11913. const logarithmicDepthBuffer = capabilities.logarithmicDepthBuffer;
  11914. const vertexTextures = capabilities.vertexTextures;
  11915. let precision = capabilities.precision;
  11916. const shaderIDs = {
  11917. MeshDepthMaterial: 'depth',
  11918. MeshDistanceMaterial: 'distanceRGBA',
  11919. MeshNormalMaterial: 'normal',
  11920. MeshBasicMaterial: 'basic',
  11921. MeshLambertMaterial: 'lambert',
  11922. MeshPhongMaterial: 'phong',
  11923. MeshToonMaterial: 'toon',
  11924. MeshStandardMaterial: 'physical',
  11925. MeshPhysicalMaterial: 'physical',
  11926. MeshMatcapMaterial: 'matcap',
  11927. LineBasicMaterial: 'basic',
  11928. LineDashedMaterial: 'dashed',
  11929. PointsMaterial: 'points',
  11930. ShadowMaterial: 'shadow',
  11931. SpriteMaterial: 'sprite'
  11932. };
  11933. function getParameters(material, lights, shadows, scene, object) {
  11934. const fog = scene.fog;
  11935. const geometry = object.geometry;
  11936. const environment = material.isMeshStandardMaterial ? scene.environment : null;
  11937. const envMap = (material.isMeshStandardMaterial ? cubeuvmaps : cubemaps).get(material.envMap || environment);
  11938. const envMapCubeUVHeight = !!envMap && envMap.mapping === CubeUVReflectionMapping ? envMap.image.height : null;
  11939. const shaderID = shaderIDs[material.type];
  11940. // heuristics to create shader parameters according to lights in the scene
  11941. // (not to blow over maxLights budget)
  11942. if (material.precision !== null) {
  11943. precision = capabilities.getMaxPrecision(material.precision);
  11944. if (precision !== material.precision) {
  11945. console.warn('THREE.WebGLProgram.getParameters:', material.precision, 'not supported, using', precision, 'instead.');
  11946. }
  11947. }
  11948. //
  11949. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  11950. const morphTargetsCount = morphAttribute !== undefined ? morphAttribute.length : 0;
  11951. let morphTextureStride = 0;
  11952. if (geometry.morphAttributes.position !== undefined) morphTextureStride = 1;
  11953. if (geometry.morphAttributes.normal !== undefined) morphTextureStride = 2;
  11954. if (geometry.morphAttributes.color !== undefined) morphTextureStride = 3;
  11955. //
  11956. let vertexShader, fragmentShader;
  11957. let customVertexShaderID, customFragmentShaderID;
  11958. if (shaderID) {
  11959. const shader = ShaderLib[shaderID];
  11960. vertexShader = shader.vertexShader;
  11961. fragmentShader = shader.fragmentShader;
  11962. } else {
  11963. vertexShader = material.vertexShader;
  11964. fragmentShader = material.fragmentShader;
  11965. _customShaders.update(material);
  11966. customVertexShaderID = _customShaders.getVertexShaderID(material);
  11967. customFragmentShaderID = _customShaders.getFragmentShaderID(material);
  11968. }
  11969. const currentRenderTarget = renderer.getRenderTarget();
  11970. const useAlphaTest = material.alphaTest > 0;
  11971. const useClearcoat = material.clearcoat > 0;
  11972. const useIridescence = material.iridescence > 0;
  11973. const parameters = {
  11974. isWebGL2: isWebGL2,
  11975. shaderID: shaderID,
  11976. shaderName: material.type,
  11977. vertexShader: vertexShader,
  11978. fragmentShader: fragmentShader,
  11979. defines: material.defines,
  11980. customVertexShaderID: customVertexShaderID,
  11981. customFragmentShaderID: customFragmentShaderID,
  11982. isRawShaderMaterial: material.isRawShaderMaterial === true,
  11983. glslVersion: material.glslVersion,
  11984. precision: precision,
  11985. instancing: object.isInstancedMesh === true,
  11986. instancingColor: object.isInstancedMesh === true && object.instanceColor !== null,
  11987. supportsVertexTextures: vertexTextures,
  11988. outputEncoding: currentRenderTarget === null ? renderer.outputEncoding : currentRenderTarget.isXRRenderTarget === true ? currentRenderTarget.texture.encoding : LinearEncoding,
  11989. map: !!material.map,
  11990. matcap: !!material.matcap,
  11991. envMap: !!envMap,
  11992. envMapMode: envMap && envMap.mapping,
  11993. envMapCubeUVHeight: envMapCubeUVHeight,
  11994. lightMap: !!material.lightMap,
  11995. aoMap: !!material.aoMap,
  11996. emissiveMap: !!material.emissiveMap,
  11997. bumpMap: !!material.bumpMap,
  11998. normalMap: !!material.normalMap,
  11999. objectSpaceNormalMap: material.normalMapType === ObjectSpaceNormalMap,
  12000. tangentSpaceNormalMap: material.normalMapType === TangentSpaceNormalMap,
  12001. decodeVideoTexture: !!material.map && material.map.isVideoTexture === true && material.map.encoding === sRGBEncoding,
  12002. clearcoat: useClearcoat,
  12003. clearcoatMap: useClearcoat && !!material.clearcoatMap,
  12004. clearcoatRoughnessMap: useClearcoat && !!material.clearcoatRoughnessMap,
  12005. clearcoatNormalMap: useClearcoat && !!material.clearcoatNormalMap,
  12006. iridescence: useIridescence,
  12007. iridescenceMap: useIridescence && !!material.iridescenceMap,
  12008. iridescenceThicknessMap: useIridescence && !!material.iridescenceThicknessMap,
  12009. displacementMap: !!material.displacementMap,
  12010. roughnessMap: !!material.roughnessMap,
  12011. metalnessMap: !!material.metalnessMap,
  12012. specularMap: !!material.specularMap,
  12013. specularIntensityMap: !!material.specularIntensityMap,
  12014. specularColorMap: !!material.specularColorMap,
  12015. opaque: material.transparent === false && material.blending === NormalBlending,
  12016. alphaMap: !!material.alphaMap,
  12017. alphaTest: useAlphaTest,
  12018. gradientMap: !!material.gradientMap,
  12019. sheen: material.sheen > 0,
  12020. sheenColorMap: !!material.sheenColorMap,
  12021. sheenRoughnessMap: !!material.sheenRoughnessMap,
  12022. transmission: material.transmission > 0,
  12023. transmissionMap: !!material.transmissionMap,
  12024. thicknessMap: !!material.thicknessMap,
  12025. combine: material.combine,
  12026. vertexTangents: !!material.normalMap && !!geometry.attributes.tangent,
  12027. vertexColors: material.vertexColors,
  12028. vertexAlphas: material.vertexColors === true && !!geometry.attributes.color && geometry.attributes.color.itemSize === 4,
  12029. 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,
  12030. 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,
  12031. fog: !!fog,
  12032. useFog: material.fog === true,
  12033. fogExp2: fog && fog.isFogExp2,
  12034. flatShading: !!material.flatShading,
  12035. sizeAttenuation: material.sizeAttenuation,
  12036. logarithmicDepthBuffer: logarithmicDepthBuffer,
  12037. skinning: object.isSkinnedMesh === true,
  12038. morphTargets: geometry.morphAttributes.position !== undefined,
  12039. morphNormals: geometry.morphAttributes.normal !== undefined,
  12040. morphColors: geometry.morphAttributes.color !== undefined,
  12041. morphTargetsCount: morphTargetsCount,
  12042. morphTextureStride: morphTextureStride,
  12043. numDirLights: lights.directional.length,
  12044. numPointLights: lights.point.length,
  12045. numSpotLights: lights.spot.length,
  12046. numSpotLightMaps: lights.spotLightMap.length,
  12047. numRectAreaLights: lights.rectArea.length,
  12048. numHemiLights: lights.hemi.length,
  12049. numDirLightShadows: lights.directionalShadowMap.length,
  12050. numPointLightShadows: lights.pointShadowMap.length,
  12051. numSpotLightShadows: lights.spotShadowMap.length,
  12052. numSpotLightShadowsWithMaps: lights.numSpotLightShadowsWithMaps,
  12053. numClippingPlanes: clipping.numPlanes,
  12054. numClipIntersection: clipping.numIntersection,
  12055. dithering: material.dithering,
  12056. shadowMapEnabled: renderer.shadowMap.enabled && shadows.length > 0,
  12057. shadowMapType: renderer.shadowMap.type,
  12058. toneMapping: material.toneMapped ? renderer.toneMapping : NoToneMapping,
  12059. physicallyCorrectLights: renderer.physicallyCorrectLights,
  12060. premultipliedAlpha: material.premultipliedAlpha,
  12061. doubleSided: material.side === DoubleSide,
  12062. flipSided: material.side === BackSide,
  12063. useDepthPacking: !!material.depthPacking,
  12064. depthPacking: material.depthPacking || 0,
  12065. index0AttributeName: material.index0AttributeName,
  12066. extensionDerivatives: material.extensions && material.extensions.derivatives,
  12067. extensionFragDepth: material.extensions && material.extensions.fragDepth,
  12068. extensionDrawBuffers: material.extensions && material.extensions.drawBuffers,
  12069. extensionShaderTextureLOD: material.extensions && material.extensions.shaderTextureLOD,
  12070. rendererExtensionFragDepth: isWebGL2 || extensions.has('EXT_frag_depth'),
  12071. rendererExtensionDrawBuffers: isWebGL2 || extensions.has('WEBGL_draw_buffers'),
  12072. rendererExtensionShaderTextureLod: isWebGL2 || extensions.has('EXT_shader_texture_lod'),
  12073. customProgramCacheKey: material.customProgramCacheKey()
  12074. };
  12075. return parameters;
  12076. }
  12077. function getProgramCacheKey(parameters) {
  12078. const array = [];
  12079. if (parameters.shaderID) {
  12080. array.push(parameters.shaderID);
  12081. } else {
  12082. array.push(parameters.customVertexShaderID);
  12083. array.push(parameters.customFragmentShaderID);
  12084. }
  12085. if (parameters.defines !== undefined) {
  12086. for (const name in parameters.defines) {
  12087. array.push(name);
  12088. array.push(parameters.defines[name]);
  12089. }
  12090. }
  12091. if (parameters.isRawShaderMaterial === false) {
  12092. getProgramCacheKeyParameters(array, parameters);
  12093. getProgramCacheKeyBooleans(array, parameters);
  12094. array.push(renderer.outputEncoding);
  12095. }
  12096. array.push(parameters.customProgramCacheKey);
  12097. return array.join();
  12098. }
  12099. function getProgramCacheKeyParameters(array, parameters) {
  12100. array.push(parameters.precision);
  12101. array.push(parameters.outputEncoding);
  12102. array.push(parameters.envMapMode);
  12103. array.push(parameters.envMapCubeUVHeight);
  12104. array.push(parameters.combine);
  12105. array.push(parameters.vertexUvs);
  12106. array.push(parameters.fogExp2);
  12107. array.push(parameters.sizeAttenuation);
  12108. array.push(parameters.morphTargetsCount);
  12109. array.push(parameters.morphAttributeCount);
  12110. array.push(parameters.numDirLights);
  12111. array.push(parameters.numPointLights);
  12112. array.push(parameters.numSpotLights);
  12113. array.push(parameters.numSpotLightMaps);
  12114. array.push(parameters.numHemiLights);
  12115. array.push(parameters.numRectAreaLights);
  12116. array.push(parameters.numDirLightShadows);
  12117. array.push(parameters.numPointLightShadows);
  12118. array.push(parameters.numSpotLightShadows);
  12119. array.push(parameters.numSpotLightShadowsWithMaps);
  12120. array.push(parameters.shadowMapType);
  12121. array.push(parameters.toneMapping);
  12122. array.push(parameters.numClippingPlanes);
  12123. array.push(parameters.numClipIntersection);
  12124. array.push(parameters.depthPacking);
  12125. }
  12126. function getProgramCacheKeyBooleans(array, parameters) {
  12127. _programLayers.disableAll();
  12128. if (parameters.isWebGL2) _programLayers.enable(0);
  12129. if (parameters.supportsVertexTextures) _programLayers.enable(1);
  12130. if (parameters.instancing) _programLayers.enable(2);
  12131. if (parameters.instancingColor) _programLayers.enable(3);
  12132. if (parameters.map) _programLayers.enable(4);
  12133. if (parameters.matcap) _programLayers.enable(5);
  12134. if (parameters.envMap) _programLayers.enable(6);
  12135. if (parameters.lightMap) _programLayers.enable(7);
  12136. if (parameters.aoMap) _programLayers.enable(8);
  12137. if (parameters.emissiveMap) _programLayers.enable(9);
  12138. if (parameters.bumpMap) _programLayers.enable(10);
  12139. if (parameters.normalMap) _programLayers.enable(11);
  12140. if (parameters.objectSpaceNormalMap) _programLayers.enable(12);
  12141. if (parameters.tangentSpaceNormalMap) _programLayers.enable(13);
  12142. if (parameters.clearcoat) _programLayers.enable(14);
  12143. if (parameters.clearcoatMap) _programLayers.enable(15);
  12144. if (parameters.clearcoatRoughnessMap) _programLayers.enable(16);
  12145. if (parameters.clearcoatNormalMap) _programLayers.enable(17);
  12146. if (parameters.iridescence) _programLayers.enable(18);
  12147. if (parameters.iridescenceMap) _programLayers.enable(19);
  12148. if (parameters.iridescenceThicknessMap) _programLayers.enable(20);
  12149. if (parameters.displacementMap) _programLayers.enable(21);
  12150. if (parameters.specularMap) _programLayers.enable(22);
  12151. if (parameters.roughnessMap) _programLayers.enable(23);
  12152. if (parameters.metalnessMap) _programLayers.enable(24);
  12153. if (parameters.gradientMap) _programLayers.enable(25);
  12154. if (parameters.alphaMap) _programLayers.enable(26);
  12155. if (parameters.alphaTest) _programLayers.enable(27);
  12156. if (parameters.vertexColors) _programLayers.enable(28);
  12157. if (parameters.vertexAlphas) _programLayers.enable(29);
  12158. if (parameters.vertexUvs) _programLayers.enable(30);
  12159. if (parameters.vertexTangents) _programLayers.enable(31);
  12160. if (parameters.uvsVertexOnly) _programLayers.enable(32);
  12161. array.push(_programLayers.mask);
  12162. _programLayers.disableAll();
  12163. if (parameters.fog) _programLayers.enable(0);
  12164. if (parameters.useFog) _programLayers.enable(1);
  12165. if (parameters.flatShading) _programLayers.enable(2);
  12166. if (parameters.logarithmicDepthBuffer) _programLayers.enable(3);
  12167. if (parameters.skinning) _programLayers.enable(4);
  12168. if (parameters.morphTargets) _programLayers.enable(5);
  12169. if (parameters.morphNormals) _programLayers.enable(6);
  12170. if (parameters.morphColors) _programLayers.enable(7);
  12171. if (parameters.premultipliedAlpha) _programLayers.enable(8);
  12172. if (parameters.shadowMapEnabled) _programLayers.enable(9);
  12173. if (parameters.physicallyCorrectLights) _programLayers.enable(10);
  12174. if (parameters.doubleSided) _programLayers.enable(11);
  12175. if (parameters.flipSided) _programLayers.enable(12);
  12176. if (parameters.useDepthPacking) _programLayers.enable(13);
  12177. if (parameters.dithering) _programLayers.enable(14);
  12178. if (parameters.specularIntensityMap) _programLayers.enable(15);
  12179. if (parameters.specularColorMap) _programLayers.enable(16);
  12180. if (parameters.transmission) _programLayers.enable(17);
  12181. if (parameters.transmissionMap) _programLayers.enable(18);
  12182. if (parameters.thicknessMap) _programLayers.enable(19);
  12183. if (parameters.sheen) _programLayers.enable(20);
  12184. if (parameters.sheenColorMap) _programLayers.enable(21);
  12185. if (parameters.sheenRoughnessMap) _programLayers.enable(22);
  12186. if (parameters.decodeVideoTexture) _programLayers.enable(23);
  12187. if (parameters.opaque) _programLayers.enable(24);
  12188. array.push(_programLayers.mask);
  12189. }
  12190. function getUniforms(material) {
  12191. const shaderID = shaderIDs[material.type];
  12192. let uniforms;
  12193. if (shaderID) {
  12194. const shader = ShaderLib[shaderID];
  12195. uniforms = UniformsUtils.clone(shader.uniforms);
  12196. } else {
  12197. uniforms = material.uniforms;
  12198. }
  12199. return uniforms;
  12200. }
  12201. function acquireProgram(parameters, cacheKey) {
  12202. let program;
  12203. // Check if code has been already compiled
  12204. for (let p = 0, pl = programs.length; p < pl; p++) {
  12205. const preexistingProgram = programs[p];
  12206. if (preexistingProgram.cacheKey === cacheKey) {
  12207. program = preexistingProgram;
  12208. ++program.usedTimes;
  12209. break;
  12210. }
  12211. }
  12212. if (program === undefined) {
  12213. program = new WebGLProgram(renderer, cacheKey, parameters, bindingStates);
  12214. programs.push(program);
  12215. }
  12216. return program;
  12217. }
  12218. function releaseProgram(program) {
  12219. if (--program.usedTimes === 0) {
  12220. // Remove from unordered set
  12221. const i = programs.indexOf(program);
  12222. programs[i] = programs[programs.length - 1];
  12223. programs.pop();
  12224. // Free WebGL resources
  12225. program.destroy();
  12226. }
  12227. }
  12228. function releaseShaderCache(material) {
  12229. _customShaders.remove(material);
  12230. }
  12231. function dispose() {
  12232. _customShaders.dispose();
  12233. }
  12234. return {
  12235. getParameters: getParameters,
  12236. getProgramCacheKey: getProgramCacheKey,
  12237. getUniforms: getUniforms,
  12238. acquireProgram: acquireProgram,
  12239. releaseProgram: releaseProgram,
  12240. releaseShaderCache: releaseShaderCache,
  12241. // Exposed for resource monitoring & error feedback via renderer.info:
  12242. programs: programs,
  12243. dispose: dispose
  12244. };
  12245. }
  12246. function WebGLProperties() {
  12247. let properties = new WeakMap();
  12248. function get(object) {
  12249. let map = properties.get(object);
  12250. if (map === undefined) {
  12251. map = {};
  12252. properties.set(object, map);
  12253. }
  12254. return map;
  12255. }
  12256. function remove(object) {
  12257. properties.delete(object);
  12258. }
  12259. function update(object, key, value) {
  12260. properties.get(object)[key] = value;
  12261. }
  12262. function dispose() {
  12263. properties = new WeakMap();
  12264. }
  12265. return {
  12266. get: get,
  12267. remove: remove,
  12268. update: update,
  12269. dispose: dispose
  12270. };
  12271. }
  12272. function painterSortStable(a, b) {
  12273. if (a.groupOrder !== b.groupOrder) {
  12274. return a.groupOrder - b.groupOrder;
  12275. } else if (a.renderOrder !== b.renderOrder) {
  12276. return a.renderOrder - b.renderOrder;
  12277. } else if (a.material.id !== b.material.id) {
  12278. return a.material.id - b.material.id;
  12279. } else if (a.z !== b.z) {
  12280. return a.z - b.z;
  12281. } else {
  12282. return a.id - b.id;
  12283. }
  12284. }
  12285. function reversePainterSortStable(a, b) {
  12286. if (a.groupOrder !== b.groupOrder) {
  12287. return a.groupOrder - b.groupOrder;
  12288. } else if (a.renderOrder !== b.renderOrder) {
  12289. return a.renderOrder - b.renderOrder;
  12290. } else if (a.z !== b.z) {
  12291. return b.z - a.z;
  12292. } else {
  12293. return a.id - b.id;
  12294. }
  12295. }
  12296. function WebGLRenderList() {
  12297. const renderItems = [];
  12298. let renderItemsIndex = 0;
  12299. const opaque = [];
  12300. const transmissive = [];
  12301. const transparent = [];
  12302. function init() {
  12303. renderItemsIndex = 0;
  12304. opaque.length = 0;
  12305. transmissive.length = 0;
  12306. transparent.length = 0;
  12307. }
  12308. function getNextRenderItem(object, geometry, material, groupOrder, z, group) {
  12309. let renderItem = renderItems[renderItemsIndex];
  12310. if (renderItem === undefined) {
  12311. renderItem = {
  12312. id: object.id,
  12313. object: object,
  12314. geometry: geometry,
  12315. material: material,
  12316. groupOrder: groupOrder,
  12317. renderOrder: object.renderOrder,
  12318. z: z,
  12319. group: group
  12320. };
  12321. renderItems[renderItemsIndex] = renderItem;
  12322. } else {
  12323. renderItem.id = object.id;
  12324. renderItem.object = object;
  12325. renderItem.geometry = geometry;
  12326. renderItem.material = material;
  12327. renderItem.groupOrder = groupOrder;
  12328. renderItem.renderOrder = object.renderOrder;
  12329. renderItem.z = z;
  12330. renderItem.group = group;
  12331. }
  12332. renderItemsIndex++;
  12333. return renderItem;
  12334. }
  12335. function push(object, geometry, material, groupOrder, z, group) {
  12336. const renderItem = getNextRenderItem(object, geometry, material, groupOrder, z, group);
  12337. if (material.transmission > 0.0) {
  12338. transmissive.push(renderItem);
  12339. } else if (material.transparent === true) {
  12340. transparent.push(renderItem);
  12341. } else {
  12342. opaque.push(renderItem);
  12343. }
  12344. }
  12345. function unshift(object, geometry, material, groupOrder, z, group) {
  12346. const renderItem = getNextRenderItem(object, geometry, material, groupOrder, z, group);
  12347. if (material.transmission > 0.0) {
  12348. transmissive.unshift(renderItem);
  12349. } else if (material.transparent === true) {
  12350. transparent.unshift(renderItem);
  12351. } else {
  12352. opaque.unshift(renderItem);
  12353. }
  12354. }
  12355. function sort(customOpaqueSort, customTransparentSort) {
  12356. if (opaque.length > 1) opaque.sort(customOpaqueSort || painterSortStable);
  12357. if (transmissive.length > 1) transmissive.sort(customTransparentSort || reversePainterSortStable);
  12358. if (transparent.length > 1) transparent.sort(customTransparentSort || reversePainterSortStable);
  12359. }
  12360. function finish() {
  12361. // Clear references from inactive renderItems in the list
  12362. for (let i = renderItemsIndex, il = renderItems.length; i < il; i++) {
  12363. const renderItem = renderItems[i];
  12364. if (renderItem.id === null) break;
  12365. renderItem.id = null;
  12366. renderItem.object = null;
  12367. renderItem.geometry = null;
  12368. renderItem.material = null;
  12369. renderItem.group = null;
  12370. }
  12371. }
  12372. return {
  12373. opaque: opaque,
  12374. transmissive: transmissive,
  12375. transparent: transparent,
  12376. init: init,
  12377. push: push,
  12378. unshift: unshift,
  12379. finish: finish,
  12380. sort: sort
  12381. };
  12382. }
  12383. function WebGLRenderLists() {
  12384. let lists = new WeakMap();
  12385. function get(scene, renderCallDepth) {
  12386. const listArray = lists.get(scene);
  12387. let list;
  12388. if (listArray === undefined) {
  12389. list = new WebGLRenderList();
  12390. lists.set(scene, [list]);
  12391. } else {
  12392. if (renderCallDepth >= listArray.length) {
  12393. list = new WebGLRenderList();
  12394. listArray.push(list);
  12395. } else {
  12396. list = listArray[renderCallDepth];
  12397. }
  12398. }
  12399. return list;
  12400. }
  12401. function dispose() {
  12402. lists = new WeakMap();
  12403. }
  12404. return {
  12405. get: get,
  12406. dispose: dispose
  12407. };
  12408. }
  12409. function UniformsCache() {
  12410. const lights = {};
  12411. return {
  12412. get: function (light) {
  12413. if (lights[light.id] !== undefined) {
  12414. return lights[light.id];
  12415. }
  12416. let uniforms;
  12417. switch (light.type) {
  12418. case 'DirectionalLight':
  12419. uniforms = {
  12420. direction: new Vector3(),
  12421. color: new Color()
  12422. };
  12423. break;
  12424. case 'SpotLight':
  12425. uniforms = {
  12426. position: new Vector3(),
  12427. direction: new Vector3(),
  12428. color: new Color(),
  12429. distance: 0,
  12430. coneCos: 0,
  12431. penumbraCos: 0,
  12432. decay: 0
  12433. };
  12434. break;
  12435. case 'PointLight':
  12436. uniforms = {
  12437. position: new Vector3(),
  12438. color: new Color(),
  12439. distance: 0,
  12440. decay: 0
  12441. };
  12442. break;
  12443. case 'HemisphereLight':
  12444. uniforms = {
  12445. direction: new Vector3(),
  12446. skyColor: new Color(),
  12447. groundColor: new Color()
  12448. };
  12449. break;
  12450. case 'RectAreaLight':
  12451. uniforms = {
  12452. color: new Color(),
  12453. position: new Vector3(),
  12454. halfWidth: new Vector3(),
  12455. halfHeight: new Vector3()
  12456. };
  12457. break;
  12458. }
  12459. lights[light.id] = uniforms;
  12460. return uniforms;
  12461. }
  12462. };
  12463. }
  12464. function ShadowUniformsCache() {
  12465. const lights = {};
  12466. return {
  12467. get: function (light) {
  12468. if (lights[light.id] !== undefined) {
  12469. return lights[light.id];
  12470. }
  12471. let uniforms;
  12472. switch (light.type) {
  12473. case 'DirectionalLight':
  12474. uniforms = {
  12475. shadowBias: 0,
  12476. shadowNormalBias: 0,
  12477. shadowRadius: 1,
  12478. shadowMapSize: new Vector2()
  12479. };
  12480. break;
  12481. case 'SpotLight':
  12482. uniforms = {
  12483. shadowBias: 0,
  12484. shadowNormalBias: 0,
  12485. shadowRadius: 1,
  12486. shadowMapSize: new Vector2()
  12487. };
  12488. break;
  12489. case 'PointLight':
  12490. uniforms = {
  12491. shadowBias: 0,
  12492. shadowNormalBias: 0,
  12493. shadowRadius: 1,
  12494. shadowMapSize: new Vector2(),
  12495. shadowCameraNear: 1,
  12496. shadowCameraFar: 1000
  12497. };
  12498. break;
  12499. // TODO (abelnation): set RectAreaLight shadow uniforms
  12500. }
  12501. lights[light.id] = uniforms;
  12502. return uniforms;
  12503. }
  12504. };
  12505. }
  12506. let nextVersion = 0;
  12507. function shadowCastingAndTexturingLightsFirst(lightA, lightB) {
  12508. return (lightB.castShadow ? 2 : 0) - (lightA.castShadow ? 2 : 0) + (lightB.map ? 1 : 0) - (lightA.map ? 1 : 0);
  12509. }
  12510. function WebGLLights(extensions, capabilities) {
  12511. const cache = new UniformsCache();
  12512. const shadowCache = ShadowUniformsCache();
  12513. const state = {
  12514. version: 0,
  12515. hash: {
  12516. directionalLength: -1,
  12517. pointLength: -1,
  12518. spotLength: -1,
  12519. rectAreaLength: -1,
  12520. hemiLength: -1,
  12521. numDirectionalShadows: -1,
  12522. numPointShadows: -1,
  12523. numSpotShadows: -1,
  12524. numSpotMaps: -1
  12525. },
  12526. ambient: [0, 0, 0],
  12527. probe: [],
  12528. directional: [],
  12529. directionalShadow: [],
  12530. directionalShadowMap: [],
  12531. directionalShadowMatrix: [],
  12532. spot: [],
  12533. spotLightMap: [],
  12534. spotShadow: [],
  12535. spotShadowMap: [],
  12536. spotLightMatrix: [],
  12537. rectArea: [],
  12538. rectAreaLTC1: null,
  12539. rectAreaLTC2: null,
  12540. point: [],
  12541. pointShadow: [],
  12542. pointShadowMap: [],
  12543. pointShadowMatrix: [],
  12544. hemi: [],
  12545. numSpotLightShadowsWithMaps: 0
  12546. };
  12547. for (let i = 0; i < 9; i++) state.probe.push(new Vector3());
  12548. const vector3 = new Vector3();
  12549. const matrix4 = new Matrix4();
  12550. const matrix42 = new Matrix4();
  12551. function setup(lights, physicallyCorrectLights) {
  12552. let r = 0,
  12553. g = 0,
  12554. b = 0;
  12555. for (let i = 0; i < 9; i++) state.probe[i].set(0, 0, 0);
  12556. let directionalLength = 0;
  12557. let pointLength = 0;
  12558. let spotLength = 0;
  12559. let rectAreaLength = 0;
  12560. let hemiLength = 0;
  12561. let numDirectionalShadows = 0;
  12562. let numPointShadows = 0;
  12563. let numSpotShadows = 0;
  12564. let numSpotMaps = 0;
  12565. let numSpotShadowsWithMaps = 0;
  12566. // ordering : [shadow casting + map texturing, map texturing, shadow casting, none ]
  12567. lights.sort(shadowCastingAndTexturingLightsFirst);
  12568. // artist-friendly light intensity scaling factor
  12569. const scaleFactor = physicallyCorrectLights !== true ? Math.PI : 1;
  12570. for (let i = 0, l = lights.length; i < l; i++) {
  12571. const light = lights[i];
  12572. const color = light.color;
  12573. const intensity = light.intensity;
  12574. const distance = light.distance;
  12575. const shadowMap = light.shadow && light.shadow.map ? light.shadow.map.texture : null;
  12576. if (light.isAmbientLight) {
  12577. r += color.r * intensity * scaleFactor;
  12578. g += color.g * intensity * scaleFactor;
  12579. b += color.b * intensity * scaleFactor;
  12580. } else if (light.isLightProbe) {
  12581. for (let j = 0; j < 9; j++) {
  12582. state.probe[j].addScaledVector(light.sh.coefficients[j], intensity);
  12583. }
  12584. } else if (light.isDirectionalLight) {
  12585. const uniforms = cache.get(light);
  12586. uniforms.color.copy(light.color).multiplyScalar(light.intensity * scaleFactor);
  12587. if (light.castShadow) {
  12588. const shadow = light.shadow;
  12589. const shadowUniforms = shadowCache.get(light);
  12590. shadowUniforms.shadowBias = shadow.bias;
  12591. shadowUniforms.shadowNormalBias = shadow.normalBias;
  12592. shadowUniforms.shadowRadius = shadow.radius;
  12593. shadowUniforms.shadowMapSize = shadow.mapSize;
  12594. state.directionalShadow[directionalLength] = shadowUniforms;
  12595. state.directionalShadowMap[directionalLength] = shadowMap;
  12596. state.directionalShadowMatrix[directionalLength] = light.shadow.matrix;
  12597. numDirectionalShadows++;
  12598. }
  12599. state.directional[directionalLength] = uniforms;
  12600. directionalLength++;
  12601. } else if (light.isSpotLight) {
  12602. const uniforms = cache.get(light);
  12603. uniforms.position.setFromMatrixPosition(light.matrixWorld);
  12604. uniforms.color.copy(color).multiplyScalar(intensity * scaleFactor);
  12605. uniforms.distance = distance;
  12606. uniforms.coneCos = Math.cos(light.angle);
  12607. uniforms.penumbraCos = Math.cos(light.angle * (1 - light.penumbra));
  12608. uniforms.decay = light.decay;
  12609. state.spot[spotLength] = uniforms;
  12610. const shadow = light.shadow;
  12611. if (light.map) {
  12612. state.spotLightMap[numSpotMaps] = light.map;
  12613. numSpotMaps++;
  12614. // make sure the lightMatrix is up to date
  12615. // TODO : do it if required only
  12616. shadow.updateMatrices(light);
  12617. if (light.castShadow) numSpotShadowsWithMaps++;
  12618. }
  12619. state.spotLightMatrix[spotLength] = shadow.matrix;
  12620. if (light.castShadow) {
  12621. const shadowUniforms = shadowCache.get(light);
  12622. shadowUniforms.shadowBias = shadow.bias;
  12623. shadowUniforms.shadowNormalBias = shadow.normalBias;
  12624. shadowUniforms.shadowRadius = shadow.radius;
  12625. shadowUniforms.shadowMapSize = shadow.mapSize;
  12626. state.spotShadow[spotLength] = shadowUniforms;
  12627. state.spotShadowMap[spotLength] = shadowMap;
  12628. numSpotShadows++;
  12629. }
  12630. spotLength++;
  12631. } else if (light.isRectAreaLight) {
  12632. const uniforms = cache.get(light);
  12633. uniforms.color.copy(color).multiplyScalar(intensity);
  12634. uniforms.halfWidth.set(light.width * 0.5, 0.0, 0.0);
  12635. uniforms.halfHeight.set(0.0, light.height * 0.5, 0.0);
  12636. state.rectArea[rectAreaLength] = uniforms;
  12637. rectAreaLength++;
  12638. } else if (light.isPointLight) {
  12639. const uniforms = cache.get(light);
  12640. uniforms.color.copy(light.color).multiplyScalar(light.intensity * scaleFactor);
  12641. uniforms.distance = light.distance;
  12642. uniforms.decay = light.decay;
  12643. if (light.castShadow) {
  12644. const shadow = light.shadow;
  12645. const shadowUniforms = shadowCache.get(light);
  12646. shadowUniforms.shadowBias = shadow.bias;
  12647. shadowUniforms.shadowNormalBias = shadow.normalBias;
  12648. shadowUniforms.shadowRadius = shadow.radius;
  12649. shadowUniforms.shadowMapSize = shadow.mapSize;
  12650. shadowUniforms.shadowCameraNear = shadow.camera.near;
  12651. shadowUniforms.shadowCameraFar = shadow.camera.far;
  12652. state.pointShadow[pointLength] = shadowUniforms;
  12653. state.pointShadowMap[pointLength] = shadowMap;
  12654. state.pointShadowMatrix[pointLength] = light.shadow.matrix;
  12655. numPointShadows++;
  12656. }
  12657. state.point[pointLength] = uniforms;
  12658. pointLength++;
  12659. } else if (light.isHemisphereLight) {
  12660. const uniforms = cache.get(light);
  12661. uniforms.skyColor.copy(light.color).multiplyScalar(intensity * scaleFactor);
  12662. uniforms.groundColor.copy(light.groundColor).multiplyScalar(intensity * scaleFactor);
  12663. state.hemi[hemiLength] = uniforms;
  12664. hemiLength++;
  12665. }
  12666. }
  12667. if (rectAreaLength > 0) {
  12668. if (capabilities.isWebGL2) {
  12669. // WebGL 2
  12670. state.rectAreaLTC1 = UniformsLib.LTC_FLOAT_1;
  12671. state.rectAreaLTC2 = UniformsLib.LTC_FLOAT_2;
  12672. } else {
  12673. // WebGL 1
  12674. if (extensions.has('OES_texture_float_linear') === true) {
  12675. state.rectAreaLTC1 = UniformsLib.LTC_FLOAT_1;
  12676. state.rectAreaLTC2 = UniformsLib.LTC_FLOAT_2;
  12677. } else if (extensions.has('OES_texture_half_float_linear') === true) {
  12678. state.rectAreaLTC1 = UniformsLib.LTC_HALF_1;
  12679. state.rectAreaLTC2 = UniformsLib.LTC_HALF_2;
  12680. } else {
  12681. console.error('THREE.WebGLRenderer: Unable to use RectAreaLight. Missing WebGL extensions.');
  12682. }
  12683. }
  12684. }
  12685. state.ambient[0] = r;
  12686. state.ambient[1] = g;
  12687. state.ambient[2] = b;
  12688. const hash = state.hash;
  12689. 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) {
  12690. state.directional.length = directionalLength;
  12691. state.spot.length = spotLength;
  12692. state.rectArea.length = rectAreaLength;
  12693. state.point.length = pointLength;
  12694. state.hemi.length = hemiLength;
  12695. state.directionalShadow.length = numDirectionalShadows;
  12696. state.directionalShadowMap.length = numDirectionalShadows;
  12697. state.pointShadow.length = numPointShadows;
  12698. state.pointShadowMap.length = numPointShadows;
  12699. state.spotShadow.length = numSpotShadows;
  12700. state.spotShadowMap.length = numSpotShadows;
  12701. state.directionalShadowMatrix.length = numDirectionalShadows;
  12702. state.pointShadowMatrix.length = numPointShadows;
  12703. state.spotLightMatrix.length = numSpotShadows + numSpotMaps - numSpotShadowsWithMaps;
  12704. state.spotLightMap.length = numSpotMaps;
  12705. state.numSpotLightShadowsWithMaps = numSpotShadowsWithMaps;
  12706. hash.directionalLength = directionalLength;
  12707. hash.pointLength = pointLength;
  12708. hash.spotLength = spotLength;
  12709. hash.rectAreaLength = rectAreaLength;
  12710. hash.hemiLength = hemiLength;
  12711. hash.numDirectionalShadows = numDirectionalShadows;
  12712. hash.numPointShadows = numPointShadows;
  12713. hash.numSpotShadows = numSpotShadows;
  12714. hash.numSpotMaps = numSpotMaps;
  12715. state.version = nextVersion++;
  12716. }
  12717. }
  12718. function setupView(lights, camera) {
  12719. let directionalLength = 0;
  12720. let pointLength = 0;
  12721. let spotLength = 0;
  12722. let rectAreaLength = 0;
  12723. let hemiLength = 0;
  12724. const viewMatrix = camera.matrixWorldInverse;
  12725. for (let i = 0, l = lights.length; i < l; i++) {
  12726. const light = lights[i];
  12727. if (light.isDirectionalLight) {
  12728. const uniforms = state.directional[directionalLength];
  12729. uniforms.direction.setFromMatrixPosition(light.matrixWorld);
  12730. vector3.setFromMatrixPosition(light.target.matrixWorld);
  12731. uniforms.direction.sub(vector3);
  12732. uniforms.direction.transformDirection(viewMatrix);
  12733. directionalLength++;
  12734. } else if (light.isSpotLight) {
  12735. const uniforms = state.spot[spotLength];
  12736. uniforms.position.setFromMatrixPosition(light.matrixWorld);
  12737. uniforms.position.applyMatrix4(viewMatrix);
  12738. uniforms.direction.setFromMatrixPosition(light.matrixWorld);
  12739. vector3.setFromMatrixPosition(light.target.matrixWorld);
  12740. uniforms.direction.sub(vector3);
  12741. uniforms.direction.transformDirection(viewMatrix);
  12742. spotLength++;
  12743. } else if (light.isRectAreaLight) {
  12744. const uniforms = state.rectArea[rectAreaLength];
  12745. uniforms.position.setFromMatrixPosition(light.matrixWorld);
  12746. uniforms.position.applyMatrix4(viewMatrix);
  12747. // extract local rotation of light to derive width/height half vectors
  12748. matrix42.identity();
  12749. matrix4.copy(light.matrixWorld);
  12750. matrix4.premultiply(viewMatrix);
  12751. matrix42.extractRotation(matrix4);
  12752. uniforms.halfWidth.set(light.width * 0.5, 0.0, 0.0);
  12753. uniforms.halfHeight.set(0.0, light.height * 0.5, 0.0);
  12754. uniforms.halfWidth.applyMatrix4(matrix42);
  12755. uniforms.halfHeight.applyMatrix4(matrix42);
  12756. rectAreaLength++;
  12757. } else if (light.isPointLight) {
  12758. const uniforms = state.point[pointLength];
  12759. uniforms.position.setFromMatrixPosition(light.matrixWorld);
  12760. uniforms.position.applyMatrix4(viewMatrix);
  12761. pointLength++;
  12762. } else if (light.isHemisphereLight) {
  12763. const uniforms = state.hemi[hemiLength];
  12764. uniforms.direction.setFromMatrixPosition(light.matrixWorld);
  12765. uniforms.direction.transformDirection(viewMatrix);
  12766. hemiLength++;
  12767. }
  12768. }
  12769. }
  12770. return {
  12771. setup: setup,
  12772. setupView: setupView,
  12773. state: state
  12774. };
  12775. }
  12776. function WebGLRenderState(extensions, capabilities) {
  12777. const lights = new WebGLLights(extensions, capabilities);
  12778. const lightsArray = [];
  12779. const shadowsArray = [];
  12780. function init() {
  12781. lightsArray.length = 0;
  12782. shadowsArray.length = 0;
  12783. }
  12784. function pushLight(light) {
  12785. lightsArray.push(light);
  12786. }
  12787. function pushShadow(shadowLight) {
  12788. shadowsArray.push(shadowLight);
  12789. }
  12790. function setupLights(physicallyCorrectLights) {
  12791. lights.setup(lightsArray, physicallyCorrectLights);
  12792. }
  12793. function setupLightsView(camera) {
  12794. lights.setupView(lightsArray, camera);
  12795. }
  12796. const state = {
  12797. lightsArray: lightsArray,
  12798. shadowsArray: shadowsArray,
  12799. lights: lights
  12800. };
  12801. return {
  12802. init: init,
  12803. state: state,
  12804. setupLights: setupLights,
  12805. setupLightsView: setupLightsView,
  12806. pushLight: pushLight,
  12807. pushShadow: pushShadow
  12808. };
  12809. }
  12810. function WebGLRenderStates(extensions, capabilities) {
  12811. let renderStates = new WeakMap();
  12812. function get(scene, renderCallDepth = 0) {
  12813. const renderStateArray = renderStates.get(scene);
  12814. let renderState;
  12815. if (renderStateArray === undefined) {
  12816. renderState = new WebGLRenderState(extensions, capabilities);
  12817. renderStates.set(scene, [renderState]);
  12818. } else {
  12819. if (renderCallDepth >= renderStateArray.length) {
  12820. renderState = new WebGLRenderState(extensions, capabilities);
  12821. renderStateArray.push(renderState);
  12822. } else {
  12823. renderState = renderStateArray[renderCallDepth];
  12824. }
  12825. }
  12826. return renderState;
  12827. }
  12828. function dispose() {
  12829. renderStates = new WeakMap();
  12830. }
  12831. return {
  12832. get: get,
  12833. dispose: dispose
  12834. };
  12835. }
  12836. class MeshDepthMaterial extends Material {
  12837. constructor(parameters) {
  12838. super();
  12839. this.isMeshDepthMaterial = true;
  12840. this.type = 'MeshDepthMaterial';
  12841. this.depthPacking = BasicDepthPacking;
  12842. this.map = null;
  12843. this.alphaMap = null;
  12844. this.displacementMap = null;
  12845. this.displacementScale = 1;
  12846. this.displacementBias = 0;
  12847. this.wireframe = false;
  12848. this.wireframeLinewidth = 1;
  12849. this.setValues(parameters);
  12850. }
  12851. copy(source) {
  12852. super.copy(source);
  12853. this.depthPacking = source.depthPacking;
  12854. this.map = source.map;
  12855. this.alphaMap = source.alphaMap;
  12856. this.displacementMap = source.displacementMap;
  12857. this.displacementScale = source.displacementScale;
  12858. this.displacementBias = source.displacementBias;
  12859. this.wireframe = source.wireframe;
  12860. this.wireframeLinewidth = source.wireframeLinewidth;
  12861. return this;
  12862. }
  12863. }
  12864. class MeshDistanceMaterial extends Material {
  12865. constructor(parameters) {
  12866. super();
  12867. this.isMeshDistanceMaterial = true;
  12868. this.type = 'MeshDistanceMaterial';
  12869. this.referencePosition = new Vector3();
  12870. this.nearDistance = 1;
  12871. this.farDistance = 1000;
  12872. this.map = null;
  12873. this.alphaMap = null;
  12874. this.displacementMap = null;
  12875. this.displacementScale = 1;
  12876. this.displacementBias = 0;
  12877. this.setValues(parameters);
  12878. }
  12879. copy(source) {
  12880. super.copy(source);
  12881. this.referencePosition.copy(source.referencePosition);
  12882. this.nearDistance = source.nearDistance;
  12883. this.farDistance = source.farDistance;
  12884. this.map = source.map;
  12885. this.alphaMap = source.alphaMap;
  12886. this.displacementMap = source.displacementMap;
  12887. this.displacementScale = source.displacementScale;
  12888. this.displacementBias = source.displacementBias;
  12889. return this;
  12890. }
  12891. }
  12892. const vertex = "void main() {\n\tgl_Position = vec4( position, 1.0 );\n}";
  12893. 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}";
  12894. function WebGLShadowMap(_renderer, _objects, _capabilities) {
  12895. let _frustum = new Frustum();
  12896. const _shadowMapSize = new Vector2(),
  12897. _viewportSize = new Vector2(),
  12898. _viewport = new Vector4(),
  12899. _depthMaterial = new MeshDepthMaterial({
  12900. depthPacking: RGBADepthPacking
  12901. }),
  12902. _distanceMaterial = new MeshDistanceMaterial(),
  12903. _materialCache = {},
  12904. _maxTextureSize = _capabilities.maxTextureSize;
  12905. const shadowSide = {
  12906. 0: BackSide,
  12907. 1: FrontSide,
  12908. 2: DoubleSide
  12909. };
  12910. const shadowMaterialVertical = new ShaderMaterial({
  12911. defines: {
  12912. VSM_SAMPLES: 8
  12913. },
  12914. uniforms: {
  12915. shadow_pass: {
  12916. value: null
  12917. },
  12918. resolution: {
  12919. value: new Vector2()
  12920. },
  12921. radius: {
  12922. value: 4.0
  12923. }
  12924. },
  12925. vertexShader: vertex,
  12926. fragmentShader: fragment
  12927. });
  12928. const shadowMaterialHorizontal = shadowMaterialVertical.clone();
  12929. shadowMaterialHorizontal.defines.HORIZONTAL_PASS = 1;
  12930. const fullScreenTri = new BufferGeometry();
  12931. fullScreenTri.setAttribute('position', new BufferAttribute(new Float32Array([-1, -1, 0.5, 3, -1, 0.5, -1, 3, 0.5]), 3));
  12932. const fullScreenMesh = new Mesh(fullScreenTri, shadowMaterialVertical);
  12933. const scope = this;
  12934. this.enabled = false;
  12935. this.autoUpdate = true;
  12936. this.needsUpdate = false;
  12937. this.type = PCFShadowMap;
  12938. this.render = function (lights, scene, camera) {
  12939. if (scope.enabled === false) return;
  12940. if (scope.autoUpdate === false && scope.needsUpdate === false) return;
  12941. if (lights.length === 0) return;
  12942. const currentRenderTarget = _renderer.getRenderTarget();
  12943. const activeCubeFace = _renderer.getActiveCubeFace();
  12944. const activeMipmapLevel = _renderer.getActiveMipmapLevel();
  12945. const _state = _renderer.state;
  12946. // Set GL state for depth map.
  12947. _state.setBlending(NoBlending);
  12948. _state.buffers.color.setClear(1, 1, 1, 1);
  12949. _state.buffers.depth.setTest(true);
  12950. _state.setScissorTest(false);
  12951. // render depth map
  12952. for (let i = 0, il = lights.length; i < il; i++) {
  12953. const light = lights[i];
  12954. const shadow = light.shadow;
  12955. if (shadow === undefined) {
  12956. console.warn('THREE.WebGLShadowMap:', light, 'has no shadow.');
  12957. continue;
  12958. }
  12959. if (shadow.autoUpdate === false && shadow.needsUpdate === false) continue;
  12960. _shadowMapSize.copy(shadow.mapSize);
  12961. const shadowFrameExtents = shadow.getFrameExtents();
  12962. _shadowMapSize.multiply(shadowFrameExtents);
  12963. _viewportSize.copy(shadow.mapSize);
  12964. if (_shadowMapSize.x > _maxTextureSize || _shadowMapSize.y > _maxTextureSize) {
  12965. if (_shadowMapSize.x > _maxTextureSize) {
  12966. _viewportSize.x = Math.floor(_maxTextureSize / shadowFrameExtents.x);
  12967. _shadowMapSize.x = _viewportSize.x * shadowFrameExtents.x;
  12968. shadow.mapSize.x = _viewportSize.x;
  12969. }
  12970. if (_shadowMapSize.y > _maxTextureSize) {
  12971. _viewportSize.y = Math.floor(_maxTextureSize / shadowFrameExtents.y);
  12972. _shadowMapSize.y = _viewportSize.y * shadowFrameExtents.y;
  12973. shadow.mapSize.y = _viewportSize.y;
  12974. }
  12975. }
  12976. if (shadow.map === null) {
  12977. const pars = this.type !== VSMShadowMap ? {
  12978. minFilter: NearestFilter,
  12979. magFilter: NearestFilter
  12980. } : {};
  12981. shadow.map = new WebGLRenderTarget(_shadowMapSize.x, _shadowMapSize.y, pars);
  12982. shadow.map.texture.name = light.name + '.shadowMap';
  12983. shadow.camera.updateProjectionMatrix();
  12984. }
  12985. _renderer.setRenderTarget(shadow.map);
  12986. _renderer.clear();
  12987. const viewportCount = shadow.getViewportCount();
  12988. for (let vp = 0; vp < viewportCount; vp++) {
  12989. const viewport = shadow.getViewport(vp);
  12990. _viewport.set(_viewportSize.x * viewport.x, _viewportSize.y * viewport.y, _viewportSize.x * viewport.z, _viewportSize.y * viewport.w);
  12991. _state.viewport(_viewport);
  12992. shadow.updateMatrices(light, vp);
  12993. _frustum = shadow.getFrustum();
  12994. renderObject(scene, camera, shadow.camera, light, this.type);
  12995. }
  12996. // do blur pass for VSM
  12997. if (shadow.isPointLightShadow !== true && this.type === VSMShadowMap) {
  12998. VSMPass(shadow, camera);
  12999. }
  13000. shadow.needsUpdate = false;
  13001. }
  13002. scope.needsUpdate = false;
  13003. _renderer.setRenderTarget(currentRenderTarget, activeCubeFace, activeMipmapLevel);
  13004. };
  13005. function VSMPass(shadow, camera) {
  13006. const geometry = _objects.update(fullScreenMesh);
  13007. if (shadowMaterialVertical.defines.VSM_SAMPLES !== shadow.blurSamples) {
  13008. shadowMaterialVertical.defines.VSM_SAMPLES = shadow.blurSamples;
  13009. shadowMaterialHorizontal.defines.VSM_SAMPLES = shadow.blurSamples;
  13010. shadowMaterialVertical.needsUpdate = true;
  13011. shadowMaterialHorizontal.needsUpdate = true;
  13012. }
  13013. if (shadow.mapPass === null) {
  13014. shadow.mapPass = new WebGLRenderTarget(_shadowMapSize.x, _shadowMapSize.y);
  13015. }
  13016. // vertical pass
  13017. shadowMaterialVertical.uniforms.shadow_pass.value = shadow.map.texture;
  13018. shadowMaterialVertical.uniforms.resolution.value = shadow.mapSize;
  13019. shadowMaterialVertical.uniforms.radius.value = shadow.radius;
  13020. _renderer.setRenderTarget(shadow.mapPass);
  13021. _renderer.clear();
  13022. _renderer.renderBufferDirect(camera, null, geometry, shadowMaterialVertical, fullScreenMesh, null);
  13023. // horizontal pass
  13024. shadowMaterialHorizontal.uniforms.shadow_pass.value = shadow.mapPass.texture;
  13025. shadowMaterialHorizontal.uniforms.resolution.value = shadow.mapSize;
  13026. shadowMaterialHorizontal.uniforms.radius.value = shadow.radius;
  13027. _renderer.setRenderTarget(shadow.map);
  13028. _renderer.clear();
  13029. _renderer.renderBufferDirect(camera, null, geometry, shadowMaterialHorizontal, fullScreenMesh, null);
  13030. }
  13031. function getDepthMaterial(object, material, light, shadowCameraNear, shadowCameraFar, type) {
  13032. let result = null;
  13033. const customMaterial = light.isPointLight === true ? object.customDistanceMaterial : object.customDepthMaterial;
  13034. if (customMaterial !== undefined) {
  13035. result = customMaterial;
  13036. } else {
  13037. result = light.isPointLight === true ? _distanceMaterial : _depthMaterial;
  13038. }
  13039. if (_renderer.localClippingEnabled && material.clipShadows === true && Array.isArray(material.clippingPlanes) && material.clippingPlanes.length !== 0 || material.displacementMap && material.displacementScale !== 0 || material.alphaMap && material.alphaTest > 0 || material.map && material.alphaTest > 0) {
  13040. // in this case we need a unique material instance reflecting the
  13041. // appropriate state
  13042. const keyA = result.uuid,
  13043. keyB = material.uuid;
  13044. let materialsForVariant = _materialCache[keyA];
  13045. if (materialsForVariant === undefined) {
  13046. materialsForVariant = {};
  13047. _materialCache[keyA] = materialsForVariant;
  13048. }
  13049. let cachedMaterial = materialsForVariant[keyB];
  13050. if (cachedMaterial === undefined) {
  13051. cachedMaterial = result.clone();
  13052. materialsForVariant[keyB] = cachedMaterial;
  13053. }
  13054. result = cachedMaterial;
  13055. }
  13056. result.visible = material.visible;
  13057. result.wireframe = material.wireframe;
  13058. if (type === VSMShadowMap) {
  13059. result.side = material.shadowSide !== null ? material.shadowSide : material.side;
  13060. } else {
  13061. result.side = material.shadowSide !== null ? material.shadowSide : shadowSide[material.side];
  13062. }
  13063. result.alphaMap = material.alphaMap;
  13064. result.alphaTest = material.alphaTest;
  13065. result.map = material.map;
  13066. result.clipShadows = material.clipShadows;
  13067. result.clippingPlanes = material.clippingPlanes;
  13068. result.clipIntersection = material.clipIntersection;
  13069. result.displacementMap = material.displacementMap;
  13070. result.displacementScale = material.displacementScale;
  13071. result.displacementBias = material.displacementBias;
  13072. result.wireframeLinewidth = material.wireframeLinewidth;
  13073. result.linewidth = material.linewidth;
  13074. if (light.isPointLight === true && result.isMeshDistanceMaterial === true) {
  13075. result.referencePosition.setFromMatrixPosition(light.matrixWorld);
  13076. result.nearDistance = shadowCameraNear;
  13077. result.farDistance = shadowCameraFar;
  13078. }
  13079. return result;
  13080. }
  13081. function renderObject(object, camera, shadowCamera, light, type) {
  13082. if (object.visible === false) return;
  13083. const visible = object.layers.test(camera.layers);
  13084. if (visible && (object.isMesh || object.isLine || object.isPoints)) {
  13085. if ((object.castShadow || object.receiveShadow && type === VSMShadowMap) && (!object.frustumCulled || _frustum.intersectsObject(object))) {
  13086. object.modelViewMatrix.multiplyMatrices(shadowCamera.matrixWorldInverse, object.matrixWorld);
  13087. const geometry = _objects.update(object);
  13088. const material = object.material;
  13089. if (Array.isArray(material)) {
  13090. const groups = geometry.groups;
  13091. for (let k = 0, kl = groups.length; k < kl; k++) {
  13092. const group = groups[k];
  13093. const groupMaterial = material[group.materialIndex];
  13094. if (groupMaterial && groupMaterial.visible) {
  13095. const depthMaterial = getDepthMaterial(object, groupMaterial, light, shadowCamera.near, shadowCamera.far, type);
  13096. _renderer.renderBufferDirect(shadowCamera, null, geometry, depthMaterial, object, group);
  13097. }
  13098. }
  13099. } else if (material.visible) {
  13100. const depthMaterial = getDepthMaterial(object, material, light, shadowCamera.near, shadowCamera.far, type);
  13101. _renderer.renderBufferDirect(shadowCamera, null, geometry, depthMaterial, object, null);
  13102. }
  13103. }
  13104. }
  13105. const children = object.children;
  13106. for (let i = 0, l = children.length; i < l; i++) {
  13107. renderObject(children[i], camera, shadowCamera, light, type);
  13108. }
  13109. }
  13110. }
  13111. function WebGLState(gl, extensions, capabilities) {
  13112. const isWebGL2 = capabilities.isWebGL2;
  13113. function ColorBuffer() {
  13114. let locked = false;
  13115. const color = new Vector4();
  13116. let currentColorMask = null;
  13117. const currentColorClear = new Vector4(0, 0, 0, 0);
  13118. return {
  13119. setMask: function (colorMask) {
  13120. if (currentColorMask !== colorMask && !locked) {
  13121. gl.colorMask(colorMask, colorMask, colorMask, colorMask);
  13122. currentColorMask = colorMask;
  13123. }
  13124. },
  13125. setLocked: function (lock) {
  13126. locked = lock;
  13127. },
  13128. setClear: function (r, g, b, a, premultipliedAlpha) {
  13129. if (premultipliedAlpha === true) {
  13130. r *= a;
  13131. g *= a;
  13132. b *= a;
  13133. }
  13134. color.set(r, g, b, a);
  13135. if (currentColorClear.equals(color) === false) {
  13136. gl.clearColor(r, g, b, a);
  13137. currentColorClear.copy(color);
  13138. }
  13139. },
  13140. reset: function () {
  13141. locked = false;
  13142. currentColorMask = null;
  13143. currentColorClear.set(-1, 0, 0, 0); // set to invalid state
  13144. }
  13145. };
  13146. }
  13147. function DepthBuffer() {
  13148. let locked = false;
  13149. let currentDepthMask = null;
  13150. let currentDepthFunc = null;
  13151. let currentDepthClear = null;
  13152. return {
  13153. setTest: function (depthTest) {
  13154. if (depthTest) {
  13155. enable(gl.DEPTH_TEST);
  13156. } else {
  13157. disable(gl.DEPTH_TEST);
  13158. }
  13159. },
  13160. setMask: function (depthMask) {
  13161. if (currentDepthMask !== depthMask && !locked) {
  13162. gl.depthMask(depthMask);
  13163. currentDepthMask = depthMask;
  13164. }
  13165. },
  13166. setFunc: function (depthFunc) {
  13167. if (currentDepthFunc !== depthFunc) {
  13168. switch (depthFunc) {
  13169. case NeverDepth:
  13170. gl.depthFunc(gl.NEVER);
  13171. break;
  13172. case AlwaysDepth:
  13173. gl.depthFunc(gl.ALWAYS);
  13174. break;
  13175. case LessDepth:
  13176. gl.depthFunc(gl.LESS);
  13177. break;
  13178. case LessEqualDepth:
  13179. gl.depthFunc(gl.LEQUAL);
  13180. break;
  13181. case EqualDepth:
  13182. gl.depthFunc(gl.EQUAL);
  13183. break;
  13184. case GreaterEqualDepth:
  13185. gl.depthFunc(gl.GEQUAL);
  13186. break;
  13187. case GreaterDepth:
  13188. gl.depthFunc(gl.GREATER);
  13189. break;
  13190. case NotEqualDepth:
  13191. gl.depthFunc(gl.NOTEQUAL);
  13192. break;
  13193. default:
  13194. gl.depthFunc(gl.LEQUAL);
  13195. }
  13196. currentDepthFunc = depthFunc;
  13197. }
  13198. },
  13199. setLocked: function (lock) {
  13200. locked = lock;
  13201. },
  13202. setClear: function (depth) {
  13203. if (currentDepthClear !== depth) {
  13204. gl.clearDepth(depth);
  13205. currentDepthClear = depth;
  13206. }
  13207. },
  13208. reset: function () {
  13209. locked = false;
  13210. currentDepthMask = null;
  13211. currentDepthFunc = null;
  13212. currentDepthClear = null;
  13213. }
  13214. };
  13215. }
  13216. function StencilBuffer() {
  13217. let locked = false;
  13218. let currentStencilMask = null;
  13219. let currentStencilFunc = null;
  13220. let currentStencilRef = null;
  13221. let currentStencilFuncMask = null;
  13222. let currentStencilFail = null;
  13223. let currentStencilZFail = null;
  13224. let currentStencilZPass = null;
  13225. let currentStencilClear = null;
  13226. return {
  13227. setTest: function (stencilTest) {
  13228. if (!locked) {
  13229. if (stencilTest) {
  13230. enable(gl.STENCIL_TEST);
  13231. } else {
  13232. disable(gl.STENCIL_TEST);
  13233. }
  13234. }
  13235. },
  13236. setMask: function (stencilMask) {
  13237. if (currentStencilMask !== stencilMask && !locked) {
  13238. gl.stencilMask(stencilMask);
  13239. currentStencilMask = stencilMask;
  13240. }
  13241. },
  13242. setFunc: function (stencilFunc, stencilRef, stencilMask) {
  13243. if (currentStencilFunc !== stencilFunc || currentStencilRef !== stencilRef || currentStencilFuncMask !== stencilMask) {
  13244. gl.stencilFunc(stencilFunc, stencilRef, stencilMask);
  13245. currentStencilFunc = stencilFunc;
  13246. currentStencilRef = stencilRef;
  13247. currentStencilFuncMask = stencilMask;
  13248. }
  13249. },
  13250. setOp: function (stencilFail, stencilZFail, stencilZPass) {
  13251. if (currentStencilFail !== stencilFail || currentStencilZFail !== stencilZFail || currentStencilZPass !== stencilZPass) {
  13252. gl.stencilOp(stencilFail, stencilZFail, stencilZPass);
  13253. currentStencilFail = stencilFail;
  13254. currentStencilZFail = stencilZFail;
  13255. currentStencilZPass = stencilZPass;
  13256. }
  13257. },
  13258. setLocked: function (lock) {
  13259. locked = lock;
  13260. },
  13261. setClear: function (stencil) {
  13262. if (currentStencilClear !== stencil) {
  13263. gl.clearStencil(stencil);
  13264. currentStencilClear = stencil;
  13265. }
  13266. },
  13267. reset: function () {
  13268. locked = false;
  13269. currentStencilMask = null;
  13270. currentStencilFunc = null;
  13271. currentStencilRef = null;
  13272. currentStencilFuncMask = null;
  13273. currentStencilFail = null;
  13274. currentStencilZFail = null;
  13275. currentStencilZPass = null;
  13276. currentStencilClear = null;
  13277. }
  13278. };
  13279. }
  13280. //
  13281. const colorBuffer = new ColorBuffer();
  13282. const depthBuffer = new DepthBuffer();
  13283. const stencilBuffer = new StencilBuffer();
  13284. const uboBindings = new WeakMap();
  13285. const uboProgramMap = new WeakMap();
  13286. let enabledCapabilities = {};
  13287. let currentBoundFramebuffers = {};
  13288. let currentDrawbuffers = new WeakMap();
  13289. let defaultDrawbuffers = [];
  13290. let currentProgram = null;
  13291. let currentBlendingEnabled = false;
  13292. let currentBlending = null;
  13293. let currentBlendEquation = null;
  13294. let currentBlendSrc = null;
  13295. let currentBlendDst = null;
  13296. let currentBlendEquationAlpha = null;
  13297. let currentBlendSrcAlpha = null;
  13298. let currentBlendDstAlpha = null;
  13299. let currentPremultipledAlpha = false;
  13300. let currentFlipSided = null;
  13301. let currentCullFace = null;
  13302. let currentLineWidth = null;
  13303. let currentPolygonOffsetFactor = null;
  13304. let currentPolygonOffsetUnits = null;
  13305. const maxTextures = gl.getParameter(gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  13306. let lineWidthAvailable = false;
  13307. let version = 0;
  13308. const glVersion = gl.getParameter(gl.VERSION);
  13309. if (glVersion.indexOf('WebGL') !== -1) {
  13310. version = parseFloat(/^WebGL (\d)/.exec(glVersion)[1]);
  13311. lineWidthAvailable = version >= 1.0;
  13312. } else if (glVersion.indexOf('OpenGL ES') !== -1) {
  13313. version = parseFloat(/^OpenGL ES (\d)/.exec(glVersion)[1]);
  13314. lineWidthAvailable = version >= 2.0;
  13315. }
  13316. let currentTextureSlot = null;
  13317. let currentBoundTextures = {};
  13318. const scissorParam = gl.getParameter(gl.SCISSOR_BOX);
  13319. const viewportParam = gl.getParameter(gl.VIEWPORT);
  13320. const currentScissor = new Vector4().fromArray(scissorParam);
  13321. const currentViewport = new Vector4().fromArray(viewportParam);
  13322. function createTexture(type, target, count) {
  13323. const data = new Uint8Array(4); // 4 is required to match default unpack alignment of 4.
  13324. const texture = gl.createTexture();
  13325. gl.bindTexture(type, texture);
  13326. gl.texParameteri(type, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  13327. gl.texParameteri(type, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  13328. for (let i = 0; i < count; i++) {
  13329. gl.texImage2D(target + i, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data);
  13330. }
  13331. return texture;
  13332. }
  13333. const emptyTextures = {};
  13334. emptyTextures[gl.TEXTURE_2D] = createTexture(gl.TEXTURE_2D, gl.TEXTURE_2D, 1);
  13335. emptyTextures[gl.TEXTURE_CUBE_MAP] = createTexture(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_CUBE_MAP_POSITIVE_X, 6);
  13336. // init
  13337. colorBuffer.setClear(0, 0, 0, 1);
  13338. depthBuffer.setClear(1);
  13339. stencilBuffer.setClear(0);
  13340. enable(gl.DEPTH_TEST);
  13341. depthBuffer.setFunc(LessEqualDepth);
  13342. setFlipSided(false);
  13343. setCullFace(CullFaceBack);
  13344. enable(gl.CULL_FACE);
  13345. setBlending(NoBlending);
  13346. //
  13347. function enable(id) {
  13348. if (enabledCapabilities[id] !== true) {
  13349. gl.enable(id);
  13350. enabledCapabilities[id] = true;
  13351. }
  13352. }
  13353. function disable(id) {
  13354. if (enabledCapabilities[id] !== false) {
  13355. gl.disable(id);
  13356. enabledCapabilities[id] = false;
  13357. }
  13358. }
  13359. function bindFramebuffer(target, framebuffer) {
  13360. if (currentBoundFramebuffers[target] !== framebuffer) {
  13361. gl.bindFramebuffer(target, framebuffer);
  13362. currentBoundFramebuffers[target] = framebuffer;
  13363. if (isWebGL2) {
  13364. // gl.DRAW_FRAMEBUFFER is equivalent to gl.FRAMEBUFFER
  13365. if (target === gl.DRAW_FRAMEBUFFER) {
  13366. currentBoundFramebuffers[gl.FRAMEBUFFER] = framebuffer;
  13367. }
  13368. if (target === gl.FRAMEBUFFER) {
  13369. currentBoundFramebuffers[gl.DRAW_FRAMEBUFFER] = framebuffer;
  13370. }
  13371. }
  13372. return true;
  13373. }
  13374. return false;
  13375. }
  13376. function drawBuffers(renderTarget, framebuffer) {
  13377. let drawBuffers = defaultDrawbuffers;
  13378. let needsUpdate = false;
  13379. if (renderTarget) {
  13380. drawBuffers = currentDrawbuffers.get(framebuffer);
  13381. if (drawBuffers === undefined) {
  13382. drawBuffers = [];
  13383. currentDrawbuffers.set(framebuffer, drawBuffers);
  13384. }
  13385. if (renderTarget.isWebGLMultipleRenderTargets) {
  13386. const textures = renderTarget.texture;
  13387. if (drawBuffers.length !== textures.length || drawBuffers[0] !== gl.COLOR_ATTACHMENT0) {
  13388. for (let i = 0, il = textures.length; i < il; i++) {
  13389. drawBuffers[i] = gl.COLOR_ATTACHMENT0 + i;
  13390. }
  13391. drawBuffers.length = textures.length;
  13392. needsUpdate = true;
  13393. }
  13394. } else {
  13395. if (drawBuffers[0] !== gl.COLOR_ATTACHMENT0) {
  13396. drawBuffers[0] = gl.COLOR_ATTACHMENT0;
  13397. needsUpdate = true;
  13398. }
  13399. }
  13400. } else {
  13401. if (drawBuffers[0] !== gl.BACK) {
  13402. drawBuffers[0] = gl.BACK;
  13403. needsUpdate = true;
  13404. }
  13405. }
  13406. if (needsUpdate) {
  13407. if (capabilities.isWebGL2) {
  13408. gl.drawBuffers(drawBuffers);
  13409. } else {
  13410. extensions.get('WEBGL_draw_buffers').drawBuffersWEBGL(drawBuffers);
  13411. }
  13412. }
  13413. }
  13414. function useProgram(program) {
  13415. if (currentProgram !== program) {
  13416. gl.useProgram(program);
  13417. currentProgram = program;
  13418. return true;
  13419. }
  13420. return false;
  13421. }
  13422. const equationToGL = {
  13423. [AddEquation]: gl.FUNC_ADD,
  13424. [SubtractEquation]: gl.FUNC_SUBTRACT,
  13425. [ReverseSubtractEquation]: gl.FUNC_REVERSE_SUBTRACT
  13426. };
  13427. if (isWebGL2) {
  13428. equationToGL[MinEquation] = gl.MIN;
  13429. equationToGL[MaxEquation] = gl.MAX;
  13430. } else {
  13431. const extension = extensions.get('EXT_blend_minmax');
  13432. if (extension !== null) {
  13433. equationToGL[MinEquation] = extension.MIN_EXT;
  13434. equationToGL[MaxEquation] = extension.MAX_EXT;
  13435. }
  13436. }
  13437. const factorToGL = {
  13438. [ZeroFactor]: gl.ZERO,
  13439. [OneFactor]: gl.ONE,
  13440. [SrcColorFactor]: gl.SRC_COLOR,
  13441. [SrcAlphaFactor]: gl.SRC_ALPHA,
  13442. [SrcAlphaSaturateFactor]: gl.SRC_ALPHA_SATURATE,
  13443. [DstColorFactor]: gl.DST_COLOR,
  13444. [DstAlphaFactor]: gl.DST_ALPHA,
  13445. [OneMinusSrcColorFactor]: gl.ONE_MINUS_SRC_COLOR,
  13446. [OneMinusSrcAlphaFactor]: gl.ONE_MINUS_SRC_ALPHA,
  13447. [OneMinusDstColorFactor]: gl.ONE_MINUS_DST_COLOR,
  13448. [OneMinusDstAlphaFactor]: gl.ONE_MINUS_DST_ALPHA
  13449. };
  13450. function setBlending(blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha) {
  13451. if (blending === NoBlending) {
  13452. if (currentBlendingEnabled === true) {
  13453. disable(gl.BLEND);
  13454. currentBlendingEnabled = false;
  13455. }
  13456. return;
  13457. }
  13458. if (currentBlendingEnabled === false) {
  13459. enable(gl.BLEND);
  13460. currentBlendingEnabled = true;
  13461. }
  13462. if (blending !== CustomBlending) {
  13463. if (blending !== currentBlending || premultipliedAlpha !== currentPremultipledAlpha) {
  13464. if (currentBlendEquation !== AddEquation || currentBlendEquationAlpha !== AddEquation) {
  13465. gl.blendEquation(gl.FUNC_ADD);
  13466. currentBlendEquation = AddEquation;
  13467. currentBlendEquationAlpha = AddEquation;
  13468. }
  13469. if (premultipliedAlpha) {
  13470. switch (blending) {
  13471. case NormalBlending:
  13472. gl.blendFuncSeparate(gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
  13473. break;
  13474. case AdditiveBlending:
  13475. gl.blendFunc(gl.ONE, gl.ONE);
  13476. break;
  13477. case SubtractiveBlending:
  13478. gl.blendFuncSeparate(gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE);
  13479. break;
  13480. case MultiplyBlending:
  13481. gl.blendFuncSeparate(gl.ZERO, gl.SRC_COLOR, gl.ZERO, gl.SRC_ALPHA);
  13482. break;
  13483. default:
  13484. console.error('THREE.WebGLState: Invalid blending: ', blending);
  13485. break;
  13486. }
  13487. } else {
  13488. switch (blending) {
  13489. case NormalBlending:
  13490. gl.blendFuncSeparate(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
  13491. break;
  13492. case AdditiveBlending:
  13493. gl.blendFunc(gl.SRC_ALPHA, gl.ONE);
  13494. break;
  13495. case SubtractiveBlending:
  13496. gl.blendFuncSeparate(gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE);
  13497. break;
  13498. case MultiplyBlending:
  13499. gl.blendFunc(gl.ZERO, gl.SRC_COLOR);
  13500. break;
  13501. default:
  13502. console.error('THREE.WebGLState: Invalid blending: ', blending);
  13503. break;
  13504. }
  13505. }
  13506. currentBlendSrc = null;
  13507. currentBlendDst = null;
  13508. currentBlendSrcAlpha = null;
  13509. currentBlendDstAlpha = null;
  13510. currentBlending = blending;
  13511. currentPremultipledAlpha = premultipliedAlpha;
  13512. }
  13513. return;
  13514. }
  13515. // custom blending
  13516. blendEquationAlpha = blendEquationAlpha || blendEquation;
  13517. blendSrcAlpha = blendSrcAlpha || blendSrc;
  13518. blendDstAlpha = blendDstAlpha || blendDst;
  13519. if (blendEquation !== currentBlendEquation || blendEquationAlpha !== currentBlendEquationAlpha) {
  13520. gl.blendEquationSeparate(equationToGL[blendEquation], equationToGL[blendEquationAlpha]);
  13521. currentBlendEquation = blendEquation;
  13522. currentBlendEquationAlpha = blendEquationAlpha;
  13523. }
  13524. if (blendSrc !== currentBlendSrc || blendDst !== currentBlendDst || blendSrcAlpha !== currentBlendSrcAlpha || blendDstAlpha !== currentBlendDstAlpha) {
  13525. gl.blendFuncSeparate(factorToGL[blendSrc], factorToGL[blendDst], factorToGL[blendSrcAlpha], factorToGL[blendDstAlpha]);
  13526. currentBlendSrc = blendSrc;
  13527. currentBlendDst = blendDst;
  13528. currentBlendSrcAlpha = blendSrcAlpha;
  13529. currentBlendDstAlpha = blendDstAlpha;
  13530. }
  13531. currentBlending = blending;
  13532. currentPremultipledAlpha = false;
  13533. }
  13534. function setMaterial(material, frontFaceCW) {
  13535. material.side === DoubleSide ? disable(gl.CULL_FACE) : enable(gl.CULL_FACE);
  13536. let flipSided = material.side === BackSide;
  13537. if (frontFaceCW) flipSided = !flipSided;
  13538. setFlipSided(flipSided);
  13539. 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);
  13540. depthBuffer.setFunc(material.depthFunc);
  13541. depthBuffer.setTest(material.depthTest);
  13542. depthBuffer.setMask(material.depthWrite);
  13543. colorBuffer.setMask(material.colorWrite);
  13544. const stencilWrite = material.stencilWrite;
  13545. stencilBuffer.setTest(stencilWrite);
  13546. if (stencilWrite) {
  13547. stencilBuffer.setMask(material.stencilWriteMask);
  13548. stencilBuffer.setFunc(material.stencilFunc, material.stencilRef, material.stencilFuncMask);
  13549. stencilBuffer.setOp(material.stencilFail, material.stencilZFail, material.stencilZPass);
  13550. }
  13551. setPolygonOffset(material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits);
  13552. material.alphaToCoverage === true ? enable(gl.SAMPLE_ALPHA_TO_COVERAGE) : disable(gl.SAMPLE_ALPHA_TO_COVERAGE);
  13553. }
  13554. //
  13555. function setFlipSided(flipSided) {
  13556. if (currentFlipSided !== flipSided) {
  13557. if (flipSided) {
  13558. gl.frontFace(gl.CW);
  13559. } else {
  13560. gl.frontFace(gl.CCW);
  13561. }
  13562. currentFlipSided = flipSided;
  13563. }
  13564. }
  13565. function setCullFace(cullFace) {
  13566. if (cullFace !== CullFaceNone) {
  13567. enable(gl.CULL_FACE);
  13568. if (cullFace !== currentCullFace) {
  13569. if (cullFace === CullFaceBack) {
  13570. gl.cullFace(gl.BACK);
  13571. } else if (cullFace === CullFaceFront) {
  13572. gl.cullFace(gl.FRONT);
  13573. } else {
  13574. gl.cullFace(gl.FRONT_AND_BACK);
  13575. }
  13576. }
  13577. } else {
  13578. disable(gl.CULL_FACE);
  13579. }
  13580. currentCullFace = cullFace;
  13581. }
  13582. function setLineWidth(width) {
  13583. if (width !== currentLineWidth) {
  13584. if (lineWidthAvailable) gl.lineWidth(width);
  13585. currentLineWidth = width;
  13586. }
  13587. }
  13588. function setPolygonOffset(polygonOffset, factor, units) {
  13589. if (polygonOffset) {
  13590. enable(gl.POLYGON_OFFSET_FILL);
  13591. if (currentPolygonOffsetFactor !== factor || currentPolygonOffsetUnits !== units) {
  13592. gl.polygonOffset(factor, units);
  13593. currentPolygonOffsetFactor = factor;
  13594. currentPolygonOffsetUnits = units;
  13595. }
  13596. } else {
  13597. disable(gl.POLYGON_OFFSET_FILL);
  13598. }
  13599. }
  13600. function setScissorTest(scissorTest) {
  13601. if (scissorTest) {
  13602. enable(gl.SCISSOR_TEST);
  13603. } else {
  13604. disable(gl.SCISSOR_TEST);
  13605. }
  13606. }
  13607. // texture
  13608. function activeTexture(webglSlot) {
  13609. if (webglSlot === undefined) webglSlot = gl.TEXTURE0 + maxTextures - 1;
  13610. if (currentTextureSlot !== webglSlot) {
  13611. gl.activeTexture(webglSlot);
  13612. currentTextureSlot = webglSlot;
  13613. }
  13614. }
  13615. function bindTexture(webglType, webglTexture, webglSlot) {
  13616. if (webglSlot === undefined) {
  13617. if (currentTextureSlot === null) {
  13618. webglSlot = gl.TEXTURE0 + maxTextures - 1;
  13619. } else {
  13620. webglSlot = currentTextureSlot;
  13621. }
  13622. }
  13623. let boundTexture = currentBoundTextures[webglSlot];
  13624. if (boundTexture === undefined) {
  13625. boundTexture = {
  13626. type: undefined,
  13627. texture: undefined
  13628. };
  13629. currentBoundTextures[webglSlot] = boundTexture;
  13630. }
  13631. if (boundTexture.type !== webglType || boundTexture.texture !== webglTexture) {
  13632. if (currentTextureSlot !== webglSlot) {
  13633. gl.activeTexture(webglSlot);
  13634. currentTextureSlot = webglSlot;
  13635. }
  13636. gl.bindTexture(webglType, webglTexture || emptyTextures[webglType]);
  13637. boundTexture.type = webglType;
  13638. boundTexture.texture = webglTexture;
  13639. }
  13640. }
  13641. function unbindTexture() {
  13642. const boundTexture = currentBoundTextures[currentTextureSlot];
  13643. if (boundTexture !== undefined && boundTexture.type !== undefined) {
  13644. gl.bindTexture(boundTexture.type, null);
  13645. boundTexture.type = undefined;
  13646. boundTexture.texture = undefined;
  13647. }
  13648. }
  13649. function compressedTexImage2D() {
  13650. try {
  13651. gl.compressedTexImage2D.apply(gl, arguments);
  13652. } catch (error) {
  13653. console.error('THREE.WebGLState:', error);
  13654. }
  13655. }
  13656. function compressedTexImage3D() {
  13657. try {
  13658. gl.compressedTexImage3D.apply(gl, arguments);
  13659. } catch (error) {
  13660. console.error('THREE.WebGLState:', error);
  13661. }
  13662. }
  13663. function texSubImage2D() {
  13664. try {
  13665. gl.texSubImage2D.apply(gl, arguments);
  13666. } catch (error) {
  13667. console.error('THREE.WebGLState:', error);
  13668. }
  13669. }
  13670. function texSubImage3D() {
  13671. try {
  13672. gl.texSubImage3D.apply(gl, arguments);
  13673. } catch (error) {
  13674. console.error('THREE.WebGLState:', error);
  13675. }
  13676. }
  13677. function compressedTexSubImage2D() {
  13678. try {
  13679. gl.compressedTexSubImage2D.apply(gl, arguments);
  13680. } catch (error) {
  13681. console.error('THREE.WebGLState:', error);
  13682. }
  13683. }
  13684. function compressedTexSubImage3D() {
  13685. try {
  13686. gl.compressedTexSubImage3D.apply(gl, arguments);
  13687. } catch (error) {
  13688. console.error('THREE.WebGLState:', error);
  13689. }
  13690. }
  13691. function texStorage2D() {
  13692. try {
  13693. gl.texStorage2D.apply(gl, arguments);
  13694. } catch (error) {
  13695. console.error('THREE.WebGLState:', error);
  13696. }
  13697. }
  13698. function texStorage3D() {
  13699. try {
  13700. gl.texStorage3D.apply(gl, arguments);
  13701. } catch (error) {
  13702. console.error('THREE.WebGLState:', error);
  13703. }
  13704. }
  13705. function texImage2D() {
  13706. try {
  13707. gl.texImage2D.apply(gl, arguments);
  13708. } catch (error) {
  13709. console.error('THREE.WebGLState:', error);
  13710. }
  13711. }
  13712. function texImage3D() {
  13713. try {
  13714. gl.texImage3D.apply(gl, arguments);
  13715. } catch (error) {
  13716. console.error('THREE.WebGLState:', error);
  13717. }
  13718. }
  13719. //
  13720. function scissor(scissor) {
  13721. if (currentScissor.equals(scissor) === false) {
  13722. gl.scissor(scissor.x, scissor.y, scissor.z, scissor.w);
  13723. currentScissor.copy(scissor);
  13724. }
  13725. }
  13726. function viewport(viewport) {
  13727. if (currentViewport.equals(viewport) === false) {
  13728. gl.viewport(viewport.x, viewport.y, viewport.z, viewport.w);
  13729. currentViewport.copy(viewport);
  13730. }
  13731. }
  13732. function updateUBOMapping(uniformsGroup, program) {
  13733. let mapping = uboProgramMap.get(program);
  13734. if (mapping === undefined) {
  13735. mapping = new WeakMap();
  13736. uboProgramMap.set(program, mapping);
  13737. }
  13738. let blockIndex = mapping.get(uniformsGroup);
  13739. if (blockIndex === undefined) {
  13740. blockIndex = gl.getUniformBlockIndex(program, uniformsGroup.name);
  13741. mapping.set(uniformsGroup, blockIndex);
  13742. }
  13743. }
  13744. function uniformBlockBinding(uniformsGroup, program) {
  13745. const mapping = uboProgramMap.get(program);
  13746. const blockIndex = mapping.get(uniformsGroup);
  13747. if (uboBindings.get(program) !== blockIndex) {
  13748. // bind shader specific block index to global block point
  13749. gl.uniformBlockBinding(program, blockIndex, uniformsGroup.__bindingPointIndex);
  13750. uboBindings.set(program, blockIndex);
  13751. }
  13752. }
  13753. //
  13754. function reset() {
  13755. // reset state
  13756. gl.disable(gl.BLEND);
  13757. gl.disable(gl.CULL_FACE);
  13758. gl.disable(gl.DEPTH_TEST);
  13759. gl.disable(gl.POLYGON_OFFSET_FILL);
  13760. gl.disable(gl.SCISSOR_TEST);
  13761. gl.disable(gl.STENCIL_TEST);
  13762. gl.disable(gl.SAMPLE_ALPHA_TO_COVERAGE);
  13763. gl.blendEquation(gl.FUNC_ADD);
  13764. gl.blendFunc(gl.ONE, gl.ZERO);
  13765. gl.blendFuncSeparate(gl.ONE, gl.ZERO, gl.ONE, gl.ZERO);
  13766. gl.colorMask(true, true, true, true);
  13767. gl.clearColor(0, 0, 0, 0);
  13768. gl.depthMask(true);
  13769. gl.depthFunc(gl.LESS);
  13770. gl.clearDepth(1);
  13771. gl.stencilMask(0xffffffff);
  13772. gl.stencilFunc(gl.ALWAYS, 0, 0xffffffff);
  13773. gl.stencilOp(gl.KEEP, gl.KEEP, gl.KEEP);
  13774. gl.clearStencil(0);
  13775. gl.cullFace(gl.BACK);
  13776. gl.frontFace(gl.CCW);
  13777. gl.polygonOffset(0, 0);
  13778. gl.activeTexture(gl.TEXTURE0);
  13779. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  13780. if (isWebGL2 === true) {
  13781. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, null);
  13782. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, null);
  13783. }
  13784. gl.useProgram(null);
  13785. gl.lineWidth(1);
  13786. gl.scissor(0, 0, gl.canvas.width, gl.canvas.height);
  13787. gl.viewport(0, 0, gl.canvas.width, gl.canvas.height);
  13788. // reset internals
  13789. enabledCapabilities = {};
  13790. currentTextureSlot = null;
  13791. currentBoundTextures = {};
  13792. currentBoundFramebuffers = {};
  13793. currentDrawbuffers = new WeakMap();
  13794. defaultDrawbuffers = [];
  13795. currentProgram = null;
  13796. currentBlendingEnabled = false;
  13797. currentBlending = null;
  13798. currentBlendEquation = null;
  13799. currentBlendSrc = null;
  13800. currentBlendDst = null;
  13801. currentBlendEquationAlpha = null;
  13802. currentBlendSrcAlpha = null;
  13803. currentBlendDstAlpha = null;
  13804. currentPremultipledAlpha = false;
  13805. currentFlipSided = null;
  13806. currentCullFace = null;
  13807. currentLineWidth = null;
  13808. currentPolygonOffsetFactor = null;
  13809. currentPolygonOffsetUnits = null;
  13810. currentScissor.set(0, 0, gl.canvas.width, gl.canvas.height);
  13811. currentViewport.set(0, 0, gl.canvas.width, gl.canvas.height);
  13812. colorBuffer.reset();
  13813. depthBuffer.reset();
  13814. stencilBuffer.reset();
  13815. }
  13816. return {
  13817. buffers: {
  13818. color: colorBuffer,
  13819. depth: depthBuffer,
  13820. stencil: stencilBuffer
  13821. },
  13822. enable: enable,
  13823. disable: disable,
  13824. bindFramebuffer: bindFramebuffer,
  13825. drawBuffers: drawBuffers,
  13826. useProgram: useProgram,
  13827. setBlending: setBlending,
  13828. setMaterial: setMaterial,
  13829. setFlipSided: setFlipSided,
  13830. setCullFace: setCullFace,
  13831. setLineWidth: setLineWidth,
  13832. setPolygonOffset: setPolygonOffset,
  13833. setScissorTest: setScissorTest,
  13834. activeTexture: activeTexture,
  13835. bindTexture: bindTexture,
  13836. unbindTexture: unbindTexture,
  13837. compressedTexImage2D: compressedTexImage2D,
  13838. compressedTexImage3D: compressedTexImage3D,
  13839. texImage2D: texImage2D,
  13840. texImage3D: texImage3D,
  13841. updateUBOMapping: updateUBOMapping,
  13842. uniformBlockBinding: uniformBlockBinding,
  13843. texStorage2D: texStorage2D,
  13844. texStorage3D: texStorage3D,
  13845. texSubImage2D: texSubImage2D,
  13846. texSubImage3D: texSubImage3D,
  13847. compressedTexSubImage2D: compressedTexSubImage2D,
  13848. compressedTexSubImage3D: compressedTexSubImage3D,
  13849. scissor: scissor,
  13850. viewport: viewport,
  13851. reset: reset
  13852. };
  13853. }
  13854. function WebGLTextures(_gl, extensions, state, properties, capabilities, utils, info) {
  13855. const isWebGL2 = capabilities.isWebGL2;
  13856. const maxTextures = capabilities.maxTextures;
  13857. const maxCubemapSize = capabilities.maxCubemapSize;
  13858. const maxTextureSize = capabilities.maxTextureSize;
  13859. const maxSamples = capabilities.maxSamples;
  13860. const multisampledRTTExt = extensions.has('WEBGL_multisampled_render_to_texture') ? extensions.get('WEBGL_multisampled_render_to_texture') : null;
  13861. const supportsInvalidateFramebuffer = typeof navigator === 'undefined' ? false : /OculusBrowser/g.test(navigator.userAgent);
  13862. const _videoTextures = new WeakMap();
  13863. let _canvas;
  13864. const _sources = new WeakMap(); // maps WebglTexture objects to instances of Source
  13865. // cordova iOS (as of 5.0) still uses UIWebView, which provides OffscreenCanvas,
  13866. // also OffscreenCanvas.getContext("webgl"), but not OffscreenCanvas.getContext("2d")!
  13867. // Some implementations may only implement OffscreenCanvas partially (e.g. lacking 2d).
  13868. let useOffscreenCanvas = false;
  13869. try {
  13870. useOffscreenCanvas = typeof OffscreenCanvas !== 'undefined'
  13871. // eslint-disable-next-line compat/compat
  13872. && new OffscreenCanvas(1, 1).getContext('2d') !== null;
  13873. } catch (err) {
  13874. // Ignore any errors
  13875. }
  13876. function createCanvas(width, height) {
  13877. // Use OffscreenCanvas when available. Specially needed in web workers
  13878. return useOffscreenCanvas ?
  13879. // eslint-disable-next-line compat/compat
  13880. new OffscreenCanvas(width, height) : createElementNS('canvas');
  13881. }
  13882. function resizeImage(image, needsPowerOfTwo, needsNewCanvas, maxSize) {
  13883. let scale = 1;
  13884. // handle case if texture exceeds max size
  13885. if (image.width > maxSize || image.height > maxSize) {
  13886. scale = maxSize / Math.max(image.width, image.height);
  13887. }
  13888. // only perform resize if necessary
  13889. if (scale < 1 || needsPowerOfTwo === true) {
  13890. // only perform resize for certain image types
  13891. if (typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement || typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement || typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap) {
  13892. const floor = needsPowerOfTwo ? floorPowerOfTwo : Math.floor;
  13893. const width = floor(scale * image.width);
  13894. const height = floor(scale * image.height);
  13895. if (_canvas === undefined) _canvas = createCanvas(width, height);
  13896. // cube textures can't reuse the same canvas
  13897. const canvas = needsNewCanvas ? createCanvas(width, height) : _canvas;
  13898. canvas.width = width;
  13899. canvas.height = height;
  13900. const context = canvas.getContext('2d');
  13901. context.drawImage(image, 0, 0, width, height);
  13902. console.warn('THREE.WebGLRenderer: Texture has been resized from (' + image.width + 'x' + image.height + ') to (' + width + 'x' + height + ').');
  13903. return canvas;
  13904. } else {
  13905. if ('data' in image) {
  13906. console.warn('THREE.WebGLRenderer: Image in DataTexture is too big (' + image.width + 'x' + image.height + ').');
  13907. }
  13908. return image;
  13909. }
  13910. }
  13911. return image;
  13912. }
  13913. function isPowerOfTwo$1(image) {
  13914. return isPowerOfTwo(image.width) && isPowerOfTwo(image.height);
  13915. }
  13916. function textureNeedsPowerOfTwo(texture) {
  13917. if (isWebGL2) return false;
  13918. return texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping || texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter;
  13919. }
  13920. function textureNeedsGenerateMipmaps(texture, supportsMips) {
  13921. return texture.generateMipmaps && supportsMips && texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter;
  13922. }
  13923. function generateMipmap(target) {
  13924. _gl.generateMipmap(target);
  13925. }
  13926. function getInternalFormat(internalFormatName, glFormat, glType, encoding, forceLinearEncoding = false) {
  13927. if (isWebGL2 === false) return glFormat;
  13928. if (internalFormatName !== null) {
  13929. if (_gl[internalFormatName] !== undefined) return _gl[internalFormatName];
  13930. console.warn('THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\'');
  13931. }
  13932. let internalFormat = glFormat;
  13933. if (glFormat === _gl.RED) {
  13934. if (glType === _gl.FLOAT) internalFormat = _gl.R32F;
  13935. if (glType === _gl.HALF_FLOAT) internalFormat = _gl.R16F;
  13936. if (glType === _gl.UNSIGNED_BYTE) internalFormat = _gl.R8;
  13937. }
  13938. if (glFormat === _gl.RG) {
  13939. if (glType === _gl.FLOAT) internalFormat = _gl.RG32F;
  13940. if (glType === _gl.HALF_FLOAT) internalFormat = _gl.RG16F;
  13941. if (glType === _gl.UNSIGNED_BYTE) internalFormat = _gl.RG8;
  13942. }
  13943. if (glFormat === _gl.RGBA) {
  13944. if (glType === _gl.FLOAT) internalFormat = _gl.RGBA32F;
  13945. if (glType === _gl.HALF_FLOAT) internalFormat = _gl.RGBA16F;
  13946. if (glType === _gl.UNSIGNED_BYTE) internalFormat = encoding === sRGBEncoding && forceLinearEncoding === false ? _gl.SRGB8_ALPHA8 : _gl.RGBA8;
  13947. if (glType === _gl.UNSIGNED_SHORT_4_4_4_4) internalFormat = _gl.RGBA4;
  13948. if (glType === _gl.UNSIGNED_SHORT_5_5_5_1) internalFormat = _gl.RGB5_A1;
  13949. }
  13950. if (internalFormat === _gl.R16F || internalFormat === _gl.R32F || internalFormat === _gl.RG16F || internalFormat === _gl.RG32F || internalFormat === _gl.RGBA16F || internalFormat === _gl.RGBA32F) {
  13951. extensions.get('EXT_color_buffer_float');
  13952. }
  13953. return internalFormat;
  13954. }
  13955. function getMipLevels(texture, image, supportsMips) {
  13956. if (textureNeedsGenerateMipmaps(texture, supportsMips) === true || texture.isFramebufferTexture && texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter) {
  13957. return Math.log2(Math.max(image.width, image.height)) + 1;
  13958. } else if (texture.mipmaps !== undefined && texture.mipmaps.length > 0) {
  13959. // user-defined mipmaps
  13960. return texture.mipmaps.length;
  13961. } else if (texture.isCompressedTexture && Array.isArray(texture.image)) {
  13962. return image.mipmaps.length;
  13963. } else {
  13964. // texture without mipmaps (only base level)
  13965. return 1;
  13966. }
  13967. }
  13968. // Fallback filters for non-power-of-2 textures
  13969. function filterFallback(f) {
  13970. if (f === NearestFilter || f === NearestMipmapNearestFilter || f === NearestMipmapLinearFilter) {
  13971. return _gl.NEAREST;
  13972. }
  13973. return _gl.LINEAR;
  13974. }
  13975. //
  13976. function onTextureDispose(event) {
  13977. const texture = event.target;
  13978. texture.removeEventListener('dispose', onTextureDispose);
  13979. deallocateTexture(texture);
  13980. if (texture.isVideoTexture) {
  13981. _videoTextures.delete(texture);
  13982. }
  13983. }
  13984. function onRenderTargetDispose(event) {
  13985. const renderTarget = event.target;
  13986. renderTarget.removeEventListener('dispose', onRenderTargetDispose);
  13987. deallocateRenderTarget(renderTarget);
  13988. }
  13989. //
  13990. function deallocateTexture(texture) {
  13991. const textureProperties = properties.get(texture);
  13992. if (textureProperties.__webglInit === undefined) return;
  13993. // check if it's necessary to remove the WebGLTexture object
  13994. const source = texture.source;
  13995. const webglTextures = _sources.get(source);
  13996. if (webglTextures) {
  13997. const webglTexture = webglTextures[textureProperties.__cacheKey];
  13998. webglTexture.usedTimes--;
  13999. // the WebGLTexture object is not used anymore, remove it
  14000. if (webglTexture.usedTimes === 0) {
  14001. deleteTexture(texture);
  14002. }
  14003. // remove the weak map entry if no WebGLTexture uses the source anymore
  14004. if (Object.keys(webglTextures).length === 0) {
  14005. _sources.delete(source);
  14006. }
  14007. }
  14008. properties.remove(texture);
  14009. }
  14010. function deleteTexture(texture) {
  14011. const textureProperties = properties.get(texture);
  14012. _gl.deleteTexture(textureProperties.__webglTexture);
  14013. const source = texture.source;
  14014. const webglTextures = _sources.get(source);
  14015. delete webglTextures[textureProperties.__cacheKey];
  14016. info.memory.textures--;
  14017. }
  14018. function deallocateRenderTarget(renderTarget) {
  14019. const texture = renderTarget.texture;
  14020. const renderTargetProperties = properties.get(renderTarget);
  14021. const textureProperties = properties.get(texture);
  14022. if (textureProperties.__webglTexture !== undefined) {
  14023. _gl.deleteTexture(textureProperties.__webglTexture);
  14024. info.memory.textures--;
  14025. }
  14026. if (renderTarget.depthTexture) {
  14027. renderTarget.depthTexture.dispose();
  14028. }
  14029. if (renderTarget.isWebGLCubeRenderTarget) {
  14030. for (let i = 0; i < 6; i++) {
  14031. _gl.deleteFramebuffer(renderTargetProperties.__webglFramebuffer[i]);
  14032. if (renderTargetProperties.__webglDepthbuffer) _gl.deleteRenderbuffer(renderTargetProperties.__webglDepthbuffer[i]);
  14033. }
  14034. } else {
  14035. _gl.deleteFramebuffer(renderTargetProperties.__webglFramebuffer);
  14036. if (renderTargetProperties.__webglDepthbuffer) _gl.deleteRenderbuffer(renderTargetProperties.__webglDepthbuffer);
  14037. if (renderTargetProperties.__webglMultisampledFramebuffer) _gl.deleteFramebuffer(renderTargetProperties.__webglMultisampledFramebuffer);
  14038. if (renderTargetProperties.__webglColorRenderbuffer) {
  14039. for (let i = 0; i < renderTargetProperties.__webglColorRenderbuffer.length; i++) {
  14040. if (renderTargetProperties.__webglColorRenderbuffer[i]) _gl.deleteRenderbuffer(renderTargetProperties.__webglColorRenderbuffer[i]);
  14041. }
  14042. }
  14043. if (renderTargetProperties.__webglDepthRenderbuffer) _gl.deleteRenderbuffer(renderTargetProperties.__webglDepthRenderbuffer);
  14044. }
  14045. if (renderTarget.isWebGLMultipleRenderTargets) {
  14046. for (let i = 0, il = texture.length; i < il; i++) {
  14047. const attachmentProperties = properties.get(texture[i]);
  14048. if (attachmentProperties.__webglTexture) {
  14049. _gl.deleteTexture(attachmentProperties.__webglTexture);
  14050. info.memory.textures--;
  14051. }
  14052. properties.remove(texture[i]);
  14053. }
  14054. }
  14055. properties.remove(texture);
  14056. properties.remove(renderTarget);
  14057. }
  14058. //
  14059. let textureUnits = 0;
  14060. function resetTextureUnits() {
  14061. textureUnits = 0;
  14062. }
  14063. function allocateTextureUnit() {
  14064. const textureUnit = textureUnits;
  14065. if (textureUnit >= maxTextures) {
  14066. console.warn('THREE.WebGLTextures: Trying to use ' + textureUnit + ' texture units while this GPU supports only ' + maxTextures);
  14067. }
  14068. textureUnits += 1;
  14069. return textureUnit;
  14070. }
  14071. function getTextureCacheKey(texture) {
  14072. const array = [];
  14073. array.push(texture.wrapS);
  14074. array.push(texture.wrapT);
  14075. array.push(texture.wrapR || 0);
  14076. array.push(texture.magFilter);
  14077. array.push(texture.minFilter);
  14078. array.push(texture.anisotropy);
  14079. array.push(texture.internalFormat);
  14080. array.push(texture.format);
  14081. array.push(texture.type);
  14082. array.push(texture.generateMipmaps);
  14083. array.push(texture.premultiplyAlpha);
  14084. array.push(texture.flipY);
  14085. array.push(texture.unpackAlignment);
  14086. array.push(texture.encoding);
  14087. return array.join();
  14088. }
  14089. //
  14090. function setTexture2D(texture, slot) {
  14091. const textureProperties = properties.get(texture);
  14092. if (texture.isVideoTexture) updateVideoTexture(texture);
  14093. if (texture.isRenderTargetTexture === false && texture.version > 0 && textureProperties.__version !== texture.version) {
  14094. const image = texture.image;
  14095. if (image === null) {
  14096. console.warn('THREE.WebGLRenderer: Texture marked for update but no image data found.');
  14097. } else if (image.complete === false) {
  14098. console.warn('THREE.WebGLRenderer: Texture marked for update but image is incomplete');
  14099. } else {
  14100. uploadTexture(textureProperties, texture, slot);
  14101. return;
  14102. }
  14103. }
  14104. state.bindTexture(_gl.TEXTURE_2D, textureProperties.__webglTexture, _gl.TEXTURE0 + slot);
  14105. }
  14106. function setTexture2DArray(texture, slot) {
  14107. const textureProperties = properties.get(texture);
  14108. if (texture.version > 0 && textureProperties.__version !== texture.version) {
  14109. uploadTexture(textureProperties, texture, slot);
  14110. return;
  14111. }
  14112. state.bindTexture(_gl.TEXTURE_2D_ARRAY, textureProperties.__webglTexture, _gl.TEXTURE0 + slot);
  14113. }
  14114. function setTexture3D(texture, slot) {
  14115. const textureProperties = properties.get(texture);
  14116. if (texture.version > 0 && textureProperties.__version !== texture.version) {
  14117. uploadTexture(textureProperties, texture, slot);
  14118. return;
  14119. }
  14120. state.bindTexture(_gl.TEXTURE_3D, textureProperties.__webglTexture, _gl.TEXTURE0 + slot);
  14121. }
  14122. function setTextureCube(texture, slot) {
  14123. const textureProperties = properties.get(texture);
  14124. if (texture.version > 0 && textureProperties.__version !== texture.version) {
  14125. uploadCubeTexture(textureProperties, texture, slot);
  14126. return;
  14127. }
  14128. state.bindTexture(_gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture, _gl.TEXTURE0 + slot);
  14129. }
  14130. const wrappingToGL = {
  14131. [RepeatWrapping]: _gl.REPEAT,
  14132. [ClampToEdgeWrapping]: _gl.CLAMP_TO_EDGE,
  14133. [MirroredRepeatWrapping]: _gl.MIRRORED_REPEAT
  14134. };
  14135. const filterToGL = {
  14136. [NearestFilter]: _gl.NEAREST,
  14137. [NearestMipmapNearestFilter]: _gl.NEAREST_MIPMAP_NEAREST,
  14138. [NearestMipmapLinearFilter]: _gl.NEAREST_MIPMAP_LINEAR,
  14139. [LinearFilter]: _gl.LINEAR,
  14140. [LinearMipmapNearestFilter]: _gl.LINEAR_MIPMAP_NEAREST,
  14141. [LinearMipmapLinearFilter]: _gl.LINEAR_MIPMAP_LINEAR
  14142. };
  14143. function setTextureParameters(textureType, texture, supportsMips) {
  14144. if (supportsMips) {
  14145. _gl.texParameteri(textureType, _gl.TEXTURE_WRAP_S, wrappingToGL[texture.wrapS]);
  14146. _gl.texParameteri(textureType, _gl.TEXTURE_WRAP_T, wrappingToGL[texture.wrapT]);
  14147. if (textureType === _gl.TEXTURE_3D || textureType === _gl.TEXTURE_2D_ARRAY) {
  14148. _gl.texParameteri(textureType, _gl.TEXTURE_WRAP_R, wrappingToGL[texture.wrapR]);
  14149. }
  14150. _gl.texParameteri(textureType, _gl.TEXTURE_MAG_FILTER, filterToGL[texture.magFilter]);
  14151. _gl.texParameteri(textureType, _gl.TEXTURE_MIN_FILTER, filterToGL[texture.minFilter]);
  14152. } else {
  14153. _gl.texParameteri(textureType, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE);
  14154. _gl.texParameteri(textureType, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE);
  14155. if (textureType === _gl.TEXTURE_3D || textureType === _gl.TEXTURE_2D_ARRAY) {
  14156. _gl.texParameteri(textureType, _gl.TEXTURE_WRAP_R, _gl.CLAMP_TO_EDGE);
  14157. }
  14158. if (texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping) {
  14159. console.warn('THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping.');
  14160. }
  14161. _gl.texParameteri(textureType, _gl.TEXTURE_MAG_FILTER, filterFallback(texture.magFilter));
  14162. _gl.texParameteri(textureType, _gl.TEXTURE_MIN_FILTER, filterFallback(texture.minFilter));
  14163. if (texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter) {
  14164. console.warn('THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.');
  14165. }
  14166. }
  14167. if (extensions.has('EXT_texture_filter_anisotropic') === true) {
  14168. const extension = extensions.get('EXT_texture_filter_anisotropic');
  14169. if (texture.type === FloatType && extensions.has('OES_texture_float_linear') === false) return; // verify extension for WebGL 1 and WebGL 2
  14170. if (isWebGL2 === false && texture.type === HalfFloatType && extensions.has('OES_texture_half_float_linear') === false) return; // verify extension for WebGL 1 only
  14171. if (texture.anisotropy > 1 || properties.get(texture).__currentAnisotropy) {
  14172. _gl.texParameterf(textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(texture.anisotropy, capabilities.getMaxAnisotropy()));
  14173. properties.get(texture).__currentAnisotropy = texture.anisotropy;
  14174. }
  14175. }
  14176. }
  14177. function initTexture(textureProperties, texture) {
  14178. let forceUpload = false;
  14179. if (textureProperties.__webglInit === undefined) {
  14180. textureProperties.__webglInit = true;
  14181. texture.addEventListener('dispose', onTextureDispose);
  14182. }
  14183. // create Source <-> WebGLTextures mapping if necessary
  14184. const source = texture.source;
  14185. let webglTextures = _sources.get(source);
  14186. if (webglTextures === undefined) {
  14187. webglTextures = {};
  14188. _sources.set(source, webglTextures);
  14189. }
  14190. // check if there is already a WebGLTexture object for the given texture parameters
  14191. const textureCacheKey = getTextureCacheKey(texture);
  14192. if (textureCacheKey !== textureProperties.__cacheKey) {
  14193. // if not, create a new instance of WebGLTexture
  14194. if (webglTextures[textureCacheKey] === undefined) {
  14195. // create new entry
  14196. webglTextures[textureCacheKey] = {
  14197. texture: _gl.createTexture(),
  14198. usedTimes: 0
  14199. };
  14200. info.memory.textures++;
  14201. // when a new instance of WebGLTexture was created, a texture upload is required
  14202. // even if the image contents are identical
  14203. forceUpload = true;
  14204. }
  14205. webglTextures[textureCacheKey].usedTimes++;
  14206. // every time the texture cache key changes, it's necessary to check if an instance of
  14207. // WebGLTexture can be deleted in order to avoid a memory leak.
  14208. const webglTexture = webglTextures[textureProperties.__cacheKey];
  14209. if (webglTexture !== undefined) {
  14210. webglTextures[textureProperties.__cacheKey].usedTimes--;
  14211. if (webglTexture.usedTimes === 0) {
  14212. deleteTexture(texture);
  14213. }
  14214. }
  14215. // store references to cache key and WebGLTexture object
  14216. textureProperties.__cacheKey = textureCacheKey;
  14217. textureProperties.__webglTexture = webglTextures[textureCacheKey].texture;
  14218. }
  14219. return forceUpload;
  14220. }
  14221. function uploadTexture(textureProperties, texture, slot) {
  14222. let textureType = _gl.TEXTURE_2D;
  14223. if (texture.isDataArrayTexture || texture.isCompressedArrayTexture) textureType = _gl.TEXTURE_2D_ARRAY;
  14224. if (texture.isData3DTexture) textureType = _gl.TEXTURE_3D;
  14225. const forceUpload = initTexture(textureProperties, texture);
  14226. const source = texture.source;
  14227. state.bindTexture(textureType, textureProperties.__webglTexture, _gl.TEXTURE0 + slot);
  14228. const sourceProperties = properties.get(source);
  14229. if (source.version !== sourceProperties.__version || forceUpload === true) {
  14230. state.activeTexture(_gl.TEXTURE0 + slot);
  14231. _gl.pixelStorei(_gl.UNPACK_FLIP_Y_WEBGL, texture.flipY);
  14232. _gl.pixelStorei(_gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha);
  14233. _gl.pixelStorei(_gl.UNPACK_ALIGNMENT, texture.unpackAlignment);
  14234. _gl.pixelStorei(_gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, _gl.NONE);
  14235. const needsPowerOfTwo = textureNeedsPowerOfTwo(texture) && isPowerOfTwo$1(texture.image) === false;
  14236. let image = resizeImage(texture.image, needsPowerOfTwo, false, maxTextureSize);
  14237. image = verifyColorSpace(texture, image);
  14238. const supportsMips = isPowerOfTwo$1(image) || isWebGL2,
  14239. glFormat = utils.convert(texture.format, texture.encoding);
  14240. let glType = utils.convert(texture.type),
  14241. glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType, texture.encoding, texture.isVideoTexture);
  14242. setTextureParameters(textureType, texture, supportsMips);
  14243. let mipmap;
  14244. const mipmaps = texture.mipmaps;
  14245. const useTexStorage = isWebGL2 && texture.isVideoTexture !== true;
  14246. const allocateMemory = sourceProperties.__version === undefined || forceUpload === true;
  14247. const levels = getMipLevels(texture, image, supportsMips);
  14248. if (texture.isDepthTexture) {
  14249. // populate depth texture with dummy data
  14250. glInternalFormat = _gl.DEPTH_COMPONENT;
  14251. if (isWebGL2) {
  14252. if (texture.type === FloatType) {
  14253. glInternalFormat = _gl.DEPTH_COMPONENT32F;
  14254. } else if (texture.type === UnsignedIntType) {
  14255. glInternalFormat = _gl.DEPTH_COMPONENT24;
  14256. } else if (texture.type === UnsignedInt248Type) {
  14257. glInternalFormat = _gl.DEPTH24_STENCIL8;
  14258. } else {
  14259. glInternalFormat = _gl.DEPTH_COMPONENT16; // WebGL2 requires sized internalformat for glTexImage2D
  14260. }
  14261. } else {
  14262. if (texture.type === FloatType) {
  14263. console.error('WebGLRenderer: Floating point depth texture requires WebGL2.');
  14264. }
  14265. }
  14266. // validation checks for WebGL 1
  14267. if (texture.format === DepthFormat && glInternalFormat === _gl.DEPTH_COMPONENT) {
  14268. // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  14269. // DEPTH_COMPONENT and type is not UNSIGNED_SHORT or UNSIGNED_INT
  14270. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  14271. if (texture.type !== UnsignedShortType && texture.type !== UnsignedIntType) {
  14272. console.warn('THREE.WebGLRenderer: Use UnsignedShortType or UnsignedIntType for DepthFormat DepthTexture.');
  14273. texture.type = UnsignedIntType;
  14274. glType = utils.convert(texture.type);
  14275. }
  14276. }
  14277. if (texture.format === DepthStencilFormat && glInternalFormat === _gl.DEPTH_COMPONENT) {
  14278. // Depth stencil textures need the DEPTH_STENCIL internal format
  14279. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  14280. glInternalFormat = _gl.DEPTH_STENCIL;
  14281. // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  14282. // DEPTH_STENCIL and type is not UNSIGNED_INT_24_8_WEBGL.
  14283. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  14284. if (texture.type !== UnsignedInt248Type) {
  14285. console.warn('THREE.WebGLRenderer: Use UnsignedInt248Type for DepthStencilFormat DepthTexture.');
  14286. texture.type = UnsignedInt248Type;
  14287. glType = utils.convert(texture.type);
  14288. }
  14289. }
  14290. //
  14291. if (allocateMemory) {
  14292. if (useTexStorage) {
  14293. state.texStorage2D(_gl.TEXTURE_2D, 1, glInternalFormat, image.width, image.height);
  14294. } else {
  14295. state.texImage2D(_gl.TEXTURE_2D, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, null);
  14296. }
  14297. }
  14298. } else if (texture.isDataTexture) {
  14299. // use manually created mipmaps if available
  14300. // if there are no manual mipmaps
  14301. // set 0 level mipmap and then use GL to generate other mipmap levels
  14302. if (mipmaps.length > 0 && supportsMips) {
  14303. if (useTexStorage && allocateMemory) {
  14304. state.texStorage2D(_gl.TEXTURE_2D, levels, glInternalFormat, mipmaps[0].width, mipmaps[0].height);
  14305. }
  14306. for (let i = 0, il = mipmaps.length; i < il; i++) {
  14307. mipmap = mipmaps[i];
  14308. if (useTexStorage) {
  14309. state.texSubImage2D(_gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data);
  14310. } else {
  14311. state.texImage2D(_gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data);
  14312. }
  14313. }
  14314. texture.generateMipmaps = false;
  14315. } else {
  14316. if (useTexStorage) {
  14317. if (allocateMemory) {
  14318. state.texStorage2D(_gl.TEXTURE_2D, levels, glInternalFormat, image.width, image.height);
  14319. }
  14320. state.texSubImage2D(_gl.TEXTURE_2D, 0, 0, 0, image.width, image.height, glFormat, glType, image.data);
  14321. } else {
  14322. state.texImage2D(_gl.TEXTURE_2D, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, image.data);
  14323. }
  14324. }
  14325. } else if (texture.isCompressedTexture) {
  14326. if (texture.isCompressedArrayTexture) {
  14327. if (useTexStorage && allocateMemory) {
  14328. state.texStorage3D(_gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, mipmaps[0].width, mipmaps[0].height, image.depth);
  14329. }
  14330. for (let i = 0, il = mipmaps.length; i < il; i++) {
  14331. mipmap = mipmaps[i];
  14332. if (texture.format !== RGBAFormat) {
  14333. if (glFormat !== null) {
  14334. if (useTexStorage) {
  14335. state.compressedTexSubImage3D(_gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, mipmap.data, 0, 0);
  14336. } else {
  14337. state.compressedTexImage3D(_gl.TEXTURE_2D_ARRAY, i, glInternalFormat, mipmap.width, mipmap.height, image.depth, 0, mipmap.data, 0, 0);
  14338. }
  14339. } else {
  14340. console.warn('THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()');
  14341. }
  14342. } else {
  14343. if (useTexStorage) {
  14344. state.texSubImage3D(_gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, glType, mipmap.data);
  14345. } else {
  14346. state.texImage3D(_gl.TEXTURE_2D_ARRAY, i, glInternalFormat, mipmap.width, mipmap.height, image.depth, 0, glFormat, glType, mipmap.data);
  14347. }
  14348. }
  14349. }
  14350. } else {
  14351. if (useTexStorage && allocateMemory) {
  14352. state.texStorage2D(_gl.TEXTURE_2D, levels, glInternalFormat, mipmaps[0].width, mipmaps[0].height);
  14353. }
  14354. for (let i = 0, il = mipmaps.length; i < il; i++) {
  14355. mipmap = mipmaps[i];
  14356. if (texture.format !== RGBAFormat) {
  14357. if (glFormat !== null) {
  14358. if (useTexStorage) {
  14359. state.compressedTexSubImage2D(_gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data);
  14360. } else {
  14361. state.compressedTexImage2D(_gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data);
  14362. }
  14363. } else {
  14364. console.warn('THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()');
  14365. }
  14366. } else {
  14367. if (useTexStorage) {
  14368. state.texSubImage2D(_gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data);
  14369. } else {
  14370. state.texImage2D(_gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data);
  14371. }
  14372. }
  14373. }
  14374. }
  14375. } else if (texture.isDataArrayTexture) {
  14376. if (useTexStorage) {
  14377. if (allocateMemory) {
  14378. state.texStorage3D(_gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, image.width, image.height, image.depth);
  14379. }
  14380. state.texSubImage3D(_gl.TEXTURE_2D_ARRAY, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data);
  14381. } else {
  14382. state.texImage3D(_gl.TEXTURE_2D_ARRAY, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data);
  14383. }
  14384. } else if (texture.isData3DTexture) {
  14385. if (useTexStorage) {
  14386. if (allocateMemory) {
  14387. state.texStorage3D(_gl.TEXTURE_3D, levels, glInternalFormat, image.width, image.height, image.depth);
  14388. }
  14389. state.texSubImage3D(_gl.TEXTURE_3D, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data);
  14390. } else {
  14391. state.texImage3D(_gl.TEXTURE_3D, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data);
  14392. }
  14393. } else if (texture.isFramebufferTexture) {
  14394. if (allocateMemory) {
  14395. if (useTexStorage) {
  14396. state.texStorage2D(_gl.TEXTURE_2D, levels, glInternalFormat, image.width, image.height);
  14397. } else {
  14398. let width = image.width,
  14399. height = image.height;
  14400. for (let i = 0; i < levels; i++) {
  14401. state.texImage2D(_gl.TEXTURE_2D, i, glInternalFormat, width, height, 0, glFormat, glType, null);
  14402. width >>= 1;
  14403. height >>= 1;
  14404. }
  14405. }
  14406. }
  14407. } else {
  14408. // regular Texture (image, video, canvas)
  14409. // use manually created mipmaps if available
  14410. // if there are no manual mipmaps
  14411. // set 0 level mipmap and then use GL to generate other mipmap levels
  14412. if (mipmaps.length > 0 && supportsMips) {
  14413. if (useTexStorage && allocateMemory) {
  14414. state.texStorage2D(_gl.TEXTURE_2D, levels, glInternalFormat, mipmaps[0].width, mipmaps[0].height);
  14415. }
  14416. for (let i = 0, il = mipmaps.length; i < il; i++) {
  14417. mipmap = mipmaps[i];
  14418. if (useTexStorage) {
  14419. state.texSubImage2D(_gl.TEXTURE_2D, i, 0, 0, glFormat, glType, mipmap);
  14420. } else {
  14421. state.texImage2D(_gl.TEXTURE_2D, i, glInternalFormat, glFormat, glType, mipmap);
  14422. }
  14423. }
  14424. texture.generateMipmaps = false;
  14425. } else {
  14426. if (useTexStorage) {
  14427. if (allocateMemory) {
  14428. state.texStorage2D(_gl.TEXTURE_2D, levels, glInternalFormat, image.width, image.height);
  14429. }
  14430. state.texSubImage2D(_gl.TEXTURE_2D, 0, 0, 0, glFormat, glType, image);
  14431. } else {
  14432. state.texImage2D(_gl.TEXTURE_2D, 0, glInternalFormat, glFormat, glType, image);
  14433. }
  14434. }
  14435. }
  14436. if (textureNeedsGenerateMipmaps(texture, supportsMips)) {
  14437. generateMipmap(textureType);
  14438. }
  14439. sourceProperties.__version = source.version;
  14440. if (texture.onUpdate) texture.onUpdate(texture);
  14441. }
  14442. textureProperties.__version = texture.version;
  14443. }
  14444. function uploadCubeTexture(textureProperties, texture, slot) {
  14445. if (texture.image.length !== 6) return;
  14446. const forceUpload = initTexture(textureProperties, texture);
  14447. const source = texture.source;
  14448. state.bindTexture(_gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture, _gl.TEXTURE0 + slot);
  14449. const sourceProperties = properties.get(source);
  14450. if (source.version !== sourceProperties.__version || forceUpload === true) {
  14451. state.activeTexture(_gl.TEXTURE0 + slot);
  14452. _gl.pixelStorei(_gl.UNPACK_FLIP_Y_WEBGL, texture.flipY);
  14453. _gl.pixelStorei(_gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha);
  14454. _gl.pixelStorei(_gl.UNPACK_ALIGNMENT, texture.unpackAlignment);
  14455. _gl.pixelStorei(_gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, _gl.NONE);
  14456. const isCompressed = texture.isCompressedTexture || texture.image[0].isCompressedTexture;
  14457. const isDataTexture = texture.image[0] && texture.image[0].isDataTexture;
  14458. const cubeImage = [];
  14459. for (let i = 0; i < 6; i++) {
  14460. if (!isCompressed && !isDataTexture) {
  14461. cubeImage[i] = resizeImage(texture.image[i], false, true, maxCubemapSize);
  14462. } else {
  14463. cubeImage[i] = isDataTexture ? texture.image[i].image : texture.image[i];
  14464. }
  14465. cubeImage[i] = verifyColorSpace(texture, cubeImage[i]);
  14466. }
  14467. const image = cubeImage[0],
  14468. supportsMips = isPowerOfTwo$1(image) || isWebGL2,
  14469. glFormat = utils.convert(texture.format, texture.encoding),
  14470. glType = utils.convert(texture.type),
  14471. glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType, texture.encoding);
  14472. const useTexStorage = isWebGL2 && texture.isVideoTexture !== true;
  14473. const allocateMemory = sourceProperties.__version === undefined || forceUpload === true;
  14474. let levels = getMipLevels(texture, image, supportsMips);
  14475. setTextureParameters(_gl.TEXTURE_CUBE_MAP, texture, supportsMips);
  14476. let mipmaps;
  14477. if (isCompressed) {
  14478. if (useTexStorage && allocateMemory) {
  14479. state.texStorage2D(_gl.TEXTURE_CUBE_MAP, levels, glInternalFormat, image.width, image.height);
  14480. }
  14481. for (let i = 0; i < 6; i++) {
  14482. mipmaps = cubeImage[i].mipmaps;
  14483. for (let j = 0; j < mipmaps.length; j++) {
  14484. const mipmap = mipmaps[j];
  14485. if (texture.format !== RGBAFormat) {
  14486. if (glFormat !== null) {
  14487. if (useTexStorage) {
  14488. state.compressedTexSubImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data);
  14489. } else {
  14490. state.compressedTexImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data);
  14491. }
  14492. } else {
  14493. console.warn('THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()');
  14494. }
  14495. } else {
  14496. if (useTexStorage) {
  14497. state.texSubImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data);
  14498. } else {
  14499. state.texImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data);
  14500. }
  14501. }
  14502. }
  14503. }
  14504. } else {
  14505. mipmaps = texture.mipmaps;
  14506. if (useTexStorage && allocateMemory) {
  14507. // TODO: Uniformly handle mipmap definitions
  14508. // Normal textures and compressed cube textures define base level + mips with their mipmap array
  14509. // Uncompressed cube textures use their mipmap array only for mips (no base level)
  14510. if (mipmaps.length > 0) levels++;
  14511. state.texStorage2D(_gl.TEXTURE_CUBE_MAP, levels, glInternalFormat, cubeImage[0].width, cubeImage[0].height);
  14512. }
  14513. for (let i = 0; i < 6; i++) {
  14514. if (isDataTexture) {
  14515. if (useTexStorage) {
  14516. state.texSubImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, cubeImage[i].width, cubeImage[i].height, glFormat, glType, cubeImage[i].data);
  14517. } else {
  14518. state.texImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glInternalFormat, cubeImage[i].width, cubeImage[i].height, 0, glFormat, glType, cubeImage[i].data);
  14519. }
  14520. for (let j = 0; j < mipmaps.length; j++) {
  14521. const mipmap = mipmaps[j];
  14522. const mipmapImage = mipmap.image[i].image;
  14523. if (useTexStorage) {
  14524. state.texSubImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, 0, 0, mipmapImage.width, mipmapImage.height, glFormat, glType, mipmapImage.data);
  14525. } else {
  14526. state.texImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, glInternalFormat, mipmapImage.width, mipmapImage.height, 0, glFormat, glType, mipmapImage.data);
  14527. }
  14528. }
  14529. } else {
  14530. if (useTexStorage) {
  14531. state.texSubImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, glFormat, glType, cubeImage[i]);
  14532. } else {
  14533. state.texImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glInternalFormat, glFormat, glType, cubeImage[i]);
  14534. }
  14535. for (let j = 0; j < mipmaps.length; j++) {
  14536. const mipmap = mipmaps[j];
  14537. if (useTexStorage) {
  14538. state.texSubImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, 0, 0, glFormat, glType, mipmap.image[i]);
  14539. } else {
  14540. state.texImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, glInternalFormat, glFormat, glType, mipmap.image[i]);
  14541. }
  14542. }
  14543. }
  14544. }
  14545. }
  14546. if (textureNeedsGenerateMipmaps(texture, supportsMips)) {
  14547. // We assume images for cube map have the same size.
  14548. generateMipmap(_gl.TEXTURE_CUBE_MAP);
  14549. }
  14550. sourceProperties.__version = source.version;
  14551. if (texture.onUpdate) texture.onUpdate(texture);
  14552. }
  14553. textureProperties.__version = texture.version;
  14554. }
  14555. // Render targets
  14556. // Setup storage for target texture and bind it to correct framebuffer
  14557. function setupFrameBufferTexture(framebuffer, renderTarget, texture, attachment, textureTarget) {
  14558. const glFormat = utils.convert(texture.format, texture.encoding);
  14559. const glType = utils.convert(texture.type);
  14560. const glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType, texture.encoding);
  14561. const renderTargetProperties = properties.get(renderTarget);
  14562. if (!renderTargetProperties.__hasExternalTextures) {
  14563. if (textureTarget === _gl.TEXTURE_3D || textureTarget === _gl.TEXTURE_2D_ARRAY) {
  14564. state.texImage3D(textureTarget, 0, glInternalFormat, renderTarget.width, renderTarget.height, renderTarget.depth, 0, glFormat, glType, null);
  14565. } else {
  14566. state.texImage2D(textureTarget, 0, glInternalFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null);
  14567. }
  14568. }
  14569. state.bindFramebuffer(_gl.FRAMEBUFFER, framebuffer);
  14570. if (useMultisampledRTT(renderTarget)) {
  14571. multisampledRTTExt.framebufferTexture2DMultisampleEXT(_gl.FRAMEBUFFER, attachment, textureTarget, properties.get(texture).__webglTexture, 0, getRenderTargetSamples(renderTarget));
  14572. } else if (textureTarget === _gl.TEXTURE_2D || textureTarget >= _gl.TEXTURE_CUBE_MAP_POSITIVE_X && textureTarget <= _gl.TEXTURE_CUBE_MAP_NEGATIVE_Z) {
  14573. // see #24753
  14574. _gl.framebufferTexture2D(_gl.FRAMEBUFFER, attachment, textureTarget, properties.get(texture).__webglTexture, 0);
  14575. }
  14576. state.bindFramebuffer(_gl.FRAMEBUFFER, null);
  14577. }
  14578. // Setup storage for internal depth/stencil buffers and bind to correct framebuffer
  14579. function setupRenderBufferStorage(renderbuffer, renderTarget, isMultisample) {
  14580. _gl.bindRenderbuffer(_gl.RENDERBUFFER, renderbuffer);
  14581. if (renderTarget.depthBuffer && !renderTarget.stencilBuffer) {
  14582. let glInternalFormat = _gl.DEPTH_COMPONENT16;
  14583. if (isMultisample || useMultisampledRTT(renderTarget)) {
  14584. const depthTexture = renderTarget.depthTexture;
  14585. if (depthTexture && depthTexture.isDepthTexture) {
  14586. if (depthTexture.type === FloatType) {
  14587. glInternalFormat = _gl.DEPTH_COMPONENT32F;
  14588. } else if (depthTexture.type === UnsignedIntType) {
  14589. glInternalFormat = _gl.DEPTH_COMPONENT24;
  14590. }
  14591. }
  14592. const samples = getRenderTargetSamples(renderTarget);
  14593. if (useMultisampledRTT(renderTarget)) {
  14594. multisampledRTTExt.renderbufferStorageMultisampleEXT(_gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height);
  14595. } else {
  14596. _gl.renderbufferStorageMultisample(_gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height);
  14597. }
  14598. } else {
  14599. _gl.renderbufferStorage(_gl.RENDERBUFFER, glInternalFormat, renderTarget.width, renderTarget.height);
  14600. }
  14601. _gl.framebufferRenderbuffer(_gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer);
  14602. } else if (renderTarget.depthBuffer && renderTarget.stencilBuffer) {
  14603. const samples = getRenderTargetSamples(renderTarget);
  14604. if (isMultisample && useMultisampledRTT(renderTarget) === false) {
  14605. _gl.renderbufferStorageMultisample(_gl.RENDERBUFFER, samples, _gl.DEPTH24_STENCIL8, renderTarget.width, renderTarget.height);
  14606. } else if (useMultisampledRTT(renderTarget)) {
  14607. multisampledRTTExt.renderbufferStorageMultisampleEXT(_gl.RENDERBUFFER, samples, _gl.DEPTH24_STENCIL8, renderTarget.width, renderTarget.height);
  14608. } else {
  14609. _gl.renderbufferStorage(_gl.RENDERBUFFER, _gl.DEPTH_STENCIL, renderTarget.width, renderTarget.height);
  14610. }
  14611. _gl.framebufferRenderbuffer(_gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer);
  14612. } else {
  14613. const textures = renderTarget.isWebGLMultipleRenderTargets === true ? renderTarget.texture : [renderTarget.texture];
  14614. for (let i = 0; i < textures.length; i++) {
  14615. const texture = textures[i];
  14616. const glFormat = utils.convert(texture.format, texture.encoding);
  14617. const glType = utils.convert(texture.type);
  14618. const glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType, texture.encoding);
  14619. const samples = getRenderTargetSamples(renderTarget);
  14620. if (isMultisample && useMultisampledRTT(renderTarget) === false) {
  14621. _gl.renderbufferStorageMultisample(_gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height);
  14622. } else if (useMultisampledRTT(renderTarget)) {
  14623. multisampledRTTExt.renderbufferStorageMultisampleEXT(_gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height);
  14624. } else {
  14625. _gl.renderbufferStorage(_gl.RENDERBUFFER, glInternalFormat, renderTarget.width, renderTarget.height);
  14626. }
  14627. }
  14628. }
  14629. _gl.bindRenderbuffer(_gl.RENDERBUFFER, null);
  14630. }
  14631. // Setup resources for a Depth Texture for a FBO (needs an extension)
  14632. function setupDepthTexture(framebuffer, renderTarget) {
  14633. const isCube = renderTarget && renderTarget.isWebGLCubeRenderTarget;
  14634. if (isCube) throw new Error('Depth Texture with cube render targets is not supported');
  14635. state.bindFramebuffer(_gl.FRAMEBUFFER, framebuffer);
  14636. if (!(renderTarget.depthTexture && renderTarget.depthTexture.isDepthTexture)) {
  14637. throw new Error('renderTarget.depthTexture must be an instance of THREE.DepthTexture');
  14638. }
  14639. // upload an empty depth texture with framebuffer size
  14640. if (!properties.get(renderTarget.depthTexture).__webglTexture || renderTarget.depthTexture.image.width !== renderTarget.width || renderTarget.depthTexture.image.height !== renderTarget.height) {
  14641. renderTarget.depthTexture.image.width = renderTarget.width;
  14642. renderTarget.depthTexture.image.height = renderTarget.height;
  14643. renderTarget.depthTexture.needsUpdate = true;
  14644. }
  14645. setTexture2D(renderTarget.depthTexture, 0);
  14646. const webglDepthTexture = properties.get(renderTarget.depthTexture).__webglTexture;
  14647. const samples = getRenderTargetSamples(renderTarget);
  14648. if (renderTarget.depthTexture.format === DepthFormat) {
  14649. if (useMultisampledRTT(renderTarget)) {
  14650. multisampledRTTExt.framebufferTexture2DMultisampleEXT(_gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0, samples);
  14651. } else {
  14652. _gl.framebufferTexture2D(_gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0);
  14653. }
  14654. } else if (renderTarget.depthTexture.format === DepthStencilFormat) {
  14655. if (useMultisampledRTT(renderTarget)) {
  14656. multisampledRTTExt.framebufferTexture2DMultisampleEXT(_gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0, samples);
  14657. } else {
  14658. _gl.framebufferTexture2D(_gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0);
  14659. }
  14660. } else {
  14661. throw new Error('Unknown depthTexture format');
  14662. }
  14663. }
  14664. // Setup GL resources for a non-texture depth buffer
  14665. function setupDepthRenderbuffer(renderTarget) {
  14666. const renderTargetProperties = properties.get(renderTarget);
  14667. const isCube = renderTarget.isWebGLCubeRenderTarget === true;
  14668. if (renderTarget.depthTexture && !renderTargetProperties.__autoAllocateDepthBuffer) {
  14669. if (isCube) throw new Error('target.depthTexture not supported in Cube render targets');
  14670. setupDepthTexture(renderTargetProperties.__webglFramebuffer, renderTarget);
  14671. } else {
  14672. if (isCube) {
  14673. renderTargetProperties.__webglDepthbuffer = [];
  14674. for (let i = 0; i < 6; i++) {
  14675. state.bindFramebuffer(_gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer[i]);
  14676. renderTargetProperties.__webglDepthbuffer[i] = _gl.createRenderbuffer();
  14677. setupRenderBufferStorage(renderTargetProperties.__webglDepthbuffer[i], renderTarget, false);
  14678. }
  14679. } else {
  14680. state.bindFramebuffer(_gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer);
  14681. renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer();
  14682. setupRenderBufferStorage(renderTargetProperties.__webglDepthbuffer, renderTarget, false);
  14683. }
  14684. }
  14685. state.bindFramebuffer(_gl.FRAMEBUFFER, null);
  14686. }
  14687. // rebind framebuffer with external textures
  14688. function rebindTextures(renderTarget, colorTexture, depthTexture) {
  14689. const renderTargetProperties = properties.get(renderTarget);
  14690. if (colorTexture !== undefined) {
  14691. setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer, renderTarget, renderTarget.texture, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D);
  14692. }
  14693. if (depthTexture !== undefined) {
  14694. setupDepthRenderbuffer(renderTarget);
  14695. }
  14696. }
  14697. // Set up GL resources for the render target
  14698. function setupRenderTarget(renderTarget) {
  14699. const texture = renderTarget.texture;
  14700. const renderTargetProperties = properties.get(renderTarget);
  14701. const textureProperties = properties.get(texture);
  14702. renderTarget.addEventListener('dispose', onRenderTargetDispose);
  14703. if (renderTarget.isWebGLMultipleRenderTargets !== true) {
  14704. if (textureProperties.__webglTexture === undefined) {
  14705. textureProperties.__webglTexture = _gl.createTexture();
  14706. }
  14707. textureProperties.__version = texture.version;
  14708. info.memory.textures++;
  14709. }
  14710. const isCube = renderTarget.isWebGLCubeRenderTarget === true;
  14711. const isMultipleRenderTargets = renderTarget.isWebGLMultipleRenderTargets === true;
  14712. const supportsMips = isPowerOfTwo$1(renderTarget) || isWebGL2;
  14713. // Setup framebuffer
  14714. if (isCube) {
  14715. renderTargetProperties.__webglFramebuffer = [];
  14716. for (let i = 0; i < 6; i++) {
  14717. renderTargetProperties.__webglFramebuffer[i] = _gl.createFramebuffer();
  14718. }
  14719. } else {
  14720. renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer();
  14721. if (isMultipleRenderTargets) {
  14722. if (capabilities.drawBuffers) {
  14723. const textures = renderTarget.texture;
  14724. for (let i = 0, il = textures.length; i < il; i++) {
  14725. const attachmentProperties = properties.get(textures[i]);
  14726. if (attachmentProperties.__webglTexture === undefined) {
  14727. attachmentProperties.__webglTexture = _gl.createTexture();
  14728. info.memory.textures++;
  14729. }
  14730. }
  14731. } else {
  14732. console.warn('THREE.WebGLRenderer: WebGLMultipleRenderTargets can only be used with WebGL2 or WEBGL_draw_buffers extension.');
  14733. }
  14734. }
  14735. if (isWebGL2 && renderTarget.samples > 0 && useMultisampledRTT(renderTarget) === false) {
  14736. const textures = isMultipleRenderTargets ? texture : [texture];
  14737. renderTargetProperties.__webglMultisampledFramebuffer = _gl.createFramebuffer();
  14738. renderTargetProperties.__webglColorRenderbuffer = [];
  14739. state.bindFramebuffer(_gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer);
  14740. for (let i = 0; i < textures.length; i++) {
  14741. const texture = textures[i];
  14742. renderTargetProperties.__webglColorRenderbuffer[i] = _gl.createRenderbuffer();
  14743. _gl.bindRenderbuffer(_gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[i]);
  14744. const glFormat = utils.convert(texture.format, texture.encoding);
  14745. const glType = utils.convert(texture.type);
  14746. const glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType, texture.encoding, renderTarget.isXRRenderTarget === true);
  14747. const samples = getRenderTargetSamples(renderTarget);
  14748. _gl.renderbufferStorageMultisample(_gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height);
  14749. _gl.framebufferRenderbuffer(_gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[i]);
  14750. }
  14751. _gl.bindRenderbuffer(_gl.RENDERBUFFER, null);
  14752. if (renderTarget.depthBuffer) {
  14753. renderTargetProperties.__webglDepthRenderbuffer = _gl.createRenderbuffer();
  14754. setupRenderBufferStorage(renderTargetProperties.__webglDepthRenderbuffer, renderTarget, true);
  14755. }
  14756. state.bindFramebuffer(_gl.FRAMEBUFFER, null);
  14757. }
  14758. }
  14759. // Setup color buffer
  14760. if (isCube) {
  14761. state.bindTexture(_gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture);
  14762. setTextureParameters(_gl.TEXTURE_CUBE_MAP, texture, supportsMips);
  14763. for (let i = 0; i < 6; i++) {
  14764. setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer[i], renderTarget, texture, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i);
  14765. }
  14766. if (textureNeedsGenerateMipmaps(texture, supportsMips)) {
  14767. generateMipmap(_gl.TEXTURE_CUBE_MAP);
  14768. }
  14769. state.unbindTexture();
  14770. } else if (isMultipleRenderTargets) {
  14771. const textures = renderTarget.texture;
  14772. for (let i = 0, il = textures.length; i < il; i++) {
  14773. const attachment = textures[i];
  14774. const attachmentProperties = properties.get(attachment);
  14775. state.bindTexture(_gl.TEXTURE_2D, attachmentProperties.__webglTexture);
  14776. setTextureParameters(_gl.TEXTURE_2D, attachment, supportsMips);
  14777. setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer, renderTarget, attachment, _gl.COLOR_ATTACHMENT0 + i, _gl.TEXTURE_2D);
  14778. if (textureNeedsGenerateMipmaps(attachment, supportsMips)) {
  14779. generateMipmap(_gl.TEXTURE_2D);
  14780. }
  14781. }
  14782. state.unbindTexture();
  14783. } else {
  14784. let glTextureType = _gl.TEXTURE_2D;
  14785. if (renderTarget.isWebGL3DRenderTarget || renderTarget.isWebGLArrayRenderTarget) {
  14786. if (isWebGL2) {
  14787. glTextureType = renderTarget.isWebGL3DRenderTarget ? _gl.TEXTURE_3D : _gl.TEXTURE_2D_ARRAY;
  14788. } else {
  14789. console.error('THREE.WebGLTextures: THREE.Data3DTexture and THREE.DataArrayTexture only supported with WebGL2.');
  14790. }
  14791. }
  14792. state.bindTexture(glTextureType, textureProperties.__webglTexture);
  14793. setTextureParameters(glTextureType, texture, supportsMips);
  14794. setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer, renderTarget, texture, _gl.COLOR_ATTACHMENT0, glTextureType);
  14795. if (textureNeedsGenerateMipmaps(texture, supportsMips)) {
  14796. generateMipmap(glTextureType);
  14797. }
  14798. state.unbindTexture();
  14799. }
  14800. // Setup depth and stencil buffers
  14801. if (renderTarget.depthBuffer) {
  14802. setupDepthRenderbuffer(renderTarget);
  14803. }
  14804. }
  14805. function updateRenderTargetMipmap(renderTarget) {
  14806. const supportsMips = isPowerOfTwo$1(renderTarget) || isWebGL2;
  14807. const textures = renderTarget.isWebGLMultipleRenderTargets === true ? renderTarget.texture : [renderTarget.texture];
  14808. for (let i = 0, il = textures.length; i < il; i++) {
  14809. const texture = textures[i];
  14810. if (textureNeedsGenerateMipmaps(texture, supportsMips)) {
  14811. const target = renderTarget.isWebGLCubeRenderTarget ? _gl.TEXTURE_CUBE_MAP : _gl.TEXTURE_2D;
  14812. const webglTexture = properties.get(texture).__webglTexture;
  14813. state.bindTexture(target, webglTexture);
  14814. generateMipmap(target);
  14815. state.unbindTexture();
  14816. }
  14817. }
  14818. }
  14819. function updateMultisampleRenderTarget(renderTarget) {
  14820. if (isWebGL2 && renderTarget.samples > 0 && useMultisampledRTT(renderTarget) === false) {
  14821. const textures = renderTarget.isWebGLMultipleRenderTargets ? renderTarget.texture : [renderTarget.texture];
  14822. const width = renderTarget.width;
  14823. const height = renderTarget.height;
  14824. let mask = _gl.COLOR_BUFFER_BIT;
  14825. const invalidationArray = [];
  14826. const depthStyle = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT;
  14827. const renderTargetProperties = properties.get(renderTarget);
  14828. const isMultipleRenderTargets = renderTarget.isWebGLMultipleRenderTargets === true;
  14829. // If MRT we need to remove FBO attachments
  14830. if (isMultipleRenderTargets) {
  14831. for (let i = 0; i < textures.length; i++) {
  14832. state.bindFramebuffer(_gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer);
  14833. _gl.framebufferRenderbuffer(_gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.RENDERBUFFER, null);
  14834. state.bindFramebuffer(_gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer);
  14835. _gl.framebufferTexture2D(_gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.TEXTURE_2D, null, 0);
  14836. }
  14837. }
  14838. state.bindFramebuffer(_gl.READ_FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer);
  14839. state.bindFramebuffer(_gl.DRAW_FRAMEBUFFER, renderTargetProperties.__webglFramebuffer);
  14840. for (let i = 0; i < textures.length; i++) {
  14841. invalidationArray.push(_gl.COLOR_ATTACHMENT0 + i);
  14842. if (renderTarget.depthBuffer) {
  14843. invalidationArray.push(depthStyle);
  14844. }
  14845. const ignoreDepthValues = renderTargetProperties.__ignoreDepthValues !== undefined ? renderTargetProperties.__ignoreDepthValues : false;
  14846. if (ignoreDepthValues === false) {
  14847. if (renderTarget.depthBuffer) mask |= _gl.DEPTH_BUFFER_BIT;
  14848. if (renderTarget.stencilBuffer) mask |= _gl.STENCIL_BUFFER_BIT;
  14849. }
  14850. if (isMultipleRenderTargets) {
  14851. _gl.framebufferRenderbuffer(_gl.READ_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[i]);
  14852. }
  14853. if (ignoreDepthValues === true) {
  14854. _gl.invalidateFramebuffer(_gl.READ_FRAMEBUFFER, [depthStyle]);
  14855. _gl.invalidateFramebuffer(_gl.DRAW_FRAMEBUFFER, [depthStyle]);
  14856. }
  14857. if (isMultipleRenderTargets) {
  14858. const webglTexture = properties.get(textures[i]).__webglTexture;
  14859. _gl.framebufferTexture2D(_gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, webglTexture, 0);
  14860. }
  14861. _gl.blitFramebuffer(0, 0, width, height, 0, 0, width, height, mask, _gl.NEAREST);
  14862. if (supportsInvalidateFramebuffer) {
  14863. _gl.invalidateFramebuffer(_gl.READ_FRAMEBUFFER, invalidationArray);
  14864. }
  14865. }
  14866. state.bindFramebuffer(_gl.READ_FRAMEBUFFER, null);
  14867. state.bindFramebuffer(_gl.DRAW_FRAMEBUFFER, null);
  14868. // If MRT since pre-blit we removed the FBO we need to reconstruct the attachments
  14869. if (isMultipleRenderTargets) {
  14870. for (let i = 0; i < textures.length; i++) {
  14871. state.bindFramebuffer(_gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer);
  14872. _gl.framebufferRenderbuffer(_gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[i]);
  14873. const webglTexture = properties.get(textures[i]).__webglTexture;
  14874. state.bindFramebuffer(_gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer);
  14875. _gl.framebufferTexture2D(_gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.TEXTURE_2D, webglTexture, 0);
  14876. }
  14877. }
  14878. state.bindFramebuffer(_gl.DRAW_FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer);
  14879. }
  14880. }
  14881. function getRenderTargetSamples(renderTarget) {
  14882. return Math.min(maxSamples, renderTarget.samples);
  14883. }
  14884. function useMultisampledRTT(renderTarget) {
  14885. const renderTargetProperties = properties.get(renderTarget);
  14886. return isWebGL2 && renderTarget.samples > 0 && extensions.has('WEBGL_multisampled_render_to_texture') === true && renderTargetProperties.__useRenderToTexture !== false;
  14887. }
  14888. function updateVideoTexture(texture) {
  14889. const frame = info.render.frame;
  14890. // Check the last frame we updated the VideoTexture
  14891. if (_videoTextures.get(texture) !== frame) {
  14892. _videoTextures.set(texture, frame);
  14893. texture.update();
  14894. }
  14895. }
  14896. function verifyColorSpace(texture, image) {
  14897. const encoding = texture.encoding;
  14898. const format = texture.format;
  14899. const type = texture.type;
  14900. if (texture.isCompressedTexture === true || texture.isVideoTexture === true || texture.format === _SRGBAFormat) return image;
  14901. if (encoding !== LinearEncoding) {
  14902. // sRGB
  14903. if (encoding === sRGBEncoding) {
  14904. if (isWebGL2 === false) {
  14905. // in WebGL 1, try to use EXT_sRGB extension and unsized formats
  14906. if (extensions.has('EXT_sRGB') === true && format === RGBAFormat) {
  14907. texture.format = _SRGBAFormat;
  14908. // it's not possible to generate mips in WebGL 1 with this extension
  14909. texture.minFilter = LinearFilter;
  14910. texture.generateMipmaps = false;
  14911. } else {
  14912. // slow fallback (CPU decode)
  14913. image = ImageUtils.sRGBToLinear(image);
  14914. }
  14915. } else {
  14916. // in WebGL 2 uncompressed textures can only be sRGB encoded if they have the RGBA8 format
  14917. if (format !== RGBAFormat || type !== UnsignedByteType) {
  14918. console.warn('THREE.WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType.');
  14919. }
  14920. }
  14921. } else {
  14922. console.error('THREE.WebGLTextures: Unsupported texture encoding:', encoding);
  14923. }
  14924. }
  14925. return image;
  14926. }
  14927. //
  14928. this.allocateTextureUnit = allocateTextureUnit;
  14929. this.resetTextureUnits = resetTextureUnits;
  14930. this.setTexture2D = setTexture2D;
  14931. this.setTexture2DArray = setTexture2DArray;
  14932. this.setTexture3D = setTexture3D;
  14933. this.setTextureCube = setTextureCube;
  14934. this.rebindTextures = rebindTextures;
  14935. this.setupRenderTarget = setupRenderTarget;
  14936. this.updateRenderTargetMipmap = updateRenderTargetMipmap;
  14937. this.updateMultisampleRenderTarget = updateMultisampleRenderTarget;
  14938. this.setupDepthRenderbuffer = setupDepthRenderbuffer;
  14939. this.setupFrameBufferTexture = setupFrameBufferTexture;
  14940. this.useMultisampledRTT = useMultisampledRTT;
  14941. }
  14942. function WebGLUtils(gl, extensions, capabilities) {
  14943. const isWebGL2 = capabilities.isWebGL2;
  14944. function convert(p, encoding = null) {
  14945. let extension;
  14946. if (p === UnsignedByteType) return gl.UNSIGNED_BYTE;
  14947. if (p === UnsignedShort4444Type) return gl.UNSIGNED_SHORT_4_4_4_4;
  14948. if (p === UnsignedShort5551Type) return gl.UNSIGNED_SHORT_5_5_5_1;
  14949. if (p === ByteType) return gl.BYTE;
  14950. if (p === ShortType) return gl.SHORT;
  14951. if (p === UnsignedShortType) return gl.UNSIGNED_SHORT;
  14952. if (p === IntType) return gl.INT;
  14953. if (p === UnsignedIntType) return gl.UNSIGNED_INT;
  14954. if (p === FloatType) return gl.FLOAT;
  14955. if (p === HalfFloatType) {
  14956. if (isWebGL2) return gl.HALF_FLOAT;
  14957. extension = extensions.get('OES_texture_half_float');
  14958. if (extension !== null) {
  14959. return extension.HALF_FLOAT_OES;
  14960. } else {
  14961. return null;
  14962. }
  14963. }
  14964. if (p === AlphaFormat) return gl.ALPHA;
  14965. if (p === RGBAFormat) return gl.RGBA;
  14966. if (p === LuminanceFormat) return gl.LUMINANCE;
  14967. if (p === LuminanceAlphaFormat) return gl.LUMINANCE_ALPHA;
  14968. if (p === DepthFormat) return gl.DEPTH_COMPONENT;
  14969. if (p === DepthStencilFormat) return gl.DEPTH_STENCIL;
  14970. // @deprecated since r137
  14971. if (p === RGBFormat) {
  14972. console.warn('THREE.WebGLRenderer: THREE.RGBFormat has been removed. Use THREE.RGBAFormat instead. https://github.com/mrdoob/three.js/pull/23228');
  14973. return gl.RGBA;
  14974. }
  14975. // WebGL 1 sRGB fallback
  14976. if (p === _SRGBAFormat) {
  14977. extension = extensions.get('EXT_sRGB');
  14978. if (extension !== null) {
  14979. return extension.SRGB_ALPHA_EXT;
  14980. } else {
  14981. return null;
  14982. }
  14983. }
  14984. // WebGL2 formats.
  14985. if (p === RedFormat) return gl.RED;
  14986. if (p === RedIntegerFormat) return gl.RED_INTEGER;
  14987. if (p === RGFormat) return gl.RG;
  14988. if (p === RGIntegerFormat) return gl.RG_INTEGER;
  14989. if (p === RGBAIntegerFormat) return gl.RGBA_INTEGER;
  14990. // S3TC
  14991. if (p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format) {
  14992. if (encoding === sRGBEncoding) {
  14993. extension = extensions.get('WEBGL_compressed_texture_s3tc_srgb');
  14994. if (extension !== null) {
  14995. if (p === RGB_S3TC_DXT1_Format) return extension.COMPRESSED_SRGB_S3TC_DXT1_EXT;
  14996. if (p === RGBA_S3TC_DXT1_Format) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;
  14997. if (p === RGBA_S3TC_DXT3_Format) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;
  14998. if (p === RGBA_S3TC_DXT5_Format) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT;
  14999. } else {
  15000. return null;
  15001. }
  15002. } else {
  15003. extension = extensions.get('WEBGL_compressed_texture_s3tc');
  15004. if (extension !== null) {
  15005. if (p === RGB_S3TC_DXT1_Format) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  15006. if (p === RGBA_S3TC_DXT1_Format) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  15007. if (p === RGBA_S3TC_DXT3_Format) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  15008. if (p === RGBA_S3TC_DXT5_Format) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  15009. } else {
  15010. return null;
  15011. }
  15012. }
  15013. }
  15014. // PVRTC
  15015. if (p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format) {
  15016. extension = extensions.get('WEBGL_compressed_texture_pvrtc');
  15017. if (extension !== null) {
  15018. if (p === RGB_PVRTC_4BPPV1_Format) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  15019. if (p === RGB_PVRTC_2BPPV1_Format) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  15020. if (p === RGBA_PVRTC_4BPPV1_Format) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  15021. if (p === RGBA_PVRTC_2BPPV1_Format) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  15022. } else {
  15023. return null;
  15024. }
  15025. }
  15026. // ETC1
  15027. if (p === RGB_ETC1_Format) {
  15028. extension = extensions.get('WEBGL_compressed_texture_etc1');
  15029. if (extension !== null) {
  15030. return extension.COMPRESSED_RGB_ETC1_WEBGL;
  15031. } else {
  15032. return null;
  15033. }
  15034. }
  15035. // ETC2
  15036. if (p === RGB_ETC2_Format || p === RGBA_ETC2_EAC_Format) {
  15037. extension = extensions.get('WEBGL_compressed_texture_etc');
  15038. if (extension !== null) {
  15039. if (p === RGB_ETC2_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB8_ETC2 : extension.COMPRESSED_RGB8_ETC2;
  15040. if (p === RGBA_ETC2_EAC_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC : extension.COMPRESSED_RGBA8_ETC2_EAC;
  15041. } else {
  15042. return null;
  15043. }
  15044. }
  15045. // ASTC
  15046. 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) {
  15047. extension = extensions.get('WEBGL_compressed_texture_astc');
  15048. if (extension !== null) {
  15049. if (p === RGBA_ASTC_4x4_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR : extension.COMPRESSED_RGBA_ASTC_4x4_KHR;
  15050. if (p === RGBA_ASTC_5x4_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR : extension.COMPRESSED_RGBA_ASTC_5x4_KHR;
  15051. if (p === RGBA_ASTC_5x5_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR : extension.COMPRESSED_RGBA_ASTC_5x5_KHR;
  15052. if (p === RGBA_ASTC_6x5_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR : extension.COMPRESSED_RGBA_ASTC_6x5_KHR;
  15053. if (p === RGBA_ASTC_6x6_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR : extension.COMPRESSED_RGBA_ASTC_6x6_KHR;
  15054. if (p === RGBA_ASTC_8x5_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR : extension.COMPRESSED_RGBA_ASTC_8x5_KHR;
  15055. if (p === RGBA_ASTC_8x6_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR : extension.COMPRESSED_RGBA_ASTC_8x6_KHR;
  15056. if (p === RGBA_ASTC_8x8_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR : extension.COMPRESSED_RGBA_ASTC_8x8_KHR;
  15057. if (p === RGBA_ASTC_10x5_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR : extension.COMPRESSED_RGBA_ASTC_10x5_KHR;
  15058. if (p === RGBA_ASTC_10x6_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR : extension.COMPRESSED_RGBA_ASTC_10x6_KHR;
  15059. if (p === RGBA_ASTC_10x8_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR : extension.COMPRESSED_RGBA_ASTC_10x8_KHR;
  15060. if (p === RGBA_ASTC_10x10_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR : extension.COMPRESSED_RGBA_ASTC_10x10_KHR;
  15061. if (p === RGBA_ASTC_12x10_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR : extension.COMPRESSED_RGBA_ASTC_12x10_KHR;
  15062. if (p === RGBA_ASTC_12x12_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR : extension.COMPRESSED_RGBA_ASTC_12x12_KHR;
  15063. } else {
  15064. return null;
  15065. }
  15066. }
  15067. // BPTC
  15068. if (p === RGBA_BPTC_Format) {
  15069. extension = extensions.get('EXT_texture_compression_bptc');
  15070. if (extension !== null) {
  15071. if (p === RGBA_BPTC_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT : extension.COMPRESSED_RGBA_BPTC_UNORM_EXT;
  15072. } else {
  15073. return null;
  15074. }
  15075. }
  15076. //
  15077. if (p === UnsignedInt248Type) {
  15078. if (isWebGL2) return gl.UNSIGNED_INT_24_8;
  15079. extension = extensions.get('WEBGL_depth_texture');
  15080. if (extension !== null) {
  15081. return extension.UNSIGNED_INT_24_8_WEBGL;
  15082. } else {
  15083. return null;
  15084. }
  15085. }
  15086. // if "p" can't be resolved, assume the user defines a WebGL constant as a string (fallback/workaround for packed RGB formats)
  15087. return gl[p] !== undefined ? gl[p] : null;
  15088. }
  15089. return {
  15090. convert: convert
  15091. };
  15092. }
  15093. class ArrayCamera extends PerspectiveCamera {
  15094. constructor(array = []) {
  15095. super();
  15096. this.isArrayCamera = true;
  15097. this.cameras = array;
  15098. }
  15099. }
  15100. class Group extends Object3D {
  15101. constructor() {
  15102. super();
  15103. this.isGroup = true;
  15104. this.type = 'Group';
  15105. }
  15106. }
  15107. const _moveEvent = {
  15108. type: 'move'
  15109. };
  15110. class WebXRController {
  15111. constructor() {
  15112. this._targetRay = null;
  15113. this._grip = null;
  15114. this._hand = null;
  15115. }
  15116. getHandSpace() {
  15117. if (this._hand === null) {
  15118. this._hand = new Group();
  15119. this._hand.matrixAutoUpdate = false;
  15120. this._hand.visible = false;
  15121. this._hand.joints = {};
  15122. this._hand.inputState = {
  15123. pinching: false
  15124. };
  15125. }
  15126. return this._hand;
  15127. }
  15128. getTargetRaySpace() {
  15129. if (this._targetRay === null) {
  15130. this._targetRay = new Group();
  15131. this._targetRay.matrixAutoUpdate = false;
  15132. this._targetRay.visible = false;
  15133. this._targetRay.hasLinearVelocity = false;
  15134. this._targetRay.linearVelocity = new Vector3();
  15135. this._targetRay.hasAngularVelocity = false;
  15136. this._targetRay.angularVelocity = new Vector3();
  15137. }
  15138. return this._targetRay;
  15139. }
  15140. getGripSpace() {
  15141. if (this._grip === null) {
  15142. this._grip = new Group();
  15143. this._grip.matrixAutoUpdate = false;
  15144. this._grip.visible = false;
  15145. this._grip.hasLinearVelocity = false;
  15146. this._grip.linearVelocity = new Vector3();
  15147. this._grip.hasAngularVelocity = false;
  15148. this._grip.angularVelocity = new Vector3();
  15149. }
  15150. return this._grip;
  15151. }
  15152. dispatchEvent(event) {
  15153. if (this._targetRay !== null) {
  15154. this._targetRay.dispatchEvent(event);
  15155. }
  15156. if (this._grip !== null) {
  15157. this._grip.dispatchEvent(event);
  15158. }
  15159. if (this._hand !== null) {
  15160. this._hand.dispatchEvent(event);
  15161. }
  15162. return this;
  15163. }
  15164. connect(inputSource) {
  15165. if (inputSource && inputSource.hand) {
  15166. const hand = this._hand;
  15167. if (hand) {
  15168. for (const inputjoint of inputSource.hand.values()) {
  15169. // Initialize hand with joints when connected
  15170. this._getHandJoint(hand, inputjoint);
  15171. }
  15172. }
  15173. }
  15174. this.dispatchEvent({
  15175. type: 'connected',
  15176. data: inputSource
  15177. });
  15178. return this;
  15179. }
  15180. disconnect(inputSource) {
  15181. this.dispatchEvent({
  15182. type: 'disconnected',
  15183. data: inputSource
  15184. });
  15185. if (this._targetRay !== null) {
  15186. this._targetRay.visible = false;
  15187. }
  15188. if (this._grip !== null) {
  15189. this._grip.visible = false;
  15190. }
  15191. if (this._hand !== null) {
  15192. this._hand.visible = false;
  15193. }
  15194. return this;
  15195. }
  15196. update(inputSource, frame, referenceSpace) {
  15197. let inputPose = null;
  15198. let gripPose = null;
  15199. let handPose = null;
  15200. const targetRay = this._targetRay;
  15201. const grip = this._grip;
  15202. const hand = this._hand;
  15203. if (inputSource && frame.session.visibilityState !== 'visible-blurred') {
  15204. if (hand && inputSource.hand) {
  15205. handPose = true;
  15206. for (const inputjoint of inputSource.hand.values()) {
  15207. // Update the joints groups with the XRJoint poses
  15208. const jointPose = frame.getJointPose(inputjoint, referenceSpace);
  15209. // The transform of this joint will be updated with the joint pose on each frame
  15210. const joint = this._getHandJoint(hand, inputjoint);
  15211. if (jointPose !== null) {
  15212. joint.matrix.fromArray(jointPose.transform.matrix);
  15213. joint.matrix.decompose(joint.position, joint.rotation, joint.scale);
  15214. joint.jointRadius = jointPose.radius;
  15215. }
  15216. joint.visible = jointPose !== null;
  15217. }
  15218. // Custom events
  15219. // Check pinchz
  15220. const indexTip = hand.joints['index-finger-tip'];
  15221. const thumbTip = hand.joints['thumb-tip'];
  15222. const distance = indexTip.position.distanceTo(thumbTip.position);
  15223. const distanceToPinch = 0.02;
  15224. const threshold = 0.005;
  15225. if (hand.inputState.pinching && distance > distanceToPinch + threshold) {
  15226. hand.inputState.pinching = false;
  15227. this.dispatchEvent({
  15228. type: 'pinchend',
  15229. handedness: inputSource.handedness,
  15230. target: this
  15231. });
  15232. } else if (!hand.inputState.pinching && distance <= distanceToPinch - threshold) {
  15233. hand.inputState.pinching = true;
  15234. this.dispatchEvent({
  15235. type: 'pinchstart',
  15236. handedness: inputSource.handedness,
  15237. target: this
  15238. });
  15239. }
  15240. } else {
  15241. if (grip !== null && inputSource.gripSpace) {
  15242. gripPose = frame.getPose(inputSource.gripSpace, referenceSpace);
  15243. if (gripPose !== null) {
  15244. grip.matrix.fromArray(gripPose.transform.matrix);
  15245. grip.matrix.decompose(grip.position, grip.rotation, grip.scale);
  15246. if (gripPose.linearVelocity) {
  15247. grip.hasLinearVelocity = true;
  15248. grip.linearVelocity.copy(gripPose.linearVelocity);
  15249. } else {
  15250. grip.hasLinearVelocity = false;
  15251. }
  15252. if (gripPose.angularVelocity) {
  15253. grip.hasAngularVelocity = true;
  15254. grip.angularVelocity.copy(gripPose.angularVelocity);
  15255. } else {
  15256. grip.hasAngularVelocity = false;
  15257. }
  15258. }
  15259. }
  15260. }
  15261. if (targetRay !== null) {
  15262. inputPose = frame.getPose(inputSource.targetRaySpace, referenceSpace);
  15263. // Some runtimes (namely Vive Cosmos with Vive OpenXR Runtime) have only grip space and ray space is equal to it
  15264. if (inputPose === null && gripPose !== null) {
  15265. inputPose = gripPose;
  15266. }
  15267. if (inputPose !== null) {
  15268. targetRay.matrix.fromArray(inputPose.transform.matrix);
  15269. targetRay.matrix.decompose(targetRay.position, targetRay.rotation, targetRay.scale);
  15270. if (inputPose.linearVelocity) {
  15271. targetRay.hasLinearVelocity = true;
  15272. targetRay.linearVelocity.copy(inputPose.linearVelocity);
  15273. } else {
  15274. targetRay.hasLinearVelocity = false;
  15275. }
  15276. if (inputPose.angularVelocity) {
  15277. targetRay.hasAngularVelocity = true;
  15278. targetRay.angularVelocity.copy(inputPose.angularVelocity);
  15279. } else {
  15280. targetRay.hasAngularVelocity = false;
  15281. }
  15282. this.dispatchEvent(_moveEvent);
  15283. }
  15284. }
  15285. }
  15286. if (targetRay !== null) {
  15287. targetRay.visible = inputPose !== null;
  15288. }
  15289. if (grip !== null) {
  15290. grip.visible = gripPose !== null;
  15291. }
  15292. if (hand !== null) {
  15293. hand.visible = handPose !== null;
  15294. }
  15295. return this;
  15296. }
  15297. // private method
  15298. _getHandJoint(hand, inputjoint) {
  15299. if (hand.joints[inputjoint.jointName] === undefined) {
  15300. const joint = new Group();
  15301. joint.matrixAutoUpdate = false;
  15302. joint.visible = false;
  15303. hand.joints[inputjoint.jointName] = joint;
  15304. hand.add(joint);
  15305. }
  15306. return hand.joints[inputjoint.jointName];
  15307. }
  15308. }
  15309. class DepthTexture extends Texture {
  15310. constructor(width, height, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, format) {
  15311. format = format !== undefined ? format : DepthFormat;
  15312. if (format !== DepthFormat && format !== DepthStencilFormat) {
  15313. throw new Error('DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat');
  15314. }
  15315. if (type === undefined && format === DepthFormat) type = UnsignedIntType;
  15316. if (type === undefined && format === DepthStencilFormat) type = UnsignedInt248Type;
  15317. super(null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy);
  15318. this.isDepthTexture = true;
  15319. this.image = {
  15320. width: width,
  15321. height: height
  15322. };
  15323. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  15324. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  15325. this.flipY = false;
  15326. this.generateMipmaps = false;
  15327. }
  15328. }
  15329. class WebXRManager extends EventDispatcher {
  15330. constructor(renderer, gl) {
  15331. super();
  15332. const scope = this;
  15333. let session = null;
  15334. let framebufferScaleFactor = 1.0;
  15335. let referenceSpace = null;
  15336. let referenceSpaceType = 'local-floor';
  15337. let customReferenceSpace = null;
  15338. let pose = null;
  15339. let glBinding = null;
  15340. let glProjLayer = null;
  15341. let glBaseLayer = null;
  15342. let xrFrame = null;
  15343. const attributes = gl.getContextAttributes();
  15344. let initialRenderTarget = null;
  15345. let newRenderTarget = null;
  15346. const controllers = [];
  15347. const controllerInputSources = [];
  15348. const planes = new Set();
  15349. const planesLastChangedTimes = new Map();
  15350. //
  15351. const cameraL = new PerspectiveCamera();
  15352. cameraL.layers.enable(1);
  15353. cameraL.viewport = new Vector4();
  15354. const cameraR = new PerspectiveCamera();
  15355. cameraR.layers.enable(2);
  15356. cameraR.viewport = new Vector4();
  15357. const cameras = [cameraL, cameraR];
  15358. const cameraVR = new ArrayCamera();
  15359. cameraVR.layers.enable(1);
  15360. cameraVR.layers.enable(2);
  15361. let _currentDepthNear = null;
  15362. let _currentDepthFar = null;
  15363. //
  15364. this.cameraAutoUpdate = true;
  15365. this.enabled = false;
  15366. this.isPresenting = false;
  15367. this.getController = function (index) {
  15368. let controller = controllers[index];
  15369. if (controller === undefined) {
  15370. controller = new WebXRController();
  15371. controllers[index] = controller;
  15372. }
  15373. return controller.getTargetRaySpace();
  15374. };
  15375. this.getControllerGrip = function (index) {
  15376. let controller = controllers[index];
  15377. if (controller === undefined) {
  15378. controller = new WebXRController();
  15379. controllers[index] = controller;
  15380. }
  15381. return controller.getGripSpace();
  15382. };
  15383. this.getHand = function (index) {
  15384. let controller = controllers[index];
  15385. if (controller === undefined) {
  15386. controller = new WebXRController();
  15387. controllers[index] = controller;
  15388. }
  15389. return controller.getHandSpace();
  15390. };
  15391. //
  15392. function onSessionEvent(event) {
  15393. const controllerIndex = controllerInputSources.indexOf(event.inputSource);
  15394. if (controllerIndex === -1) {
  15395. return;
  15396. }
  15397. const controller = controllers[controllerIndex];
  15398. if (controller !== undefined) {
  15399. controller.dispatchEvent({
  15400. type: event.type,
  15401. data: event.inputSource
  15402. });
  15403. }
  15404. }
  15405. function onSessionEnd() {
  15406. session.removeEventListener('select', onSessionEvent);
  15407. session.removeEventListener('selectstart', onSessionEvent);
  15408. session.removeEventListener('selectend', onSessionEvent);
  15409. session.removeEventListener('squeeze', onSessionEvent);
  15410. session.removeEventListener('squeezestart', onSessionEvent);
  15411. session.removeEventListener('squeezeend', onSessionEvent);
  15412. session.removeEventListener('end', onSessionEnd);
  15413. session.removeEventListener('inputsourceschange', onInputSourcesChange);
  15414. for (let i = 0; i < controllers.length; i++) {
  15415. const inputSource = controllerInputSources[i];
  15416. if (inputSource === null) continue;
  15417. controllerInputSources[i] = null;
  15418. controllers[i].disconnect(inputSource);
  15419. }
  15420. _currentDepthNear = null;
  15421. _currentDepthFar = null;
  15422. // restore framebuffer/rendering state
  15423. renderer.setRenderTarget(initialRenderTarget);
  15424. glBaseLayer = null;
  15425. glProjLayer = null;
  15426. glBinding = null;
  15427. session = null;
  15428. newRenderTarget = null;
  15429. //
  15430. animation.stop();
  15431. scope.isPresenting = false;
  15432. scope.dispatchEvent({
  15433. type: 'sessionend'
  15434. });
  15435. }
  15436. this.setFramebufferScaleFactor = function (value) {
  15437. framebufferScaleFactor = value;
  15438. if (scope.isPresenting === true) {
  15439. console.warn('THREE.WebXRManager: Cannot change framebuffer scale while presenting.');
  15440. }
  15441. };
  15442. this.setReferenceSpaceType = function (value) {
  15443. referenceSpaceType = value;
  15444. if (scope.isPresenting === true) {
  15445. console.warn('THREE.WebXRManager: Cannot change reference space type while presenting.');
  15446. }
  15447. };
  15448. this.getReferenceSpace = function () {
  15449. return customReferenceSpace || referenceSpace;
  15450. };
  15451. this.setReferenceSpace = function (space) {
  15452. customReferenceSpace = space;
  15453. };
  15454. this.getBaseLayer = function () {
  15455. return glProjLayer !== null ? glProjLayer : glBaseLayer;
  15456. };
  15457. this.getBinding = function () {
  15458. return glBinding;
  15459. };
  15460. this.getFrame = function () {
  15461. return xrFrame;
  15462. };
  15463. this.getSession = function () {
  15464. return session;
  15465. };
  15466. this.setSession = async function (value) {
  15467. session = value;
  15468. if (session !== null) {
  15469. initialRenderTarget = renderer.getRenderTarget();
  15470. session.addEventListener('select', onSessionEvent);
  15471. session.addEventListener('selectstart', onSessionEvent);
  15472. session.addEventListener('selectend', onSessionEvent);
  15473. session.addEventListener('squeeze', onSessionEvent);
  15474. session.addEventListener('squeezestart', onSessionEvent);
  15475. session.addEventListener('squeezeend', onSessionEvent);
  15476. session.addEventListener('end', onSessionEnd);
  15477. session.addEventListener('inputsourceschange', onInputSourcesChange);
  15478. if (attributes.xrCompatible !== true) {
  15479. await gl.makeXRCompatible();
  15480. }
  15481. if (session.renderState.layers === undefined || renderer.capabilities.isWebGL2 === false) {
  15482. const layerInit = {
  15483. antialias: session.renderState.layers === undefined ? attributes.antialias : true,
  15484. alpha: attributes.alpha,
  15485. depth: attributes.depth,
  15486. stencil: attributes.stencil,
  15487. framebufferScaleFactor: framebufferScaleFactor
  15488. };
  15489. glBaseLayer = new XRWebGLLayer(session, gl, layerInit);
  15490. session.updateRenderState({
  15491. baseLayer: glBaseLayer
  15492. });
  15493. newRenderTarget = new WebGLRenderTarget(glBaseLayer.framebufferWidth, glBaseLayer.framebufferHeight, {
  15494. format: RGBAFormat,
  15495. type: UnsignedByteType,
  15496. encoding: renderer.outputEncoding,
  15497. stencilBuffer: attributes.stencil
  15498. });
  15499. } else {
  15500. let depthFormat = null;
  15501. let depthType = null;
  15502. let glDepthFormat = null;
  15503. if (attributes.depth) {
  15504. glDepthFormat = attributes.stencil ? gl.DEPTH24_STENCIL8 : gl.DEPTH_COMPONENT24;
  15505. depthFormat = attributes.stencil ? DepthStencilFormat : DepthFormat;
  15506. depthType = attributes.stencil ? UnsignedInt248Type : UnsignedIntType;
  15507. }
  15508. const projectionlayerInit = {
  15509. colorFormat: gl.RGBA8,
  15510. depthFormat: glDepthFormat,
  15511. scaleFactor: framebufferScaleFactor
  15512. };
  15513. glBinding = new XRWebGLBinding(session, gl);
  15514. glProjLayer = glBinding.createProjectionLayer(projectionlayerInit);
  15515. session.updateRenderState({
  15516. layers: [glProjLayer]
  15517. });
  15518. newRenderTarget = new WebGLRenderTarget(glProjLayer.textureWidth, glProjLayer.textureHeight, {
  15519. format: RGBAFormat,
  15520. type: UnsignedByteType,
  15521. depthTexture: new DepthTexture(glProjLayer.textureWidth, glProjLayer.textureHeight, depthType, undefined, undefined, undefined, undefined, undefined, undefined, depthFormat),
  15522. stencilBuffer: attributes.stencil,
  15523. encoding: renderer.outputEncoding,
  15524. samples: attributes.antialias ? 4 : 0
  15525. });
  15526. const renderTargetProperties = renderer.properties.get(newRenderTarget);
  15527. renderTargetProperties.__ignoreDepthValues = glProjLayer.ignoreDepthValues;
  15528. }
  15529. newRenderTarget.isXRRenderTarget = true; // TODO Remove this when possible, see #23278
  15530. // Set foveation to maximum.
  15531. this.setFoveation(1.0);
  15532. customReferenceSpace = null;
  15533. referenceSpace = await session.requestReferenceSpace(referenceSpaceType);
  15534. animation.setContext(session);
  15535. animation.start();
  15536. scope.isPresenting = true;
  15537. scope.dispatchEvent({
  15538. type: 'sessionstart'
  15539. });
  15540. }
  15541. };
  15542. function onInputSourcesChange(event) {
  15543. // Notify disconnected
  15544. for (let i = 0; i < event.removed.length; i++) {
  15545. const inputSource = event.removed[i];
  15546. const index = controllerInputSources.indexOf(inputSource);
  15547. if (index >= 0) {
  15548. controllerInputSources[index] = null;
  15549. controllers[index].disconnect(inputSource);
  15550. }
  15551. }
  15552. // Notify connected
  15553. for (let i = 0; i < event.added.length; i++) {
  15554. const inputSource = event.added[i];
  15555. let controllerIndex = controllerInputSources.indexOf(inputSource);
  15556. if (controllerIndex === -1) {
  15557. // Assign input source a controller that currently has no input source
  15558. for (let i = 0; i < controllers.length; i++) {
  15559. if (i >= controllerInputSources.length) {
  15560. controllerInputSources.push(inputSource);
  15561. controllerIndex = i;
  15562. break;
  15563. } else if (controllerInputSources[i] === null) {
  15564. controllerInputSources[i] = inputSource;
  15565. controllerIndex = i;
  15566. break;
  15567. }
  15568. }
  15569. // If all controllers do currently receive input we ignore new ones
  15570. if (controllerIndex === -1) break;
  15571. }
  15572. const controller = controllers[controllerIndex];
  15573. if (controller) {
  15574. controller.connect(inputSource);
  15575. }
  15576. }
  15577. }
  15578. //
  15579. const cameraLPos = new Vector3();
  15580. const cameraRPos = new Vector3();
  15581. /**
  15582. * Assumes 2 cameras that are parallel and share an X-axis, and that
  15583. * the cameras' projection and world matrices have already been set.
  15584. * And that near and far planes are identical for both cameras.
  15585. * Visualization of this technique: https://computergraphics.stackexchange.com/a/4765
  15586. */
  15587. function setProjectionFromUnion(camera, cameraL, cameraR) {
  15588. cameraLPos.setFromMatrixPosition(cameraL.matrixWorld);
  15589. cameraRPos.setFromMatrixPosition(cameraR.matrixWorld);
  15590. const ipd = cameraLPos.distanceTo(cameraRPos);
  15591. const projL = cameraL.projectionMatrix.elements;
  15592. const projR = cameraR.projectionMatrix.elements;
  15593. // VR systems will have identical far and near planes, and
  15594. // most likely identical top and bottom frustum extents.
  15595. // Use the left camera for these values.
  15596. const near = projL[14] / (projL[10] - 1);
  15597. const far = projL[14] / (projL[10] + 1);
  15598. const topFov = (projL[9] + 1) / projL[5];
  15599. const bottomFov = (projL[9] - 1) / projL[5];
  15600. const leftFov = (projL[8] - 1) / projL[0];
  15601. const rightFov = (projR[8] + 1) / projR[0];
  15602. const left = near * leftFov;
  15603. const right = near * rightFov;
  15604. // Calculate the new camera's position offset from the
  15605. // left camera. xOffset should be roughly half `ipd`.
  15606. const zOffset = ipd / (-leftFov + rightFov);
  15607. const xOffset = zOffset * -leftFov;
  15608. // TODO: Better way to apply this offset?
  15609. cameraL.matrixWorld.decompose(camera.position, camera.quaternion, camera.scale);
  15610. camera.translateX(xOffset);
  15611. camera.translateZ(zOffset);
  15612. camera.matrixWorld.compose(camera.position, camera.quaternion, camera.scale);
  15613. camera.matrixWorldInverse.copy(camera.matrixWorld).invert();
  15614. // Find the union of the frustum values of the cameras and scale
  15615. // the values so that the near plane's position does not change in world space,
  15616. // although must now be relative to the new union camera.
  15617. const near2 = near + zOffset;
  15618. const far2 = far + zOffset;
  15619. const left2 = left - xOffset;
  15620. const right2 = right + (ipd - xOffset);
  15621. const top2 = topFov * far / far2 * near2;
  15622. const bottom2 = bottomFov * far / far2 * near2;
  15623. camera.projectionMatrix.makePerspective(left2, right2, top2, bottom2, near2, far2);
  15624. }
  15625. function updateCamera(camera, parent) {
  15626. if (parent === null) {
  15627. camera.matrixWorld.copy(camera.matrix);
  15628. } else {
  15629. camera.matrixWorld.multiplyMatrices(parent.matrixWorld, camera.matrix);
  15630. }
  15631. camera.matrixWorldInverse.copy(camera.matrixWorld).invert();
  15632. }
  15633. this.updateCamera = function (camera) {
  15634. if (session === null) return;
  15635. cameraVR.near = cameraR.near = cameraL.near = camera.near;
  15636. cameraVR.far = cameraR.far = cameraL.far = camera.far;
  15637. if (_currentDepthNear !== cameraVR.near || _currentDepthFar !== cameraVR.far) {
  15638. // Note that the new renderState won't apply until the next frame. See #18320
  15639. session.updateRenderState({
  15640. depthNear: cameraVR.near,
  15641. depthFar: cameraVR.far
  15642. });
  15643. _currentDepthNear = cameraVR.near;
  15644. _currentDepthFar = cameraVR.far;
  15645. }
  15646. const parent = camera.parent;
  15647. const cameras = cameraVR.cameras;
  15648. updateCamera(cameraVR, parent);
  15649. for (let i = 0; i < cameras.length; i++) {
  15650. updateCamera(cameras[i], parent);
  15651. }
  15652. cameraVR.matrixWorld.decompose(cameraVR.position, cameraVR.quaternion, cameraVR.scale);
  15653. // update user camera and its children
  15654. camera.matrix.copy(cameraVR.matrix);
  15655. camera.matrix.decompose(camera.position, camera.quaternion, camera.scale);
  15656. const children = camera.children;
  15657. for (let i = 0, l = children.length; i < l; i++) {
  15658. children[i].updateMatrixWorld(true);
  15659. }
  15660. // update projection matrix for proper view frustum culling
  15661. if (cameras.length === 2) {
  15662. setProjectionFromUnion(cameraVR, cameraL, cameraR);
  15663. } else {
  15664. // assume single camera setup (AR)
  15665. cameraVR.projectionMatrix.copy(cameraL.projectionMatrix);
  15666. }
  15667. };
  15668. this.getCamera = function () {
  15669. return cameraVR;
  15670. };
  15671. this.getFoveation = function () {
  15672. if (glProjLayer !== null) {
  15673. return glProjLayer.fixedFoveation;
  15674. }
  15675. if (glBaseLayer !== null) {
  15676. return glBaseLayer.fixedFoveation;
  15677. }
  15678. return undefined;
  15679. };
  15680. this.setFoveation = function (foveation) {
  15681. // 0 = no foveation = full resolution
  15682. // 1 = maximum foveation = the edges render at lower resolution
  15683. if (glProjLayer !== null) {
  15684. glProjLayer.fixedFoveation = foveation;
  15685. }
  15686. if (glBaseLayer !== null && glBaseLayer.fixedFoveation !== undefined) {
  15687. glBaseLayer.fixedFoveation = foveation;
  15688. }
  15689. };
  15690. this.getPlanes = function () {
  15691. return planes;
  15692. };
  15693. // Animation Loop
  15694. let onAnimationFrameCallback = null;
  15695. function onAnimationFrame(time, frame) {
  15696. pose = frame.getViewerPose(customReferenceSpace || referenceSpace);
  15697. xrFrame = frame;
  15698. if (pose !== null) {
  15699. const views = pose.views;
  15700. if (glBaseLayer !== null) {
  15701. renderer.setRenderTargetFramebuffer(newRenderTarget, glBaseLayer.framebuffer);
  15702. renderer.setRenderTarget(newRenderTarget);
  15703. }
  15704. let cameraVRNeedsUpdate = false;
  15705. // check if it's necessary to rebuild cameraVR's camera list
  15706. if (views.length !== cameraVR.cameras.length) {
  15707. cameraVR.cameras.length = 0;
  15708. cameraVRNeedsUpdate = true;
  15709. }
  15710. for (let i = 0; i < views.length; i++) {
  15711. const view = views[i];
  15712. let viewport = null;
  15713. if (glBaseLayer !== null) {
  15714. viewport = glBaseLayer.getViewport(view);
  15715. } else {
  15716. const glSubImage = glBinding.getViewSubImage(glProjLayer, view);
  15717. viewport = glSubImage.viewport;
  15718. // For side-by-side projection, we only produce a single texture for both eyes.
  15719. if (i === 0) {
  15720. renderer.setRenderTargetTextures(newRenderTarget, glSubImage.colorTexture, glProjLayer.ignoreDepthValues ? undefined : glSubImage.depthStencilTexture);
  15721. renderer.setRenderTarget(newRenderTarget);
  15722. }
  15723. }
  15724. let camera = cameras[i];
  15725. if (camera === undefined) {
  15726. camera = new PerspectiveCamera();
  15727. camera.layers.enable(i);
  15728. camera.viewport = new Vector4();
  15729. cameras[i] = camera;
  15730. }
  15731. camera.matrix.fromArray(view.transform.matrix);
  15732. camera.projectionMatrix.fromArray(view.projectionMatrix);
  15733. camera.viewport.set(viewport.x, viewport.y, viewport.width, viewport.height);
  15734. if (i === 0) {
  15735. cameraVR.matrix.copy(camera.matrix);
  15736. }
  15737. if (cameraVRNeedsUpdate === true) {
  15738. cameraVR.cameras.push(camera);
  15739. }
  15740. }
  15741. }
  15742. //
  15743. for (let i = 0; i < controllers.length; i++) {
  15744. const inputSource = controllerInputSources[i];
  15745. const controller = controllers[i];
  15746. if (inputSource !== null && controller !== undefined) {
  15747. controller.update(inputSource, frame, customReferenceSpace || referenceSpace);
  15748. }
  15749. }
  15750. if (onAnimationFrameCallback) onAnimationFrameCallback(time, frame);
  15751. if (frame.detectedPlanes) {
  15752. scope.dispatchEvent({
  15753. type: 'planesdetected',
  15754. data: frame.detectedPlanes
  15755. });
  15756. let planesToRemove = null;
  15757. for (const plane of planes) {
  15758. if (!frame.detectedPlanes.has(plane)) {
  15759. if (planesToRemove === null) {
  15760. planesToRemove = [];
  15761. }
  15762. planesToRemove.push(plane);
  15763. }
  15764. }
  15765. if (planesToRemove !== null) {
  15766. for (const plane of planesToRemove) {
  15767. planes.delete(plane);
  15768. planesLastChangedTimes.delete(plane);
  15769. scope.dispatchEvent({
  15770. type: 'planeremoved',
  15771. data: plane
  15772. });
  15773. }
  15774. }
  15775. for (const plane of frame.detectedPlanes) {
  15776. if (!planes.has(plane)) {
  15777. planes.add(plane);
  15778. planesLastChangedTimes.set(plane, frame.lastChangedTime);
  15779. scope.dispatchEvent({
  15780. type: 'planeadded',
  15781. data: plane
  15782. });
  15783. } else {
  15784. const lastKnownTime = planesLastChangedTimes.get(plane);
  15785. if (plane.lastChangedTime > lastKnownTime) {
  15786. planesLastChangedTimes.set(plane, plane.lastChangedTime);
  15787. scope.dispatchEvent({
  15788. type: 'planechanged',
  15789. data: plane
  15790. });
  15791. }
  15792. }
  15793. }
  15794. }
  15795. xrFrame = null;
  15796. }
  15797. const animation = new WebGLAnimation();
  15798. animation.setAnimationLoop(onAnimationFrame);
  15799. this.setAnimationLoop = function (callback) {
  15800. onAnimationFrameCallback = callback;
  15801. };
  15802. this.dispose = function () {};
  15803. }
  15804. }
  15805. function WebGLMaterials(renderer, properties) {
  15806. function refreshFogUniforms(uniforms, fog) {
  15807. fog.color.getRGB(uniforms.fogColor.value, getUnlitUniformColorSpace(renderer));
  15808. if (fog.isFog) {
  15809. uniforms.fogNear.value = fog.near;
  15810. uniforms.fogFar.value = fog.far;
  15811. } else if (fog.isFogExp2) {
  15812. uniforms.fogDensity.value = fog.density;
  15813. }
  15814. }
  15815. function refreshMaterialUniforms(uniforms, material, pixelRatio, height, transmissionRenderTarget) {
  15816. if (material.isMeshBasicMaterial) {
  15817. refreshUniformsCommon(uniforms, material);
  15818. } else if (material.isMeshLambertMaterial) {
  15819. refreshUniformsCommon(uniforms, material);
  15820. } else if (material.isMeshToonMaterial) {
  15821. refreshUniformsCommon(uniforms, material);
  15822. refreshUniformsToon(uniforms, material);
  15823. } else if (material.isMeshPhongMaterial) {
  15824. refreshUniformsCommon(uniforms, material);
  15825. refreshUniformsPhong(uniforms, material);
  15826. } else if (material.isMeshStandardMaterial) {
  15827. refreshUniformsCommon(uniforms, material);
  15828. refreshUniformsStandard(uniforms, material);
  15829. if (material.isMeshPhysicalMaterial) {
  15830. refreshUniformsPhysical(uniforms, material, transmissionRenderTarget);
  15831. }
  15832. } else if (material.isMeshMatcapMaterial) {
  15833. refreshUniformsCommon(uniforms, material);
  15834. refreshUniformsMatcap(uniforms, material);
  15835. } else if (material.isMeshDepthMaterial) {
  15836. refreshUniformsCommon(uniforms, material);
  15837. } else if (material.isMeshDistanceMaterial) {
  15838. refreshUniformsCommon(uniforms, material);
  15839. refreshUniformsDistance(uniforms, material);
  15840. } else if (material.isMeshNormalMaterial) {
  15841. refreshUniformsCommon(uniforms, material);
  15842. } else if (material.isLineBasicMaterial) {
  15843. refreshUniformsLine(uniforms, material);
  15844. if (material.isLineDashedMaterial) {
  15845. refreshUniformsDash(uniforms, material);
  15846. }
  15847. } else if (material.isPointsMaterial) {
  15848. refreshUniformsPoints(uniforms, material, pixelRatio, height);
  15849. } else if (material.isSpriteMaterial) {
  15850. refreshUniformsSprites(uniforms, material);
  15851. } else if (material.isShadowMaterial) {
  15852. uniforms.color.value.copy(material.color);
  15853. uniforms.opacity.value = material.opacity;
  15854. } else if (material.isShaderMaterial) {
  15855. material.uniformsNeedUpdate = false; // #15581
  15856. }
  15857. }
  15858. function refreshUniformsCommon(uniforms, material) {
  15859. uniforms.opacity.value = material.opacity;
  15860. if (material.color) {
  15861. uniforms.diffuse.value.copy(material.color);
  15862. }
  15863. if (material.emissive) {
  15864. uniforms.emissive.value.copy(material.emissive).multiplyScalar(material.emissiveIntensity);
  15865. }
  15866. if (material.map) {
  15867. uniforms.map.value = material.map;
  15868. }
  15869. if (material.alphaMap) {
  15870. uniforms.alphaMap.value = material.alphaMap;
  15871. }
  15872. if (material.bumpMap) {
  15873. uniforms.bumpMap.value = material.bumpMap;
  15874. uniforms.bumpScale.value = material.bumpScale;
  15875. if (material.side === BackSide) uniforms.bumpScale.value *= -1;
  15876. }
  15877. if (material.displacementMap) {
  15878. uniforms.displacementMap.value = material.displacementMap;
  15879. uniforms.displacementScale.value = material.displacementScale;
  15880. uniforms.displacementBias.value = material.displacementBias;
  15881. }
  15882. if (material.emissiveMap) {
  15883. uniforms.emissiveMap.value = material.emissiveMap;
  15884. }
  15885. if (material.normalMap) {
  15886. uniforms.normalMap.value = material.normalMap;
  15887. uniforms.normalScale.value.copy(material.normalScale);
  15888. if (material.side === BackSide) uniforms.normalScale.value.negate();
  15889. }
  15890. if (material.specularMap) {
  15891. uniforms.specularMap.value = material.specularMap;
  15892. }
  15893. if (material.alphaTest > 0) {
  15894. uniforms.alphaTest.value = material.alphaTest;
  15895. }
  15896. const envMap = properties.get(material).envMap;
  15897. if (envMap) {
  15898. uniforms.envMap.value = envMap;
  15899. uniforms.flipEnvMap.value = envMap.isCubeTexture && envMap.isRenderTargetTexture === false ? -1 : 1;
  15900. uniforms.reflectivity.value = material.reflectivity;
  15901. uniforms.ior.value = material.ior;
  15902. uniforms.refractionRatio.value = material.refractionRatio;
  15903. }
  15904. if (material.lightMap) {
  15905. uniforms.lightMap.value = material.lightMap;
  15906. // artist-friendly light intensity scaling factor
  15907. const scaleFactor = renderer.physicallyCorrectLights !== true ? Math.PI : 1;
  15908. uniforms.lightMapIntensity.value = material.lightMapIntensity * scaleFactor;
  15909. }
  15910. if (material.aoMap) {
  15911. uniforms.aoMap.value = material.aoMap;
  15912. uniforms.aoMapIntensity.value = material.aoMapIntensity;
  15913. }
  15914. // uv repeat and offset setting priorities
  15915. // 1. color map
  15916. // 2. specular map
  15917. // 3. displacementMap map
  15918. // 4. normal map
  15919. // 5. bump map
  15920. // 6. roughnessMap map
  15921. // 7. metalnessMap map
  15922. // 8. alphaMap map
  15923. // 9. emissiveMap map
  15924. // 10. clearcoat map
  15925. // 11. clearcoat normal map
  15926. // 12. clearcoat roughnessMap map
  15927. // 13. iridescence map
  15928. // 14. iridescence thickness map
  15929. // 15. specular intensity map
  15930. // 16. specular tint map
  15931. // 17. transmission map
  15932. // 18. thickness map
  15933. let uvScaleMap;
  15934. if (material.map) {
  15935. uvScaleMap = material.map;
  15936. } else if (material.specularMap) {
  15937. uvScaleMap = material.specularMap;
  15938. } else if (material.displacementMap) {
  15939. uvScaleMap = material.displacementMap;
  15940. } else if (material.normalMap) {
  15941. uvScaleMap = material.normalMap;
  15942. } else if (material.bumpMap) {
  15943. uvScaleMap = material.bumpMap;
  15944. } else if (material.roughnessMap) {
  15945. uvScaleMap = material.roughnessMap;
  15946. } else if (material.metalnessMap) {
  15947. uvScaleMap = material.metalnessMap;
  15948. } else if (material.alphaMap) {
  15949. uvScaleMap = material.alphaMap;
  15950. } else if (material.emissiveMap) {
  15951. uvScaleMap = material.emissiveMap;
  15952. } else if (material.clearcoatMap) {
  15953. uvScaleMap = material.clearcoatMap;
  15954. } else if (material.clearcoatNormalMap) {
  15955. uvScaleMap = material.clearcoatNormalMap;
  15956. } else if (material.clearcoatRoughnessMap) {
  15957. uvScaleMap = material.clearcoatRoughnessMap;
  15958. } else if (material.iridescenceMap) {
  15959. uvScaleMap = material.iridescenceMap;
  15960. } else if (material.iridescenceThicknessMap) {
  15961. uvScaleMap = material.iridescenceThicknessMap;
  15962. } else if (material.specularIntensityMap) {
  15963. uvScaleMap = material.specularIntensityMap;
  15964. } else if (material.specularColorMap) {
  15965. uvScaleMap = material.specularColorMap;
  15966. } else if (material.transmissionMap) {
  15967. uvScaleMap = material.transmissionMap;
  15968. } else if (material.thicknessMap) {
  15969. uvScaleMap = material.thicknessMap;
  15970. } else if (material.sheenColorMap) {
  15971. uvScaleMap = material.sheenColorMap;
  15972. } else if (material.sheenRoughnessMap) {
  15973. uvScaleMap = material.sheenRoughnessMap;
  15974. }
  15975. if (uvScaleMap !== undefined) {
  15976. // backwards compatibility
  15977. if (uvScaleMap.isWebGLRenderTarget) {
  15978. uvScaleMap = uvScaleMap.texture;
  15979. }
  15980. if (uvScaleMap.matrixAutoUpdate === true) {
  15981. uvScaleMap.updateMatrix();
  15982. }
  15983. uniforms.uvTransform.value.copy(uvScaleMap.matrix);
  15984. }
  15985. // uv repeat and offset setting priorities for uv2
  15986. // 1. ao map
  15987. // 2. light map
  15988. let uv2ScaleMap;
  15989. if (material.aoMap) {
  15990. uv2ScaleMap = material.aoMap;
  15991. } else if (material.lightMap) {
  15992. uv2ScaleMap = material.lightMap;
  15993. }
  15994. if (uv2ScaleMap !== undefined) {
  15995. // backwards compatibility
  15996. if (uv2ScaleMap.isWebGLRenderTarget) {
  15997. uv2ScaleMap = uv2ScaleMap.texture;
  15998. }
  15999. if (uv2ScaleMap.matrixAutoUpdate === true) {
  16000. uv2ScaleMap.updateMatrix();
  16001. }
  16002. uniforms.uv2Transform.value.copy(uv2ScaleMap.matrix);
  16003. }
  16004. }
  16005. function refreshUniformsLine(uniforms, material) {
  16006. uniforms.diffuse.value.copy(material.color);
  16007. uniforms.opacity.value = material.opacity;
  16008. }
  16009. function refreshUniformsDash(uniforms, material) {
  16010. uniforms.dashSize.value = material.dashSize;
  16011. uniforms.totalSize.value = material.dashSize + material.gapSize;
  16012. uniforms.scale.value = material.scale;
  16013. }
  16014. function refreshUniformsPoints(uniforms, material, pixelRatio, height) {
  16015. uniforms.diffuse.value.copy(material.color);
  16016. uniforms.opacity.value = material.opacity;
  16017. uniforms.size.value = material.size * pixelRatio;
  16018. uniforms.scale.value = height * 0.5;
  16019. if (material.map) {
  16020. uniforms.map.value = material.map;
  16021. }
  16022. if (material.alphaMap) {
  16023. uniforms.alphaMap.value = material.alphaMap;
  16024. }
  16025. if (material.alphaTest > 0) {
  16026. uniforms.alphaTest.value = material.alphaTest;
  16027. }
  16028. // uv repeat and offset setting priorities
  16029. // 1. color map
  16030. // 2. alpha map
  16031. let uvScaleMap;
  16032. if (material.map) {
  16033. uvScaleMap = material.map;
  16034. } else if (material.alphaMap) {
  16035. uvScaleMap = material.alphaMap;
  16036. }
  16037. if (uvScaleMap !== undefined) {
  16038. if (uvScaleMap.matrixAutoUpdate === true) {
  16039. uvScaleMap.updateMatrix();
  16040. }
  16041. uniforms.uvTransform.value.copy(uvScaleMap.matrix);
  16042. }
  16043. }
  16044. function refreshUniformsSprites(uniforms, material) {
  16045. uniforms.diffuse.value.copy(material.color);
  16046. uniforms.opacity.value = material.opacity;
  16047. uniforms.rotation.value = material.rotation;
  16048. if (material.map) {
  16049. uniforms.map.value = material.map;
  16050. }
  16051. if (material.alphaMap) {
  16052. uniforms.alphaMap.value = material.alphaMap;
  16053. }
  16054. if (material.alphaTest > 0) {
  16055. uniforms.alphaTest.value = material.alphaTest;
  16056. }
  16057. // uv repeat and offset setting priorities
  16058. // 1. color map
  16059. // 2. alpha map
  16060. let uvScaleMap;
  16061. if (material.map) {
  16062. uvScaleMap = material.map;
  16063. } else if (material.alphaMap) {
  16064. uvScaleMap = material.alphaMap;
  16065. }
  16066. if (uvScaleMap !== undefined) {
  16067. if (uvScaleMap.matrixAutoUpdate === true) {
  16068. uvScaleMap.updateMatrix();
  16069. }
  16070. uniforms.uvTransform.value.copy(uvScaleMap.matrix);
  16071. }
  16072. }
  16073. function refreshUniformsPhong(uniforms, material) {
  16074. uniforms.specular.value.copy(material.specular);
  16075. uniforms.shininess.value = Math.max(material.shininess, 1e-4); // to prevent pow( 0.0, 0.0 )
  16076. }
  16077. function refreshUniformsToon(uniforms, material) {
  16078. if (material.gradientMap) {
  16079. uniforms.gradientMap.value = material.gradientMap;
  16080. }
  16081. }
  16082. function refreshUniformsStandard(uniforms, material) {
  16083. uniforms.roughness.value = material.roughness;
  16084. uniforms.metalness.value = material.metalness;
  16085. if (material.roughnessMap) {
  16086. uniforms.roughnessMap.value = material.roughnessMap;
  16087. }
  16088. if (material.metalnessMap) {
  16089. uniforms.metalnessMap.value = material.metalnessMap;
  16090. }
  16091. const envMap = properties.get(material).envMap;
  16092. if (envMap) {
  16093. //uniforms.envMap.value = material.envMap; // part of uniforms common
  16094. uniforms.envMapIntensity.value = material.envMapIntensity;
  16095. }
  16096. }
  16097. function refreshUniformsPhysical(uniforms, material, transmissionRenderTarget) {
  16098. uniforms.ior.value = material.ior; // also part of uniforms common
  16099. if (material.sheen > 0) {
  16100. uniforms.sheenColor.value.copy(material.sheenColor).multiplyScalar(material.sheen);
  16101. uniforms.sheenRoughness.value = material.sheenRoughness;
  16102. if (material.sheenColorMap) {
  16103. uniforms.sheenColorMap.value = material.sheenColorMap;
  16104. }
  16105. if (material.sheenRoughnessMap) {
  16106. uniforms.sheenRoughnessMap.value = material.sheenRoughnessMap;
  16107. }
  16108. }
  16109. if (material.clearcoat > 0) {
  16110. uniforms.clearcoat.value = material.clearcoat;
  16111. uniforms.clearcoatRoughness.value = material.clearcoatRoughness;
  16112. if (material.clearcoatMap) {
  16113. uniforms.clearcoatMap.value = material.clearcoatMap;
  16114. }
  16115. if (material.clearcoatRoughnessMap) {
  16116. uniforms.clearcoatRoughnessMap.value = material.clearcoatRoughnessMap;
  16117. }
  16118. if (material.clearcoatNormalMap) {
  16119. uniforms.clearcoatNormalScale.value.copy(material.clearcoatNormalScale);
  16120. uniforms.clearcoatNormalMap.value = material.clearcoatNormalMap;
  16121. if (material.side === BackSide) {
  16122. uniforms.clearcoatNormalScale.value.negate();
  16123. }
  16124. }
  16125. }
  16126. if (material.iridescence > 0) {
  16127. uniforms.iridescence.value = material.iridescence;
  16128. uniforms.iridescenceIOR.value = material.iridescenceIOR;
  16129. uniforms.iridescenceThicknessMinimum.value = material.iridescenceThicknessRange[0];
  16130. uniforms.iridescenceThicknessMaximum.value = material.iridescenceThicknessRange[1];
  16131. if (material.iridescenceMap) {
  16132. uniforms.iridescenceMap.value = material.iridescenceMap;
  16133. }
  16134. if (material.iridescenceThicknessMap) {
  16135. uniforms.iridescenceThicknessMap.value = material.iridescenceThicknessMap;
  16136. }
  16137. }
  16138. if (material.transmission > 0) {
  16139. uniforms.transmission.value = material.transmission;
  16140. uniforms.transmissionSamplerMap.value = transmissionRenderTarget.texture;
  16141. uniforms.transmissionSamplerSize.value.set(transmissionRenderTarget.width, transmissionRenderTarget.height);
  16142. if (material.transmissionMap) {
  16143. uniforms.transmissionMap.value = material.transmissionMap;
  16144. }
  16145. uniforms.thickness.value = material.thickness;
  16146. if (material.thicknessMap) {
  16147. uniforms.thicknessMap.value = material.thicknessMap;
  16148. }
  16149. uniforms.attenuationDistance.value = material.attenuationDistance;
  16150. uniforms.attenuationColor.value.copy(material.attenuationColor);
  16151. }
  16152. uniforms.specularIntensity.value = material.specularIntensity;
  16153. uniforms.specularColor.value.copy(material.specularColor);
  16154. if (material.specularIntensityMap) {
  16155. uniforms.specularIntensityMap.value = material.specularIntensityMap;
  16156. }
  16157. if (material.specularColorMap) {
  16158. uniforms.specularColorMap.value = material.specularColorMap;
  16159. }
  16160. }
  16161. function refreshUniformsMatcap(uniforms, material) {
  16162. if (material.matcap) {
  16163. uniforms.matcap.value = material.matcap;
  16164. }
  16165. }
  16166. function refreshUniformsDistance(uniforms, material) {
  16167. uniforms.referencePosition.value.copy(material.referencePosition);
  16168. uniforms.nearDistance.value = material.nearDistance;
  16169. uniforms.farDistance.value = material.farDistance;
  16170. }
  16171. return {
  16172. refreshFogUniforms: refreshFogUniforms,
  16173. refreshMaterialUniforms: refreshMaterialUniforms
  16174. };
  16175. }
  16176. function WebGLUniformsGroups(gl, info, capabilities, state) {
  16177. let buffers = {};
  16178. let updateList = {};
  16179. let allocatedBindingPoints = [];
  16180. const maxBindingPoints = capabilities.isWebGL2 ? gl.getParameter(gl.MAX_UNIFORM_BUFFER_BINDINGS) : 0; // binding points are global whereas block indices are per shader program
  16181. function bind(uniformsGroup, program) {
  16182. const webglProgram = program.program;
  16183. state.uniformBlockBinding(uniformsGroup, webglProgram);
  16184. }
  16185. function update(uniformsGroup, program) {
  16186. let buffer = buffers[uniformsGroup.id];
  16187. if (buffer === undefined) {
  16188. prepareUniformsGroup(uniformsGroup);
  16189. buffer = createBuffer(uniformsGroup);
  16190. buffers[uniformsGroup.id] = buffer;
  16191. uniformsGroup.addEventListener('dispose', onUniformsGroupsDispose);
  16192. }
  16193. // ensure to update the binding points/block indices mapping for this program
  16194. const webglProgram = program.program;
  16195. state.updateUBOMapping(uniformsGroup, webglProgram);
  16196. // update UBO once per frame
  16197. const frame = info.render.frame;
  16198. if (updateList[uniformsGroup.id] !== frame) {
  16199. updateBufferData(uniformsGroup);
  16200. updateList[uniformsGroup.id] = frame;
  16201. }
  16202. }
  16203. function createBuffer(uniformsGroup) {
  16204. // the setup of an UBO is independent of a particular shader program but global
  16205. const bindingPointIndex = allocateBindingPointIndex();
  16206. uniformsGroup.__bindingPointIndex = bindingPointIndex;
  16207. const buffer = gl.createBuffer();
  16208. const size = uniformsGroup.__size;
  16209. const usage = uniformsGroup.usage;
  16210. gl.bindBuffer(gl.UNIFORM_BUFFER, buffer);
  16211. gl.bufferData(gl.UNIFORM_BUFFER, size, usage);
  16212. gl.bindBuffer(gl.UNIFORM_BUFFER, null);
  16213. gl.bindBufferBase(gl.UNIFORM_BUFFER, bindingPointIndex, buffer);
  16214. return buffer;
  16215. }
  16216. function allocateBindingPointIndex() {
  16217. for (let i = 0; i < maxBindingPoints; i++) {
  16218. if (allocatedBindingPoints.indexOf(i) === -1) {
  16219. allocatedBindingPoints.push(i);
  16220. return i;
  16221. }
  16222. }
  16223. console.error('THREE.WebGLRenderer: Maximum number of simultaneously usable uniforms groups reached.');
  16224. return 0;
  16225. }
  16226. function updateBufferData(uniformsGroup) {
  16227. const buffer = buffers[uniformsGroup.id];
  16228. const uniforms = uniformsGroup.uniforms;
  16229. const cache = uniformsGroup.__cache;
  16230. gl.bindBuffer(gl.UNIFORM_BUFFER, buffer);
  16231. for (let i = 0, il = uniforms.length; i < il; i++) {
  16232. const uniform = uniforms[i];
  16233. // partly update the buffer if necessary
  16234. if (hasUniformChanged(uniform, i, cache) === true) {
  16235. const offset = uniform.__offset;
  16236. const values = Array.isArray(uniform.value) ? uniform.value : [uniform.value];
  16237. let arrayOffset = 0;
  16238. for (let i = 0; i < values.length; i++) {
  16239. const value = values[i];
  16240. const info = getUniformSize(value);
  16241. if (typeof value === 'number') {
  16242. uniform.__data[0] = value;
  16243. gl.bufferSubData(gl.UNIFORM_BUFFER, offset + arrayOffset, uniform.__data);
  16244. } else if (value.isMatrix3) {
  16245. // manually converting 3x3 to 3x4
  16246. uniform.__data[0] = value.elements[0];
  16247. uniform.__data[1] = value.elements[1];
  16248. uniform.__data[2] = value.elements[2];
  16249. uniform.__data[3] = value.elements[0];
  16250. uniform.__data[4] = value.elements[3];
  16251. uniform.__data[5] = value.elements[4];
  16252. uniform.__data[6] = value.elements[5];
  16253. uniform.__data[7] = value.elements[0];
  16254. uniform.__data[8] = value.elements[6];
  16255. uniform.__data[9] = value.elements[7];
  16256. uniform.__data[10] = value.elements[8];
  16257. uniform.__data[11] = value.elements[0];
  16258. } else {
  16259. value.toArray(uniform.__data, arrayOffset);
  16260. arrayOffset += info.storage / Float32Array.BYTES_PER_ELEMENT;
  16261. }
  16262. }
  16263. gl.bufferSubData(gl.UNIFORM_BUFFER, offset, uniform.__data);
  16264. }
  16265. }
  16266. gl.bindBuffer(gl.UNIFORM_BUFFER, null);
  16267. }
  16268. function hasUniformChanged(uniform, index, cache) {
  16269. const value = uniform.value;
  16270. if (cache[index] === undefined) {
  16271. // cache entry does not exist so far
  16272. if (typeof value === 'number') {
  16273. cache[index] = value;
  16274. } else {
  16275. const values = Array.isArray(value) ? value : [value];
  16276. const tempValues = [];
  16277. for (let i = 0; i < values.length; i++) {
  16278. tempValues.push(values[i].clone());
  16279. }
  16280. cache[index] = tempValues;
  16281. }
  16282. return true;
  16283. } else {
  16284. // compare current value with cached entry
  16285. if (typeof value === 'number') {
  16286. if (cache[index] !== value) {
  16287. cache[index] = value;
  16288. return true;
  16289. }
  16290. } else {
  16291. const cachedObjects = Array.isArray(cache[index]) ? cache[index] : [cache[index]];
  16292. const values = Array.isArray(value) ? value : [value];
  16293. for (let i = 0; i < cachedObjects.length; i++) {
  16294. const cachedObject = cachedObjects[i];
  16295. if (cachedObject.equals(values[i]) === false) {
  16296. cachedObject.copy(values[i]);
  16297. return true;
  16298. }
  16299. }
  16300. }
  16301. }
  16302. return false;
  16303. }
  16304. function prepareUniformsGroup(uniformsGroup) {
  16305. // determine total buffer size according to the STD140 layout
  16306. // Hint: STD140 is the only supported layout in WebGL 2
  16307. const uniforms = uniformsGroup.uniforms;
  16308. let offset = 0; // global buffer offset in bytes
  16309. const chunkSize = 16; // size of a chunk in bytes
  16310. let chunkOffset = 0; // offset within a single chunk in bytes
  16311. for (let i = 0, l = uniforms.length; i < l; i++) {
  16312. const uniform = uniforms[i];
  16313. const infos = {
  16314. boundary: 0,
  16315. // bytes
  16316. storage: 0 // bytes
  16317. };
  16318. const values = Array.isArray(uniform.value) ? uniform.value : [uniform.value];
  16319. for (let j = 0, jl = values.length; j < jl; j++) {
  16320. const value = values[j];
  16321. const info = getUniformSize(value);
  16322. infos.boundary += info.boundary;
  16323. infos.storage += info.storage;
  16324. }
  16325. // the following two properties will be used for partial buffer updates
  16326. uniform.__data = new Float32Array(infos.storage / Float32Array.BYTES_PER_ELEMENT);
  16327. uniform.__offset = offset;
  16328. //
  16329. if (i > 0) {
  16330. chunkOffset = offset % chunkSize;
  16331. const remainingSizeInChunk = chunkSize - chunkOffset;
  16332. // check for chunk overflow
  16333. if (chunkOffset !== 0 && remainingSizeInChunk - infos.boundary < 0) {
  16334. // add padding and adjust offset
  16335. offset += chunkSize - chunkOffset;
  16336. uniform.__offset = offset;
  16337. }
  16338. }
  16339. offset += infos.storage;
  16340. }
  16341. // ensure correct final padding
  16342. chunkOffset = offset % chunkSize;
  16343. if (chunkOffset > 0) offset += chunkSize - chunkOffset;
  16344. //
  16345. uniformsGroup.__size = offset;
  16346. uniformsGroup.__cache = {};
  16347. return this;
  16348. }
  16349. function getUniformSize(value) {
  16350. const info = {
  16351. boundary: 0,
  16352. // bytes
  16353. storage: 0 // bytes
  16354. };
  16355. // determine sizes according to STD140
  16356. if (typeof value === 'number') {
  16357. // float/int
  16358. info.boundary = 4;
  16359. info.storage = 4;
  16360. } else if (value.isVector2) {
  16361. // vec2
  16362. info.boundary = 8;
  16363. info.storage = 8;
  16364. } else if (value.isVector3 || value.isColor) {
  16365. // vec3
  16366. info.boundary = 16;
  16367. info.storage = 12; // evil: vec3 must start on a 16-byte boundary but it only consumes 12 bytes
  16368. } else if (value.isVector4) {
  16369. // vec4
  16370. info.boundary = 16;
  16371. info.storage = 16;
  16372. } else if (value.isMatrix3) {
  16373. // mat3 (in STD140 a 3x3 matrix is represented as 3x4)
  16374. info.boundary = 48;
  16375. info.storage = 48;
  16376. } else if (value.isMatrix4) {
  16377. // mat4
  16378. info.boundary = 64;
  16379. info.storage = 64;
  16380. } else if (value.isTexture) {
  16381. console.warn('THREE.WebGLRenderer: Texture samplers can not be part of an uniforms group.');
  16382. } else {
  16383. console.warn('THREE.WebGLRenderer: Unsupported uniform value type.', value);
  16384. }
  16385. return info;
  16386. }
  16387. function onUniformsGroupsDispose(event) {
  16388. const uniformsGroup = event.target;
  16389. uniformsGroup.removeEventListener('dispose', onUniformsGroupsDispose);
  16390. const index = allocatedBindingPoints.indexOf(uniformsGroup.__bindingPointIndex);
  16391. allocatedBindingPoints.splice(index, 1);
  16392. gl.deleteBuffer(buffers[uniformsGroup.id]);
  16393. delete buffers[uniformsGroup.id];
  16394. delete updateList[uniformsGroup.id];
  16395. }
  16396. function dispose() {
  16397. for (const id in buffers) {
  16398. gl.deleteBuffer(buffers[id]);
  16399. }
  16400. allocatedBindingPoints = [];
  16401. buffers = {};
  16402. updateList = {};
  16403. }
  16404. return {
  16405. bind: bind,
  16406. update: update,
  16407. dispose: dispose
  16408. };
  16409. }
  16410. function createCanvasElement() {
  16411. const canvas = createElementNS('canvas');
  16412. canvas.style.display = 'block';
  16413. return canvas;
  16414. }
  16415. function WebGLRenderer(parameters = {}) {
  16416. this.isWebGLRenderer = true;
  16417. const _canvas = parameters.canvas !== undefined ? parameters.canvas : createCanvasElement(),
  16418. _context = parameters.context !== undefined ? parameters.context : null,
  16419. _depth = parameters.depth !== undefined ? parameters.depth : true,
  16420. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  16421. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  16422. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  16423. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false,
  16424. _powerPreference = parameters.powerPreference !== undefined ? parameters.powerPreference : 'default',
  16425. _failIfMajorPerformanceCaveat = parameters.failIfMajorPerformanceCaveat !== undefined ? parameters.failIfMajorPerformanceCaveat : false;
  16426. let _alpha;
  16427. if (_context !== null) {
  16428. _alpha = _context.getContextAttributes().alpha;
  16429. } else {
  16430. _alpha = parameters.alpha !== undefined ? parameters.alpha : false;
  16431. }
  16432. let currentRenderList = null;
  16433. let currentRenderState = null;
  16434. // render() can be called from within a callback triggered by another render.
  16435. // We track this so that the nested render call gets its list and state isolated from the parent render call.
  16436. const renderListStack = [];
  16437. const renderStateStack = [];
  16438. // public properties
  16439. this.domElement = _canvas;
  16440. // Debug configuration container
  16441. this.debug = {
  16442. /**
  16443. * Enables error checking and reporting when shader programs are being compiled
  16444. * @type {boolean}
  16445. */
  16446. checkShaderErrors: true
  16447. };
  16448. // clearing
  16449. this.autoClear = true;
  16450. this.autoClearColor = true;
  16451. this.autoClearDepth = true;
  16452. this.autoClearStencil = true;
  16453. // scene graph
  16454. this.sortObjects = true;
  16455. // user-defined clipping
  16456. this.clippingPlanes = [];
  16457. this.localClippingEnabled = false;
  16458. // physically based shading
  16459. this.outputEncoding = LinearEncoding;
  16460. // physical lights
  16461. this.physicallyCorrectLights = false;
  16462. // tone mapping
  16463. this.toneMapping = NoToneMapping;
  16464. this.toneMappingExposure = 1.0;
  16465. // internal properties
  16466. const _this = this;
  16467. let _isContextLost = false;
  16468. // internal state cache
  16469. let _currentActiveCubeFace = 0;
  16470. let _currentActiveMipmapLevel = 0;
  16471. let _currentRenderTarget = null;
  16472. let _currentMaterialId = -1;
  16473. let _currentCamera = null;
  16474. const _currentViewport = new Vector4();
  16475. const _currentScissor = new Vector4();
  16476. let _currentScissorTest = null;
  16477. //
  16478. let _width = _canvas.width;
  16479. let _height = _canvas.height;
  16480. let _pixelRatio = 1;
  16481. let _opaqueSort = null;
  16482. let _transparentSort = null;
  16483. const _viewport = new Vector4(0, 0, _width, _height);
  16484. const _scissor = new Vector4(0, 0, _width, _height);
  16485. let _scissorTest = false;
  16486. // frustum
  16487. const _frustum = new Frustum();
  16488. // clipping
  16489. let _clippingEnabled = false;
  16490. let _localClippingEnabled = false;
  16491. // transmission
  16492. let _transmissionRenderTarget = null;
  16493. // camera matrices cache
  16494. const _projScreenMatrix = new Matrix4();
  16495. const _vector2 = new Vector2();
  16496. const _vector3 = new Vector3();
  16497. const _emptyScene = {
  16498. background: null,
  16499. fog: null,
  16500. environment: null,
  16501. overrideMaterial: null,
  16502. isScene: true
  16503. };
  16504. function getTargetPixelRatio() {
  16505. return _currentRenderTarget === null ? _pixelRatio : 1;
  16506. }
  16507. // initialize
  16508. let _gl = _context;
  16509. function getContext(contextNames, contextAttributes) {
  16510. for (let i = 0; i < contextNames.length; i++) {
  16511. const contextName = contextNames[i];
  16512. const context = _canvas.getContext(contextName, contextAttributes);
  16513. if (context !== null) return context;
  16514. }
  16515. return null;
  16516. }
  16517. try {
  16518. const contextAttributes = {
  16519. alpha: true,
  16520. depth: _depth,
  16521. stencil: _stencil,
  16522. antialias: _antialias,
  16523. premultipliedAlpha: _premultipliedAlpha,
  16524. preserveDrawingBuffer: _preserveDrawingBuffer,
  16525. powerPreference: _powerPreference,
  16526. failIfMajorPerformanceCaveat: _failIfMajorPerformanceCaveat
  16527. };
  16528. // OffscreenCanvas does not have setAttribute, see #22811
  16529. if ('setAttribute' in _canvas) _canvas.setAttribute('data-engine', `three.js r${REVISION}`);
  16530. // event listeners must be registered before WebGL context is created, see #12753
  16531. _canvas.addEventListener('webglcontextlost', onContextLost, false);
  16532. _canvas.addEventListener('webglcontextrestored', onContextRestore, false);
  16533. _canvas.addEventListener('webglcontextcreationerror', onContextCreationError, false);
  16534. if (_gl === null) {
  16535. const contextNames = ['webgl2', 'webgl', 'experimental-webgl'];
  16536. if (_this.isWebGL1Renderer === true) {
  16537. contextNames.shift();
  16538. }
  16539. _gl = getContext(contextNames, contextAttributes);
  16540. if (_gl === null) {
  16541. if (getContext(contextNames)) {
  16542. throw new Error('Error creating WebGL context with your selected attributes.');
  16543. } else {
  16544. throw new Error('Error creating WebGL context.');
  16545. }
  16546. }
  16547. }
  16548. // Some experimental-webgl implementations do not have getShaderPrecisionFormat
  16549. if (_gl.getShaderPrecisionFormat === undefined) {
  16550. _gl.getShaderPrecisionFormat = function () {
  16551. return {
  16552. 'rangeMin': 1,
  16553. 'rangeMax': 1,
  16554. 'precision': 1
  16555. };
  16556. };
  16557. }
  16558. } catch (error) {
  16559. console.error('THREE.WebGLRenderer: ' + error.message);
  16560. throw error;
  16561. }
  16562. let extensions, capabilities, state, info;
  16563. let properties, textures, cubemaps, cubeuvmaps, attributes, geometries, objects;
  16564. let programCache, materials, renderLists, renderStates, clipping, shadowMap;
  16565. let background, morphtargets, bufferRenderer, indexedBufferRenderer;
  16566. let utils, bindingStates, uniformsGroups;
  16567. function initGLContext() {
  16568. extensions = new WebGLExtensions(_gl);
  16569. capabilities = new WebGLCapabilities(_gl, extensions, parameters);
  16570. extensions.init(capabilities);
  16571. utils = new WebGLUtils(_gl, extensions, capabilities);
  16572. state = new WebGLState(_gl, extensions, capabilities);
  16573. info = new WebGLInfo(_gl);
  16574. properties = new WebGLProperties();
  16575. textures = new WebGLTextures(_gl, extensions, state, properties, capabilities, utils, info);
  16576. cubemaps = new WebGLCubeMaps(_this);
  16577. cubeuvmaps = new WebGLCubeUVMaps(_this);
  16578. attributes = new WebGLAttributes(_gl, capabilities);
  16579. bindingStates = new WebGLBindingStates(_gl, extensions, attributes, capabilities);
  16580. geometries = new WebGLGeometries(_gl, attributes, info, bindingStates);
  16581. objects = new WebGLObjects(_gl, geometries, attributes, info);
  16582. morphtargets = new WebGLMorphtargets(_gl, capabilities, textures);
  16583. clipping = new WebGLClipping(properties);
  16584. programCache = new WebGLPrograms(_this, cubemaps, cubeuvmaps, extensions, capabilities, bindingStates, clipping);
  16585. materials = new WebGLMaterials(_this, properties);
  16586. renderLists = new WebGLRenderLists();
  16587. renderStates = new WebGLRenderStates(extensions, capabilities);
  16588. background = new WebGLBackground(_this, cubemaps, cubeuvmaps, state, objects, _alpha, _premultipliedAlpha);
  16589. shadowMap = new WebGLShadowMap(_this, objects, capabilities);
  16590. uniformsGroups = new WebGLUniformsGroups(_gl, info, capabilities, state);
  16591. bufferRenderer = new WebGLBufferRenderer(_gl, extensions, info, capabilities);
  16592. indexedBufferRenderer = new WebGLIndexedBufferRenderer(_gl, extensions, info, capabilities);
  16593. info.programs = programCache.programs;
  16594. _this.capabilities = capabilities;
  16595. _this.extensions = extensions;
  16596. _this.properties = properties;
  16597. _this.renderLists = renderLists;
  16598. _this.shadowMap = shadowMap;
  16599. _this.state = state;
  16600. _this.info = info;
  16601. }
  16602. initGLContext();
  16603. // xr
  16604. const xr = new WebXRManager(_this, _gl);
  16605. this.xr = xr;
  16606. // API
  16607. this.getContext = function () {
  16608. return _gl;
  16609. };
  16610. this.getContextAttributes = function () {
  16611. return _gl.getContextAttributes();
  16612. };
  16613. this.forceContextLoss = function () {
  16614. const extension = extensions.get('WEBGL_lose_context');
  16615. if (extension) extension.loseContext();
  16616. };
  16617. this.forceContextRestore = function () {
  16618. const extension = extensions.get('WEBGL_lose_context');
  16619. if (extension) extension.restoreContext();
  16620. };
  16621. this.getPixelRatio = function () {
  16622. return _pixelRatio;
  16623. };
  16624. this.setPixelRatio = function (value) {
  16625. if (value === undefined) return;
  16626. _pixelRatio = value;
  16627. this.setSize(_width, _height, false);
  16628. };
  16629. this.getSize = function (target) {
  16630. return target.set(_width, _height);
  16631. };
  16632. this.setSize = function (width, height, updateStyle) {
  16633. if (xr.isPresenting) {
  16634. console.warn('THREE.WebGLRenderer: Can\'t change size while VR device is presenting.');
  16635. return;
  16636. }
  16637. _width = width;
  16638. _height = height;
  16639. _canvas.width = Math.floor(width * _pixelRatio);
  16640. _canvas.height = Math.floor(height * _pixelRatio);
  16641. if (updateStyle !== false) {
  16642. _canvas.style.width = width + 'px';
  16643. _canvas.style.height = height + 'px';
  16644. }
  16645. this.setViewport(0, 0, width, height);
  16646. };
  16647. this.getDrawingBufferSize = function (target) {
  16648. return target.set(_width * _pixelRatio, _height * _pixelRatio).floor();
  16649. };
  16650. this.setDrawingBufferSize = function (width, height, pixelRatio) {
  16651. _width = width;
  16652. _height = height;
  16653. _pixelRatio = pixelRatio;
  16654. _canvas.width = Math.floor(width * pixelRatio);
  16655. _canvas.height = Math.floor(height * pixelRatio);
  16656. this.setViewport(0, 0, width, height);
  16657. };
  16658. this.getCurrentViewport = function (target) {
  16659. return target.copy(_currentViewport);
  16660. };
  16661. this.getViewport = function (target) {
  16662. return target.copy(_viewport);
  16663. };
  16664. this.setViewport = function (x, y, width, height) {
  16665. if (x.isVector4) {
  16666. _viewport.set(x.x, x.y, x.z, x.w);
  16667. } else {
  16668. _viewport.set(x, y, width, height);
  16669. }
  16670. state.viewport(_currentViewport.copy(_viewport).multiplyScalar(_pixelRatio).floor());
  16671. };
  16672. this.getScissor = function (target) {
  16673. return target.copy(_scissor);
  16674. };
  16675. this.setScissor = function (x, y, width, height) {
  16676. if (x.isVector4) {
  16677. _scissor.set(x.x, x.y, x.z, x.w);
  16678. } else {
  16679. _scissor.set(x, y, width, height);
  16680. }
  16681. state.scissor(_currentScissor.copy(_scissor).multiplyScalar(_pixelRatio).floor());
  16682. };
  16683. this.getScissorTest = function () {
  16684. return _scissorTest;
  16685. };
  16686. this.setScissorTest = function (boolean) {
  16687. state.setScissorTest(_scissorTest = boolean);
  16688. };
  16689. this.setOpaqueSort = function (method) {
  16690. _opaqueSort = method;
  16691. };
  16692. this.setTransparentSort = function (method) {
  16693. _transparentSort = method;
  16694. };
  16695. // Clearing
  16696. this.getClearColor = function (target) {
  16697. return target.copy(background.getClearColor());
  16698. };
  16699. this.setClearColor = function () {
  16700. background.setClearColor.apply(background, arguments);
  16701. };
  16702. this.getClearAlpha = function () {
  16703. return background.getClearAlpha();
  16704. };
  16705. this.setClearAlpha = function () {
  16706. background.setClearAlpha.apply(background, arguments);
  16707. };
  16708. this.clear = function (color = true, depth = true, stencil = true) {
  16709. let bits = 0;
  16710. if (color) bits |= _gl.COLOR_BUFFER_BIT;
  16711. if (depth) bits |= _gl.DEPTH_BUFFER_BIT;
  16712. if (stencil) bits |= _gl.STENCIL_BUFFER_BIT;
  16713. _gl.clear(bits);
  16714. };
  16715. this.clearColor = function () {
  16716. this.clear(true, false, false);
  16717. };
  16718. this.clearDepth = function () {
  16719. this.clear(false, true, false);
  16720. };
  16721. this.clearStencil = function () {
  16722. this.clear(false, false, true);
  16723. };
  16724. //
  16725. this.dispose = function () {
  16726. _canvas.removeEventListener('webglcontextlost', onContextLost, false);
  16727. _canvas.removeEventListener('webglcontextrestored', onContextRestore, false);
  16728. _canvas.removeEventListener('webglcontextcreationerror', onContextCreationError, false);
  16729. renderLists.dispose();
  16730. renderStates.dispose();
  16731. properties.dispose();
  16732. cubemaps.dispose();
  16733. cubeuvmaps.dispose();
  16734. objects.dispose();
  16735. bindingStates.dispose();
  16736. uniformsGroups.dispose();
  16737. programCache.dispose();
  16738. xr.dispose();
  16739. xr.removeEventListener('sessionstart', onXRSessionStart);
  16740. xr.removeEventListener('sessionend', onXRSessionEnd);
  16741. if (_transmissionRenderTarget) {
  16742. _transmissionRenderTarget.dispose();
  16743. _transmissionRenderTarget = null;
  16744. }
  16745. animation.stop();
  16746. };
  16747. // Events
  16748. function onContextLost(event) {
  16749. event.preventDefault();
  16750. console.log('THREE.WebGLRenderer: Context Lost.');
  16751. _isContextLost = true;
  16752. }
  16753. function onContextRestore( /* event */
  16754. ) {
  16755. console.log('THREE.WebGLRenderer: Context Restored.');
  16756. _isContextLost = false;
  16757. const infoAutoReset = info.autoReset;
  16758. const shadowMapEnabled = shadowMap.enabled;
  16759. const shadowMapAutoUpdate = shadowMap.autoUpdate;
  16760. const shadowMapNeedsUpdate = shadowMap.needsUpdate;
  16761. const shadowMapType = shadowMap.type;
  16762. initGLContext();
  16763. info.autoReset = infoAutoReset;
  16764. shadowMap.enabled = shadowMapEnabled;
  16765. shadowMap.autoUpdate = shadowMapAutoUpdate;
  16766. shadowMap.needsUpdate = shadowMapNeedsUpdate;
  16767. shadowMap.type = shadowMapType;
  16768. }
  16769. function onContextCreationError(event) {
  16770. console.error('THREE.WebGLRenderer: A WebGL context could not be created. Reason: ', event.statusMessage);
  16771. }
  16772. function onMaterialDispose(event) {
  16773. const material = event.target;
  16774. material.removeEventListener('dispose', onMaterialDispose);
  16775. deallocateMaterial(material);
  16776. }
  16777. // Buffer deallocation
  16778. function deallocateMaterial(material) {
  16779. releaseMaterialProgramReferences(material);
  16780. properties.remove(material);
  16781. }
  16782. function releaseMaterialProgramReferences(material) {
  16783. const programs = properties.get(material).programs;
  16784. if (programs !== undefined) {
  16785. programs.forEach(function (program) {
  16786. programCache.releaseProgram(program);
  16787. });
  16788. if (material.isShaderMaterial) {
  16789. programCache.releaseShaderCache(material);
  16790. }
  16791. }
  16792. }
  16793. // Buffer rendering
  16794. this.renderBufferDirect = function (camera, scene, geometry, material, object, group) {
  16795. if (scene === null) scene = _emptyScene; // renderBufferDirect second parameter used to be fog (could be null)
  16796. const frontFaceCW = object.isMesh && object.matrixWorld.determinant() < 0;
  16797. const program = setProgram(camera, scene, geometry, material, object);
  16798. state.setMaterial(material, frontFaceCW);
  16799. //
  16800. let index = geometry.index;
  16801. let rangeFactor = 1;
  16802. if (material.wireframe === true) {
  16803. index = geometries.getWireframeAttribute(geometry);
  16804. rangeFactor = 2;
  16805. }
  16806. //
  16807. const drawRange = geometry.drawRange;
  16808. const position = geometry.attributes.position;
  16809. let drawStart = drawRange.start * rangeFactor;
  16810. let drawEnd = (drawRange.start + drawRange.count) * rangeFactor;
  16811. if (group !== null) {
  16812. drawStart = Math.max(drawStart, group.start * rangeFactor);
  16813. drawEnd = Math.min(drawEnd, (group.start + group.count) * rangeFactor);
  16814. }
  16815. if (index !== null) {
  16816. drawStart = Math.max(drawStart, 0);
  16817. drawEnd = Math.min(drawEnd, index.count);
  16818. } else if (position !== undefined && position !== null) {
  16819. drawStart = Math.max(drawStart, 0);
  16820. drawEnd = Math.min(drawEnd, position.count);
  16821. }
  16822. const drawCount = drawEnd - drawStart;
  16823. if (drawCount < 0 || drawCount === Infinity) return;
  16824. //
  16825. bindingStates.setup(object, material, program, geometry, index);
  16826. let attribute;
  16827. let renderer = bufferRenderer;
  16828. if (index !== null) {
  16829. attribute = attributes.get(index);
  16830. renderer = indexedBufferRenderer;
  16831. renderer.setIndex(attribute);
  16832. }
  16833. //
  16834. if (object.isMesh) {
  16835. if (material.wireframe === true) {
  16836. state.setLineWidth(material.wireframeLinewidth * getTargetPixelRatio());
  16837. renderer.setMode(_gl.LINES);
  16838. } else {
  16839. renderer.setMode(_gl.TRIANGLES);
  16840. }
  16841. } else if (object.isLine) {
  16842. let lineWidth = material.linewidth;
  16843. if (lineWidth === undefined) lineWidth = 1; // Not using Line*Material
  16844. state.setLineWidth(lineWidth * getTargetPixelRatio());
  16845. if (object.isLineSegments) {
  16846. renderer.setMode(_gl.LINES);
  16847. } else if (object.isLineLoop) {
  16848. renderer.setMode(_gl.LINE_LOOP);
  16849. } else {
  16850. renderer.setMode(_gl.LINE_STRIP);
  16851. }
  16852. } else if (object.isPoints) {
  16853. renderer.setMode(_gl.POINTS);
  16854. } else if (object.isSprite) {
  16855. renderer.setMode(_gl.TRIANGLES);
  16856. }
  16857. if (object.isInstancedMesh) {
  16858. renderer.renderInstances(drawStart, drawCount, object.count);
  16859. } else if (geometry.isInstancedBufferGeometry) {
  16860. const maxInstanceCount = geometry._maxInstanceCount !== undefined ? geometry._maxInstanceCount : Infinity;
  16861. const instanceCount = Math.min(geometry.instanceCount, maxInstanceCount);
  16862. renderer.renderInstances(drawStart, drawCount, instanceCount);
  16863. } else {
  16864. renderer.render(drawStart, drawCount);
  16865. }
  16866. };
  16867. // Compile
  16868. this.compile = function (scene, camera) {
  16869. function prepare(material, scene, object) {
  16870. if (material.transparent === true && material.side === DoubleSide) {
  16871. material.side = BackSide;
  16872. material.needsUpdate = true;
  16873. getProgram(material, scene, object);
  16874. material.side = FrontSide;
  16875. material.needsUpdate = true;
  16876. getProgram(material, scene, object);
  16877. material.side = DoubleSide;
  16878. } else {
  16879. getProgram(material, scene, object);
  16880. }
  16881. }
  16882. currentRenderState = renderStates.get(scene);
  16883. currentRenderState.init();
  16884. renderStateStack.push(currentRenderState);
  16885. scene.traverseVisible(function (object) {
  16886. if (object.isLight && object.layers.test(camera.layers)) {
  16887. currentRenderState.pushLight(object);
  16888. if (object.castShadow) {
  16889. currentRenderState.pushShadow(object);
  16890. }
  16891. }
  16892. });
  16893. currentRenderState.setupLights(_this.physicallyCorrectLights);
  16894. scene.traverse(function (object) {
  16895. const material = object.material;
  16896. if (material) {
  16897. if (Array.isArray(material)) {
  16898. for (let i = 0; i < material.length; i++) {
  16899. const material2 = material[i];
  16900. prepare(material2, scene, object);
  16901. }
  16902. } else {
  16903. prepare(material, scene, object);
  16904. }
  16905. }
  16906. });
  16907. renderStateStack.pop();
  16908. currentRenderState = null;
  16909. };
  16910. // Animation Loop
  16911. let onAnimationFrameCallback = null;
  16912. function onAnimationFrame(time) {
  16913. if (onAnimationFrameCallback) onAnimationFrameCallback(time);
  16914. }
  16915. function onXRSessionStart() {
  16916. animation.stop();
  16917. }
  16918. function onXRSessionEnd() {
  16919. animation.start();
  16920. }
  16921. const animation = new WebGLAnimation();
  16922. animation.setAnimationLoop(onAnimationFrame);
  16923. if (typeof self !== 'undefined') animation.setContext(self);
  16924. this.setAnimationLoop = function (callback) {
  16925. onAnimationFrameCallback = callback;
  16926. xr.setAnimationLoop(callback);
  16927. callback === null ? animation.stop() : animation.start();
  16928. };
  16929. xr.addEventListener('sessionstart', onXRSessionStart);
  16930. xr.addEventListener('sessionend', onXRSessionEnd);
  16931. // Rendering
  16932. this.render = function (scene, camera) {
  16933. if (camera !== undefined && camera.isCamera !== true) {
  16934. console.error('THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.');
  16935. return;
  16936. }
  16937. if (_isContextLost === true) return;
  16938. // update scene graph
  16939. if (scene.matrixWorldAutoUpdate === true) scene.updateMatrixWorld();
  16940. // update camera matrices and frustum
  16941. if (camera.parent === null && camera.matrixWorldAutoUpdate === true) camera.updateMatrixWorld();
  16942. if (xr.enabled === true && xr.isPresenting === true) {
  16943. if (xr.cameraAutoUpdate === true) xr.updateCamera(camera);
  16944. camera = xr.getCamera(); // use XR camera for rendering
  16945. }
  16946. //
  16947. if (scene.isScene === true) scene.onBeforeRender(_this, scene, camera, _currentRenderTarget);
  16948. currentRenderState = renderStates.get(scene, renderStateStack.length);
  16949. currentRenderState.init();
  16950. renderStateStack.push(currentRenderState);
  16951. _projScreenMatrix.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse);
  16952. _frustum.setFromProjectionMatrix(_projScreenMatrix);
  16953. _localClippingEnabled = this.localClippingEnabled;
  16954. _clippingEnabled = clipping.init(this.clippingPlanes, _localClippingEnabled, camera);
  16955. currentRenderList = renderLists.get(scene, renderListStack.length);
  16956. currentRenderList.init();
  16957. renderListStack.push(currentRenderList);
  16958. projectObject(scene, camera, 0, _this.sortObjects);
  16959. currentRenderList.finish();
  16960. if (_this.sortObjects === true) {
  16961. currentRenderList.sort(_opaqueSort, _transparentSort);
  16962. }
  16963. //
  16964. if (_clippingEnabled === true) clipping.beginShadows();
  16965. const shadowsArray = currentRenderState.state.shadowsArray;
  16966. shadowMap.render(shadowsArray, scene, camera);
  16967. if (_clippingEnabled === true) clipping.endShadows();
  16968. //
  16969. if (this.info.autoReset === true) this.info.reset();
  16970. //
  16971. background.render(currentRenderList, scene);
  16972. // render scene
  16973. currentRenderState.setupLights(_this.physicallyCorrectLights);
  16974. if (camera.isArrayCamera) {
  16975. const cameras = camera.cameras;
  16976. for (let i = 0, l = cameras.length; i < l; i++) {
  16977. const camera2 = cameras[i];
  16978. renderScene(currentRenderList, scene, camera2, camera2.viewport);
  16979. }
  16980. } else {
  16981. renderScene(currentRenderList, scene, camera);
  16982. }
  16983. //
  16984. if (_currentRenderTarget !== null) {
  16985. // resolve multisample renderbuffers to a single-sample texture if necessary
  16986. textures.updateMultisampleRenderTarget(_currentRenderTarget);
  16987. // Generate mipmap if we're using any kind of mipmap filtering
  16988. textures.updateRenderTargetMipmap(_currentRenderTarget);
  16989. }
  16990. //
  16991. if (scene.isScene === true) scene.onAfterRender(_this, scene, camera);
  16992. // _gl.finish();
  16993. bindingStates.resetDefaultState();
  16994. _currentMaterialId = -1;
  16995. _currentCamera = null;
  16996. renderStateStack.pop();
  16997. if (renderStateStack.length > 0) {
  16998. currentRenderState = renderStateStack[renderStateStack.length - 1];
  16999. } else {
  17000. currentRenderState = null;
  17001. }
  17002. renderListStack.pop();
  17003. if (renderListStack.length > 0) {
  17004. currentRenderList = renderListStack[renderListStack.length - 1];
  17005. } else {
  17006. currentRenderList = null;
  17007. }
  17008. };
  17009. function projectObject(object, camera, groupOrder, sortObjects) {
  17010. if (object.visible === false) return;
  17011. const visible = object.layers.test(camera.layers);
  17012. if (visible) {
  17013. if (object.isGroup) {
  17014. groupOrder = object.renderOrder;
  17015. } else if (object.isLOD) {
  17016. if (object.autoUpdate === true) object.update(camera);
  17017. } else if (object.isLight) {
  17018. currentRenderState.pushLight(object);
  17019. if (object.castShadow) {
  17020. currentRenderState.pushShadow(object);
  17021. }
  17022. } else if (object.isSprite) {
  17023. if (!object.frustumCulled || _frustum.intersectsSprite(object)) {
  17024. if (sortObjects) {
  17025. _vector3.setFromMatrixPosition(object.matrixWorld).applyMatrix4(_projScreenMatrix);
  17026. }
  17027. const geometry = objects.update(object);
  17028. const material = object.material;
  17029. if (material.visible) {
  17030. currentRenderList.push(object, geometry, material, groupOrder, _vector3.z, null);
  17031. }
  17032. }
  17033. } else if (object.isMesh || object.isLine || object.isPoints) {
  17034. if (object.isSkinnedMesh) {
  17035. // update skeleton only once in a frame
  17036. if (object.skeleton.frame !== info.render.frame) {
  17037. object.skeleton.update();
  17038. object.skeleton.frame = info.render.frame;
  17039. }
  17040. }
  17041. if (!object.frustumCulled || _frustum.intersectsObject(object)) {
  17042. if (sortObjects) {
  17043. _vector3.setFromMatrixPosition(object.matrixWorld).applyMatrix4(_projScreenMatrix);
  17044. }
  17045. const geometry = objects.update(object);
  17046. const material = object.material;
  17047. if (Array.isArray(material)) {
  17048. const groups = geometry.groups;
  17049. for (let i = 0, l = groups.length; i < l; i++) {
  17050. const group = groups[i];
  17051. const groupMaterial = material[group.materialIndex];
  17052. if (groupMaterial && groupMaterial.visible) {
  17053. currentRenderList.push(object, geometry, groupMaterial, groupOrder, _vector3.z, group);
  17054. }
  17055. }
  17056. } else if (material.visible) {
  17057. currentRenderList.push(object, geometry, material, groupOrder, _vector3.z, null);
  17058. }
  17059. }
  17060. }
  17061. }
  17062. const children = object.children;
  17063. for (let i = 0, l = children.length; i < l; i++) {
  17064. projectObject(children[i], camera, groupOrder, sortObjects);
  17065. }
  17066. }
  17067. function renderScene(currentRenderList, scene, camera, viewport) {
  17068. const opaqueObjects = currentRenderList.opaque;
  17069. const transmissiveObjects = currentRenderList.transmissive;
  17070. const transparentObjects = currentRenderList.transparent;
  17071. currentRenderState.setupLightsView(camera);
  17072. if (transmissiveObjects.length > 0) renderTransmissionPass(opaqueObjects, scene, camera);
  17073. if (viewport) state.viewport(_currentViewport.copy(viewport));
  17074. if (opaqueObjects.length > 0) renderObjects(opaqueObjects, scene, camera);
  17075. if (transmissiveObjects.length > 0) renderObjects(transmissiveObjects, scene, camera);
  17076. if (transparentObjects.length > 0) renderObjects(transparentObjects, scene, camera);
  17077. // Ensure depth buffer writing is enabled so it can be cleared on next render
  17078. state.buffers.depth.setTest(true);
  17079. state.buffers.depth.setMask(true);
  17080. state.buffers.color.setMask(true);
  17081. state.setPolygonOffset(false);
  17082. }
  17083. function renderTransmissionPass(opaqueObjects, scene, camera) {
  17084. const isWebGL2 = capabilities.isWebGL2;
  17085. if (_transmissionRenderTarget === null) {
  17086. _transmissionRenderTarget = new WebGLRenderTarget(1, 1, {
  17087. generateMipmaps: true,
  17088. type: extensions.has('EXT_color_buffer_half_float') ? HalfFloatType : UnsignedByteType,
  17089. minFilter: LinearMipmapLinearFilter,
  17090. samples: isWebGL2 && _antialias === true ? 4 : 0
  17091. });
  17092. }
  17093. _this.getDrawingBufferSize(_vector2);
  17094. if (isWebGL2) {
  17095. _transmissionRenderTarget.setSize(_vector2.x, _vector2.y);
  17096. } else {
  17097. _transmissionRenderTarget.setSize(floorPowerOfTwo(_vector2.x), floorPowerOfTwo(_vector2.y));
  17098. }
  17099. //
  17100. const currentRenderTarget = _this.getRenderTarget();
  17101. _this.setRenderTarget(_transmissionRenderTarget);
  17102. _this.clear();
  17103. // Turn off the features which can affect the frag color for opaque objects pass.
  17104. // Otherwise they are applied twice in opaque objects pass and transmission objects pass.
  17105. const currentToneMapping = _this.toneMapping;
  17106. _this.toneMapping = NoToneMapping;
  17107. renderObjects(opaqueObjects, scene, camera);
  17108. _this.toneMapping = currentToneMapping;
  17109. textures.updateMultisampleRenderTarget(_transmissionRenderTarget);
  17110. textures.updateRenderTargetMipmap(_transmissionRenderTarget);
  17111. _this.setRenderTarget(currentRenderTarget);
  17112. }
  17113. function renderObjects(renderList, scene, camera) {
  17114. const overrideMaterial = scene.isScene === true ? scene.overrideMaterial : null;
  17115. for (let i = 0, l = renderList.length; i < l; i++) {
  17116. const renderItem = renderList[i];
  17117. const object = renderItem.object;
  17118. const geometry = renderItem.geometry;
  17119. const material = overrideMaterial === null ? renderItem.material : overrideMaterial;
  17120. const group = renderItem.group;
  17121. if (object.layers.test(camera.layers)) {
  17122. renderObject(object, scene, camera, geometry, material, group);
  17123. }
  17124. }
  17125. }
  17126. function renderObject(object, scene, camera, geometry, material, group) {
  17127. object.onBeforeRender(_this, scene, camera, geometry, material, group);
  17128. object.modelViewMatrix.multiplyMatrices(camera.matrixWorldInverse, object.matrixWorld);
  17129. object.normalMatrix.getNormalMatrix(object.modelViewMatrix);
  17130. material.onBeforeRender(_this, scene, camera, geometry, object, group);
  17131. if (material.transparent === true && material.side === DoubleSide) {
  17132. material.side = BackSide;
  17133. material.needsUpdate = true;
  17134. _this.renderBufferDirect(camera, scene, geometry, material, object, group);
  17135. material.side = FrontSide;
  17136. material.needsUpdate = true;
  17137. _this.renderBufferDirect(camera, scene, geometry, material, object, group);
  17138. material.side = DoubleSide;
  17139. } else {
  17140. _this.renderBufferDirect(camera, scene, geometry, material, object, group);
  17141. }
  17142. object.onAfterRender(_this, scene, camera, geometry, material, group);
  17143. }
  17144. function getProgram(material, scene, object) {
  17145. if (scene.isScene !== true) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...
  17146. const materialProperties = properties.get(material);
  17147. const lights = currentRenderState.state.lights;
  17148. const shadowsArray = currentRenderState.state.shadowsArray;
  17149. const lightsStateVersion = lights.state.version;
  17150. const parameters = programCache.getParameters(material, lights.state, shadowsArray, scene, object);
  17151. const programCacheKey = programCache.getProgramCacheKey(parameters);
  17152. let programs = materialProperties.programs;
  17153. // always update environment and fog - changing these trigger an getProgram call, but it's possible that the program doesn't change
  17154. materialProperties.environment = material.isMeshStandardMaterial ? scene.environment : null;
  17155. materialProperties.fog = scene.fog;
  17156. materialProperties.envMap = (material.isMeshStandardMaterial ? cubeuvmaps : cubemaps).get(material.envMap || materialProperties.environment);
  17157. if (programs === undefined) {
  17158. // new material
  17159. material.addEventListener('dispose', onMaterialDispose);
  17160. programs = new Map();
  17161. materialProperties.programs = programs;
  17162. }
  17163. let program = programs.get(programCacheKey);
  17164. if (program !== undefined) {
  17165. // early out if program and light state is identical
  17166. if (materialProperties.currentProgram === program && materialProperties.lightsStateVersion === lightsStateVersion) {
  17167. updateCommonMaterialProperties(material, parameters);
  17168. return program;
  17169. }
  17170. } else {
  17171. parameters.uniforms = programCache.getUniforms(material);
  17172. material.onBuild(object, parameters, _this);
  17173. material.onBeforeCompile(parameters, _this);
  17174. program = programCache.acquireProgram(parameters, programCacheKey);
  17175. programs.set(programCacheKey, program);
  17176. materialProperties.uniforms = parameters.uniforms;
  17177. }
  17178. const uniforms = materialProperties.uniforms;
  17179. if (!material.isShaderMaterial && !material.isRawShaderMaterial || material.clipping === true) {
  17180. uniforms.clippingPlanes = clipping.uniform;
  17181. }
  17182. updateCommonMaterialProperties(material, parameters);
  17183. // store the light setup it was created for
  17184. materialProperties.needsLights = materialNeedsLights(material);
  17185. materialProperties.lightsStateVersion = lightsStateVersion;
  17186. if (materialProperties.needsLights) {
  17187. // wire up the material to this renderer's lighting state
  17188. uniforms.ambientLightColor.value = lights.state.ambient;
  17189. uniforms.lightProbe.value = lights.state.probe;
  17190. uniforms.directionalLights.value = lights.state.directional;
  17191. uniforms.directionalLightShadows.value = lights.state.directionalShadow;
  17192. uniforms.spotLights.value = lights.state.spot;
  17193. uniforms.spotLightShadows.value = lights.state.spotShadow;
  17194. uniforms.rectAreaLights.value = lights.state.rectArea;
  17195. uniforms.ltc_1.value = lights.state.rectAreaLTC1;
  17196. uniforms.ltc_2.value = lights.state.rectAreaLTC2;
  17197. uniforms.pointLights.value = lights.state.point;
  17198. uniforms.pointLightShadows.value = lights.state.pointShadow;
  17199. uniforms.hemisphereLights.value = lights.state.hemi;
  17200. uniforms.directionalShadowMap.value = lights.state.directionalShadowMap;
  17201. uniforms.directionalShadowMatrix.value = lights.state.directionalShadowMatrix;
  17202. uniforms.spotShadowMap.value = lights.state.spotShadowMap;
  17203. uniforms.spotLightMatrix.value = lights.state.spotLightMatrix;
  17204. uniforms.spotLightMap.value = lights.state.spotLightMap;
  17205. uniforms.pointShadowMap.value = lights.state.pointShadowMap;
  17206. uniforms.pointShadowMatrix.value = lights.state.pointShadowMatrix;
  17207. // TODO (abelnation): add area lights shadow info to uniforms
  17208. }
  17209. const progUniforms = program.getUniforms();
  17210. const uniformsList = WebGLUniforms.seqWithValue(progUniforms.seq, uniforms);
  17211. materialProperties.currentProgram = program;
  17212. materialProperties.uniformsList = uniformsList;
  17213. return program;
  17214. }
  17215. function updateCommonMaterialProperties(material, parameters) {
  17216. const materialProperties = properties.get(material);
  17217. materialProperties.outputEncoding = parameters.outputEncoding;
  17218. materialProperties.instancing = parameters.instancing;
  17219. materialProperties.skinning = parameters.skinning;
  17220. materialProperties.morphTargets = parameters.morphTargets;
  17221. materialProperties.morphNormals = parameters.morphNormals;
  17222. materialProperties.morphColors = parameters.morphColors;
  17223. materialProperties.morphTargetsCount = parameters.morphTargetsCount;
  17224. materialProperties.numClippingPlanes = parameters.numClippingPlanes;
  17225. materialProperties.numIntersection = parameters.numClipIntersection;
  17226. materialProperties.vertexAlphas = parameters.vertexAlphas;
  17227. materialProperties.vertexTangents = parameters.vertexTangents;
  17228. materialProperties.toneMapping = parameters.toneMapping;
  17229. }
  17230. function setProgram(camera, scene, geometry, material, object) {
  17231. if (scene.isScene !== true) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...
  17232. textures.resetTextureUnits();
  17233. const fog = scene.fog;
  17234. const environment = material.isMeshStandardMaterial ? scene.environment : null;
  17235. const encoding = _currentRenderTarget === null ? _this.outputEncoding : _currentRenderTarget.isXRRenderTarget === true ? _currentRenderTarget.texture.encoding : LinearEncoding;
  17236. const envMap = (material.isMeshStandardMaterial ? cubeuvmaps : cubemaps).get(material.envMap || environment);
  17237. const vertexAlphas = material.vertexColors === true && !!geometry.attributes.color && geometry.attributes.color.itemSize === 4;
  17238. const vertexTangents = !!material.normalMap && !!geometry.attributes.tangent;
  17239. const morphTargets = !!geometry.morphAttributes.position;
  17240. const morphNormals = !!geometry.morphAttributes.normal;
  17241. const morphColors = !!geometry.morphAttributes.color;
  17242. const toneMapping = material.toneMapped ? _this.toneMapping : NoToneMapping;
  17243. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  17244. const morphTargetsCount = morphAttribute !== undefined ? morphAttribute.length : 0;
  17245. const materialProperties = properties.get(material);
  17246. const lights = currentRenderState.state.lights;
  17247. if (_clippingEnabled === true) {
  17248. if (_localClippingEnabled === true || camera !== _currentCamera) {
  17249. const useCache = camera === _currentCamera && material.id === _currentMaterialId;
  17250. // we might want to call this function with some ClippingGroup
  17251. // object instead of the material, once it becomes feasible
  17252. // (#8465, #8379)
  17253. clipping.setState(material, camera, useCache);
  17254. }
  17255. }
  17256. //
  17257. let needsProgramChange = false;
  17258. if (material.version === materialProperties.__version) {
  17259. if (materialProperties.needsLights && materialProperties.lightsStateVersion !== lights.state.version) {
  17260. needsProgramChange = true;
  17261. } else if (materialProperties.outputEncoding !== encoding) {
  17262. needsProgramChange = true;
  17263. } else if (object.isInstancedMesh && materialProperties.instancing === false) {
  17264. needsProgramChange = true;
  17265. } else if (!object.isInstancedMesh && materialProperties.instancing === true) {
  17266. needsProgramChange = true;
  17267. } else if (object.isSkinnedMesh && materialProperties.skinning === false) {
  17268. needsProgramChange = true;
  17269. } else if (!object.isSkinnedMesh && materialProperties.skinning === true) {
  17270. needsProgramChange = true;
  17271. } else if (materialProperties.envMap !== envMap) {
  17272. needsProgramChange = true;
  17273. } else if (material.fog === true && materialProperties.fog !== fog) {
  17274. needsProgramChange = true;
  17275. } else if (materialProperties.numClippingPlanes !== undefined && (materialProperties.numClippingPlanes !== clipping.numPlanes || materialProperties.numIntersection !== clipping.numIntersection)) {
  17276. needsProgramChange = true;
  17277. } else if (materialProperties.vertexAlphas !== vertexAlphas) {
  17278. needsProgramChange = true;
  17279. } else if (materialProperties.vertexTangents !== vertexTangents) {
  17280. needsProgramChange = true;
  17281. } else if (materialProperties.morphTargets !== morphTargets) {
  17282. needsProgramChange = true;
  17283. } else if (materialProperties.morphNormals !== morphNormals) {
  17284. needsProgramChange = true;
  17285. } else if (materialProperties.morphColors !== morphColors) {
  17286. needsProgramChange = true;
  17287. } else if (materialProperties.toneMapping !== toneMapping) {
  17288. needsProgramChange = true;
  17289. } else if (capabilities.isWebGL2 === true && materialProperties.morphTargetsCount !== morphTargetsCount) {
  17290. needsProgramChange = true;
  17291. }
  17292. } else {
  17293. needsProgramChange = true;
  17294. materialProperties.__version = material.version;
  17295. }
  17296. //
  17297. let program = materialProperties.currentProgram;
  17298. if (needsProgramChange === true) {
  17299. program = getProgram(material, scene, object);
  17300. }
  17301. let refreshProgram = false;
  17302. let refreshMaterial = false;
  17303. let refreshLights = false;
  17304. const p_uniforms = program.getUniforms(),
  17305. m_uniforms = materialProperties.uniforms;
  17306. if (state.useProgram(program.program)) {
  17307. refreshProgram = true;
  17308. refreshMaterial = true;
  17309. refreshLights = true;
  17310. }
  17311. if (material.id !== _currentMaterialId) {
  17312. _currentMaterialId = material.id;
  17313. refreshMaterial = true;
  17314. }
  17315. if (refreshProgram || _currentCamera !== camera) {
  17316. p_uniforms.setValue(_gl, 'projectionMatrix', camera.projectionMatrix);
  17317. if (capabilities.logarithmicDepthBuffer) {
  17318. p_uniforms.setValue(_gl, 'logDepthBufFC', 2.0 / (Math.log(camera.far + 1.0) / Math.LN2));
  17319. }
  17320. if (_currentCamera !== camera) {
  17321. _currentCamera = camera;
  17322. // lighting uniforms depend on the camera so enforce an update
  17323. // now, in case this material supports lights - or later, when
  17324. // the next material that does gets activated:
  17325. refreshMaterial = true; // set to true on material change
  17326. refreshLights = true; // remains set until update done
  17327. }
  17328. // load material specific uniforms
  17329. // (shader material also gets them for the sake of genericity)
  17330. if (material.isShaderMaterial || material.isMeshPhongMaterial || material.isMeshToonMaterial || material.isMeshStandardMaterial || material.envMap) {
  17331. const uCamPos = p_uniforms.map.cameraPosition;
  17332. if (uCamPos !== undefined) {
  17333. uCamPos.setValue(_gl, _vector3.setFromMatrixPosition(camera.matrixWorld));
  17334. }
  17335. }
  17336. if (material.isMeshPhongMaterial || material.isMeshToonMaterial || material.isMeshLambertMaterial || material.isMeshBasicMaterial || material.isMeshStandardMaterial || material.isShaderMaterial) {
  17337. p_uniforms.setValue(_gl, 'isOrthographic', camera.isOrthographicCamera === true);
  17338. }
  17339. if (material.isMeshPhongMaterial || material.isMeshToonMaterial || material.isMeshLambertMaterial || material.isMeshBasicMaterial || material.isMeshStandardMaterial || material.isShaderMaterial || material.isShadowMaterial || object.isSkinnedMesh) {
  17340. p_uniforms.setValue(_gl, 'viewMatrix', camera.matrixWorldInverse);
  17341. }
  17342. }
  17343. // skinning and morph target uniforms must be set even if material didn't change
  17344. // auto-setting of texture unit for bone and morph texture must go before other textures
  17345. // otherwise textures used for skinning and morphing can take over texture units reserved for other material textures
  17346. if (object.isSkinnedMesh) {
  17347. p_uniforms.setOptional(_gl, object, 'bindMatrix');
  17348. p_uniforms.setOptional(_gl, object, 'bindMatrixInverse');
  17349. const skeleton = object.skeleton;
  17350. if (skeleton) {
  17351. if (capabilities.floatVertexTextures) {
  17352. if (skeleton.boneTexture === null) skeleton.computeBoneTexture();
  17353. p_uniforms.setValue(_gl, 'boneTexture', skeleton.boneTexture, textures);
  17354. p_uniforms.setValue(_gl, 'boneTextureSize', skeleton.boneTextureSize);
  17355. } else {
  17356. console.warn('THREE.WebGLRenderer: SkinnedMesh can only be used with WebGL 2. With WebGL 1 OES_texture_float and vertex textures support is required.');
  17357. }
  17358. }
  17359. }
  17360. const morphAttributes = geometry.morphAttributes;
  17361. if (morphAttributes.position !== undefined || morphAttributes.normal !== undefined || morphAttributes.color !== undefined && capabilities.isWebGL2 === true) {
  17362. morphtargets.update(object, geometry, material, program);
  17363. }
  17364. if (refreshMaterial || materialProperties.receiveShadow !== object.receiveShadow) {
  17365. materialProperties.receiveShadow = object.receiveShadow;
  17366. p_uniforms.setValue(_gl, 'receiveShadow', object.receiveShadow);
  17367. }
  17368. // https://github.com/mrdoob/three.js/pull/24467#issuecomment-1209031512
  17369. if (material.isMeshGouraudMaterial && material.envMap !== null) {
  17370. m_uniforms.envMap.value = envMap;
  17371. m_uniforms.flipEnvMap.value = envMap.isCubeTexture && envMap.isRenderTargetTexture === false ? -1 : 1;
  17372. }
  17373. if (refreshMaterial) {
  17374. p_uniforms.setValue(_gl, 'toneMappingExposure', _this.toneMappingExposure);
  17375. if (materialProperties.needsLights) {
  17376. // the current material requires lighting info
  17377. // note: all lighting uniforms are always set correctly
  17378. // they simply reference the renderer's state for their
  17379. // values
  17380. //
  17381. // use the current material's .needsUpdate flags to set
  17382. // the GL state when required
  17383. markUniformsLightsNeedsUpdate(m_uniforms, refreshLights);
  17384. }
  17385. // refresh uniforms common to several materials
  17386. if (fog && material.fog === true) {
  17387. materials.refreshFogUniforms(m_uniforms, fog);
  17388. }
  17389. materials.refreshMaterialUniforms(m_uniforms, material, _pixelRatio, _height, _transmissionRenderTarget);
  17390. WebGLUniforms.upload(_gl, materialProperties.uniformsList, m_uniforms, textures);
  17391. }
  17392. if (material.isShaderMaterial && material.uniformsNeedUpdate === true) {
  17393. WebGLUniforms.upload(_gl, materialProperties.uniformsList, m_uniforms, textures);
  17394. material.uniformsNeedUpdate = false;
  17395. }
  17396. if (material.isSpriteMaterial) {
  17397. p_uniforms.setValue(_gl, 'center', object.center);
  17398. }
  17399. // common matrices
  17400. p_uniforms.setValue(_gl, 'modelViewMatrix', object.modelViewMatrix);
  17401. p_uniforms.setValue(_gl, 'normalMatrix', object.normalMatrix);
  17402. p_uniforms.setValue(_gl, 'modelMatrix', object.matrixWorld);
  17403. // UBOs
  17404. if (material.isShaderMaterial || material.isRawShaderMaterial) {
  17405. const groups = material.uniformsGroups;
  17406. for (let i = 0, l = groups.length; i < l; i++) {
  17407. if (capabilities.isWebGL2) {
  17408. const group = groups[i];
  17409. uniformsGroups.update(group, program);
  17410. uniformsGroups.bind(group, program);
  17411. } else {
  17412. console.warn('THREE.WebGLRenderer: Uniform Buffer Objects can only be used with WebGL 2.');
  17413. }
  17414. }
  17415. }
  17416. return program;
  17417. }
  17418. // If uniforms are marked as clean, they don't need to be loaded to the GPU.
  17419. function markUniformsLightsNeedsUpdate(uniforms, value) {
  17420. uniforms.ambientLightColor.needsUpdate = value;
  17421. uniforms.lightProbe.needsUpdate = value;
  17422. uniforms.directionalLights.needsUpdate = value;
  17423. uniforms.directionalLightShadows.needsUpdate = value;
  17424. uniforms.pointLights.needsUpdate = value;
  17425. uniforms.pointLightShadows.needsUpdate = value;
  17426. uniforms.spotLights.needsUpdate = value;
  17427. uniforms.spotLightShadows.needsUpdate = value;
  17428. uniforms.rectAreaLights.needsUpdate = value;
  17429. uniforms.hemisphereLights.needsUpdate = value;
  17430. }
  17431. function materialNeedsLights(material) {
  17432. return material.isMeshLambertMaterial || material.isMeshToonMaterial || material.isMeshPhongMaterial || material.isMeshStandardMaterial || material.isShadowMaterial || material.isShaderMaterial && material.lights === true;
  17433. }
  17434. this.getActiveCubeFace = function () {
  17435. return _currentActiveCubeFace;
  17436. };
  17437. this.getActiveMipmapLevel = function () {
  17438. return _currentActiveMipmapLevel;
  17439. };
  17440. this.getRenderTarget = function () {
  17441. return _currentRenderTarget;
  17442. };
  17443. this.setRenderTargetTextures = function (renderTarget, colorTexture, depthTexture) {
  17444. properties.get(renderTarget.texture).__webglTexture = colorTexture;
  17445. properties.get(renderTarget.depthTexture).__webglTexture = depthTexture;
  17446. const renderTargetProperties = properties.get(renderTarget);
  17447. renderTargetProperties.__hasExternalTextures = true;
  17448. if (renderTargetProperties.__hasExternalTextures) {
  17449. renderTargetProperties.__autoAllocateDepthBuffer = depthTexture === undefined;
  17450. if (!renderTargetProperties.__autoAllocateDepthBuffer) {
  17451. // The multisample_render_to_texture extension doesn't work properly if there
  17452. // are midframe flushes and an external depth buffer. Disable use of the extension.
  17453. if (extensions.has('WEBGL_multisampled_render_to_texture') === true) {
  17454. console.warn('THREE.WebGLRenderer: Render-to-texture extension was disabled because an external texture was provided');
  17455. renderTargetProperties.__useRenderToTexture = false;
  17456. }
  17457. }
  17458. }
  17459. };
  17460. this.setRenderTargetFramebuffer = function (renderTarget, defaultFramebuffer) {
  17461. const renderTargetProperties = properties.get(renderTarget);
  17462. renderTargetProperties.__webglFramebuffer = defaultFramebuffer;
  17463. renderTargetProperties.__useDefaultFramebuffer = defaultFramebuffer === undefined;
  17464. };
  17465. this.setRenderTarget = function (renderTarget, activeCubeFace = 0, activeMipmapLevel = 0) {
  17466. _currentRenderTarget = renderTarget;
  17467. _currentActiveCubeFace = activeCubeFace;
  17468. _currentActiveMipmapLevel = activeMipmapLevel;
  17469. let useDefaultFramebuffer = true;
  17470. let framebuffer = null;
  17471. let isCube = false;
  17472. let isRenderTarget3D = false;
  17473. if (renderTarget) {
  17474. const renderTargetProperties = properties.get(renderTarget);
  17475. if (renderTargetProperties.__useDefaultFramebuffer !== undefined) {
  17476. // We need to make sure to rebind the framebuffer.
  17477. state.bindFramebuffer(_gl.FRAMEBUFFER, null);
  17478. useDefaultFramebuffer = false;
  17479. } else if (renderTargetProperties.__webglFramebuffer === undefined) {
  17480. textures.setupRenderTarget(renderTarget);
  17481. } else if (renderTargetProperties.__hasExternalTextures) {
  17482. // Color and depth texture must be rebound in order for the swapchain to update.
  17483. textures.rebindTextures(renderTarget, properties.get(renderTarget.texture).__webglTexture, properties.get(renderTarget.depthTexture).__webglTexture);
  17484. }
  17485. const texture = renderTarget.texture;
  17486. if (texture.isData3DTexture || texture.isDataArrayTexture || texture.isCompressedArrayTexture) {
  17487. isRenderTarget3D = true;
  17488. }
  17489. const __webglFramebuffer = properties.get(renderTarget).__webglFramebuffer;
  17490. if (renderTarget.isWebGLCubeRenderTarget) {
  17491. framebuffer = __webglFramebuffer[activeCubeFace];
  17492. isCube = true;
  17493. } else if (capabilities.isWebGL2 && renderTarget.samples > 0 && textures.useMultisampledRTT(renderTarget) === false) {
  17494. framebuffer = properties.get(renderTarget).__webglMultisampledFramebuffer;
  17495. } else {
  17496. framebuffer = __webglFramebuffer;
  17497. }
  17498. _currentViewport.copy(renderTarget.viewport);
  17499. _currentScissor.copy(renderTarget.scissor);
  17500. _currentScissorTest = renderTarget.scissorTest;
  17501. } else {
  17502. _currentViewport.copy(_viewport).multiplyScalar(_pixelRatio).floor();
  17503. _currentScissor.copy(_scissor).multiplyScalar(_pixelRatio).floor();
  17504. _currentScissorTest = _scissorTest;
  17505. }
  17506. const framebufferBound = state.bindFramebuffer(_gl.FRAMEBUFFER, framebuffer);
  17507. if (framebufferBound && capabilities.drawBuffers && useDefaultFramebuffer) {
  17508. state.drawBuffers(renderTarget, framebuffer);
  17509. }
  17510. state.viewport(_currentViewport);
  17511. state.scissor(_currentScissor);
  17512. state.setScissorTest(_currentScissorTest);
  17513. if (isCube) {
  17514. const textureProperties = properties.get(renderTarget.texture);
  17515. _gl.framebufferTexture2D(_gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + activeCubeFace, textureProperties.__webglTexture, activeMipmapLevel);
  17516. } else if (isRenderTarget3D) {
  17517. const textureProperties = properties.get(renderTarget.texture);
  17518. const layer = activeCubeFace || 0;
  17519. _gl.framebufferTextureLayer(_gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, textureProperties.__webglTexture, activeMipmapLevel || 0, layer);
  17520. }
  17521. _currentMaterialId = -1; // reset current material to ensure correct uniform bindings
  17522. };
  17523. this.readRenderTargetPixels = function (renderTarget, x, y, width, height, buffer, activeCubeFaceIndex) {
  17524. if (!(renderTarget && renderTarget.isWebGLRenderTarget)) {
  17525. console.error('THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.');
  17526. return;
  17527. }
  17528. let framebuffer = properties.get(renderTarget).__webglFramebuffer;
  17529. if (renderTarget.isWebGLCubeRenderTarget && activeCubeFaceIndex !== undefined) {
  17530. framebuffer = framebuffer[activeCubeFaceIndex];
  17531. }
  17532. if (framebuffer) {
  17533. state.bindFramebuffer(_gl.FRAMEBUFFER, framebuffer);
  17534. try {
  17535. const texture = renderTarget.texture;
  17536. const textureFormat = texture.format;
  17537. const textureType = texture.type;
  17538. if (textureFormat !== RGBAFormat && utils.convert(textureFormat) !== _gl.getParameter(_gl.IMPLEMENTATION_COLOR_READ_FORMAT)) {
  17539. console.error('THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.');
  17540. return;
  17541. }
  17542. const halfFloatSupportedByExt = textureType === HalfFloatType && (extensions.has('EXT_color_buffer_half_float') || capabilities.isWebGL2 && extensions.has('EXT_color_buffer_float'));
  17543. if (textureType !== UnsignedByteType && utils.convert(textureType) !== _gl.getParameter(_gl.IMPLEMENTATION_COLOR_READ_TYPE) &&
  17544. // Edge and Chrome Mac < 52 (#9513)
  17545. !(textureType === FloatType && (capabilities.isWebGL2 || extensions.has('OES_texture_float') || extensions.has('WEBGL_color_buffer_float'))) &&
  17546. // Chrome Mac >= 52 and Firefox
  17547. !halfFloatSupportedByExt) {
  17548. console.error('THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.');
  17549. return;
  17550. }
  17551. // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604)
  17552. if (x >= 0 && x <= renderTarget.width - width && y >= 0 && y <= renderTarget.height - height) {
  17553. _gl.readPixels(x, y, width, height, utils.convert(textureFormat), utils.convert(textureType), buffer);
  17554. }
  17555. } finally {
  17556. // restore framebuffer of current render target if necessary
  17557. const framebuffer = _currentRenderTarget !== null ? properties.get(_currentRenderTarget).__webglFramebuffer : null;
  17558. state.bindFramebuffer(_gl.FRAMEBUFFER, framebuffer);
  17559. }
  17560. }
  17561. };
  17562. this.copyFramebufferToTexture = function (position, texture, level = 0) {
  17563. const levelScale = Math.pow(2, -level);
  17564. const width = Math.floor(texture.image.width * levelScale);
  17565. const height = Math.floor(texture.image.height * levelScale);
  17566. textures.setTexture2D(texture, 0);
  17567. _gl.copyTexSubImage2D(_gl.TEXTURE_2D, level, 0, 0, position.x, position.y, width, height);
  17568. state.unbindTexture();
  17569. };
  17570. this.copyTextureToTexture = function (position, srcTexture, dstTexture, level = 0) {
  17571. const width = srcTexture.image.width;
  17572. const height = srcTexture.image.height;
  17573. const glFormat = utils.convert(dstTexture.format);
  17574. const glType = utils.convert(dstTexture.type);
  17575. textures.setTexture2D(dstTexture, 0);
  17576. // As another texture upload may have changed pixelStorei
  17577. // parameters, make sure they are correct for the dstTexture
  17578. _gl.pixelStorei(_gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY);
  17579. _gl.pixelStorei(_gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha);
  17580. _gl.pixelStorei(_gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment);
  17581. if (srcTexture.isDataTexture) {
  17582. _gl.texSubImage2D(_gl.TEXTURE_2D, level, position.x, position.y, width, height, glFormat, glType, srcTexture.image.data);
  17583. } else {
  17584. if (srcTexture.isCompressedTexture) {
  17585. _gl.compressedTexSubImage2D(_gl.TEXTURE_2D, level, position.x, position.y, srcTexture.mipmaps[0].width, srcTexture.mipmaps[0].height, glFormat, srcTexture.mipmaps[0].data);
  17586. } else {
  17587. _gl.texSubImage2D(_gl.TEXTURE_2D, level, position.x, position.y, glFormat, glType, srcTexture.image);
  17588. }
  17589. }
  17590. // Generate mipmaps only when copying level 0
  17591. if (level === 0 && dstTexture.generateMipmaps) _gl.generateMipmap(_gl.TEXTURE_2D);
  17592. state.unbindTexture();
  17593. };
  17594. this.copyTextureToTexture3D = function (sourceBox, position, srcTexture, dstTexture, level = 0) {
  17595. if (_this.isWebGL1Renderer) {
  17596. console.warn('THREE.WebGLRenderer.copyTextureToTexture3D: can only be used with WebGL2.');
  17597. return;
  17598. }
  17599. const width = sourceBox.max.x - sourceBox.min.x + 1;
  17600. const height = sourceBox.max.y - sourceBox.min.y + 1;
  17601. const depth = sourceBox.max.z - sourceBox.min.z + 1;
  17602. const glFormat = utils.convert(dstTexture.format);
  17603. const glType = utils.convert(dstTexture.type);
  17604. let glTarget;
  17605. if (dstTexture.isData3DTexture) {
  17606. textures.setTexture3D(dstTexture, 0);
  17607. glTarget = _gl.TEXTURE_3D;
  17608. } else if (dstTexture.isDataArrayTexture) {
  17609. textures.setTexture2DArray(dstTexture, 0);
  17610. glTarget = _gl.TEXTURE_2D_ARRAY;
  17611. } else {
  17612. console.warn('THREE.WebGLRenderer.copyTextureToTexture3D: only supports THREE.DataTexture3D and THREE.DataTexture2DArray.');
  17613. return;
  17614. }
  17615. _gl.pixelStorei(_gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY);
  17616. _gl.pixelStorei(_gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha);
  17617. _gl.pixelStorei(_gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment);
  17618. const unpackRowLen = _gl.getParameter(_gl.UNPACK_ROW_LENGTH);
  17619. const unpackImageHeight = _gl.getParameter(_gl.UNPACK_IMAGE_HEIGHT);
  17620. const unpackSkipPixels = _gl.getParameter(_gl.UNPACK_SKIP_PIXELS);
  17621. const unpackSkipRows = _gl.getParameter(_gl.UNPACK_SKIP_ROWS);
  17622. const unpackSkipImages = _gl.getParameter(_gl.UNPACK_SKIP_IMAGES);
  17623. const image = srcTexture.isCompressedTexture ? srcTexture.mipmaps[0] : srcTexture.image;
  17624. _gl.pixelStorei(_gl.UNPACK_ROW_LENGTH, image.width);
  17625. _gl.pixelStorei(_gl.UNPACK_IMAGE_HEIGHT, image.height);
  17626. _gl.pixelStorei(_gl.UNPACK_SKIP_PIXELS, sourceBox.min.x);
  17627. _gl.pixelStorei(_gl.UNPACK_SKIP_ROWS, sourceBox.min.y);
  17628. _gl.pixelStorei(_gl.UNPACK_SKIP_IMAGES, sourceBox.min.z);
  17629. if (srcTexture.isDataTexture || srcTexture.isData3DTexture) {
  17630. _gl.texSubImage3D(glTarget, level, position.x, position.y, position.z, width, height, depth, glFormat, glType, image.data);
  17631. } else {
  17632. if (srcTexture.isCompressedArrayTexture) {
  17633. console.warn('THREE.WebGLRenderer.copyTextureToTexture3D: untested support for compressed srcTexture.');
  17634. _gl.compressedTexSubImage3D(glTarget, level, position.x, position.y, position.z, width, height, depth, glFormat, image.data);
  17635. } else {
  17636. _gl.texSubImage3D(glTarget, level, position.x, position.y, position.z, width, height, depth, glFormat, glType, image);
  17637. }
  17638. }
  17639. _gl.pixelStorei(_gl.UNPACK_ROW_LENGTH, unpackRowLen);
  17640. _gl.pixelStorei(_gl.UNPACK_IMAGE_HEIGHT, unpackImageHeight);
  17641. _gl.pixelStorei(_gl.UNPACK_SKIP_PIXELS, unpackSkipPixels);
  17642. _gl.pixelStorei(_gl.UNPACK_SKIP_ROWS, unpackSkipRows);
  17643. _gl.pixelStorei(_gl.UNPACK_SKIP_IMAGES, unpackSkipImages);
  17644. // Generate mipmaps only when copying level 0
  17645. if (level === 0 && dstTexture.generateMipmaps) _gl.generateMipmap(glTarget);
  17646. state.unbindTexture();
  17647. };
  17648. this.initTexture = function (texture) {
  17649. if (texture.isCubeTexture) {
  17650. textures.setTextureCube(texture, 0);
  17651. } else if (texture.isData3DTexture) {
  17652. textures.setTexture3D(texture, 0);
  17653. } else if (texture.isDataArrayTexture || texture.isCompressedArrayTexture) {
  17654. textures.setTexture2DArray(texture, 0);
  17655. } else {
  17656. textures.setTexture2D(texture, 0);
  17657. }
  17658. state.unbindTexture();
  17659. };
  17660. this.resetState = function () {
  17661. _currentActiveCubeFace = 0;
  17662. _currentActiveMipmapLevel = 0;
  17663. _currentRenderTarget = null;
  17664. state.reset();
  17665. bindingStates.reset();
  17666. };
  17667. if (typeof __THREE_DEVTOOLS__ !== 'undefined') {
  17668. __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent('observe', {
  17669. detail: this
  17670. }));
  17671. }
  17672. }
  17673. class WebGL1Renderer extends WebGLRenderer {}
  17674. WebGL1Renderer.prototype.isWebGL1Renderer = true;
  17675. class FogExp2 {
  17676. constructor(color, density = 0.00025) {
  17677. this.isFogExp2 = true;
  17678. this.name = '';
  17679. this.color = new Color(color);
  17680. this.density = density;
  17681. }
  17682. clone() {
  17683. return new FogExp2(this.color, this.density);
  17684. }
  17685. toJSON( /* meta */
  17686. ) {
  17687. return {
  17688. type: 'FogExp2',
  17689. color: this.color.getHex(),
  17690. density: this.density
  17691. };
  17692. }
  17693. }
  17694. class Fog {
  17695. constructor(color, near = 1, far = 1000) {
  17696. this.isFog = true;
  17697. this.name = '';
  17698. this.color = new Color(color);
  17699. this.near = near;
  17700. this.far = far;
  17701. }
  17702. clone() {
  17703. return new Fog(this.color, this.near, this.far);
  17704. }
  17705. toJSON( /* meta */
  17706. ) {
  17707. return {
  17708. type: 'Fog',
  17709. color: this.color.getHex(),
  17710. near: this.near,
  17711. far: this.far
  17712. };
  17713. }
  17714. }
  17715. class Scene extends Object3D {
  17716. constructor() {
  17717. super();
  17718. this.isScene = true;
  17719. this.type = 'Scene';
  17720. this.background = null;
  17721. this.environment = null;
  17722. this.fog = null;
  17723. this.backgroundBlurriness = 0;
  17724. this.backgroundIntensity = 1;
  17725. this.overrideMaterial = null;
  17726. if (typeof __THREE_DEVTOOLS__ !== 'undefined') {
  17727. __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent('observe', {
  17728. detail: this
  17729. }));
  17730. }
  17731. }
  17732. copy(source, recursive) {
  17733. super.copy(source, recursive);
  17734. if (source.background !== null) this.background = source.background.clone();
  17735. if (source.environment !== null) this.environment = source.environment.clone();
  17736. if (source.fog !== null) this.fog = source.fog.clone();
  17737. this.backgroundBlurriness = source.backgroundBlurriness;
  17738. this.backgroundIntensity = source.backgroundIntensity;
  17739. if (source.overrideMaterial !== null) this.overrideMaterial = source.overrideMaterial.clone();
  17740. this.matrixAutoUpdate = source.matrixAutoUpdate;
  17741. return this;
  17742. }
  17743. toJSON(meta) {
  17744. const data = super.toJSON(meta);
  17745. if (this.fog !== null) data.object.fog = this.fog.toJSON();
  17746. if (this.backgroundBlurriness > 0) data.backgroundBlurriness = this.backgroundBlurriness;
  17747. if (this.backgroundIntensity !== 1) data.backgroundIntensity = this.backgroundIntensity;
  17748. return data;
  17749. }
  17750. // @deprecated
  17751. get autoUpdate() {
  17752. console.warn('THREE.Scene: autoUpdate was renamed to matrixWorldAutoUpdate in r144.');
  17753. return this.matrixWorldAutoUpdate;
  17754. }
  17755. set autoUpdate(value) {
  17756. console.warn('THREE.Scene: autoUpdate was renamed to matrixWorldAutoUpdate in r144.');
  17757. this.matrixWorldAutoUpdate = value;
  17758. }
  17759. }
  17760. class InterleavedBuffer {
  17761. constructor(array, stride) {
  17762. this.isInterleavedBuffer = true;
  17763. this.array = array;
  17764. this.stride = stride;
  17765. this.count = array !== undefined ? array.length / stride : 0;
  17766. this.usage = StaticDrawUsage;
  17767. this.updateRange = {
  17768. offset: 0,
  17769. count: -1
  17770. };
  17771. this.version = 0;
  17772. this.uuid = generateUUID();
  17773. }
  17774. onUploadCallback() {}
  17775. set needsUpdate(value) {
  17776. if (value === true) this.version++;
  17777. }
  17778. setUsage(value) {
  17779. this.usage = value;
  17780. return this;
  17781. }
  17782. copy(source) {
  17783. this.array = new source.array.constructor(source.array);
  17784. this.count = source.count;
  17785. this.stride = source.stride;
  17786. this.usage = source.usage;
  17787. return this;
  17788. }
  17789. copyAt(index1, attribute, index2) {
  17790. index1 *= this.stride;
  17791. index2 *= attribute.stride;
  17792. for (let i = 0, l = this.stride; i < l; i++) {
  17793. this.array[index1 + i] = attribute.array[index2 + i];
  17794. }
  17795. return this;
  17796. }
  17797. set(value, offset = 0) {
  17798. this.array.set(value, offset);
  17799. return this;
  17800. }
  17801. clone(data) {
  17802. if (data.arrayBuffers === undefined) {
  17803. data.arrayBuffers = {};
  17804. }
  17805. if (this.array.buffer._uuid === undefined) {
  17806. this.array.buffer._uuid = generateUUID();
  17807. }
  17808. if (data.arrayBuffers[this.array.buffer._uuid] === undefined) {
  17809. data.arrayBuffers[this.array.buffer._uuid] = this.array.slice(0).buffer;
  17810. }
  17811. const array = new this.array.constructor(data.arrayBuffers[this.array.buffer._uuid]);
  17812. const ib = new this.constructor(array, this.stride);
  17813. ib.setUsage(this.usage);
  17814. return ib;
  17815. }
  17816. onUpload(callback) {
  17817. this.onUploadCallback = callback;
  17818. return this;
  17819. }
  17820. toJSON(data) {
  17821. if (data.arrayBuffers === undefined) {
  17822. data.arrayBuffers = {};
  17823. }
  17824. // generate UUID for array buffer if necessary
  17825. if (this.array.buffer._uuid === undefined) {
  17826. this.array.buffer._uuid = generateUUID();
  17827. }
  17828. if (data.arrayBuffers[this.array.buffer._uuid] === undefined) {
  17829. data.arrayBuffers[this.array.buffer._uuid] = Array.from(new Uint32Array(this.array.buffer));
  17830. }
  17831. //
  17832. return {
  17833. uuid: this.uuid,
  17834. buffer: this.array.buffer._uuid,
  17835. type: this.array.constructor.name,
  17836. stride: this.stride
  17837. };
  17838. }
  17839. }
  17840. const _vector$6 = /*@__PURE__*/new Vector3();
  17841. class InterleavedBufferAttribute {
  17842. constructor(interleavedBuffer, itemSize, offset, normalized = false) {
  17843. this.isInterleavedBufferAttribute = true;
  17844. this.name = '';
  17845. this.data = interleavedBuffer;
  17846. this.itemSize = itemSize;
  17847. this.offset = offset;
  17848. this.normalized = normalized;
  17849. }
  17850. get count() {
  17851. return this.data.count;
  17852. }
  17853. get array() {
  17854. return this.data.array;
  17855. }
  17856. set needsUpdate(value) {
  17857. this.data.needsUpdate = value;
  17858. }
  17859. applyMatrix4(m) {
  17860. for (let i = 0, l = this.data.count; i < l; i++) {
  17861. _vector$6.fromBufferAttribute(this, i);
  17862. _vector$6.applyMatrix4(m);
  17863. this.setXYZ(i, _vector$6.x, _vector$6.y, _vector$6.z);
  17864. }
  17865. return this;
  17866. }
  17867. applyNormalMatrix(m) {
  17868. for (let i = 0, l = this.count; i < l; i++) {
  17869. _vector$6.fromBufferAttribute(this, i);
  17870. _vector$6.applyNormalMatrix(m);
  17871. this.setXYZ(i, _vector$6.x, _vector$6.y, _vector$6.z);
  17872. }
  17873. return this;
  17874. }
  17875. transformDirection(m) {
  17876. for (let i = 0, l = this.count; i < l; i++) {
  17877. _vector$6.fromBufferAttribute(this, i);
  17878. _vector$6.transformDirection(m);
  17879. this.setXYZ(i, _vector$6.x, _vector$6.y, _vector$6.z);
  17880. }
  17881. return this;
  17882. }
  17883. setX(index, x) {
  17884. if (this.normalized) x = normalize(x, this.array);
  17885. this.data.array[index * this.data.stride + this.offset] = x;
  17886. return this;
  17887. }
  17888. setY(index, y) {
  17889. if (this.normalized) y = normalize(y, this.array);
  17890. this.data.array[index * this.data.stride + this.offset + 1] = y;
  17891. return this;
  17892. }
  17893. setZ(index, z) {
  17894. if (this.normalized) z = normalize(z, this.array);
  17895. this.data.array[index * this.data.stride + this.offset + 2] = z;
  17896. return this;
  17897. }
  17898. setW(index, w) {
  17899. if (this.normalized) w = normalize(w, this.array);
  17900. this.data.array[index * this.data.stride + this.offset + 3] = w;
  17901. return this;
  17902. }
  17903. getX(index) {
  17904. let x = this.data.array[index * this.data.stride + this.offset];
  17905. if (this.normalized) x = denormalize(x, this.array);
  17906. return x;
  17907. }
  17908. getY(index) {
  17909. let y = this.data.array[index * this.data.stride + this.offset + 1];
  17910. if (this.normalized) y = denormalize(y, this.array);
  17911. return y;
  17912. }
  17913. getZ(index) {
  17914. let z = this.data.array[index * this.data.stride + this.offset + 2];
  17915. if (this.normalized) z = denormalize(z, this.array);
  17916. return z;
  17917. }
  17918. getW(index) {
  17919. let w = this.data.array[index * this.data.stride + this.offset + 3];
  17920. if (this.normalized) w = denormalize(w, this.array);
  17921. return w;
  17922. }
  17923. setXY(index, x, y) {
  17924. index = index * this.data.stride + this.offset;
  17925. if (this.normalized) {
  17926. x = normalize(x, this.array);
  17927. y = normalize(y, this.array);
  17928. }
  17929. this.data.array[index + 0] = x;
  17930. this.data.array[index + 1] = y;
  17931. return this;
  17932. }
  17933. setXYZ(index, x, y, z) {
  17934. index = index * this.data.stride + this.offset;
  17935. if (this.normalized) {
  17936. x = normalize(x, this.array);
  17937. y = normalize(y, this.array);
  17938. z = normalize(z, this.array);
  17939. }
  17940. this.data.array[index + 0] = x;
  17941. this.data.array[index + 1] = y;
  17942. this.data.array[index + 2] = z;
  17943. return this;
  17944. }
  17945. setXYZW(index, x, y, z, w) {
  17946. index = index * this.data.stride + this.offset;
  17947. if (this.normalized) {
  17948. x = normalize(x, this.array);
  17949. y = normalize(y, this.array);
  17950. z = normalize(z, this.array);
  17951. w = normalize(w, this.array);
  17952. }
  17953. this.data.array[index + 0] = x;
  17954. this.data.array[index + 1] = y;
  17955. this.data.array[index + 2] = z;
  17956. this.data.array[index + 3] = w;
  17957. return this;
  17958. }
  17959. clone(data) {
  17960. if (data === undefined) {
  17961. console.log('THREE.InterleavedBufferAttribute.clone(): Cloning an interleaved buffer attribute will de-interleave buffer data.');
  17962. const array = [];
  17963. for (let i = 0; i < this.count; i++) {
  17964. const index = i * this.data.stride + this.offset;
  17965. for (let j = 0; j < this.itemSize; j++) {
  17966. array.push(this.data.array[index + j]);
  17967. }
  17968. }
  17969. return new BufferAttribute(new this.array.constructor(array), this.itemSize, this.normalized);
  17970. } else {
  17971. if (data.interleavedBuffers === undefined) {
  17972. data.interleavedBuffers = {};
  17973. }
  17974. if (data.interleavedBuffers[this.data.uuid] === undefined) {
  17975. data.interleavedBuffers[this.data.uuid] = this.data.clone(data);
  17976. }
  17977. return new InterleavedBufferAttribute(data.interleavedBuffers[this.data.uuid], this.itemSize, this.offset, this.normalized);
  17978. }
  17979. }
  17980. toJSON(data) {
  17981. if (data === undefined) {
  17982. console.log('THREE.InterleavedBufferAttribute.toJSON(): Serializing an interleaved buffer attribute will de-interleave buffer data.');
  17983. const array = [];
  17984. for (let i = 0; i < this.count; i++) {
  17985. const index = i * this.data.stride + this.offset;
  17986. for (let j = 0; j < this.itemSize; j++) {
  17987. array.push(this.data.array[index + j]);
  17988. }
  17989. }
  17990. // de-interleave data and save it as an ordinary buffer attribute for now
  17991. return {
  17992. itemSize: this.itemSize,
  17993. type: this.array.constructor.name,
  17994. array: array,
  17995. normalized: this.normalized
  17996. };
  17997. } else {
  17998. // save as true interleaved attribute
  17999. if (data.interleavedBuffers === undefined) {
  18000. data.interleavedBuffers = {};
  18001. }
  18002. if (data.interleavedBuffers[this.data.uuid] === undefined) {
  18003. data.interleavedBuffers[this.data.uuid] = this.data.toJSON(data);
  18004. }
  18005. return {
  18006. isInterleavedBufferAttribute: true,
  18007. itemSize: this.itemSize,
  18008. data: this.data.uuid,
  18009. offset: this.offset,
  18010. normalized: this.normalized
  18011. };
  18012. }
  18013. }
  18014. }
  18015. class SpriteMaterial extends Material {
  18016. constructor(parameters) {
  18017. super();
  18018. this.isSpriteMaterial = true;
  18019. this.type = 'SpriteMaterial';
  18020. this.color = new Color(0xffffff);
  18021. this.map = null;
  18022. this.alphaMap = null;
  18023. this.rotation = 0;
  18024. this.sizeAttenuation = true;
  18025. this.transparent = true;
  18026. this.fog = true;
  18027. this.setValues(parameters);
  18028. }
  18029. copy(source) {
  18030. super.copy(source);
  18031. this.color.copy(source.color);
  18032. this.map = source.map;
  18033. this.alphaMap = source.alphaMap;
  18034. this.rotation = source.rotation;
  18035. this.sizeAttenuation = source.sizeAttenuation;
  18036. this.fog = source.fog;
  18037. return this;
  18038. }
  18039. }
  18040. let _geometry;
  18041. const _intersectPoint = /*@__PURE__*/new Vector3();
  18042. const _worldScale = /*@__PURE__*/new Vector3();
  18043. const _mvPosition = /*@__PURE__*/new Vector3();
  18044. const _alignedPosition = /*@__PURE__*/new Vector2();
  18045. const _rotatedPosition = /*@__PURE__*/new Vector2();
  18046. const _viewWorldMatrix = /*@__PURE__*/new Matrix4();
  18047. const _vA = /*@__PURE__*/new Vector3();
  18048. const _vB = /*@__PURE__*/new Vector3();
  18049. const _vC = /*@__PURE__*/new Vector3();
  18050. const _uvA = /*@__PURE__*/new Vector2();
  18051. const _uvB = /*@__PURE__*/new Vector2();
  18052. const _uvC = /*@__PURE__*/new Vector2();
  18053. class Sprite extends Object3D {
  18054. constructor(material) {
  18055. super();
  18056. this.isSprite = true;
  18057. this.type = 'Sprite';
  18058. if (_geometry === undefined) {
  18059. _geometry = new BufferGeometry();
  18060. 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]);
  18061. const interleavedBuffer = new InterleavedBuffer(float32Array, 5);
  18062. _geometry.setIndex([0, 1, 2, 0, 2, 3]);
  18063. _geometry.setAttribute('position', new InterleavedBufferAttribute(interleavedBuffer, 3, 0, false));
  18064. _geometry.setAttribute('uv', new InterleavedBufferAttribute(interleavedBuffer, 2, 3, false));
  18065. }
  18066. this.geometry = _geometry;
  18067. this.material = material !== undefined ? material : new SpriteMaterial();
  18068. this.center = new Vector2(0.5, 0.5);
  18069. }
  18070. raycast(raycaster, intersects) {
  18071. if (raycaster.camera === null) {
  18072. console.error('THREE.Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.');
  18073. }
  18074. _worldScale.setFromMatrixScale(this.matrixWorld);
  18075. _viewWorldMatrix.copy(raycaster.camera.matrixWorld);
  18076. this.modelViewMatrix.multiplyMatrices(raycaster.camera.matrixWorldInverse, this.matrixWorld);
  18077. _mvPosition.setFromMatrixPosition(this.modelViewMatrix);
  18078. if (raycaster.camera.isPerspectiveCamera && this.material.sizeAttenuation === false) {
  18079. _worldScale.multiplyScalar(-_mvPosition.z);
  18080. }
  18081. const rotation = this.material.rotation;
  18082. let sin, cos;
  18083. if (rotation !== 0) {
  18084. cos = Math.cos(rotation);
  18085. sin = Math.sin(rotation);
  18086. }
  18087. const center = this.center;
  18088. transformVertex(_vA.set(-0.5, -0.5, 0), _mvPosition, center, _worldScale, sin, cos);
  18089. transformVertex(_vB.set(0.5, -0.5, 0), _mvPosition, center, _worldScale, sin, cos);
  18090. transformVertex(_vC.set(0.5, 0.5, 0), _mvPosition, center, _worldScale, sin, cos);
  18091. _uvA.set(0, 0);
  18092. _uvB.set(1, 0);
  18093. _uvC.set(1, 1);
  18094. // check first triangle
  18095. let intersect = raycaster.ray.intersectTriangle(_vA, _vB, _vC, false, _intersectPoint);
  18096. if (intersect === null) {
  18097. // check second triangle
  18098. transformVertex(_vB.set(-0.5, 0.5, 0), _mvPosition, center, _worldScale, sin, cos);
  18099. _uvB.set(0, 1);
  18100. intersect = raycaster.ray.intersectTriangle(_vA, _vC, _vB, false, _intersectPoint);
  18101. if (intersect === null) {
  18102. return;
  18103. }
  18104. }
  18105. const distance = raycaster.ray.origin.distanceTo(_intersectPoint);
  18106. if (distance < raycaster.near || distance > raycaster.far) return;
  18107. intersects.push({
  18108. distance: distance,
  18109. point: _intersectPoint.clone(),
  18110. uv: Triangle.getUV(_intersectPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2()),
  18111. face: null,
  18112. object: this
  18113. });
  18114. }
  18115. copy(source, recursive) {
  18116. super.copy(source, recursive);
  18117. if (source.center !== undefined) this.center.copy(source.center);
  18118. this.material = source.material;
  18119. return this;
  18120. }
  18121. }
  18122. function transformVertex(vertexPosition, mvPosition, center, scale, sin, cos) {
  18123. // compute position in camera space
  18124. _alignedPosition.subVectors(vertexPosition, center).addScalar(0.5).multiply(scale);
  18125. // to check if rotation is not zero
  18126. if (sin !== undefined) {
  18127. _rotatedPosition.x = cos * _alignedPosition.x - sin * _alignedPosition.y;
  18128. _rotatedPosition.y = sin * _alignedPosition.x + cos * _alignedPosition.y;
  18129. } else {
  18130. _rotatedPosition.copy(_alignedPosition);
  18131. }
  18132. vertexPosition.copy(mvPosition);
  18133. vertexPosition.x += _rotatedPosition.x;
  18134. vertexPosition.y += _rotatedPosition.y;
  18135. // transform to world space
  18136. vertexPosition.applyMatrix4(_viewWorldMatrix);
  18137. }
  18138. const _v1$2 = /*@__PURE__*/new Vector3();
  18139. const _v2$1 = /*@__PURE__*/new Vector3();
  18140. class LOD extends Object3D {
  18141. constructor() {
  18142. super();
  18143. this._currentLevel = 0;
  18144. this.type = 'LOD';
  18145. Object.defineProperties(this, {
  18146. levels: {
  18147. enumerable: true,
  18148. value: []
  18149. },
  18150. isLOD: {
  18151. value: true
  18152. }
  18153. });
  18154. this.autoUpdate = true;
  18155. }
  18156. copy(source) {
  18157. super.copy(source, false);
  18158. const levels = source.levels;
  18159. for (let i = 0, l = levels.length; i < l; i++) {
  18160. const level = levels[i];
  18161. this.addLevel(level.object.clone(), level.distance, level.hysteresis);
  18162. }
  18163. this.autoUpdate = source.autoUpdate;
  18164. return this;
  18165. }
  18166. addLevel(object, distance = 0, hysteresis = 0) {
  18167. distance = Math.abs(distance);
  18168. const levels = this.levels;
  18169. let l;
  18170. for (l = 0; l < levels.length; l++) {
  18171. if (distance < levels[l].distance) {
  18172. break;
  18173. }
  18174. }
  18175. levels.splice(l, 0, {
  18176. distance: distance,
  18177. hysteresis: hysteresis,
  18178. object: object
  18179. });
  18180. this.add(object);
  18181. return this;
  18182. }
  18183. getCurrentLevel() {
  18184. return this._currentLevel;
  18185. }
  18186. getObjectForDistance(distance) {
  18187. const levels = this.levels;
  18188. if (levels.length > 0) {
  18189. let i, l;
  18190. for (i = 1, l = levels.length; i < l; i++) {
  18191. let levelDistance = levels[i].distance;
  18192. if (levels[i].object.visible) {
  18193. levelDistance -= levelDistance * levels[i].hysteresis;
  18194. }
  18195. if (distance < levelDistance) {
  18196. break;
  18197. }
  18198. }
  18199. return levels[i - 1].object;
  18200. }
  18201. return null;
  18202. }
  18203. raycast(raycaster, intersects) {
  18204. const levels = this.levels;
  18205. if (levels.length > 0) {
  18206. _v1$2.setFromMatrixPosition(this.matrixWorld);
  18207. const distance = raycaster.ray.origin.distanceTo(_v1$2);
  18208. this.getObjectForDistance(distance).raycast(raycaster, intersects);
  18209. }
  18210. }
  18211. update(camera) {
  18212. const levels = this.levels;
  18213. if (levels.length > 1) {
  18214. _v1$2.setFromMatrixPosition(camera.matrixWorld);
  18215. _v2$1.setFromMatrixPosition(this.matrixWorld);
  18216. const distance = _v1$2.distanceTo(_v2$1) / camera.zoom;
  18217. levels[0].object.visible = true;
  18218. let i, l;
  18219. for (i = 1, l = levels.length; i < l; i++) {
  18220. let levelDistance = levels[i].distance;
  18221. if (levels[i].object.visible) {
  18222. levelDistance -= levelDistance * levels[i].hysteresis;
  18223. }
  18224. if (distance >= levelDistance) {
  18225. levels[i - 1].object.visible = false;
  18226. levels[i].object.visible = true;
  18227. } else {
  18228. break;
  18229. }
  18230. }
  18231. this._currentLevel = i - 1;
  18232. for (; i < l; i++) {
  18233. levels[i].object.visible = false;
  18234. }
  18235. }
  18236. }
  18237. toJSON(meta) {
  18238. const data = super.toJSON(meta);
  18239. if (this.autoUpdate === false) data.object.autoUpdate = false;
  18240. data.object.levels = [];
  18241. const levels = this.levels;
  18242. for (let i = 0, l = levels.length; i < l; i++) {
  18243. const level = levels[i];
  18244. data.object.levels.push({
  18245. object: level.object.uuid,
  18246. distance: level.distance,
  18247. hysteresis: level.hysteresis
  18248. });
  18249. }
  18250. return data;
  18251. }
  18252. }
  18253. const _basePosition = /*@__PURE__*/new Vector3();
  18254. const _skinIndex = /*@__PURE__*/new Vector4();
  18255. const _skinWeight = /*@__PURE__*/new Vector4();
  18256. const _vector$5 = /*@__PURE__*/new Vector3();
  18257. const _matrix = /*@__PURE__*/new Matrix4();
  18258. class SkinnedMesh extends Mesh {
  18259. constructor(geometry, material) {
  18260. super(geometry, material);
  18261. this.isSkinnedMesh = true;
  18262. this.type = 'SkinnedMesh';
  18263. this.bindMode = 'attached';
  18264. this.bindMatrix = new Matrix4();
  18265. this.bindMatrixInverse = new Matrix4();
  18266. }
  18267. copy(source, recursive) {
  18268. super.copy(source, recursive);
  18269. this.bindMode = source.bindMode;
  18270. this.bindMatrix.copy(source.bindMatrix);
  18271. this.bindMatrixInverse.copy(source.bindMatrixInverse);
  18272. this.skeleton = source.skeleton;
  18273. return this;
  18274. }
  18275. bind(skeleton, bindMatrix) {
  18276. this.skeleton = skeleton;
  18277. if (bindMatrix === undefined) {
  18278. this.updateMatrixWorld(true);
  18279. this.skeleton.calculateInverses();
  18280. bindMatrix = this.matrixWorld;
  18281. }
  18282. this.bindMatrix.copy(bindMatrix);
  18283. this.bindMatrixInverse.copy(bindMatrix).invert();
  18284. }
  18285. pose() {
  18286. this.skeleton.pose();
  18287. }
  18288. normalizeSkinWeights() {
  18289. const vector = new Vector4();
  18290. const skinWeight = this.geometry.attributes.skinWeight;
  18291. for (let i = 0, l = skinWeight.count; i < l; i++) {
  18292. vector.fromBufferAttribute(skinWeight, i);
  18293. const scale = 1.0 / vector.manhattanLength();
  18294. if (scale !== Infinity) {
  18295. vector.multiplyScalar(scale);
  18296. } else {
  18297. vector.set(1, 0, 0, 0); // do something reasonable
  18298. }
  18299. skinWeight.setXYZW(i, vector.x, vector.y, vector.z, vector.w);
  18300. }
  18301. }
  18302. updateMatrixWorld(force) {
  18303. super.updateMatrixWorld(force);
  18304. if (this.bindMode === 'attached') {
  18305. this.bindMatrixInverse.copy(this.matrixWorld).invert();
  18306. } else if (this.bindMode === 'detached') {
  18307. this.bindMatrixInverse.copy(this.bindMatrix).invert();
  18308. } else {
  18309. console.warn('THREE.SkinnedMesh: Unrecognized bindMode: ' + this.bindMode);
  18310. }
  18311. }
  18312. boneTransform(index, target) {
  18313. const skeleton = this.skeleton;
  18314. const geometry = this.geometry;
  18315. _skinIndex.fromBufferAttribute(geometry.attributes.skinIndex, index);
  18316. _skinWeight.fromBufferAttribute(geometry.attributes.skinWeight, index);
  18317. _basePosition.copy(target).applyMatrix4(this.bindMatrix);
  18318. target.set(0, 0, 0);
  18319. for (let i = 0; i < 4; i++) {
  18320. const weight = _skinWeight.getComponent(i);
  18321. if (weight !== 0) {
  18322. const boneIndex = _skinIndex.getComponent(i);
  18323. _matrix.multiplyMatrices(skeleton.bones[boneIndex].matrixWorld, skeleton.boneInverses[boneIndex]);
  18324. target.addScaledVector(_vector$5.copy(_basePosition).applyMatrix4(_matrix), weight);
  18325. }
  18326. }
  18327. return target.applyMatrix4(this.bindMatrixInverse);
  18328. }
  18329. }
  18330. class Bone extends Object3D {
  18331. constructor() {
  18332. super();
  18333. this.isBone = true;
  18334. this.type = 'Bone';
  18335. }
  18336. }
  18337. class DataTexture extends Texture {
  18338. constructor(data = null, width = 1, height = 1, format, type, mapping, wrapS, wrapT, magFilter = NearestFilter, minFilter = NearestFilter, anisotropy, encoding) {
  18339. super(null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding);
  18340. this.isDataTexture = true;
  18341. this.image = {
  18342. data: data,
  18343. width: width,
  18344. height: height
  18345. };
  18346. this.generateMipmaps = false;
  18347. this.flipY = false;
  18348. this.unpackAlignment = 1;
  18349. }
  18350. }
  18351. const _offsetMatrix = /*@__PURE__*/new Matrix4();
  18352. const _identityMatrix = /*@__PURE__*/new Matrix4();
  18353. class Skeleton {
  18354. constructor(bones = [], boneInverses = []) {
  18355. this.uuid = generateUUID();
  18356. this.bones = bones.slice(0);
  18357. this.boneInverses = boneInverses;
  18358. this.boneMatrices = null;
  18359. this.boneTexture = null;
  18360. this.boneTextureSize = 0;
  18361. this.frame = -1;
  18362. this.init();
  18363. }
  18364. init() {
  18365. const bones = this.bones;
  18366. const boneInverses = this.boneInverses;
  18367. this.boneMatrices = new Float32Array(bones.length * 16);
  18368. // calculate inverse bone matrices if necessary
  18369. if (boneInverses.length === 0) {
  18370. this.calculateInverses();
  18371. } else {
  18372. // handle special case
  18373. if (bones.length !== boneInverses.length) {
  18374. console.warn('THREE.Skeleton: Number of inverse bone matrices does not match amount of bones.');
  18375. this.boneInverses = [];
  18376. for (let i = 0, il = this.bones.length; i < il; i++) {
  18377. this.boneInverses.push(new Matrix4());
  18378. }
  18379. }
  18380. }
  18381. }
  18382. calculateInverses() {
  18383. this.boneInverses.length = 0;
  18384. for (let i = 0, il = this.bones.length; i < il; i++) {
  18385. const inverse = new Matrix4();
  18386. if (this.bones[i]) {
  18387. inverse.copy(this.bones[i].matrixWorld).invert();
  18388. }
  18389. this.boneInverses.push(inverse);
  18390. }
  18391. }
  18392. pose() {
  18393. // recover the bind-time world matrices
  18394. for (let i = 0, il = this.bones.length; i < il; i++) {
  18395. const bone = this.bones[i];
  18396. if (bone) {
  18397. bone.matrixWorld.copy(this.boneInverses[i]).invert();
  18398. }
  18399. }
  18400. // compute the local matrices, positions, rotations and scales
  18401. for (let i = 0, il = this.bones.length; i < il; i++) {
  18402. const bone = this.bones[i];
  18403. if (bone) {
  18404. if (bone.parent && bone.parent.isBone) {
  18405. bone.matrix.copy(bone.parent.matrixWorld).invert();
  18406. bone.matrix.multiply(bone.matrixWorld);
  18407. } else {
  18408. bone.matrix.copy(bone.matrixWorld);
  18409. }
  18410. bone.matrix.decompose(bone.position, bone.quaternion, bone.scale);
  18411. }
  18412. }
  18413. }
  18414. update() {
  18415. const bones = this.bones;
  18416. const boneInverses = this.boneInverses;
  18417. const boneMatrices = this.boneMatrices;
  18418. const boneTexture = this.boneTexture;
  18419. // flatten bone matrices to array
  18420. for (let i = 0, il = bones.length; i < il; i++) {
  18421. // compute the offset between the current and the original transform
  18422. const matrix = bones[i] ? bones[i].matrixWorld : _identityMatrix;
  18423. _offsetMatrix.multiplyMatrices(matrix, boneInverses[i]);
  18424. _offsetMatrix.toArray(boneMatrices, i * 16);
  18425. }
  18426. if (boneTexture !== null) {
  18427. boneTexture.needsUpdate = true;
  18428. }
  18429. }
  18430. clone() {
  18431. return new Skeleton(this.bones, this.boneInverses);
  18432. }
  18433. computeBoneTexture() {
  18434. // layout (1 matrix = 4 pixels)
  18435. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  18436. // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8)
  18437. // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16)
  18438. // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32)
  18439. // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64)
  18440. let size = Math.sqrt(this.bones.length * 4); // 4 pixels needed for 1 matrix
  18441. size = ceilPowerOfTwo(size);
  18442. size = Math.max(size, 4);
  18443. const boneMatrices = new Float32Array(size * size * 4); // 4 floats per RGBA pixel
  18444. boneMatrices.set(this.boneMatrices); // copy current values
  18445. const boneTexture = new DataTexture(boneMatrices, size, size, RGBAFormat, FloatType);
  18446. boneTexture.needsUpdate = true;
  18447. this.boneMatrices = boneMatrices;
  18448. this.boneTexture = boneTexture;
  18449. this.boneTextureSize = size;
  18450. return this;
  18451. }
  18452. getBoneByName(name) {
  18453. for (let i = 0, il = this.bones.length; i < il; i++) {
  18454. const bone = this.bones[i];
  18455. if (bone.name === name) {
  18456. return bone;
  18457. }
  18458. }
  18459. return undefined;
  18460. }
  18461. dispose() {
  18462. if (this.boneTexture !== null) {
  18463. this.boneTexture.dispose();
  18464. this.boneTexture = null;
  18465. }
  18466. }
  18467. fromJSON(json, bones) {
  18468. this.uuid = json.uuid;
  18469. for (let i = 0, l = json.bones.length; i < l; i++) {
  18470. const uuid = json.bones[i];
  18471. let bone = bones[uuid];
  18472. if (bone === undefined) {
  18473. console.warn('THREE.Skeleton: No bone found with UUID:', uuid);
  18474. bone = new Bone();
  18475. }
  18476. this.bones.push(bone);
  18477. this.boneInverses.push(new Matrix4().fromArray(json.boneInverses[i]));
  18478. }
  18479. this.init();
  18480. return this;
  18481. }
  18482. toJSON() {
  18483. const data = {
  18484. metadata: {
  18485. version: 4.5,
  18486. type: 'Skeleton',
  18487. generator: 'Skeleton.toJSON'
  18488. },
  18489. bones: [],
  18490. boneInverses: []
  18491. };
  18492. data.uuid = this.uuid;
  18493. const bones = this.bones;
  18494. const boneInverses = this.boneInverses;
  18495. for (let i = 0, l = bones.length; i < l; i++) {
  18496. const bone = bones[i];
  18497. data.bones.push(bone.uuid);
  18498. const boneInverse = boneInverses[i];
  18499. data.boneInverses.push(boneInverse.toArray());
  18500. }
  18501. return data;
  18502. }
  18503. }
  18504. class InstancedBufferAttribute extends BufferAttribute {
  18505. constructor(array, itemSize, normalized, meshPerAttribute = 1) {
  18506. super(array, itemSize, normalized);
  18507. this.isInstancedBufferAttribute = true;
  18508. this.meshPerAttribute = meshPerAttribute;
  18509. }
  18510. copy(source) {
  18511. super.copy(source);
  18512. this.meshPerAttribute = source.meshPerAttribute;
  18513. return this;
  18514. }
  18515. toJSON() {
  18516. const data = super.toJSON();
  18517. data.meshPerAttribute = this.meshPerAttribute;
  18518. data.isInstancedBufferAttribute = true;
  18519. return data;
  18520. }
  18521. }
  18522. const _instanceLocalMatrix = /*@__PURE__*/new Matrix4();
  18523. const _instanceWorldMatrix = /*@__PURE__*/new Matrix4();
  18524. const _instanceIntersects = [];
  18525. const _identity = /*@__PURE__*/new Matrix4();
  18526. const _mesh = /*@__PURE__*/new Mesh();
  18527. class InstancedMesh extends Mesh {
  18528. constructor(geometry, material, count) {
  18529. super(geometry, material);
  18530. this.isInstancedMesh = true;
  18531. this.instanceMatrix = new InstancedBufferAttribute(new Float32Array(count * 16), 16);
  18532. this.instanceColor = null;
  18533. this.count = count;
  18534. this.frustumCulled = false;
  18535. for (let i = 0; i < count; i++) {
  18536. this.setMatrixAt(i, _identity);
  18537. }
  18538. }
  18539. copy(source, recursive) {
  18540. super.copy(source, recursive);
  18541. this.instanceMatrix.copy(source.instanceMatrix);
  18542. if (source.instanceColor !== null) this.instanceColor = source.instanceColor.clone();
  18543. this.count = source.count;
  18544. return this;
  18545. }
  18546. getColorAt(index, color) {
  18547. color.fromArray(this.instanceColor.array, index * 3);
  18548. }
  18549. getMatrixAt(index, matrix) {
  18550. matrix.fromArray(this.instanceMatrix.array, index * 16);
  18551. }
  18552. raycast(raycaster, intersects) {
  18553. const matrixWorld = this.matrixWorld;
  18554. const raycastTimes = this.count;
  18555. _mesh.geometry = this.geometry;
  18556. _mesh.material = this.material;
  18557. if (_mesh.material === undefined) return;
  18558. for (let instanceId = 0; instanceId < raycastTimes; instanceId++) {
  18559. // calculate the world matrix for each instance
  18560. this.getMatrixAt(instanceId, _instanceLocalMatrix);
  18561. _instanceWorldMatrix.multiplyMatrices(matrixWorld, _instanceLocalMatrix);
  18562. // the mesh represents this single instance
  18563. _mesh.matrixWorld = _instanceWorldMatrix;
  18564. _mesh.raycast(raycaster, _instanceIntersects);
  18565. // process the result of raycast
  18566. for (let i = 0, l = _instanceIntersects.length; i < l; i++) {
  18567. const intersect = _instanceIntersects[i];
  18568. intersect.instanceId = instanceId;
  18569. intersect.object = this;
  18570. intersects.push(intersect);
  18571. }
  18572. _instanceIntersects.length = 0;
  18573. }
  18574. }
  18575. setColorAt(index, color) {
  18576. if (this.instanceColor === null) {
  18577. this.instanceColor = new InstancedBufferAttribute(new Float32Array(this.instanceMatrix.count * 3), 3);
  18578. }
  18579. color.toArray(this.instanceColor.array, index * 3);
  18580. }
  18581. setMatrixAt(index, matrix) {
  18582. matrix.toArray(this.instanceMatrix.array, index * 16);
  18583. }
  18584. updateMorphTargets() {}
  18585. dispose() {
  18586. this.dispatchEvent({
  18587. type: 'dispose'
  18588. });
  18589. }
  18590. }
  18591. class LineBasicMaterial extends Material {
  18592. constructor(parameters) {
  18593. super();
  18594. this.isLineBasicMaterial = true;
  18595. this.type = 'LineBasicMaterial';
  18596. this.color = new Color(0xffffff);
  18597. this.linewidth = 1;
  18598. this.linecap = 'round';
  18599. this.linejoin = 'round';
  18600. this.fog = true;
  18601. this.setValues(parameters);
  18602. }
  18603. copy(source) {
  18604. super.copy(source);
  18605. this.color.copy(source.color);
  18606. this.linewidth = source.linewidth;
  18607. this.linecap = source.linecap;
  18608. this.linejoin = source.linejoin;
  18609. this.fog = source.fog;
  18610. return this;
  18611. }
  18612. }
  18613. const _start$1 = /*@__PURE__*/new Vector3();
  18614. const _end$1 = /*@__PURE__*/new Vector3();
  18615. const _inverseMatrix$1 = /*@__PURE__*/new Matrix4();
  18616. const _ray$1 = /*@__PURE__*/new Ray();
  18617. const _sphere$1 = /*@__PURE__*/new Sphere();
  18618. class Line extends Object3D {
  18619. constructor(geometry = new BufferGeometry(), material = new LineBasicMaterial()) {
  18620. super();
  18621. this.isLine = true;
  18622. this.type = 'Line';
  18623. this.geometry = geometry;
  18624. this.material = material;
  18625. this.updateMorphTargets();
  18626. }
  18627. copy(source, recursive) {
  18628. super.copy(source, recursive);
  18629. this.material = source.material;
  18630. this.geometry = source.geometry;
  18631. return this;
  18632. }
  18633. computeLineDistances() {
  18634. const geometry = this.geometry;
  18635. // we assume non-indexed geometry
  18636. if (geometry.index === null) {
  18637. const positionAttribute = geometry.attributes.position;
  18638. const lineDistances = [0];
  18639. for (let i = 1, l = positionAttribute.count; i < l; i++) {
  18640. _start$1.fromBufferAttribute(positionAttribute, i - 1);
  18641. _end$1.fromBufferAttribute(positionAttribute, i);
  18642. lineDistances[i] = lineDistances[i - 1];
  18643. lineDistances[i] += _start$1.distanceTo(_end$1);
  18644. }
  18645. geometry.setAttribute('lineDistance', new Float32BufferAttribute(lineDistances, 1));
  18646. } else {
  18647. console.warn('THREE.Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.');
  18648. }
  18649. return this;
  18650. }
  18651. raycast(raycaster, intersects) {
  18652. const geometry = this.geometry;
  18653. const matrixWorld = this.matrixWorld;
  18654. const threshold = raycaster.params.Line.threshold;
  18655. const drawRange = geometry.drawRange;
  18656. // Checking boundingSphere distance to ray
  18657. if (geometry.boundingSphere === null) geometry.computeBoundingSphere();
  18658. _sphere$1.copy(geometry.boundingSphere);
  18659. _sphere$1.applyMatrix4(matrixWorld);
  18660. _sphere$1.radius += threshold;
  18661. if (raycaster.ray.intersectsSphere(_sphere$1) === false) return;
  18662. //
  18663. _inverseMatrix$1.copy(matrixWorld).invert();
  18664. _ray$1.copy(raycaster.ray).applyMatrix4(_inverseMatrix$1);
  18665. const localThreshold = threshold / ((this.scale.x + this.scale.y + this.scale.z) / 3);
  18666. const localThresholdSq = localThreshold * localThreshold;
  18667. const vStart = new Vector3();
  18668. const vEnd = new Vector3();
  18669. const interSegment = new Vector3();
  18670. const interRay = new Vector3();
  18671. const step = this.isLineSegments ? 2 : 1;
  18672. const index = geometry.index;
  18673. const attributes = geometry.attributes;
  18674. const positionAttribute = attributes.position;
  18675. if (index !== null) {
  18676. const start = Math.max(0, drawRange.start);
  18677. const end = Math.min(index.count, drawRange.start + drawRange.count);
  18678. for (let i = start, l = end - 1; i < l; i += step) {
  18679. const a = index.getX(i);
  18680. const b = index.getX(i + 1);
  18681. vStart.fromBufferAttribute(positionAttribute, a);
  18682. vEnd.fromBufferAttribute(positionAttribute, b);
  18683. const distSq = _ray$1.distanceSqToSegment(vStart, vEnd, interRay, interSegment);
  18684. if (distSq > localThresholdSq) continue;
  18685. interRay.applyMatrix4(this.matrixWorld); //Move back to world space for distance calculation
  18686. const distance = raycaster.ray.origin.distanceTo(interRay);
  18687. if (distance < raycaster.near || distance > raycaster.far) continue;
  18688. intersects.push({
  18689. distance: distance,
  18690. // What do we want? intersection point on the ray or on the segment??
  18691. // point: raycaster.ray.at( distance ),
  18692. point: interSegment.clone().applyMatrix4(this.matrixWorld),
  18693. index: i,
  18694. face: null,
  18695. faceIndex: null,
  18696. object: this
  18697. });
  18698. }
  18699. } else {
  18700. const start = Math.max(0, drawRange.start);
  18701. const end = Math.min(positionAttribute.count, drawRange.start + drawRange.count);
  18702. for (let i = start, l = end - 1; i < l; i += step) {
  18703. vStart.fromBufferAttribute(positionAttribute, i);
  18704. vEnd.fromBufferAttribute(positionAttribute, i + 1);
  18705. const distSq = _ray$1.distanceSqToSegment(vStart, vEnd, interRay, interSegment);
  18706. if (distSq > localThresholdSq) continue;
  18707. interRay.applyMatrix4(this.matrixWorld); //Move back to world space for distance calculation
  18708. const distance = raycaster.ray.origin.distanceTo(interRay);
  18709. if (distance < raycaster.near || distance > raycaster.far) continue;
  18710. intersects.push({
  18711. distance: distance,
  18712. // What do we want? intersection point on the ray or on the segment??
  18713. // point: raycaster.ray.at( distance ),
  18714. point: interSegment.clone().applyMatrix4(this.matrixWorld),
  18715. index: i,
  18716. face: null,
  18717. faceIndex: null,
  18718. object: this
  18719. });
  18720. }
  18721. }
  18722. }
  18723. updateMorphTargets() {
  18724. const geometry = this.geometry;
  18725. const morphAttributes = geometry.morphAttributes;
  18726. const keys = Object.keys(morphAttributes);
  18727. if (keys.length > 0) {
  18728. const morphAttribute = morphAttributes[keys[0]];
  18729. if (morphAttribute !== undefined) {
  18730. this.morphTargetInfluences = [];
  18731. this.morphTargetDictionary = {};
  18732. for (let m = 0, ml = morphAttribute.length; m < ml; m++) {
  18733. const name = morphAttribute[m].name || String(m);
  18734. this.morphTargetInfluences.push(0);
  18735. this.morphTargetDictionary[name] = m;
  18736. }
  18737. }
  18738. }
  18739. }
  18740. }
  18741. const _start = /*@__PURE__*/new Vector3();
  18742. const _end = /*@__PURE__*/new Vector3();
  18743. class LineSegments extends Line {
  18744. constructor(geometry, material) {
  18745. super(geometry, material);
  18746. this.isLineSegments = true;
  18747. this.type = 'LineSegments';
  18748. }
  18749. computeLineDistances() {
  18750. const geometry = this.geometry;
  18751. // we assume non-indexed geometry
  18752. if (geometry.index === null) {
  18753. const positionAttribute = geometry.attributes.position;
  18754. const lineDistances = [];
  18755. for (let i = 0, l = positionAttribute.count; i < l; i += 2) {
  18756. _start.fromBufferAttribute(positionAttribute, i);
  18757. _end.fromBufferAttribute(positionAttribute, i + 1);
  18758. lineDistances[i] = i === 0 ? 0 : lineDistances[i - 1];
  18759. lineDistances[i + 1] = lineDistances[i] + _start.distanceTo(_end);
  18760. }
  18761. geometry.setAttribute('lineDistance', new Float32BufferAttribute(lineDistances, 1));
  18762. } else {
  18763. console.warn('THREE.LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.');
  18764. }
  18765. return this;
  18766. }
  18767. }
  18768. class LineLoop extends Line {
  18769. constructor(geometry, material) {
  18770. super(geometry, material);
  18771. this.isLineLoop = true;
  18772. this.type = 'LineLoop';
  18773. }
  18774. }
  18775. class PointsMaterial extends Material {
  18776. constructor(parameters) {
  18777. super();
  18778. this.isPointsMaterial = true;
  18779. this.type = 'PointsMaterial';
  18780. this.color = new Color(0xffffff);
  18781. this.map = null;
  18782. this.alphaMap = null;
  18783. this.size = 1;
  18784. this.sizeAttenuation = true;
  18785. this.fog = true;
  18786. this.setValues(parameters);
  18787. }
  18788. copy(source) {
  18789. super.copy(source);
  18790. this.color.copy(source.color);
  18791. this.map = source.map;
  18792. this.alphaMap = source.alphaMap;
  18793. this.size = source.size;
  18794. this.sizeAttenuation = source.sizeAttenuation;
  18795. this.fog = source.fog;
  18796. return this;
  18797. }
  18798. }
  18799. const _inverseMatrix = /*@__PURE__*/new Matrix4();
  18800. const _ray = /*@__PURE__*/new Ray();
  18801. const _sphere = /*@__PURE__*/new Sphere();
  18802. const _position$2 = /*@__PURE__*/new Vector3();
  18803. class Points extends Object3D {
  18804. constructor(geometry = new BufferGeometry(), material = new PointsMaterial()) {
  18805. super();
  18806. this.isPoints = true;
  18807. this.type = 'Points';
  18808. this.geometry = geometry;
  18809. this.material = material;
  18810. this.updateMorphTargets();
  18811. }
  18812. copy(source, recursive) {
  18813. super.copy(source, recursive);
  18814. this.material = source.material;
  18815. this.geometry = source.geometry;
  18816. return this;
  18817. }
  18818. raycast(raycaster, intersects) {
  18819. const geometry = this.geometry;
  18820. const matrixWorld = this.matrixWorld;
  18821. const threshold = raycaster.params.Points.threshold;
  18822. const drawRange = geometry.drawRange;
  18823. // Checking boundingSphere distance to ray
  18824. if (geometry.boundingSphere === null) geometry.computeBoundingSphere();
  18825. _sphere.copy(geometry.boundingSphere);
  18826. _sphere.applyMatrix4(matrixWorld);
  18827. _sphere.radius += threshold;
  18828. if (raycaster.ray.intersectsSphere(_sphere) === false) return;
  18829. //
  18830. _inverseMatrix.copy(matrixWorld).invert();
  18831. _ray.copy(raycaster.ray).applyMatrix4(_inverseMatrix);
  18832. const localThreshold = threshold / ((this.scale.x + this.scale.y + this.scale.z) / 3);
  18833. const localThresholdSq = localThreshold * localThreshold;
  18834. const index = geometry.index;
  18835. const attributes = geometry.attributes;
  18836. const positionAttribute = attributes.position;
  18837. if (index !== null) {
  18838. const start = Math.max(0, drawRange.start);
  18839. const end = Math.min(index.count, drawRange.start + drawRange.count);
  18840. for (let i = start, il = end; i < il; i++) {
  18841. const a = index.getX(i);
  18842. _position$2.fromBufferAttribute(positionAttribute, a);
  18843. testPoint(_position$2, a, localThresholdSq, matrixWorld, raycaster, intersects, this);
  18844. }
  18845. } else {
  18846. const start = Math.max(0, drawRange.start);
  18847. const end = Math.min(positionAttribute.count, drawRange.start + drawRange.count);
  18848. for (let i = start, l = end; i < l; i++) {
  18849. _position$2.fromBufferAttribute(positionAttribute, i);
  18850. testPoint(_position$2, i, localThresholdSq, matrixWorld, raycaster, intersects, this);
  18851. }
  18852. }
  18853. }
  18854. updateMorphTargets() {
  18855. const geometry = this.geometry;
  18856. const morphAttributes = geometry.morphAttributes;
  18857. const keys = Object.keys(morphAttributes);
  18858. if (keys.length > 0) {
  18859. const morphAttribute = morphAttributes[keys[0]];
  18860. if (morphAttribute !== undefined) {
  18861. this.morphTargetInfluences = [];
  18862. this.morphTargetDictionary = {};
  18863. for (let m = 0, ml = morphAttribute.length; m < ml; m++) {
  18864. const name = morphAttribute[m].name || String(m);
  18865. this.morphTargetInfluences.push(0);
  18866. this.morphTargetDictionary[name] = m;
  18867. }
  18868. }
  18869. }
  18870. }
  18871. }
  18872. function testPoint(point, index, localThresholdSq, matrixWorld, raycaster, intersects, object) {
  18873. const rayPointDistanceSq = _ray.distanceSqToPoint(point);
  18874. if (rayPointDistanceSq < localThresholdSq) {
  18875. const intersectPoint = new Vector3();
  18876. _ray.closestPointToPoint(point, intersectPoint);
  18877. intersectPoint.applyMatrix4(matrixWorld);
  18878. const distance = raycaster.ray.origin.distanceTo(intersectPoint);
  18879. if (distance < raycaster.near || distance > raycaster.far) return;
  18880. intersects.push({
  18881. distance: distance,
  18882. distanceToRay: Math.sqrt(rayPointDistanceSq),
  18883. point: intersectPoint,
  18884. index: index,
  18885. face: null,
  18886. object: object
  18887. });
  18888. }
  18889. }
  18890. class VideoTexture extends Texture {
  18891. constructor(video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy) {
  18892. super(video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy);
  18893. this.isVideoTexture = true;
  18894. this.minFilter = minFilter !== undefined ? minFilter : LinearFilter;
  18895. this.magFilter = magFilter !== undefined ? magFilter : LinearFilter;
  18896. this.generateMipmaps = false;
  18897. const scope = this;
  18898. function updateVideo() {
  18899. scope.needsUpdate = true;
  18900. video.requestVideoFrameCallback(updateVideo);
  18901. }
  18902. if ('requestVideoFrameCallback' in video) {
  18903. video.requestVideoFrameCallback(updateVideo);
  18904. }
  18905. }
  18906. clone() {
  18907. return new this.constructor(this.image).copy(this);
  18908. }
  18909. update() {
  18910. const video = this.image;
  18911. const hasVideoFrameCallback = ('requestVideoFrameCallback' in video);
  18912. if (hasVideoFrameCallback === false && video.readyState >= video.HAVE_CURRENT_DATA) {
  18913. this.needsUpdate = true;
  18914. }
  18915. }
  18916. }
  18917. class FramebufferTexture extends Texture {
  18918. constructor(width, height, format) {
  18919. super({
  18920. width,
  18921. height
  18922. });
  18923. this.isFramebufferTexture = true;
  18924. this.format = format;
  18925. this.magFilter = NearestFilter;
  18926. this.minFilter = NearestFilter;
  18927. this.generateMipmaps = false;
  18928. this.needsUpdate = true;
  18929. }
  18930. }
  18931. class CompressedTexture extends Texture {
  18932. constructor(mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding) {
  18933. super(null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding);
  18934. this.isCompressedTexture = true;
  18935. this.image = {
  18936. width: width,
  18937. height: height
  18938. };
  18939. this.mipmaps = mipmaps;
  18940. // no flipping for cube textures
  18941. // (also flipping doesn't work for compressed textures )
  18942. this.flipY = false;
  18943. // can't generate mipmaps for compressed textures
  18944. // mips must be embedded in DDS files
  18945. this.generateMipmaps = false;
  18946. }
  18947. }
  18948. class CompressedArrayTexture extends CompressedTexture {
  18949. constructor(mipmaps, width, height, depth, format, type) {
  18950. super(mipmaps, width, height, format, type);
  18951. this.isCompressedArrayTexture = true;
  18952. this.image.depth = depth;
  18953. this.wrapR = ClampToEdgeWrapping;
  18954. }
  18955. }
  18956. class CanvasTexture extends Texture {
  18957. constructor(canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy) {
  18958. super(canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy);
  18959. this.isCanvasTexture = true;
  18960. this.needsUpdate = true;
  18961. }
  18962. }
  18963. /**
  18964. * Extensible curve object.
  18965. *
  18966. * Some common of curve methods:
  18967. * .getPoint( t, optionalTarget ), .getTangent( t, optionalTarget )
  18968. * .getPointAt( u, optionalTarget ), .getTangentAt( u, optionalTarget )
  18969. * .getPoints(), .getSpacedPoints()
  18970. * .getLength()
  18971. * .updateArcLengths()
  18972. *
  18973. * This following curves inherit from THREE.Curve:
  18974. *
  18975. * -- 2D curves --
  18976. * THREE.ArcCurve
  18977. * THREE.CubicBezierCurve
  18978. * THREE.EllipseCurve
  18979. * THREE.LineCurve
  18980. * THREE.QuadraticBezierCurve
  18981. * THREE.SplineCurve
  18982. *
  18983. * -- 3D curves --
  18984. * THREE.CatmullRomCurve3
  18985. * THREE.CubicBezierCurve3
  18986. * THREE.LineCurve3
  18987. * THREE.QuadraticBezierCurve3
  18988. *
  18989. * A series of curves can be represented as a THREE.CurvePath.
  18990. *
  18991. **/
  18992. class Curve {
  18993. constructor() {
  18994. this.type = 'Curve';
  18995. this.arcLengthDivisions = 200;
  18996. }
  18997. // Virtual base class method to overwrite and implement in subclasses
  18998. // - t [0 .. 1]
  18999. getPoint( /* t, optionalTarget */
  19000. ) {
  19001. console.warn('THREE.Curve: .getPoint() not implemented.');
  19002. return null;
  19003. }
  19004. // Get point at relative position in curve according to arc length
  19005. // - u [0 .. 1]
  19006. getPointAt(u, optionalTarget) {
  19007. const t = this.getUtoTmapping(u);
  19008. return this.getPoint(t, optionalTarget);
  19009. }
  19010. // Get sequence of points using getPoint( t )
  19011. getPoints(divisions = 5) {
  19012. const points = [];
  19013. for (let d = 0; d <= divisions; d++) {
  19014. points.push(this.getPoint(d / divisions));
  19015. }
  19016. return points;
  19017. }
  19018. // Get sequence of points using getPointAt( u )
  19019. getSpacedPoints(divisions = 5) {
  19020. const points = [];
  19021. for (let d = 0; d <= divisions; d++) {
  19022. points.push(this.getPointAt(d / divisions));
  19023. }
  19024. return points;
  19025. }
  19026. // Get total curve arc length
  19027. getLength() {
  19028. const lengths = this.getLengths();
  19029. return lengths[lengths.length - 1];
  19030. }
  19031. // Get list of cumulative segment lengths
  19032. getLengths(divisions = this.arcLengthDivisions) {
  19033. if (this.cacheArcLengths && this.cacheArcLengths.length === divisions + 1 && !this.needsUpdate) {
  19034. return this.cacheArcLengths;
  19035. }
  19036. this.needsUpdate = false;
  19037. const cache = [];
  19038. let current,
  19039. last = this.getPoint(0);
  19040. let sum = 0;
  19041. cache.push(0);
  19042. for (let p = 1; p <= divisions; p++) {
  19043. current = this.getPoint(p / divisions);
  19044. sum += current.distanceTo(last);
  19045. cache.push(sum);
  19046. last = current;
  19047. }
  19048. this.cacheArcLengths = cache;
  19049. return cache; // { sums: cache, sum: sum }; Sum is in the last element.
  19050. }
  19051. updateArcLengths() {
  19052. this.needsUpdate = true;
  19053. this.getLengths();
  19054. }
  19055. // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equidistant
  19056. getUtoTmapping(u, distance) {
  19057. const arcLengths = this.getLengths();
  19058. let i = 0;
  19059. const il = arcLengths.length;
  19060. let targetArcLength; // The targeted u distance value to get
  19061. if (distance) {
  19062. targetArcLength = distance;
  19063. } else {
  19064. targetArcLength = u * arcLengths[il - 1];
  19065. }
  19066. // binary search for the index with largest value smaller than target u distance
  19067. let low = 0,
  19068. high = il - 1,
  19069. comparison;
  19070. while (low <= high) {
  19071. 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
  19072. comparison = arcLengths[i] - targetArcLength;
  19073. if (comparison < 0) {
  19074. low = i + 1;
  19075. } else if (comparison > 0) {
  19076. high = i - 1;
  19077. } else {
  19078. high = i;
  19079. break;
  19080. // DONE
  19081. }
  19082. }
  19083. i = high;
  19084. if (arcLengths[i] === targetArcLength) {
  19085. return i / (il - 1);
  19086. }
  19087. // we could get finer grain at lengths, or use simple interpolation between two points
  19088. const lengthBefore = arcLengths[i];
  19089. const lengthAfter = arcLengths[i + 1];
  19090. const segmentLength = lengthAfter - lengthBefore;
  19091. // determine where we are between the 'before' and 'after' points
  19092. const segmentFraction = (targetArcLength - lengthBefore) / segmentLength;
  19093. // add that fractional amount to t
  19094. const t = (i + segmentFraction) / (il - 1);
  19095. return t;
  19096. }
  19097. // Returns a unit vector tangent at t
  19098. // In case any sub curve does not implement its tangent derivation,
  19099. // 2 points a small delta apart will be used to find its gradient
  19100. // which seems to give a reasonable approximation
  19101. getTangent(t, optionalTarget) {
  19102. const delta = 0.0001;
  19103. let t1 = t - delta;
  19104. let t2 = t + delta;
  19105. // Capping in case of danger
  19106. if (t1 < 0) t1 = 0;
  19107. if (t2 > 1) t2 = 1;
  19108. const pt1 = this.getPoint(t1);
  19109. const pt2 = this.getPoint(t2);
  19110. const tangent = optionalTarget || (pt1.isVector2 ? new Vector2() : new Vector3());
  19111. tangent.copy(pt2).sub(pt1).normalize();
  19112. return tangent;
  19113. }
  19114. getTangentAt(u, optionalTarget) {
  19115. const t = this.getUtoTmapping(u);
  19116. return this.getTangent(t, optionalTarget);
  19117. }
  19118. computeFrenetFrames(segments, closed) {
  19119. // see http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  19120. const normal = new Vector3();
  19121. const tangents = [];
  19122. const normals = [];
  19123. const binormals = [];
  19124. const vec = new Vector3();
  19125. const mat = new Matrix4();
  19126. // compute the tangent vectors for each segment on the curve
  19127. for (let i = 0; i <= segments; i++) {
  19128. const u = i / segments;
  19129. tangents[i] = this.getTangentAt(u, new Vector3());
  19130. }
  19131. // select an initial normal vector perpendicular to the first tangent vector,
  19132. // and in the direction of the minimum tangent xyz component
  19133. normals[0] = new Vector3();
  19134. binormals[0] = new Vector3();
  19135. let min = Number.MAX_VALUE;
  19136. const tx = Math.abs(tangents[0].x);
  19137. const ty = Math.abs(tangents[0].y);
  19138. const tz = Math.abs(tangents[0].z);
  19139. if (tx <= min) {
  19140. min = tx;
  19141. normal.set(1, 0, 0);
  19142. }
  19143. if (ty <= min) {
  19144. min = ty;
  19145. normal.set(0, 1, 0);
  19146. }
  19147. if (tz <= min) {
  19148. normal.set(0, 0, 1);
  19149. }
  19150. vec.crossVectors(tangents[0], normal).normalize();
  19151. normals[0].crossVectors(tangents[0], vec);
  19152. binormals[0].crossVectors(tangents[0], normals[0]);
  19153. // compute the slowly-varying normal and binormal vectors for each segment on the curve
  19154. for (let i = 1; i <= segments; i++) {
  19155. normals[i] = normals[i - 1].clone();
  19156. binormals[i] = binormals[i - 1].clone();
  19157. vec.crossVectors(tangents[i - 1], tangents[i]);
  19158. if (vec.length() > Number.EPSILON) {
  19159. vec.normalize();
  19160. const theta = Math.acos(clamp(tangents[i - 1].dot(tangents[i]), -1, 1)); // clamp for floating pt errors
  19161. normals[i].applyMatrix4(mat.makeRotationAxis(vec, theta));
  19162. }
  19163. binormals[i].crossVectors(tangents[i], normals[i]);
  19164. }
  19165. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  19166. if (closed === true) {
  19167. let theta = Math.acos(clamp(normals[0].dot(normals[segments]), -1, 1));
  19168. theta /= segments;
  19169. if (tangents[0].dot(vec.crossVectors(normals[0], normals[segments])) > 0) {
  19170. theta = -theta;
  19171. }
  19172. for (let i = 1; i <= segments; i++) {
  19173. // twist a little...
  19174. normals[i].applyMatrix4(mat.makeRotationAxis(tangents[i], theta * i));
  19175. binormals[i].crossVectors(tangents[i], normals[i]);
  19176. }
  19177. }
  19178. return {
  19179. tangents: tangents,
  19180. normals: normals,
  19181. binormals: binormals
  19182. };
  19183. }
  19184. clone() {
  19185. return new this.constructor().copy(this);
  19186. }
  19187. copy(source) {
  19188. this.arcLengthDivisions = source.arcLengthDivisions;
  19189. return this;
  19190. }
  19191. toJSON() {
  19192. const data = {
  19193. metadata: {
  19194. version: 4.5,
  19195. type: 'Curve',
  19196. generator: 'Curve.toJSON'
  19197. }
  19198. };
  19199. data.arcLengthDivisions = this.arcLengthDivisions;
  19200. data.type = this.type;
  19201. return data;
  19202. }
  19203. fromJSON(json) {
  19204. this.arcLengthDivisions = json.arcLengthDivisions;
  19205. return this;
  19206. }
  19207. }
  19208. class EllipseCurve extends Curve {
  19209. constructor(aX = 0, aY = 0, xRadius = 1, yRadius = 1, aStartAngle = 0, aEndAngle = Math.PI * 2, aClockwise = false, aRotation = 0) {
  19210. super();
  19211. this.isEllipseCurve = true;
  19212. this.type = 'EllipseCurve';
  19213. this.aX = aX;
  19214. this.aY = aY;
  19215. this.xRadius = xRadius;
  19216. this.yRadius = yRadius;
  19217. this.aStartAngle = aStartAngle;
  19218. this.aEndAngle = aEndAngle;
  19219. this.aClockwise = aClockwise;
  19220. this.aRotation = aRotation;
  19221. }
  19222. getPoint(t, optionalTarget) {
  19223. const point = optionalTarget || new Vector2();
  19224. const twoPi = Math.PI * 2;
  19225. let deltaAngle = this.aEndAngle - this.aStartAngle;
  19226. const samePoints = Math.abs(deltaAngle) < Number.EPSILON;
  19227. // ensures that deltaAngle is 0 .. 2 PI
  19228. while (deltaAngle < 0) deltaAngle += twoPi;
  19229. while (deltaAngle > twoPi) deltaAngle -= twoPi;
  19230. if (deltaAngle < Number.EPSILON) {
  19231. if (samePoints) {
  19232. deltaAngle = 0;
  19233. } else {
  19234. deltaAngle = twoPi;
  19235. }
  19236. }
  19237. if (this.aClockwise === true && !samePoints) {
  19238. if (deltaAngle === twoPi) {
  19239. deltaAngle = -twoPi;
  19240. } else {
  19241. deltaAngle = deltaAngle - twoPi;
  19242. }
  19243. }
  19244. const angle = this.aStartAngle + t * deltaAngle;
  19245. let x = this.aX + this.xRadius * Math.cos(angle);
  19246. let y = this.aY + this.yRadius * Math.sin(angle);
  19247. if (this.aRotation !== 0) {
  19248. const cos = Math.cos(this.aRotation);
  19249. const sin = Math.sin(this.aRotation);
  19250. const tx = x - this.aX;
  19251. const ty = y - this.aY;
  19252. // Rotate the point about the center of the ellipse.
  19253. x = tx * cos - ty * sin + this.aX;
  19254. y = tx * sin + ty * cos + this.aY;
  19255. }
  19256. return point.set(x, y);
  19257. }
  19258. copy(source) {
  19259. super.copy(source);
  19260. this.aX = source.aX;
  19261. this.aY = source.aY;
  19262. this.xRadius = source.xRadius;
  19263. this.yRadius = source.yRadius;
  19264. this.aStartAngle = source.aStartAngle;
  19265. this.aEndAngle = source.aEndAngle;
  19266. this.aClockwise = source.aClockwise;
  19267. this.aRotation = source.aRotation;
  19268. return this;
  19269. }
  19270. toJSON() {
  19271. const data = super.toJSON();
  19272. data.aX = this.aX;
  19273. data.aY = this.aY;
  19274. data.xRadius = this.xRadius;
  19275. data.yRadius = this.yRadius;
  19276. data.aStartAngle = this.aStartAngle;
  19277. data.aEndAngle = this.aEndAngle;
  19278. data.aClockwise = this.aClockwise;
  19279. data.aRotation = this.aRotation;
  19280. return data;
  19281. }
  19282. fromJSON(json) {
  19283. super.fromJSON(json);
  19284. this.aX = json.aX;
  19285. this.aY = json.aY;
  19286. this.xRadius = json.xRadius;
  19287. this.yRadius = json.yRadius;
  19288. this.aStartAngle = json.aStartAngle;
  19289. this.aEndAngle = json.aEndAngle;
  19290. this.aClockwise = json.aClockwise;
  19291. this.aRotation = json.aRotation;
  19292. return this;
  19293. }
  19294. }
  19295. class ArcCurve extends EllipseCurve {
  19296. constructor(aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise) {
  19297. super(aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise);
  19298. this.isArcCurve = true;
  19299. this.type = 'ArcCurve';
  19300. }
  19301. }
  19302. /**
  19303. * Centripetal CatmullRom Curve - which is useful for avoiding
  19304. * cusps and self-intersections in non-uniform catmull rom curves.
  19305. * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf
  19306. *
  19307. * curve.type accepts centripetal(default), chordal and catmullrom
  19308. * curve.tension is used for catmullrom which defaults to 0.5
  19309. */
  19310. /*
  19311. Based on an optimized c++ solution in
  19312. - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/
  19313. - http://ideone.com/NoEbVM
  19314. This CubicPoly class could be used for reusing some variables and calculations,
  19315. but for three.js curve use, it could be possible inlined and flatten into a single function call
  19316. which can be placed in CurveUtils.
  19317. */
  19318. function CubicPoly() {
  19319. let c0 = 0,
  19320. c1 = 0,
  19321. c2 = 0,
  19322. c3 = 0;
  19323. /*
  19324. * Compute coefficients for a cubic polynomial
  19325. * p(s) = c0 + c1*s + c2*s^2 + c3*s^3
  19326. * such that
  19327. * p(0) = x0, p(1) = x1
  19328. * and
  19329. * p'(0) = t0, p'(1) = t1.
  19330. */
  19331. function init(x0, x1, t0, t1) {
  19332. c0 = x0;
  19333. c1 = t0;
  19334. c2 = -3 * x0 + 3 * x1 - 2 * t0 - t1;
  19335. c3 = 2 * x0 - 2 * x1 + t0 + t1;
  19336. }
  19337. return {
  19338. initCatmullRom: function (x0, x1, x2, x3, tension) {
  19339. init(x1, x2, tension * (x2 - x0), tension * (x3 - x1));
  19340. },
  19341. initNonuniformCatmullRom: function (x0, x1, x2, x3, dt0, dt1, dt2) {
  19342. // compute tangents when parameterized in [t1,t2]
  19343. let t1 = (x1 - x0) / dt0 - (x2 - x0) / (dt0 + dt1) + (x2 - x1) / dt1;
  19344. let t2 = (x2 - x1) / dt1 - (x3 - x1) / (dt1 + dt2) + (x3 - x2) / dt2;
  19345. // rescale tangents for parametrization in [0,1]
  19346. t1 *= dt1;
  19347. t2 *= dt1;
  19348. init(x1, x2, t1, t2);
  19349. },
  19350. calc: function (t) {
  19351. const t2 = t * t;
  19352. const t3 = t2 * t;
  19353. return c0 + c1 * t + c2 * t2 + c3 * t3;
  19354. }
  19355. };
  19356. }
  19357. //
  19358. const tmp = /*@__PURE__*/new Vector3();
  19359. const px = /*@__PURE__*/new CubicPoly();
  19360. const py = /*@__PURE__*/new CubicPoly();
  19361. const pz = /*@__PURE__*/new CubicPoly();
  19362. class CatmullRomCurve3 extends Curve {
  19363. constructor(points = [], closed = false, curveType = 'centripetal', tension = 0.5) {
  19364. super();
  19365. this.isCatmullRomCurve3 = true;
  19366. this.type = 'CatmullRomCurve3';
  19367. this.points = points;
  19368. this.closed = closed;
  19369. this.curveType = curveType;
  19370. this.tension = tension;
  19371. }
  19372. getPoint(t, optionalTarget = new Vector3()) {
  19373. const point = optionalTarget;
  19374. const points = this.points;
  19375. const l = points.length;
  19376. const p = (l - (this.closed ? 0 : 1)) * t;
  19377. let intPoint = Math.floor(p);
  19378. let weight = p - intPoint;
  19379. if (this.closed) {
  19380. intPoint += intPoint > 0 ? 0 : (Math.floor(Math.abs(intPoint) / l) + 1) * l;
  19381. } else if (weight === 0 && intPoint === l - 1) {
  19382. intPoint = l - 2;
  19383. weight = 1;
  19384. }
  19385. let p0, p3; // 4 points (p1 & p2 defined below)
  19386. if (this.closed || intPoint > 0) {
  19387. p0 = points[(intPoint - 1) % l];
  19388. } else {
  19389. // extrapolate first point
  19390. tmp.subVectors(points[0], points[1]).add(points[0]);
  19391. p0 = tmp;
  19392. }
  19393. const p1 = points[intPoint % l];
  19394. const p2 = points[(intPoint + 1) % l];
  19395. if (this.closed || intPoint + 2 < l) {
  19396. p3 = points[(intPoint + 2) % l];
  19397. } else {
  19398. // extrapolate last point
  19399. tmp.subVectors(points[l - 1], points[l - 2]).add(points[l - 1]);
  19400. p3 = tmp;
  19401. }
  19402. if (this.curveType === 'centripetal' || this.curveType === 'chordal') {
  19403. // init Centripetal / Chordal Catmull-Rom
  19404. const pow = this.curveType === 'chordal' ? 0.5 : 0.25;
  19405. let dt0 = Math.pow(p0.distanceToSquared(p1), pow);
  19406. let dt1 = Math.pow(p1.distanceToSquared(p2), pow);
  19407. let dt2 = Math.pow(p2.distanceToSquared(p3), pow);
  19408. // safety check for repeated points
  19409. if (dt1 < 1e-4) dt1 = 1.0;
  19410. if (dt0 < 1e-4) dt0 = dt1;
  19411. if (dt2 < 1e-4) dt2 = dt1;
  19412. px.initNonuniformCatmullRom(p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2);
  19413. py.initNonuniformCatmullRom(p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2);
  19414. pz.initNonuniformCatmullRom(p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2);
  19415. } else if (this.curveType === 'catmullrom') {
  19416. px.initCatmullRom(p0.x, p1.x, p2.x, p3.x, this.tension);
  19417. py.initCatmullRom(p0.y, p1.y, p2.y, p3.y, this.tension);
  19418. pz.initCatmullRom(p0.z, p1.z, p2.z, p3.z, this.tension);
  19419. }
  19420. point.set(px.calc(weight), py.calc(weight), pz.calc(weight));
  19421. return point;
  19422. }
  19423. copy(source) {
  19424. super.copy(source);
  19425. this.points = [];
  19426. for (let i = 0, l = source.points.length; i < l; i++) {
  19427. const point = source.points[i];
  19428. this.points.push(point.clone());
  19429. }
  19430. this.closed = source.closed;
  19431. this.curveType = source.curveType;
  19432. this.tension = source.tension;
  19433. return this;
  19434. }
  19435. toJSON() {
  19436. const data = super.toJSON();
  19437. data.points = [];
  19438. for (let i = 0, l = this.points.length; i < l; i++) {
  19439. const point = this.points[i];
  19440. data.points.push(point.toArray());
  19441. }
  19442. data.closed = this.closed;
  19443. data.curveType = this.curveType;
  19444. data.tension = this.tension;
  19445. return data;
  19446. }
  19447. fromJSON(json) {
  19448. super.fromJSON(json);
  19449. this.points = [];
  19450. for (let i = 0, l = json.points.length; i < l; i++) {
  19451. const point = json.points[i];
  19452. this.points.push(new Vector3().fromArray(point));
  19453. }
  19454. this.closed = json.closed;
  19455. this.curveType = json.curveType;
  19456. this.tension = json.tension;
  19457. return this;
  19458. }
  19459. }
  19460. /**
  19461. * Bezier Curves formulas obtained from
  19462. * https://en.wikipedia.org/wiki/B%C3%A9zier_curve
  19463. */
  19464. function CatmullRom(t, p0, p1, p2, p3) {
  19465. const v0 = (p2 - p0) * 0.5;
  19466. const v1 = (p3 - p1) * 0.5;
  19467. const t2 = t * t;
  19468. const t3 = t * t2;
  19469. return (2 * p1 - 2 * p2 + v0 + v1) * t3 + (-3 * p1 + 3 * p2 - 2 * v0 - v1) * t2 + v0 * t + p1;
  19470. }
  19471. //
  19472. function QuadraticBezierP0(t, p) {
  19473. const k = 1 - t;
  19474. return k * k * p;
  19475. }
  19476. function QuadraticBezierP1(t, p) {
  19477. return 2 * (1 - t) * t * p;
  19478. }
  19479. function QuadraticBezierP2(t, p) {
  19480. return t * t * p;
  19481. }
  19482. function QuadraticBezier(t, p0, p1, p2) {
  19483. return QuadraticBezierP0(t, p0) + QuadraticBezierP1(t, p1) + QuadraticBezierP2(t, p2);
  19484. }
  19485. //
  19486. function CubicBezierP0(t, p) {
  19487. const k = 1 - t;
  19488. return k * k * k * p;
  19489. }
  19490. function CubicBezierP1(t, p) {
  19491. const k = 1 - t;
  19492. return 3 * k * k * t * p;
  19493. }
  19494. function CubicBezierP2(t, p) {
  19495. return 3 * (1 - t) * t * t * p;
  19496. }
  19497. function CubicBezierP3(t, p) {
  19498. return t * t * t * p;
  19499. }
  19500. function CubicBezier(t, p0, p1, p2, p3) {
  19501. return CubicBezierP0(t, p0) + CubicBezierP1(t, p1) + CubicBezierP2(t, p2) + CubicBezierP3(t, p3);
  19502. }
  19503. class CubicBezierCurve extends Curve {
  19504. constructor(v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2(), v3 = new Vector2()) {
  19505. super();
  19506. this.isCubicBezierCurve = true;
  19507. this.type = 'CubicBezierCurve';
  19508. this.v0 = v0;
  19509. this.v1 = v1;
  19510. this.v2 = v2;
  19511. this.v3 = v3;
  19512. }
  19513. getPoint(t, optionalTarget = new Vector2()) {
  19514. const point = optionalTarget;
  19515. const v0 = this.v0,
  19516. v1 = this.v1,
  19517. v2 = this.v2,
  19518. v3 = this.v3;
  19519. point.set(CubicBezier(t, v0.x, v1.x, v2.x, v3.x), CubicBezier(t, v0.y, v1.y, v2.y, v3.y));
  19520. return point;
  19521. }
  19522. copy(source) {
  19523. super.copy(source);
  19524. this.v0.copy(source.v0);
  19525. this.v1.copy(source.v1);
  19526. this.v2.copy(source.v2);
  19527. this.v3.copy(source.v3);
  19528. return this;
  19529. }
  19530. toJSON() {
  19531. const data = super.toJSON();
  19532. data.v0 = this.v0.toArray();
  19533. data.v1 = this.v1.toArray();
  19534. data.v2 = this.v2.toArray();
  19535. data.v3 = this.v3.toArray();
  19536. return data;
  19537. }
  19538. fromJSON(json) {
  19539. super.fromJSON(json);
  19540. this.v0.fromArray(json.v0);
  19541. this.v1.fromArray(json.v1);
  19542. this.v2.fromArray(json.v2);
  19543. this.v3.fromArray(json.v3);
  19544. return this;
  19545. }
  19546. }
  19547. class CubicBezierCurve3 extends Curve {
  19548. constructor(v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3(), v3 = new Vector3()) {
  19549. super();
  19550. this.isCubicBezierCurve3 = true;
  19551. this.type = 'CubicBezierCurve3';
  19552. this.v0 = v0;
  19553. this.v1 = v1;
  19554. this.v2 = v2;
  19555. this.v3 = v3;
  19556. }
  19557. getPoint(t, optionalTarget = new Vector3()) {
  19558. const point = optionalTarget;
  19559. const v0 = this.v0,
  19560. v1 = this.v1,
  19561. v2 = this.v2,
  19562. v3 = this.v3;
  19563. 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));
  19564. return point;
  19565. }
  19566. copy(source) {
  19567. super.copy(source);
  19568. this.v0.copy(source.v0);
  19569. this.v1.copy(source.v1);
  19570. this.v2.copy(source.v2);
  19571. this.v3.copy(source.v3);
  19572. return this;
  19573. }
  19574. toJSON() {
  19575. const data = super.toJSON();
  19576. data.v0 = this.v0.toArray();
  19577. data.v1 = this.v1.toArray();
  19578. data.v2 = this.v2.toArray();
  19579. data.v3 = this.v3.toArray();
  19580. return data;
  19581. }
  19582. fromJSON(json) {
  19583. super.fromJSON(json);
  19584. this.v0.fromArray(json.v0);
  19585. this.v1.fromArray(json.v1);
  19586. this.v2.fromArray(json.v2);
  19587. this.v3.fromArray(json.v3);
  19588. return this;
  19589. }
  19590. }
  19591. class LineCurve extends Curve {
  19592. constructor(v1 = new Vector2(), v2 = new Vector2()) {
  19593. super();
  19594. this.isLineCurve = true;
  19595. this.type = 'LineCurve';
  19596. this.v1 = v1;
  19597. this.v2 = v2;
  19598. }
  19599. getPoint(t, optionalTarget = new Vector2()) {
  19600. const point = optionalTarget;
  19601. if (t === 1) {
  19602. point.copy(this.v2);
  19603. } else {
  19604. point.copy(this.v2).sub(this.v1);
  19605. point.multiplyScalar(t).add(this.v1);
  19606. }
  19607. return point;
  19608. }
  19609. // Line curve is linear, so we can overwrite default getPointAt
  19610. getPointAt(u, optionalTarget) {
  19611. return this.getPoint(u, optionalTarget);
  19612. }
  19613. getTangent(t, optionalTarget) {
  19614. const tangent = optionalTarget || new Vector2();
  19615. tangent.copy(this.v2).sub(this.v1).normalize();
  19616. return tangent;
  19617. }
  19618. copy(source) {
  19619. super.copy(source);
  19620. this.v1.copy(source.v1);
  19621. this.v2.copy(source.v2);
  19622. return this;
  19623. }
  19624. toJSON() {
  19625. const data = super.toJSON();
  19626. data.v1 = this.v1.toArray();
  19627. data.v2 = this.v2.toArray();
  19628. return data;
  19629. }
  19630. fromJSON(json) {
  19631. super.fromJSON(json);
  19632. this.v1.fromArray(json.v1);
  19633. this.v2.fromArray(json.v2);
  19634. return this;
  19635. }
  19636. }
  19637. class LineCurve3 extends Curve {
  19638. constructor(v1 = new Vector3(), v2 = new Vector3()) {
  19639. super();
  19640. this.isLineCurve3 = true;
  19641. this.type = 'LineCurve3';
  19642. this.v1 = v1;
  19643. this.v2 = v2;
  19644. }
  19645. getPoint(t, optionalTarget = new Vector3()) {
  19646. const point = optionalTarget;
  19647. if (t === 1) {
  19648. point.copy(this.v2);
  19649. } else {
  19650. point.copy(this.v2).sub(this.v1);
  19651. point.multiplyScalar(t).add(this.v1);
  19652. }
  19653. return point;
  19654. }
  19655. // Line curve is linear, so we can overwrite default getPointAt
  19656. getPointAt(u, optionalTarget) {
  19657. return this.getPoint(u, optionalTarget);
  19658. }
  19659. copy(source) {
  19660. super.copy(source);
  19661. this.v1.copy(source.v1);
  19662. this.v2.copy(source.v2);
  19663. return this;
  19664. }
  19665. toJSON() {
  19666. const data = super.toJSON();
  19667. data.v1 = this.v1.toArray();
  19668. data.v2 = this.v2.toArray();
  19669. return data;
  19670. }
  19671. fromJSON(json) {
  19672. super.fromJSON(json);
  19673. this.v1.fromArray(json.v1);
  19674. this.v2.fromArray(json.v2);
  19675. return this;
  19676. }
  19677. }
  19678. class QuadraticBezierCurve extends Curve {
  19679. constructor(v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2()) {
  19680. super();
  19681. this.isQuadraticBezierCurve = true;
  19682. this.type = 'QuadraticBezierCurve';
  19683. this.v0 = v0;
  19684. this.v1 = v1;
  19685. this.v2 = v2;
  19686. }
  19687. getPoint(t, optionalTarget = new Vector2()) {
  19688. const point = optionalTarget;
  19689. const v0 = this.v0,
  19690. v1 = this.v1,
  19691. v2 = this.v2;
  19692. point.set(QuadraticBezier(t, v0.x, v1.x, v2.x), QuadraticBezier(t, v0.y, v1.y, v2.y));
  19693. return point;
  19694. }
  19695. copy(source) {
  19696. super.copy(source);
  19697. this.v0.copy(source.v0);
  19698. this.v1.copy(source.v1);
  19699. this.v2.copy(source.v2);
  19700. return this;
  19701. }
  19702. toJSON() {
  19703. const data = super.toJSON();
  19704. data.v0 = this.v0.toArray();
  19705. data.v1 = this.v1.toArray();
  19706. data.v2 = this.v2.toArray();
  19707. return data;
  19708. }
  19709. fromJSON(json) {
  19710. super.fromJSON(json);
  19711. this.v0.fromArray(json.v0);
  19712. this.v1.fromArray(json.v1);
  19713. this.v2.fromArray(json.v2);
  19714. return this;
  19715. }
  19716. }
  19717. class QuadraticBezierCurve3 extends Curve {
  19718. constructor(v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3()) {
  19719. super();
  19720. this.isQuadraticBezierCurve3 = true;
  19721. this.type = 'QuadraticBezierCurve3';
  19722. this.v0 = v0;
  19723. this.v1 = v1;
  19724. this.v2 = v2;
  19725. }
  19726. getPoint(t, optionalTarget = new Vector3()) {
  19727. const point = optionalTarget;
  19728. const v0 = this.v0,
  19729. v1 = this.v1,
  19730. v2 = this.v2;
  19731. 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));
  19732. return point;
  19733. }
  19734. copy(source) {
  19735. super.copy(source);
  19736. this.v0.copy(source.v0);
  19737. this.v1.copy(source.v1);
  19738. this.v2.copy(source.v2);
  19739. return this;
  19740. }
  19741. toJSON() {
  19742. const data = super.toJSON();
  19743. data.v0 = this.v0.toArray();
  19744. data.v1 = this.v1.toArray();
  19745. data.v2 = this.v2.toArray();
  19746. return data;
  19747. }
  19748. fromJSON(json) {
  19749. super.fromJSON(json);
  19750. this.v0.fromArray(json.v0);
  19751. this.v1.fromArray(json.v1);
  19752. this.v2.fromArray(json.v2);
  19753. return this;
  19754. }
  19755. }
  19756. class SplineCurve extends Curve {
  19757. constructor(points = []) {
  19758. super();
  19759. this.isSplineCurve = true;
  19760. this.type = 'SplineCurve';
  19761. this.points = points;
  19762. }
  19763. getPoint(t, optionalTarget = new Vector2()) {
  19764. const point = optionalTarget;
  19765. const points = this.points;
  19766. const p = (points.length - 1) * t;
  19767. const intPoint = Math.floor(p);
  19768. const weight = p - intPoint;
  19769. const p0 = points[intPoint === 0 ? intPoint : intPoint - 1];
  19770. const p1 = points[intPoint];
  19771. const p2 = points[intPoint > points.length - 2 ? points.length - 1 : intPoint + 1];
  19772. const p3 = points[intPoint > points.length - 3 ? points.length - 1 : intPoint + 2];
  19773. point.set(CatmullRom(weight, p0.x, p1.x, p2.x, p3.x), CatmullRom(weight, p0.y, p1.y, p2.y, p3.y));
  19774. return point;
  19775. }
  19776. copy(source) {
  19777. super.copy(source);
  19778. this.points = [];
  19779. for (let i = 0, l = source.points.length; i < l; i++) {
  19780. const point = source.points[i];
  19781. this.points.push(point.clone());
  19782. }
  19783. return this;
  19784. }
  19785. toJSON() {
  19786. const data = super.toJSON();
  19787. data.points = [];
  19788. for (let i = 0, l = this.points.length; i < l; i++) {
  19789. const point = this.points[i];
  19790. data.points.push(point.toArray());
  19791. }
  19792. return data;
  19793. }
  19794. fromJSON(json) {
  19795. super.fromJSON(json);
  19796. this.points = [];
  19797. for (let i = 0, l = json.points.length; i < l; i++) {
  19798. const point = json.points[i];
  19799. this.points.push(new Vector2().fromArray(point));
  19800. }
  19801. return this;
  19802. }
  19803. }
  19804. var Curves = /*#__PURE__*/Object.freeze({
  19805. __proto__: null,
  19806. ArcCurve: ArcCurve,
  19807. CatmullRomCurve3: CatmullRomCurve3,
  19808. CubicBezierCurve: CubicBezierCurve,
  19809. CubicBezierCurve3: CubicBezierCurve3,
  19810. EllipseCurve: EllipseCurve,
  19811. LineCurve: LineCurve,
  19812. LineCurve3: LineCurve3,
  19813. QuadraticBezierCurve: QuadraticBezierCurve,
  19814. QuadraticBezierCurve3: QuadraticBezierCurve3,
  19815. SplineCurve: SplineCurve
  19816. });
  19817. /**************************************************************
  19818. * Curved Path - a curve path is simply a array of connected
  19819. * curves, but retains the api of a curve
  19820. **************************************************************/
  19821. class CurvePath extends Curve {
  19822. constructor() {
  19823. super();
  19824. this.type = 'CurvePath';
  19825. this.curves = [];
  19826. this.autoClose = false; // Automatically closes the path
  19827. }
  19828. add(curve) {
  19829. this.curves.push(curve);
  19830. }
  19831. closePath() {
  19832. // Add a line curve if start and end of lines are not connected
  19833. const startPoint = this.curves[0].getPoint(0);
  19834. const endPoint = this.curves[this.curves.length - 1].getPoint(1);
  19835. if (!startPoint.equals(endPoint)) {
  19836. this.curves.push(new LineCurve(endPoint, startPoint));
  19837. }
  19838. }
  19839. // To get accurate point with reference to
  19840. // entire path distance at time t,
  19841. // following has to be done:
  19842. // 1. Length of each sub path have to be known
  19843. // 2. Locate and identify type of curve
  19844. // 3. Get t for the curve
  19845. // 4. Return curve.getPointAt(t')
  19846. getPoint(t, optionalTarget) {
  19847. const d = t * this.getLength();
  19848. const curveLengths = this.getCurveLengths();
  19849. let i = 0;
  19850. // To think about boundaries points.
  19851. while (i < curveLengths.length) {
  19852. if (curveLengths[i] >= d) {
  19853. const diff = curveLengths[i] - d;
  19854. const curve = this.curves[i];
  19855. const segmentLength = curve.getLength();
  19856. const u = segmentLength === 0 ? 0 : 1 - diff / segmentLength;
  19857. return curve.getPointAt(u, optionalTarget);
  19858. }
  19859. i++;
  19860. }
  19861. return null;
  19862. // loop where sum != 0, sum > d , sum+1 <d
  19863. }
  19864. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  19865. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  19866. // getPoint() depends on getLength
  19867. getLength() {
  19868. const lens = this.getCurveLengths();
  19869. return lens[lens.length - 1];
  19870. }
  19871. // cacheLengths must be recalculated.
  19872. updateArcLengths() {
  19873. this.needsUpdate = true;
  19874. this.cacheLengths = null;
  19875. this.getCurveLengths();
  19876. }
  19877. // Compute lengths and cache them
  19878. // We cannot overwrite getLengths() because UtoT mapping uses it.
  19879. getCurveLengths() {
  19880. // We use cache values if curves and cache array are same length
  19881. if (this.cacheLengths && this.cacheLengths.length === this.curves.length) {
  19882. return this.cacheLengths;
  19883. }
  19884. // Get length of sub-curve
  19885. // Push sums into cached array
  19886. const lengths = [];
  19887. let sums = 0;
  19888. for (let i = 0, l = this.curves.length; i < l; i++) {
  19889. sums += this.curves[i].getLength();
  19890. lengths.push(sums);
  19891. }
  19892. this.cacheLengths = lengths;
  19893. return lengths;
  19894. }
  19895. getSpacedPoints(divisions = 40) {
  19896. const points = [];
  19897. for (let i = 0; i <= divisions; i++) {
  19898. points.push(this.getPoint(i / divisions));
  19899. }
  19900. if (this.autoClose) {
  19901. points.push(points[0]);
  19902. }
  19903. return points;
  19904. }
  19905. getPoints(divisions = 12) {
  19906. const points = [];
  19907. let last;
  19908. for (let i = 0, curves = this.curves; i < curves.length; i++) {
  19909. const curve = curves[i];
  19910. const resolution = curve.isEllipseCurve ? divisions * 2 : curve.isLineCurve || curve.isLineCurve3 ? 1 : curve.isSplineCurve ? divisions * curve.points.length : divisions;
  19911. const pts = curve.getPoints(resolution);
  19912. for (let j = 0; j < pts.length; j++) {
  19913. const point = pts[j];
  19914. if (last && last.equals(point)) continue; // ensures no consecutive points are duplicates
  19915. points.push(point);
  19916. last = point;
  19917. }
  19918. }
  19919. if (this.autoClose && points.length > 1 && !points[points.length - 1].equals(points[0])) {
  19920. points.push(points[0]);
  19921. }
  19922. return points;
  19923. }
  19924. copy(source) {
  19925. super.copy(source);
  19926. this.curves = [];
  19927. for (let i = 0, l = source.curves.length; i < l; i++) {
  19928. const curve = source.curves[i];
  19929. this.curves.push(curve.clone());
  19930. }
  19931. this.autoClose = source.autoClose;
  19932. return this;
  19933. }
  19934. toJSON() {
  19935. const data = super.toJSON();
  19936. data.autoClose = this.autoClose;
  19937. data.curves = [];
  19938. for (let i = 0, l = this.curves.length; i < l; i++) {
  19939. const curve = this.curves[i];
  19940. data.curves.push(curve.toJSON());
  19941. }
  19942. return data;
  19943. }
  19944. fromJSON(json) {
  19945. super.fromJSON(json);
  19946. this.autoClose = json.autoClose;
  19947. this.curves = [];
  19948. for (let i = 0, l = json.curves.length; i < l; i++) {
  19949. const curve = json.curves[i];
  19950. this.curves.push(new Curves[curve.type]().fromJSON(curve));
  19951. }
  19952. return this;
  19953. }
  19954. }
  19955. class Path extends CurvePath {
  19956. constructor(points) {
  19957. super();
  19958. this.type = 'Path';
  19959. this.currentPoint = new Vector2();
  19960. if (points) {
  19961. this.setFromPoints(points);
  19962. }
  19963. }
  19964. setFromPoints(points) {
  19965. this.moveTo(points[0].x, points[0].y);
  19966. for (let i = 1, l = points.length; i < l; i++) {
  19967. this.lineTo(points[i].x, points[i].y);
  19968. }
  19969. return this;
  19970. }
  19971. moveTo(x, y) {
  19972. this.currentPoint.set(x, y); // TODO consider referencing vectors instead of copying?
  19973. return this;
  19974. }
  19975. lineTo(x, y) {
  19976. const curve = new LineCurve(this.currentPoint.clone(), new Vector2(x, y));
  19977. this.curves.push(curve);
  19978. this.currentPoint.set(x, y);
  19979. return this;
  19980. }
  19981. quadraticCurveTo(aCPx, aCPy, aX, aY) {
  19982. const curve = new QuadraticBezierCurve(this.currentPoint.clone(), new Vector2(aCPx, aCPy), new Vector2(aX, aY));
  19983. this.curves.push(curve);
  19984. this.currentPoint.set(aX, aY);
  19985. return this;
  19986. }
  19987. bezierCurveTo(aCP1x, aCP1y, aCP2x, aCP2y, aX, aY) {
  19988. const curve = new CubicBezierCurve(this.currentPoint.clone(), new Vector2(aCP1x, aCP1y), new Vector2(aCP2x, aCP2y), new Vector2(aX, aY));
  19989. this.curves.push(curve);
  19990. this.currentPoint.set(aX, aY);
  19991. return this;
  19992. }
  19993. splineThru(pts /*Array of Vector*/) {
  19994. const npts = [this.currentPoint.clone()].concat(pts);
  19995. const curve = new SplineCurve(npts);
  19996. this.curves.push(curve);
  19997. this.currentPoint.copy(pts[pts.length - 1]);
  19998. return this;
  19999. }
  20000. arc(aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise) {
  20001. const x0 = this.currentPoint.x;
  20002. const y0 = this.currentPoint.y;
  20003. this.absarc(aX + x0, aY + y0, aRadius, aStartAngle, aEndAngle, aClockwise);
  20004. return this;
  20005. }
  20006. absarc(aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise) {
  20007. this.absellipse(aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise);
  20008. return this;
  20009. }
  20010. ellipse(aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation) {
  20011. const x0 = this.currentPoint.x;
  20012. const y0 = this.currentPoint.y;
  20013. this.absellipse(aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation);
  20014. return this;
  20015. }
  20016. absellipse(aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation) {
  20017. const curve = new EllipseCurve(aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation);
  20018. if (this.curves.length > 0) {
  20019. // if a previous curve is present, attempt to join
  20020. const firstPoint = curve.getPoint(0);
  20021. if (!firstPoint.equals(this.currentPoint)) {
  20022. this.lineTo(firstPoint.x, firstPoint.y);
  20023. }
  20024. }
  20025. this.curves.push(curve);
  20026. const lastPoint = curve.getPoint(1);
  20027. this.currentPoint.copy(lastPoint);
  20028. return this;
  20029. }
  20030. copy(source) {
  20031. super.copy(source);
  20032. this.currentPoint.copy(source.currentPoint);
  20033. return this;
  20034. }
  20035. toJSON() {
  20036. const data = super.toJSON();
  20037. data.currentPoint = this.currentPoint.toArray();
  20038. return data;
  20039. }
  20040. fromJSON(json) {
  20041. super.fromJSON(json);
  20042. this.currentPoint.fromArray(json.currentPoint);
  20043. return this;
  20044. }
  20045. }
  20046. class LatheGeometry extends BufferGeometry {
  20047. 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) {
  20048. super();
  20049. this.type = 'LatheGeometry';
  20050. this.parameters = {
  20051. points: points,
  20052. segments: segments,
  20053. phiStart: phiStart,
  20054. phiLength: phiLength
  20055. };
  20056. segments = Math.floor(segments);
  20057. // clamp phiLength so it's in range of [ 0, 2PI ]
  20058. phiLength = clamp(phiLength, 0, Math.PI * 2);
  20059. // buffers
  20060. const indices = [];
  20061. const vertices = [];
  20062. const uvs = [];
  20063. const initNormals = [];
  20064. const normals = [];
  20065. // helper variables
  20066. const inverseSegments = 1.0 / segments;
  20067. const vertex = new Vector3();
  20068. const uv = new Vector2();
  20069. const normal = new Vector3();
  20070. const curNormal = new Vector3();
  20071. const prevNormal = new Vector3();
  20072. let dx = 0;
  20073. let dy = 0;
  20074. // pre-compute normals for initial "meridian"
  20075. for (let j = 0; j <= points.length - 1; j++) {
  20076. switch (j) {
  20077. case 0:
  20078. // special handling for 1st vertex on path
  20079. dx = points[j + 1].x - points[j].x;
  20080. dy = points[j + 1].y - points[j].y;
  20081. normal.x = dy * 1.0;
  20082. normal.y = -dx;
  20083. normal.z = dy * 0.0;
  20084. prevNormal.copy(normal);
  20085. normal.normalize();
  20086. initNormals.push(normal.x, normal.y, normal.z);
  20087. break;
  20088. case points.length - 1:
  20089. // special handling for last Vertex on path
  20090. initNormals.push(prevNormal.x, prevNormal.y, prevNormal.z);
  20091. break;
  20092. default:
  20093. // default handling for all vertices in between
  20094. dx = points[j + 1].x - points[j].x;
  20095. dy = points[j + 1].y - points[j].y;
  20096. normal.x = dy * 1.0;
  20097. normal.y = -dx;
  20098. normal.z = dy * 0.0;
  20099. curNormal.copy(normal);
  20100. normal.x += prevNormal.x;
  20101. normal.y += prevNormal.y;
  20102. normal.z += prevNormal.z;
  20103. normal.normalize();
  20104. initNormals.push(normal.x, normal.y, normal.z);
  20105. prevNormal.copy(curNormal);
  20106. }
  20107. }
  20108. // generate vertices, uvs and normals
  20109. for (let i = 0; i <= segments; i++) {
  20110. const phi = phiStart + i * inverseSegments * phiLength;
  20111. const sin = Math.sin(phi);
  20112. const cos = Math.cos(phi);
  20113. for (let j = 0; j <= points.length - 1; j++) {
  20114. // vertex
  20115. vertex.x = points[j].x * sin;
  20116. vertex.y = points[j].y;
  20117. vertex.z = points[j].x * cos;
  20118. vertices.push(vertex.x, vertex.y, vertex.z);
  20119. // uv
  20120. uv.x = i / segments;
  20121. uv.y = j / (points.length - 1);
  20122. uvs.push(uv.x, uv.y);
  20123. // normal
  20124. const x = initNormals[3 * j + 0] * sin;
  20125. const y = initNormals[3 * j + 1];
  20126. const z = initNormals[3 * j + 0] * cos;
  20127. normals.push(x, y, z);
  20128. }
  20129. }
  20130. // indices
  20131. for (let i = 0; i < segments; i++) {
  20132. for (let j = 0; j < points.length - 1; j++) {
  20133. const base = j + i * points.length;
  20134. const a = base;
  20135. const b = base + points.length;
  20136. const c = base + points.length + 1;
  20137. const d = base + 1;
  20138. // faces
  20139. indices.push(a, b, d);
  20140. indices.push(c, d, b);
  20141. }
  20142. }
  20143. // build geometry
  20144. this.setIndex(indices);
  20145. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  20146. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  20147. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  20148. }
  20149. static fromJSON(data) {
  20150. return new LatheGeometry(data.points, data.segments, data.phiStart, data.phiLength);
  20151. }
  20152. }
  20153. class CapsuleGeometry extends LatheGeometry {
  20154. constructor(radius = 1, length = 1, capSegments = 4, radialSegments = 8) {
  20155. const path = new Path();
  20156. path.absarc(0, -length / 2, radius, Math.PI * 1.5, 0);
  20157. path.absarc(0, length / 2, radius, 0, Math.PI * 0.5);
  20158. super(path.getPoints(capSegments), radialSegments);
  20159. this.type = 'CapsuleGeometry';
  20160. this.parameters = {
  20161. radius: radius,
  20162. height: length,
  20163. capSegments: capSegments,
  20164. radialSegments: radialSegments
  20165. };
  20166. }
  20167. static fromJSON(data) {
  20168. return new CapsuleGeometry(data.radius, data.length, data.capSegments, data.radialSegments);
  20169. }
  20170. }
  20171. class CircleGeometry extends BufferGeometry {
  20172. constructor(radius = 1, segments = 8, thetaStart = 0, thetaLength = Math.PI * 2) {
  20173. super();
  20174. this.type = 'CircleGeometry';
  20175. this.parameters = {
  20176. radius: radius,
  20177. segments: segments,
  20178. thetaStart: thetaStart,
  20179. thetaLength: thetaLength
  20180. };
  20181. segments = Math.max(3, segments);
  20182. // buffers
  20183. const indices = [];
  20184. const vertices = [];
  20185. const normals = [];
  20186. const uvs = [];
  20187. // helper variables
  20188. const vertex = new Vector3();
  20189. const uv = new Vector2();
  20190. // center point
  20191. vertices.push(0, 0, 0);
  20192. normals.push(0, 0, 1);
  20193. uvs.push(0.5, 0.5);
  20194. for (let s = 0, i = 3; s <= segments; s++, i += 3) {
  20195. const segment = thetaStart + s / segments * thetaLength;
  20196. // vertex
  20197. vertex.x = radius * Math.cos(segment);
  20198. vertex.y = radius * Math.sin(segment);
  20199. vertices.push(vertex.x, vertex.y, vertex.z);
  20200. // normal
  20201. normals.push(0, 0, 1);
  20202. // uvs
  20203. uv.x = (vertices[i] / radius + 1) / 2;
  20204. uv.y = (vertices[i + 1] / radius + 1) / 2;
  20205. uvs.push(uv.x, uv.y);
  20206. }
  20207. // indices
  20208. for (let i = 1; i <= segments; i++) {
  20209. indices.push(i, i + 1, 0);
  20210. }
  20211. // build geometry
  20212. this.setIndex(indices);
  20213. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  20214. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  20215. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  20216. }
  20217. static fromJSON(data) {
  20218. return new CircleGeometry(data.radius, data.segments, data.thetaStart, data.thetaLength);
  20219. }
  20220. }
  20221. class CylinderGeometry extends BufferGeometry {
  20222. constructor(radiusTop = 1, radiusBottom = 1, height = 1, radialSegments = 8, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2) {
  20223. super();
  20224. this.type = 'CylinderGeometry';
  20225. this.parameters = {
  20226. radiusTop: radiusTop,
  20227. radiusBottom: radiusBottom,
  20228. height: height,
  20229. radialSegments: radialSegments,
  20230. heightSegments: heightSegments,
  20231. openEnded: openEnded,
  20232. thetaStart: thetaStart,
  20233. thetaLength: thetaLength
  20234. };
  20235. const scope = this;
  20236. radialSegments = Math.floor(radialSegments);
  20237. heightSegments = Math.floor(heightSegments);
  20238. // buffers
  20239. const indices = [];
  20240. const vertices = [];
  20241. const normals = [];
  20242. const uvs = [];
  20243. // helper variables
  20244. let index = 0;
  20245. const indexArray = [];
  20246. const halfHeight = height / 2;
  20247. let groupStart = 0;
  20248. // generate geometry
  20249. generateTorso();
  20250. if (openEnded === false) {
  20251. if (radiusTop > 0) generateCap(true);
  20252. if (radiusBottom > 0) generateCap(false);
  20253. }
  20254. // build geometry
  20255. this.setIndex(indices);
  20256. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  20257. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  20258. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  20259. function generateTorso() {
  20260. const normal = new Vector3();
  20261. const vertex = new Vector3();
  20262. let groupCount = 0;
  20263. // this will be used to calculate the normal
  20264. const slope = (radiusBottom - radiusTop) / height;
  20265. // generate vertices, normals and uvs
  20266. for (let y = 0; y <= heightSegments; y++) {
  20267. const indexRow = [];
  20268. const v = y / heightSegments;
  20269. // calculate the radius of the current row
  20270. const radius = v * (radiusBottom - radiusTop) + radiusTop;
  20271. for (let x = 0; x <= radialSegments; x++) {
  20272. const u = x / radialSegments;
  20273. const theta = u * thetaLength + thetaStart;
  20274. const sinTheta = Math.sin(theta);
  20275. const cosTheta = Math.cos(theta);
  20276. // vertex
  20277. vertex.x = radius * sinTheta;
  20278. vertex.y = -v * height + halfHeight;
  20279. vertex.z = radius * cosTheta;
  20280. vertices.push(vertex.x, vertex.y, vertex.z);
  20281. // normal
  20282. normal.set(sinTheta, slope, cosTheta).normalize();
  20283. normals.push(normal.x, normal.y, normal.z);
  20284. // uv
  20285. uvs.push(u, 1 - v);
  20286. // save index of vertex in respective row
  20287. indexRow.push(index++);
  20288. }
  20289. // now save vertices of the row in our index array
  20290. indexArray.push(indexRow);
  20291. }
  20292. // generate indices
  20293. for (let x = 0; x < radialSegments; x++) {
  20294. for (let y = 0; y < heightSegments; y++) {
  20295. // we use the index array to access the correct indices
  20296. const a = indexArray[y][x];
  20297. const b = indexArray[y + 1][x];
  20298. const c = indexArray[y + 1][x + 1];
  20299. const d = indexArray[y][x + 1];
  20300. // faces
  20301. indices.push(a, b, d);
  20302. indices.push(b, c, d);
  20303. // update group counter
  20304. groupCount += 6;
  20305. }
  20306. }
  20307. // add a group to the geometry. this will ensure multi material support
  20308. scope.addGroup(groupStart, groupCount, 0);
  20309. // calculate new start value for groups
  20310. groupStart += groupCount;
  20311. }
  20312. function generateCap(top) {
  20313. // save the index of the first center vertex
  20314. const centerIndexStart = index;
  20315. const uv = new Vector2();
  20316. const vertex = new Vector3();
  20317. let groupCount = 0;
  20318. const radius = top === true ? radiusTop : radiusBottom;
  20319. const sign = top === true ? 1 : -1;
  20320. // first we generate the center vertex data of the cap.
  20321. // because the geometry needs one set of uvs per face,
  20322. // we must generate a center vertex per face/segment
  20323. for (let x = 1; x <= radialSegments; x++) {
  20324. // vertex
  20325. vertices.push(0, halfHeight * sign, 0);
  20326. // normal
  20327. normals.push(0, sign, 0);
  20328. // uv
  20329. uvs.push(0.5, 0.5);
  20330. // increase index
  20331. index++;
  20332. }
  20333. // save the index of the last center vertex
  20334. const centerIndexEnd = index;
  20335. // now we generate the surrounding vertices, normals and uvs
  20336. for (let x = 0; x <= radialSegments; x++) {
  20337. const u = x / radialSegments;
  20338. const theta = u * thetaLength + thetaStart;
  20339. const cosTheta = Math.cos(theta);
  20340. const sinTheta = Math.sin(theta);
  20341. // vertex
  20342. vertex.x = radius * sinTheta;
  20343. vertex.y = halfHeight * sign;
  20344. vertex.z = radius * cosTheta;
  20345. vertices.push(vertex.x, vertex.y, vertex.z);
  20346. // normal
  20347. normals.push(0, sign, 0);
  20348. // uv
  20349. uv.x = cosTheta * 0.5 + 0.5;
  20350. uv.y = sinTheta * 0.5 * sign + 0.5;
  20351. uvs.push(uv.x, uv.y);
  20352. // increase index
  20353. index++;
  20354. }
  20355. // generate indices
  20356. for (let x = 0; x < radialSegments; x++) {
  20357. const c = centerIndexStart + x;
  20358. const i = centerIndexEnd + x;
  20359. if (top === true) {
  20360. // face top
  20361. indices.push(i, i + 1, c);
  20362. } else {
  20363. // face bottom
  20364. indices.push(i + 1, i, c);
  20365. }
  20366. groupCount += 3;
  20367. }
  20368. // add a group to the geometry. this will ensure multi material support
  20369. scope.addGroup(groupStart, groupCount, top === true ? 1 : 2);
  20370. // calculate new start value for groups
  20371. groupStart += groupCount;
  20372. }
  20373. }
  20374. static fromJSON(data) {
  20375. return new CylinderGeometry(data.radiusTop, data.radiusBottom, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength);
  20376. }
  20377. }
  20378. class ConeGeometry extends CylinderGeometry {
  20379. constructor(radius = 1, height = 1, radialSegments = 8, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2) {
  20380. super(0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength);
  20381. this.type = 'ConeGeometry';
  20382. this.parameters = {
  20383. radius: radius,
  20384. height: height,
  20385. radialSegments: radialSegments,
  20386. heightSegments: heightSegments,
  20387. openEnded: openEnded,
  20388. thetaStart: thetaStart,
  20389. thetaLength: thetaLength
  20390. };
  20391. }
  20392. static fromJSON(data) {
  20393. return new ConeGeometry(data.radius, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength);
  20394. }
  20395. }
  20396. class PolyhedronGeometry extends BufferGeometry {
  20397. constructor(vertices = [], indices = [], radius = 1, detail = 0) {
  20398. super();
  20399. this.type = 'PolyhedronGeometry';
  20400. this.parameters = {
  20401. vertices: vertices,
  20402. indices: indices,
  20403. radius: radius,
  20404. detail: detail
  20405. };
  20406. // default buffer data
  20407. const vertexBuffer = [];
  20408. const uvBuffer = [];
  20409. // the subdivision creates the vertex buffer data
  20410. subdivide(detail);
  20411. // all vertices should lie on a conceptual sphere with a given radius
  20412. applyRadius(radius);
  20413. // finally, create the uv data
  20414. generateUVs();
  20415. // build non-indexed geometry
  20416. this.setAttribute('position', new Float32BufferAttribute(vertexBuffer, 3));
  20417. this.setAttribute('normal', new Float32BufferAttribute(vertexBuffer.slice(), 3));
  20418. this.setAttribute('uv', new Float32BufferAttribute(uvBuffer, 2));
  20419. if (detail === 0) {
  20420. this.computeVertexNormals(); // flat normals
  20421. } else {
  20422. this.normalizeNormals(); // smooth normals
  20423. }
  20424. // helper functions
  20425. function subdivide(detail) {
  20426. const a = new Vector3();
  20427. const b = new Vector3();
  20428. const c = new Vector3();
  20429. // iterate over all faces and apply a subdivision with the given detail value
  20430. for (let i = 0; i < indices.length; i += 3) {
  20431. // get the vertices of the face
  20432. getVertexByIndex(indices[i + 0], a);
  20433. getVertexByIndex(indices[i + 1], b);
  20434. getVertexByIndex(indices[i + 2], c);
  20435. // perform subdivision
  20436. subdivideFace(a, b, c, detail);
  20437. }
  20438. }
  20439. function subdivideFace(a, b, c, detail) {
  20440. const cols = detail + 1;
  20441. // we use this multidimensional array as a data structure for creating the subdivision
  20442. const v = [];
  20443. // construct all of the vertices for this subdivision
  20444. for (let i = 0; i <= cols; i++) {
  20445. v[i] = [];
  20446. const aj = a.clone().lerp(c, i / cols);
  20447. const bj = b.clone().lerp(c, i / cols);
  20448. const rows = cols - i;
  20449. for (let j = 0; j <= rows; j++) {
  20450. if (j === 0 && i === cols) {
  20451. v[i][j] = aj;
  20452. } else {
  20453. v[i][j] = aj.clone().lerp(bj, j / rows);
  20454. }
  20455. }
  20456. }
  20457. // construct all of the faces
  20458. for (let i = 0; i < cols; i++) {
  20459. for (let j = 0; j < 2 * (cols - i) - 1; j++) {
  20460. const k = Math.floor(j / 2);
  20461. if (j % 2 === 0) {
  20462. pushVertex(v[i][k + 1]);
  20463. pushVertex(v[i + 1][k]);
  20464. pushVertex(v[i][k]);
  20465. } else {
  20466. pushVertex(v[i][k + 1]);
  20467. pushVertex(v[i + 1][k + 1]);
  20468. pushVertex(v[i + 1][k]);
  20469. }
  20470. }
  20471. }
  20472. }
  20473. function applyRadius(radius) {
  20474. const vertex = new Vector3();
  20475. // iterate over the entire buffer and apply the radius to each vertex
  20476. for (let i = 0; i < vertexBuffer.length; i += 3) {
  20477. vertex.x = vertexBuffer[i + 0];
  20478. vertex.y = vertexBuffer[i + 1];
  20479. vertex.z = vertexBuffer[i + 2];
  20480. vertex.normalize().multiplyScalar(radius);
  20481. vertexBuffer[i + 0] = vertex.x;
  20482. vertexBuffer[i + 1] = vertex.y;
  20483. vertexBuffer[i + 2] = vertex.z;
  20484. }
  20485. }
  20486. function generateUVs() {
  20487. const vertex = new Vector3();
  20488. for (let i = 0; i < vertexBuffer.length; i += 3) {
  20489. vertex.x = vertexBuffer[i + 0];
  20490. vertex.y = vertexBuffer[i + 1];
  20491. vertex.z = vertexBuffer[i + 2];
  20492. const u = azimuth(vertex) / 2 / Math.PI + 0.5;
  20493. const v = inclination(vertex) / Math.PI + 0.5;
  20494. uvBuffer.push(u, 1 - v);
  20495. }
  20496. correctUVs();
  20497. correctSeam();
  20498. }
  20499. function correctSeam() {
  20500. // handle case when face straddles the seam, see #3269
  20501. for (let i = 0; i < uvBuffer.length; i += 6) {
  20502. // uv data of a single face
  20503. const x0 = uvBuffer[i + 0];
  20504. const x1 = uvBuffer[i + 2];
  20505. const x2 = uvBuffer[i + 4];
  20506. const max = Math.max(x0, x1, x2);
  20507. const min = Math.min(x0, x1, x2);
  20508. // 0.9 is somewhat arbitrary
  20509. if (max > 0.9 && min < 0.1) {
  20510. if (x0 < 0.2) uvBuffer[i + 0] += 1;
  20511. if (x1 < 0.2) uvBuffer[i + 2] += 1;
  20512. if (x2 < 0.2) uvBuffer[i + 4] += 1;
  20513. }
  20514. }
  20515. }
  20516. function pushVertex(vertex) {
  20517. vertexBuffer.push(vertex.x, vertex.y, vertex.z);
  20518. }
  20519. function getVertexByIndex(index, vertex) {
  20520. const stride = index * 3;
  20521. vertex.x = vertices[stride + 0];
  20522. vertex.y = vertices[stride + 1];
  20523. vertex.z = vertices[stride + 2];
  20524. }
  20525. function correctUVs() {
  20526. const a = new Vector3();
  20527. const b = new Vector3();
  20528. const c = new Vector3();
  20529. const centroid = new Vector3();
  20530. const uvA = new Vector2();
  20531. const uvB = new Vector2();
  20532. const uvC = new Vector2();
  20533. for (let i = 0, j = 0; i < vertexBuffer.length; i += 9, j += 6) {
  20534. a.set(vertexBuffer[i + 0], vertexBuffer[i + 1], vertexBuffer[i + 2]);
  20535. b.set(vertexBuffer[i + 3], vertexBuffer[i + 4], vertexBuffer[i + 5]);
  20536. c.set(vertexBuffer[i + 6], vertexBuffer[i + 7], vertexBuffer[i + 8]);
  20537. uvA.set(uvBuffer[j + 0], uvBuffer[j + 1]);
  20538. uvB.set(uvBuffer[j + 2], uvBuffer[j + 3]);
  20539. uvC.set(uvBuffer[j + 4], uvBuffer[j + 5]);
  20540. centroid.copy(a).add(b).add(c).divideScalar(3);
  20541. const azi = azimuth(centroid);
  20542. correctUV(uvA, j + 0, a, azi);
  20543. correctUV(uvB, j + 2, b, azi);
  20544. correctUV(uvC, j + 4, c, azi);
  20545. }
  20546. }
  20547. function correctUV(uv, stride, vector, azimuth) {
  20548. if (azimuth < 0 && uv.x === 1) {
  20549. uvBuffer[stride] = uv.x - 1;
  20550. }
  20551. if (vector.x === 0 && vector.z === 0) {
  20552. uvBuffer[stride] = azimuth / 2 / Math.PI + 0.5;
  20553. }
  20554. }
  20555. // Angle around the Y axis, counter-clockwise when looking from above.
  20556. function azimuth(vector) {
  20557. return Math.atan2(vector.z, -vector.x);
  20558. }
  20559. // Angle above the XZ plane.
  20560. function inclination(vector) {
  20561. return Math.atan2(-vector.y, Math.sqrt(vector.x * vector.x + vector.z * vector.z));
  20562. }
  20563. }
  20564. static fromJSON(data) {
  20565. return new PolyhedronGeometry(data.vertices, data.indices, data.radius, data.details);
  20566. }
  20567. }
  20568. class DodecahedronGeometry extends PolyhedronGeometry {
  20569. constructor(radius = 1, detail = 0) {
  20570. const t = (1 + Math.sqrt(5)) / 2;
  20571. const r = 1 / t;
  20572. const vertices = [
  20573. // (±1, ±1, ±1)
  20574. -1, -1, -1, -1, -1, 1, -1, 1, -1, -1, 1, 1, 1, -1, -1, 1, -1, 1, 1, 1, -1, 1, 1, 1,
  20575. // (0, ±1/φ, ±φ)
  20576. 0, -r, -t, 0, -r, t, 0, r, -t, 0, r, t,
  20577. // (±1/φ, ±φ, 0)
  20578. -r, -t, 0, -r, t, 0, r, -t, 0, r, t, 0,
  20579. // (±φ, 0, ±1/φ)
  20580. -t, 0, -r, t, 0, -r, -t, 0, r, t, 0, r];
  20581. 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];
  20582. super(vertices, indices, radius, detail);
  20583. this.type = 'DodecahedronGeometry';
  20584. this.parameters = {
  20585. radius: radius,
  20586. detail: detail
  20587. };
  20588. }
  20589. static fromJSON(data) {
  20590. return new DodecahedronGeometry(data.radius, data.detail);
  20591. }
  20592. }
  20593. const _v0 = /*@__PURE__*/new Vector3();
  20594. const _v1$1 = /*@__PURE__*/new Vector3();
  20595. const _normal = /*@__PURE__*/new Vector3();
  20596. const _triangle = /*@__PURE__*/new Triangle();
  20597. class EdgesGeometry extends BufferGeometry {
  20598. constructor(geometry = null, thresholdAngle = 1) {
  20599. super();
  20600. this.type = 'EdgesGeometry';
  20601. this.parameters = {
  20602. geometry: geometry,
  20603. thresholdAngle: thresholdAngle
  20604. };
  20605. if (geometry !== null) {
  20606. const precisionPoints = 4;
  20607. const precision = Math.pow(10, precisionPoints);
  20608. const thresholdDot = Math.cos(DEG2RAD * thresholdAngle);
  20609. const indexAttr = geometry.getIndex();
  20610. const positionAttr = geometry.getAttribute('position');
  20611. const indexCount = indexAttr ? indexAttr.count : positionAttr.count;
  20612. const indexArr = [0, 0, 0];
  20613. const vertKeys = ['a', 'b', 'c'];
  20614. const hashes = new Array(3);
  20615. const edgeData = {};
  20616. const vertices = [];
  20617. for (let i = 0; i < indexCount; i += 3) {
  20618. if (indexAttr) {
  20619. indexArr[0] = indexAttr.getX(i);
  20620. indexArr[1] = indexAttr.getX(i + 1);
  20621. indexArr[2] = indexAttr.getX(i + 2);
  20622. } else {
  20623. indexArr[0] = i;
  20624. indexArr[1] = i + 1;
  20625. indexArr[2] = i + 2;
  20626. }
  20627. const {
  20628. a,
  20629. b,
  20630. c
  20631. } = _triangle;
  20632. a.fromBufferAttribute(positionAttr, indexArr[0]);
  20633. b.fromBufferAttribute(positionAttr, indexArr[1]);
  20634. c.fromBufferAttribute(positionAttr, indexArr[2]);
  20635. _triangle.getNormal(_normal);
  20636. // create hashes for the edge from the vertices
  20637. hashes[0] = `${Math.round(a.x * precision)},${Math.round(a.y * precision)},${Math.round(a.z * precision)}`;
  20638. hashes[1] = `${Math.round(b.x * precision)},${Math.round(b.y * precision)},${Math.round(b.z * precision)}`;
  20639. hashes[2] = `${Math.round(c.x * precision)},${Math.round(c.y * precision)},${Math.round(c.z * precision)}`;
  20640. // skip degenerate triangles
  20641. if (hashes[0] === hashes[1] || hashes[1] === hashes[2] || hashes[2] === hashes[0]) {
  20642. continue;
  20643. }
  20644. // iterate over every edge
  20645. for (let j = 0; j < 3; j++) {
  20646. // get the first and next vertex making up the edge
  20647. const jNext = (j + 1) % 3;
  20648. const vecHash0 = hashes[j];
  20649. const vecHash1 = hashes[jNext];
  20650. const v0 = _triangle[vertKeys[j]];
  20651. const v1 = _triangle[vertKeys[jNext]];
  20652. const hash = `${vecHash0}_${vecHash1}`;
  20653. const reverseHash = `${vecHash1}_${vecHash0}`;
  20654. if (reverseHash in edgeData && edgeData[reverseHash]) {
  20655. // if we found a sibling edge add it into the vertex array if
  20656. // it meets the angle threshold and delete the edge from the map.
  20657. if (_normal.dot(edgeData[reverseHash].normal) <= thresholdDot) {
  20658. vertices.push(v0.x, v0.y, v0.z);
  20659. vertices.push(v1.x, v1.y, v1.z);
  20660. }
  20661. edgeData[reverseHash] = null;
  20662. } else if (!(hash in edgeData)) {
  20663. // if we've already got an edge here then skip adding a new one
  20664. edgeData[hash] = {
  20665. index0: indexArr[j],
  20666. index1: indexArr[jNext],
  20667. normal: _normal.clone()
  20668. };
  20669. }
  20670. }
  20671. }
  20672. // iterate over all remaining, unmatched edges and add them to the vertex array
  20673. for (const key in edgeData) {
  20674. if (edgeData[key]) {
  20675. const {
  20676. index0,
  20677. index1
  20678. } = edgeData[key];
  20679. _v0.fromBufferAttribute(positionAttr, index0);
  20680. _v1$1.fromBufferAttribute(positionAttr, index1);
  20681. vertices.push(_v0.x, _v0.y, _v0.z);
  20682. vertices.push(_v1$1.x, _v1$1.y, _v1$1.z);
  20683. }
  20684. }
  20685. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  20686. }
  20687. }
  20688. }
  20689. class Shape extends Path {
  20690. constructor(points) {
  20691. super(points);
  20692. this.uuid = generateUUID();
  20693. this.type = 'Shape';
  20694. this.holes = [];
  20695. }
  20696. getPointsHoles(divisions) {
  20697. const holesPts = [];
  20698. for (let i = 0, l = this.holes.length; i < l; i++) {
  20699. holesPts[i] = this.holes[i].getPoints(divisions);
  20700. }
  20701. return holesPts;
  20702. }
  20703. // get points of shape and holes (keypoints based on segments parameter)
  20704. extractPoints(divisions) {
  20705. return {
  20706. shape: this.getPoints(divisions),
  20707. holes: this.getPointsHoles(divisions)
  20708. };
  20709. }
  20710. copy(source) {
  20711. super.copy(source);
  20712. this.holes = [];
  20713. for (let i = 0, l = source.holes.length; i < l; i++) {
  20714. const hole = source.holes[i];
  20715. this.holes.push(hole.clone());
  20716. }
  20717. return this;
  20718. }
  20719. toJSON() {
  20720. const data = super.toJSON();
  20721. data.uuid = this.uuid;
  20722. data.holes = [];
  20723. for (let i = 0, l = this.holes.length; i < l; i++) {
  20724. const hole = this.holes[i];
  20725. data.holes.push(hole.toJSON());
  20726. }
  20727. return data;
  20728. }
  20729. fromJSON(json) {
  20730. super.fromJSON(json);
  20731. this.uuid = json.uuid;
  20732. this.holes = [];
  20733. for (let i = 0, l = json.holes.length; i < l; i++) {
  20734. const hole = json.holes[i];
  20735. this.holes.push(new Path().fromJSON(hole));
  20736. }
  20737. return this;
  20738. }
  20739. }
  20740. /**
  20741. * Port from https://github.com/mapbox/earcut (v2.2.4)
  20742. */
  20743. const Earcut = {
  20744. triangulate: function (data, holeIndices, dim = 2) {
  20745. const hasHoles = holeIndices && holeIndices.length;
  20746. const outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  20747. let outerNode = linkedList(data, 0, outerLen, dim, true);
  20748. const triangles = [];
  20749. if (!outerNode || outerNode.next === outerNode.prev) return triangles;
  20750. let minX, minY, maxX, maxY, x, y, invSize;
  20751. if (hasHoles) outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  20752. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  20753. if (data.length > 80 * dim) {
  20754. minX = maxX = data[0];
  20755. minY = maxY = data[1];
  20756. for (let i = dim; i < outerLen; i += dim) {
  20757. x = data[i];
  20758. y = data[i + 1];
  20759. if (x < minX) minX = x;
  20760. if (y < minY) minY = y;
  20761. if (x > maxX) maxX = x;
  20762. if (y > maxY) maxY = y;
  20763. }
  20764. // minX, minY and invSize are later used to transform coords into integers for z-order calculation
  20765. invSize = Math.max(maxX - minX, maxY - minY);
  20766. invSize = invSize !== 0 ? 32767 / invSize : 0;
  20767. }
  20768. earcutLinked(outerNode, triangles, dim, minX, minY, invSize, 0);
  20769. return triangles;
  20770. }
  20771. };
  20772. // create a circular doubly linked list from polygon points in the specified winding order
  20773. function linkedList(data, start, end, dim, clockwise) {
  20774. let i, last;
  20775. if (clockwise === signedArea(data, start, end, dim) > 0) {
  20776. for (i = start; i < end; i += dim) last = insertNode(i, data[i], data[i + 1], last);
  20777. } else {
  20778. for (i = end - dim; i >= start; i -= dim) last = insertNode(i, data[i], data[i + 1], last);
  20779. }
  20780. if (last && equals(last, last.next)) {
  20781. removeNode(last);
  20782. last = last.next;
  20783. }
  20784. return last;
  20785. }
  20786. // eliminate colinear or duplicate points
  20787. function filterPoints(start, end) {
  20788. if (!start) return start;
  20789. if (!end) end = start;
  20790. let p = start,
  20791. again;
  20792. do {
  20793. again = false;
  20794. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  20795. removeNode(p);
  20796. p = end = p.prev;
  20797. if (p === p.next) break;
  20798. again = true;
  20799. } else {
  20800. p = p.next;
  20801. }
  20802. } while (again || p !== end);
  20803. return end;
  20804. }
  20805. // main ear slicing loop which triangulates a polygon (given as a linked list)
  20806. function earcutLinked(ear, triangles, dim, minX, minY, invSize, pass) {
  20807. if (!ear) return;
  20808. // interlink polygon nodes in z-order
  20809. if (!pass && invSize) indexCurve(ear, minX, minY, invSize);
  20810. let stop = ear,
  20811. prev,
  20812. next;
  20813. // iterate through ears, slicing them one by one
  20814. while (ear.prev !== ear.next) {
  20815. prev = ear.prev;
  20816. next = ear.next;
  20817. if (invSize ? isEarHashed(ear, minX, minY, invSize) : isEar(ear)) {
  20818. // cut off the triangle
  20819. triangles.push(prev.i / dim | 0);
  20820. triangles.push(ear.i / dim | 0);
  20821. triangles.push(next.i / dim | 0);
  20822. removeNode(ear);
  20823. // skipping the next vertex leads to less sliver triangles
  20824. ear = next.next;
  20825. stop = next.next;
  20826. continue;
  20827. }
  20828. ear = next;
  20829. // if we looped through the whole remaining polygon and can't find any more ears
  20830. if (ear === stop) {
  20831. // try filtering points and slicing again
  20832. if (!pass) {
  20833. earcutLinked(filterPoints(ear), triangles, dim, minX, minY, invSize, 1);
  20834. // if this didn't work, try curing all small self-intersections locally
  20835. } else if (pass === 1) {
  20836. ear = cureLocalIntersections(filterPoints(ear), triangles, dim);
  20837. earcutLinked(ear, triangles, dim, minX, minY, invSize, 2);
  20838. // as a last resort, try splitting the remaining polygon into two
  20839. } else if (pass === 2) {
  20840. splitEarcut(ear, triangles, dim, minX, minY, invSize);
  20841. }
  20842. break;
  20843. }
  20844. }
  20845. }
  20846. // check whether a polygon node forms a valid ear with adjacent nodes
  20847. function isEar(ear) {
  20848. const a = ear.prev,
  20849. b = ear,
  20850. c = ear.next;
  20851. if (area(a, b, c) >= 0) return false; // reflex, can't be an ear
  20852. // now make sure we don't have other points inside the potential ear
  20853. const ax = a.x,
  20854. bx = b.x,
  20855. cx = c.x,
  20856. ay = a.y,
  20857. by = b.y,
  20858. cy = c.y;
  20859. // triangle bbox; min & max are calculated like this for speed
  20860. const x0 = ax < bx ? ax < cx ? ax : cx : bx < cx ? bx : cx,
  20861. y0 = ay < by ? ay < cy ? ay : cy : by < cy ? by : cy,
  20862. x1 = ax > bx ? ax > cx ? ax : cx : bx > cx ? bx : cx,
  20863. y1 = ay > by ? ay > cy ? ay : cy : by > cy ? by : cy;
  20864. let p = c.next;
  20865. while (p !== a) {
  20866. if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && pointInTriangle(ax, ay, bx, by, cx, cy, p.x, p.y) && area(p.prev, p, p.next) >= 0) return false;
  20867. p = p.next;
  20868. }
  20869. return true;
  20870. }
  20871. function isEarHashed(ear, minX, minY, invSize) {
  20872. const a = ear.prev,
  20873. b = ear,
  20874. c = ear.next;
  20875. if (area(a, b, c) >= 0) return false; // reflex, can't be an ear
  20876. const ax = a.x,
  20877. bx = b.x,
  20878. cx = c.x,
  20879. ay = a.y,
  20880. by = b.y,
  20881. cy = c.y;
  20882. // triangle bbox; min & max are calculated like this for speed
  20883. const x0 = ax < bx ? ax < cx ? ax : cx : bx < cx ? bx : cx,
  20884. y0 = ay < by ? ay < cy ? ay : cy : by < cy ? by : cy,
  20885. x1 = ax > bx ? ax > cx ? ax : cx : bx > cx ? bx : cx,
  20886. y1 = ay > by ? ay > cy ? ay : cy : by > cy ? by : cy;
  20887. // z-order range for the current triangle bbox;
  20888. const minZ = zOrder(x0, y0, minX, minY, invSize),
  20889. maxZ = zOrder(x1, y1, minX, minY, invSize);
  20890. let p = ear.prevZ,
  20891. n = ear.nextZ;
  20892. // look for points inside the triangle in both directions
  20893. while (p && p.z >= minZ && n && n.z <= maxZ) {
  20894. if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c && pointInTriangle(ax, ay, bx, by, cx, cy, p.x, p.y) && area(p.prev, p, p.next) >= 0) return false;
  20895. p = p.prevZ;
  20896. if (n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c && pointInTriangle(ax, ay, bx, by, cx, cy, n.x, n.y) && area(n.prev, n, n.next) >= 0) return false;
  20897. n = n.nextZ;
  20898. }
  20899. // look for remaining points in decreasing z-order
  20900. while (p && p.z >= minZ) {
  20901. if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c && pointInTriangle(ax, ay, bx, by, cx, cy, p.x, p.y) && area(p.prev, p, p.next) >= 0) return false;
  20902. p = p.prevZ;
  20903. }
  20904. // look for remaining points in increasing z-order
  20905. while (n && n.z <= maxZ) {
  20906. if (n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c && pointInTriangle(ax, ay, bx, by, cx, cy, n.x, n.y) && area(n.prev, n, n.next) >= 0) return false;
  20907. n = n.nextZ;
  20908. }
  20909. return true;
  20910. }
  20911. // go through all polygon nodes and cure small local self-intersections
  20912. function cureLocalIntersections(start, triangles, dim) {
  20913. let p = start;
  20914. do {
  20915. const a = p.prev,
  20916. b = p.next.next;
  20917. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  20918. triangles.push(a.i / dim | 0);
  20919. triangles.push(p.i / dim | 0);
  20920. triangles.push(b.i / dim | 0);
  20921. // remove two nodes involved
  20922. removeNode(p);
  20923. removeNode(p.next);
  20924. p = start = b;
  20925. }
  20926. p = p.next;
  20927. } while (p !== start);
  20928. return filterPoints(p);
  20929. }
  20930. // try splitting polygon into two and triangulate them independently
  20931. function splitEarcut(start, triangles, dim, minX, minY, invSize) {
  20932. // look for a valid diagonal that divides the polygon into two
  20933. let a = start;
  20934. do {
  20935. let b = a.next.next;
  20936. while (b !== a.prev) {
  20937. if (a.i !== b.i && isValidDiagonal(a, b)) {
  20938. // split the polygon in two by the diagonal
  20939. let c = splitPolygon(a, b);
  20940. // filter colinear points around the cuts
  20941. a = filterPoints(a, a.next);
  20942. c = filterPoints(c, c.next);
  20943. // run earcut on each half
  20944. earcutLinked(a, triangles, dim, minX, minY, invSize, 0);
  20945. earcutLinked(c, triangles, dim, minX, minY, invSize, 0);
  20946. return;
  20947. }
  20948. b = b.next;
  20949. }
  20950. a = a.next;
  20951. } while (a !== start);
  20952. }
  20953. // link every hole into the outer loop, producing a single-ring polygon without holes
  20954. function eliminateHoles(data, holeIndices, outerNode, dim) {
  20955. const queue = [];
  20956. let i, len, start, end, list;
  20957. for (i = 0, len = holeIndices.length; i < len; i++) {
  20958. start = holeIndices[i] * dim;
  20959. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  20960. list = linkedList(data, start, end, dim, false);
  20961. if (list === list.next) list.steiner = true;
  20962. queue.push(getLeftmost(list));
  20963. }
  20964. queue.sort(compareX);
  20965. // process holes from left to right
  20966. for (i = 0; i < queue.length; i++) {
  20967. outerNode = eliminateHole(queue[i], outerNode);
  20968. }
  20969. return outerNode;
  20970. }
  20971. function compareX(a, b) {
  20972. return a.x - b.x;
  20973. }
  20974. // find a bridge between vertices that connects hole with an outer ring and link it
  20975. function eliminateHole(hole, outerNode) {
  20976. const bridge = findHoleBridge(hole, outerNode);
  20977. if (!bridge) {
  20978. return outerNode;
  20979. }
  20980. const bridgeReverse = splitPolygon(bridge, hole);
  20981. // filter collinear points around the cuts
  20982. filterPoints(bridgeReverse, bridgeReverse.next);
  20983. return filterPoints(bridge, bridge.next);
  20984. }
  20985. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  20986. function findHoleBridge(hole, outerNode) {
  20987. let p = outerNode,
  20988. qx = -Infinity,
  20989. m;
  20990. const hx = hole.x,
  20991. hy = hole.y;
  20992. // find a segment intersected by a ray from the hole's leftmost point to the left;
  20993. // segment's endpoint with lesser x will be potential connection point
  20994. do {
  20995. if (hy <= p.y && hy >= p.next.y && p.next.y !== p.y) {
  20996. const x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  20997. if (x <= hx && x > qx) {
  20998. qx = x;
  20999. m = p.x < p.next.x ? p : p.next;
  21000. if (x === hx) return m; // hole touches outer segment; pick leftmost endpoint
  21001. }
  21002. }
  21003. p = p.next;
  21004. } while (p !== outerNode);
  21005. if (!m) return null;
  21006. // look for points inside the triangle of hole point, segment intersection and endpoint;
  21007. // if there are no points found, we have a valid connection;
  21008. // otherwise choose the point of the minimum angle with the ray as connection point
  21009. const stop = m,
  21010. mx = m.x,
  21011. my = m.y;
  21012. let tanMin = Infinity,
  21013. tan;
  21014. p = m;
  21015. do {
  21016. 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)) {
  21017. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  21018. if (locallyInside(p, hole) && (tan < tanMin || tan === tanMin && (p.x > m.x || p.x === m.x && sectorContainsSector(m, p)))) {
  21019. m = p;
  21020. tanMin = tan;
  21021. }
  21022. }
  21023. p = p.next;
  21024. } while (p !== stop);
  21025. return m;
  21026. }
  21027. // whether sector in vertex m contains sector in vertex p in the same coordinates
  21028. function sectorContainsSector(m, p) {
  21029. return area(m.prev, m, p.prev) < 0 && area(p.next, m, m.next) < 0;
  21030. }
  21031. // interlink polygon nodes in z-order
  21032. function indexCurve(start, minX, minY, invSize) {
  21033. let p = start;
  21034. do {
  21035. if (p.z === 0) p.z = zOrder(p.x, p.y, minX, minY, invSize);
  21036. p.prevZ = p.prev;
  21037. p.nextZ = p.next;
  21038. p = p.next;
  21039. } while (p !== start);
  21040. p.prevZ.nextZ = null;
  21041. p.prevZ = null;
  21042. sortLinked(p);
  21043. }
  21044. // Simon Tatham's linked list merge sort algorithm
  21045. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  21046. function sortLinked(list) {
  21047. let i,
  21048. p,
  21049. q,
  21050. e,
  21051. tail,
  21052. numMerges,
  21053. pSize,
  21054. qSize,
  21055. inSize = 1;
  21056. do {
  21057. p = list;
  21058. list = null;
  21059. tail = null;
  21060. numMerges = 0;
  21061. while (p) {
  21062. numMerges++;
  21063. q = p;
  21064. pSize = 0;
  21065. for (i = 0; i < inSize; i++) {
  21066. pSize++;
  21067. q = q.nextZ;
  21068. if (!q) break;
  21069. }
  21070. qSize = inSize;
  21071. while (pSize > 0 || qSize > 0 && q) {
  21072. if (pSize !== 0 && (qSize === 0 || !q || p.z <= q.z)) {
  21073. e = p;
  21074. p = p.nextZ;
  21075. pSize--;
  21076. } else {
  21077. e = q;
  21078. q = q.nextZ;
  21079. qSize--;
  21080. }
  21081. if (tail) tail.nextZ = e;else list = e;
  21082. e.prevZ = tail;
  21083. tail = e;
  21084. }
  21085. p = q;
  21086. }
  21087. tail.nextZ = null;
  21088. inSize *= 2;
  21089. } while (numMerges > 1);
  21090. return list;
  21091. }
  21092. // z-order of a point given coords and inverse of the longer side of data bbox
  21093. function zOrder(x, y, minX, minY, invSize) {
  21094. // coords are transformed into non-negative 15-bit integer range
  21095. x = (x - minX) * invSize | 0;
  21096. y = (y - minY) * invSize | 0;
  21097. x = (x | x << 8) & 0x00FF00FF;
  21098. x = (x | x << 4) & 0x0F0F0F0F;
  21099. x = (x | x << 2) & 0x33333333;
  21100. x = (x | x << 1) & 0x55555555;
  21101. y = (y | y << 8) & 0x00FF00FF;
  21102. y = (y | y << 4) & 0x0F0F0F0F;
  21103. y = (y | y << 2) & 0x33333333;
  21104. y = (y | y << 1) & 0x55555555;
  21105. return x | y << 1;
  21106. }
  21107. // find the leftmost node of a polygon ring
  21108. function getLeftmost(start) {
  21109. let p = start,
  21110. leftmost = start;
  21111. do {
  21112. if (p.x < leftmost.x || p.x === leftmost.x && p.y < leftmost.y) leftmost = p;
  21113. p = p.next;
  21114. } while (p !== start);
  21115. return leftmost;
  21116. }
  21117. // check if a point lies within a convex triangle
  21118. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  21119. return (cx - px) * (ay - py) >= (ax - px) * (cy - py) && (ax - px) * (by - py) >= (bx - px) * (ay - py) && (bx - px) * (cy - py) >= (cx - px) * (by - py);
  21120. }
  21121. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  21122. function isValidDiagonal(a, b) {
  21123. return a.next.i !== b.i && a.prev.i !== b.i && !intersectsPolygon(a, b) && (
  21124. // dones't intersect other edges
  21125. locallyInside(a, b) && locallyInside(b, a) && middleInside(a, b) && (
  21126. // locally visible
  21127. area(a.prev, a, b.prev) || area(a, b.prev, b)) ||
  21128. // does not create opposite-facing sectors
  21129. equals(a, b) && area(a.prev, a, a.next) > 0 && area(b.prev, b, b.next) > 0); // special zero-length case
  21130. }
  21131. // signed area of a triangle
  21132. function area(p, q, r) {
  21133. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  21134. }
  21135. // check if two points are equal
  21136. function equals(p1, p2) {
  21137. return p1.x === p2.x && p1.y === p2.y;
  21138. }
  21139. // check if two segments intersect
  21140. function intersects(p1, q1, p2, q2) {
  21141. const o1 = sign(area(p1, q1, p2));
  21142. const o2 = sign(area(p1, q1, q2));
  21143. const o3 = sign(area(p2, q2, p1));
  21144. const o4 = sign(area(p2, q2, q1));
  21145. if (o1 !== o2 && o3 !== o4) return true; // general case
  21146. if (o1 === 0 && onSegment(p1, p2, q1)) return true; // p1, q1 and p2 are collinear and p2 lies on p1q1
  21147. if (o2 === 0 && onSegment(p1, q2, q1)) return true; // p1, q1 and q2 are collinear and q2 lies on p1q1
  21148. if (o3 === 0 && onSegment(p2, p1, q2)) return true; // p2, q2 and p1 are collinear and p1 lies on p2q2
  21149. if (o4 === 0 && onSegment(p2, q1, q2)) return true; // p2, q2 and q1 are collinear and q1 lies on p2q2
  21150. return false;
  21151. }
  21152. // for collinear points p, q, r, check if point q lies on segment pr
  21153. function onSegment(p, q, r) {
  21154. 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);
  21155. }
  21156. function sign(num) {
  21157. return num > 0 ? 1 : num < 0 ? -1 : 0;
  21158. }
  21159. // check if a polygon diagonal intersects any polygon segments
  21160. function intersectsPolygon(a, b) {
  21161. let p = a;
  21162. do {
  21163. 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;
  21164. p = p.next;
  21165. } while (p !== a);
  21166. return false;
  21167. }
  21168. // check if a polygon diagonal is locally inside the polygon
  21169. function locallyInside(a, b) {
  21170. 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;
  21171. }
  21172. // check if the middle point of a polygon diagonal is inside the polygon
  21173. function middleInside(a, b) {
  21174. let p = a,
  21175. inside = false;
  21176. const px = (a.x + b.x) / 2,
  21177. py = (a.y + b.y) / 2;
  21178. do {
  21179. 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;
  21180. p = p.next;
  21181. } while (p !== a);
  21182. return inside;
  21183. }
  21184. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  21185. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  21186. function splitPolygon(a, b) {
  21187. const a2 = new Node(a.i, a.x, a.y),
  21188. b2 = new Node(b.i, b.x, b.y),
  21189. an = a.next,
  21190. bp = b.prev;
  21191. a.next = b;
  21192. b.prev = a;
  21193. a2.next = an;
  21194. an.prev = a2;
  21195. b2.next = a2;
  21196. a2.prev = b2;
  21197. bp.next = b2;
  21198. b2.prev = bp;
  21199. return b2;
  21200. }
  21201. // create a node and optionally link it with previous one (in a circular doubly linked list)
  21202. function insertNode(i, x, y, last) {
  21203. const p = new Node(i, x, y);
  21204. if (!last) {
  21205. p.prev = p;
  21206. p.next = p;
  21207. } else {
  21208. p.next = last.next;
  21209. p.prev = last;
  21210. last.next.prev = p;
  21211. last.next = p;
  21212. }
  21213. return p;
  21214. }
  21215. function removeNode(p) {
  21216. p.next.prev = p.prev;
  21217. p.prev.next = p.next;
  21218. if (p.prevZ) p.prevZ.nextZ = p.nextZ;
  21219. if (p.nextZ) p.nextZ.prevZ = p.prevZ;
  21220. }
  21221. function Node(i, x, y) {
  21222. // vertex index in coordinates array
  21223. this.i = i;
  21224. // vertex coordinates
  21225. this.x = x;
  21226. this.y = y;
  21227. // previous and next vertex nodes in a polygon ring
  21228. this.prev = null;
  21229. this.next = null;
  21230. // z-order curve value
  21231. this.z = 0;
  21232. // previous and next nodes in z-order
  21233. this.prevZ = null;
  21234. this.nextZ = null;
  21235. // indicates whether this is a steiner point
  21236. this.steiner = false;
  21237. }
  21238. function signedArea(data, start, end, dim) {
  21239. let sum = 0;
  21240. for (let i = start, j = end - dim; i < end; i += dim) {
  21241. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  21242. j = i;
  21243. }
  21244. return sum;
  21245. }
  21246. class ShapeUtils {
  21247. // calculate area of the contour polygon
  21248. static area(contour) {
  21249. const n = contour.length;
  21250. let a = 0.0;
  21251. for (let p = n - 1, q = 0; q < n; p = q++) {
  21252. a += contour[p].x * contour[q].y - contour[q].x * contour[p].y;
  21253. }
  21254. return a * 0.5;
  21255. }
  21256. static isClockWise(pts) {
  21257. return ShapeUtils.area(pts) < 0;
  21258. }
  21259. static triangulateShape(contour, holes) {
  21260. const vertices = []; // flat array of vertices like [ x0,y0, x1,y1, x2,y2, ... ]
  21261. const holeIndices = []; // array of hole indices
  21262. const faces = []; // final array of vertex indices like [ [ a,b,d ], [ b,c,d ] ]
  21263. removeDupEndPts(contour);
  21264. addContour(vertices, contour);
  21265. //
  21266. let holeIndex = contour.length;
  21267. holes.forEach(removeDupEndPts);
  21268. for (let i = 0; i < holes.length; i++) {
  21269. holeIndices.push(holeIndex);
  21270. holeIndex += holes[i].length;
  21271. addContour(vertices, holes[i]);
  21272. }
  21273. //
  21274. const triangles = Earcut.triangulate(vertices, holeIndices);
  21275. //
  21276. for (let i = 0; i < triangles.length; i += 3) {
  21277. faces.push(triangles.slice(i, i + 3));
  21278. }
  21279. return faces;
  21280. }
  21281. }
  21282. function removeDupEndPts(points) {
  21283. const l = points.length;
  21284. if (l > 2 && points[l - 1].equals(points[0])) {
  21285. points.pop();
  21286. }
  21287. }
  21288. function addContour(vertices, contour) {
  21289. for (let i = 0; i < contour.length; i++) {
  21290. vertices.push(contour[i].x);
  21291. vertices.push(contour[i].y);
  21292. }
  21293. }
  21294. /**
  21295. * Creates extruded geometry from a path shape.
  21296. *
  21297. * parameters = {
  21298. *
  21299. * curveSegments: <int>, // number of points on the curves
  21300. * steps: <int>, // number of points for z-side extrusions / used for subdividing segments of extrude spline too
  21301. * depth: <float>, // Depth to extrude the shape
  21302. *
  21303. * bevelEnabled: <bool>, // turn on bevel
  21304. * bevelThickness: <float>, // how deep into the original shape bevel goes
  21305. * bevelSize: <float>, // how far from shape outline (including bevelOffset) is bevel
  21306. * bevelOffset: <float>, // how far from shape outline does bevel start
  21307. * bevelSegments: <int>, // number of bevel layers
  21308. *
  21309. * extrudePath: <THREE.Curve> // curve to extrude shape along
  21310. *
  21311. * UVGenerator: <Object> // object that provides UV generator functions
  21312. *
  21313. * }
  21314. */
  21315. class ExtrudeGeometry extends BufferGeometry {
  21316. 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 = {}) {
  21317. super();
  21318. this.type = 'ExtrudeGeometry';
  21319. this.parameters = {
  21320. shapes: shapes,
  21321. options: options
  21322. };
  21323. shapes = Array.isArray(shapes) ? shapes : [shapes];
  21324. const scope = this;
  21325. const verticesArray = [];
  21326. const uvArray = [];
  21327. for (let i = 0, l = shapes.length; i < l; i++) {
  21328. const shape = shapes[i];
  21329. addShape(shape);
  21330. }
  21331. // build geometry
  21332. this.setAttribute('position', new Float32BufferAttribute(verticesArray, 3));
  21333. this.setAttribute('uv', new Float32BufferAttribute(uvArray, 2));
  21334. this.computeVertexNormals();
  21335. // functions
  21336. function addShape(shape) {
  21337. const placeholder = [];
  21338. // options
  21339. const curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  21340. const steps = options.steps !== undefined ? options.steps : 1;
  21341. const depth = options.depth !== undefined ? options.depth : 1;
  21342. let bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true;
  21343. let bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 0.2;
  21344. let bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 0.1;
  21345. let bevelOffset = options.bevelOffset !== undefined ? options.bevelOffset : 0;
  21346. let bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  21347. const extrudePath = options.extrudePath;
  21348. const uvgen = options.UVGenerator !== undefined ? options.UVGenerator : WorldUVGenerator;
  21349. //
  21350. let extrudePts,
  21351. extrudeByPath = false;
  21352. let splineTube, binormal, normal, position2;
  21353. if (extrudePath) {
  21354. extrudePts = extrudePath.getSpacedPoints(steps);
  21355. extrudeByPath = true;
  21356. bevelEnabled = false; // bevels not supported for path extrusion
  21357. // SETUP TNB variables
  21358. // TODO1 - have a .isClosed in spline?
  21359. splineTube = extrudePath.computeFrenetFrames(steps, false);
  21360. // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  21361. binormal = new Vector3();
  21362. normal = new Vector3();
  21363. position2 = new Vector3();
  21364. }
  21365. // Safeguards if bevels are not enabled
  21366. if (!bevelEnabled) {
  21367. bevelSegments = 0;
  21368. bevelThickness = 0;
  21369. bevelSize = 0;
  21370. bevelOffset = 0;
  21371. }
  21372. // Variables initialization
  21373. const shapePoints = shape.extractPoints(curveSegments);
  21374. let vertices = shapePoints.shape;
  21375. const holes = shapePoints.holes;
  21376. const reverse = !ShapeUtils.isClockWise(vertices);
  21377. if (reverse) {
  21378. vertices = vertices.reverse();
  21379. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  21380. for (let h = 0, hl = holes.length; h < hl; h++) {
  21381. const ahole = holes[h];
  21382. if (ShapeUtils.isClockWise(ahole)) {
  21383. holes[h] = ahole.reverse();
  21384. }
  21385. }
  21386. }
  21387. const faces = ShapeUtils.triangulateShape(vertices, holes);
  21388. /* Vertices */
  21389. const contour = vertices; // vertices has all points but contour has only points of circumference
  21390. for (let h = 0, hl = holes.length; h < hl; h++) {
  21391. const ahole = holes[h];
  21392. vertices = vertices.concat(ahole);
  21393. }
  21394. function scalePt2(pt, vec, size) {
  21395. if (!vec) console.error('THREE.ExtrudeGeometry: vec does not exist');
  21396. return vec.clone().multiplyScalar(size).add(pt);
  21397. }
  21398. const vlen = vertices.length,
  21399. flen = faces.length;
  21400. // Find directions for point movement
  21401. function getBevelVec(inPt, inPrev, inNext) {
  21402. // computes for inPt the corresponding point inPt' on a new contour
  21403. // shifted by 1 unit (length of normalized vector) to the left
  21404. // if we walk along contour clockwise, this new contour is outside the old one
  21405. //
  21406. // inPt' is the intersection of the two lines parallel to the two
  21407. // adjacent edges of inPt at a distance of 1 unit on the left side.
  21408. let v_trans_x, v_trans_y, shrink_by; // resulting translation vector for inPt
  21409. // good reading for geometry algorithms (here: line-line intersection)
  21410. // http://geomalgorithms.com/a05-_intersect-1.html
  21411. const v_prev_x = inPt.x - inPrev.x,
  21412. v_prev_y = inPt.y - inPrev.y;
  21413. const v_next_x = inNext.x - inPt.x,
  21414. v_next_y = inNext.y - inPt.y;
  21415. const v_prev_lensq = v_prev_x * v_prev_x + v_prev_y * v_prev_y;
  21416. // check for collinear edges
  21417. const collinear0 = v_prev_x * v_next_y - v_prev_y * v_next_x;
  21418. if (Math.abs(collinear0) > Number.EPSILON) {
  21419. // not collinear
  21420. // length of vectors for normalizing
  21421. const v_prev_len = Math.sqrt(v_prev_lensq);
  21422. const v_next_len = Math.sqrt(v_next_x * v_next_x + v_next_y * v_next_y);
  21423. // shift adjacent points by unit vectors to the left
  21424. const ptPrevShift_x = inPrev.x - v_prev_y / v_prev_len;
  21425. const ptPrevShift_y = inPrev.y + v_prev_x / v_prev_len;
  21426. const ptNextShift_x = inNext.x - v_next_y / v_next_len;
  21427. const ptNextShift_y = inNext.y + v_next_x / v_next_len;
  21428. // scaling factor for v_prev to intersection point
  21429. 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);
  21430. // vector from inPt to intersection point
  21431. v_trans_x = ptPrevShift_x + v_prev_x * sf - inPt.x;
  21432. v_trans_y = ptPrevShift_y + v_prev_y * sf - inPt.y;
  21433. // Don't normalize!, otherwise sharp corners become ugly
  21434. // but prevent crazy spikes
  21435. const v_trans_lensq = v_trans_x * v_trans_x + v_trans_y * v_trans_y;
  21436. if (v_trans_lensq <= 2) {
  21437. return new Vector2(v_trans_x, v_trans_y);
  21438. } else {
  21439. shrink_by = Math.sqrt(v_trans_lensq / 2);
  21440. }
  21441. } else {
  21442. // handle special case of collinear edges
  21443. let direction_eq = false; // assumes: opposite
  21444. if (v_prev_x > Number.EPSILON) {
  21445. if (v_next_x > Number.EPSILON) {
  21446. direction_eq = true;
  21447. }
  21448. } else {
  21449. if (v_prev_x < -Number.EPSILON) {
  21450. if (v_next_x < -Number.EPSILON) {
  21451. direction_eq = true;
  21452. }
  21453. } else {
  21454. if (Math.sign(v_prev_y) === Math.sign(v_next_y)) {
  21455. direction_eq = true;
  21456. }
  21457. }
  21458. }
  21459. if (direction_eq) {
  21460. // console.log("Warning: lines are a straight sequence");
  21461. v_trans_x = -v_prev_y;
  21462. v_trans_y = v_prev_x;
  21463. shrink_by = Math.sqrt(v_prev_lensq);
  21464. } else {
  21465. // console.log("Warning: lines are a straight spike");
  21466. v_trans_x = v_prev_x;
  21467. v_trans_y = v_prev_y;
  21468. shrink_by = Math.sqrt(v_prev_lensq / 2);
  21469. }
  21470. }
  21471. return new Vector2(v_trans_x / shrink_by, v_trans_y / shrink_by);
  21472. }
  21473. const contourMovements = [];
  21474. for (let i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i++, j++, k++) {
  21475. if (j === il) j = 0;
  21476. if (k === il) k = 0;
  21477. // (j)---(i)---(k)
  21478. // console.log('i,j,k', i, j , k)
  21479. contourMovements[i] = getBevelVec(contour[i], contour[j], contour[k]);
  21480. }
  21481. const holesMovements = [];
  21482. let oneHoleMovements,
  21483. verticesMovements = contourMovements.concat();
  21484. for (let h = 0, hl = holes.length; h < hl; h++) {
  21485. const ahole = holes[h];
  21486. oneHoleMovements = [];
  21487. for (let i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i++, j++, k++) {
  21488. if (j === il) j = 0;
  21489. if (k === il) k = 0;
  21490. // (j)---(i)---(k)
  21491. oneHoleMovements[i] = getBevelVec(ahole[i], ahole[j], ahole[k]);
  21492. }
  21493. holesMovements.push(oneHoleMovements);
  21494. verticesMovements = verticesMovements.concat(oneHoleMovements);
  21495. }
  21496. // Loop bevelSegments, 1 for the front, 1 for the back
  21497. for (let b = 0; b < bevelSegments; b++) {
  21498. //for ( b = bevelSegments; b > 0; b -- ) {
  21499. const t = b / bevelSegments;
  21500. const z = bevelThickness * Math.cos(t * Math.PI / 2);
  21501. const bs = bevelSize * Math.sin(t * Math.PI / 2) + bevelOffset;
  21502. // contract shape
  21503. for (let i = 0, il = contour.length; i < il; i++) {
  21504. const vert = scalePt2(contour[i], contourMovements[i], bs);
  21505. v(vert.x, vert.y, -z);
  21506. }
  21507. // expand holes
  21508. for (let h = 0, hl = holes.length; h < hl; h++) {
  21509. const ahole = holes[h];
  21510. oneHoleMovements = holesMovements[h];
  21511. for (let i = 0, il = ahole.length; i < il; i++) {
  21512. const vert = scalePt2(ahole[i], oneHoleMovements[i], bs);
  21513. v(vert.x, vert.y, -z);
  21514. }
  21515. }
  21516. }
  21517. const bs = bevelSize + bevelOffset;
  21518. // Back facing vertices
  21519. for (let i = 0; i < vlen; i++) {
  21520. const vert = bevelEnabled ? scalePt2(vertices[i], verticesMovements[i], bs) : vertices[i];
  21521. if (!extrudeByPath) {
  21522. v(vert.x, vert.y, 0);
  21523. } else {
  21524. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  21525. normal.copy(splineTube.normals[0]).multiplyScalar(vert.x);
  21526. binormal.copy(splineTube.binormals[0]).multiplyScalar(vert.y);
  21527. position2.copy(extrudePts[0]).add(normal).add(binormal);
  21528. v(position2.x, position2.y, position2.z);
  21529. }
  21530. }
  21531. // Add stepped vertices...
  21532. // Including front facing vertices
  21533. for (let s = 1; s <= steps; s++) {
  21534. for (let i = 0; i < vlen; i++) {
  21535. const vert = bevelEnabled ? scalePt2(vertices[i], verticesMovements[i], bs) : vertices[i];
  21536. if (!extrudeByPath) {
  21537. v(vert.x, vert.y, depth / steps * s);
  21538. } else {
  21539. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  21540. normal.copy(splineTube.normals[s]).multiplyScalar(vert.x);
  21541. binormal.copy(splineTube.binormals[s]).multiplyScalar(vert.y);
  21542. position2.copy(extrudePts[s]).add(normal).add(binormal);
  21543. v(position2.x, position2.y, position2.z);
  21544. }
  21545. }
  21546. }
  21547. // Add bevel segments planes
  21548. //for ( b = 1; b <= bevelSegments; b ++ ) {
  21549. for (let b = bevelSegments - 1; b >= 0; b--) {
  21550. const t = b / bevelSegments;
  21551. const z = bevelThickness * Math.cos(t * Math.PI / 2);
  21552. const bs = bevelSize * Math.sin(t * Math.PI / 2) + bevelOffset;
  21553. // contract shape
  21554. for (let i = 0, il = contour.length; i < il; i++) {
  21555. const vert = scalePt2(contour[i], contourMovements[i], bs);
  21556. v(vert.x, vert.y, depth + z);
  21557. }
  21558. // expand holes
  21559. for (let h = 0, hl = holes.length; h < hl; h++) {
  21560. const ahole = holes[h];
  21561. oneHoleMovements = holesMovements[h];
  21562. for (let i = 0, il = ahole.length; i < il; i++) {
  21563. const vert = scalePt2(ahole[i], oneHoleMovements[i], bs);
  21564. if (!extrudeByPath) {
  21565. v(vert.x, vert.y, depth + z);
  21566. } else {
  21567. v(vert.x, vert.y + extrudePts[steps - 1].y, extrudePts[steps - 1].x + z);
  21568. }
  21569. }
  21570. }
  21571. }
  21572. /* Faces */
  21573. // Top and bottom faces
  21574. buildLidFaces();
  21575. // Sides faces
  21576. buildSideFaces();
  21577. ///// Internal functions
  21578. function buildLidFaces() {
  21579. const start = verticesArray.length / 3;
  21580. if (bevelEnabled) {
  21581. let layer = 0; // steps + 1
  21582. let offset = vlen * layer;
  21583. // Bottom faces
  21584. for (let i = 0; i < flen; i++) {
  21585. const face = faces[i];
  21586. f3(face[2] + offset, face[1] + offset, face[0] + offset);
  21587. }
  21588. layer = steps + bevelSegments * 2;
  21589. offset = vlen * layer;
  21590. // Top faces
  21591. for (let i = 0; i < flen; i++) {
  21592. const face = faces[i];
  21593. f3(face[0] + offset, face[1] + offset, face[2] + offset);
  21594. }
  21595. } else {
  21596. // Bottom faces
  21597. for (let i = 0; i < flen; i++) {
  21598. const face = faces[i];
  21599. f3(face[2], face[1], face[0]);
  21600. }
  21601. // Top faces
  21602. for (let i = 0; i < flen; i++) {
  21603. const face = faces[i];
  21604. f3(face[0] + vlen * steps, face[1] + vlen * steps, face[2] + vlen * steps);
  21605. }
  21606. }
  21607. scope.addGroup(start, verticesArray.length / 3 - start, 0);
  21608. }
  21609. // Create faces for the z-sides of the shape
  21610. function buildSideFaces() {
  21611. const start = verticesArray.length / 3;
  21612. let layeroffset = 0;
  21613. sidewalls(contour, layeroffset);
  21614. layeroffset += contour.length;
  21615. for (let h = 0, hl = holes.length; h < hl; h++) {
  21616. const ahole = holes[h];
  21617. sidewalls(ahole, layeroffset);
  21618. //, true
  21619. layeroffset += ahole.length;
  21620. }
  21621. scope.addGroup(start, verticesArray.length / 3 - start, 1);
  21622. }
  21623. function sidewalls(contour, layeroffset) {
  21624. let i = contour.length;
  21625. while (--i >= 0) {
  21626. const j = i;
  21627. let k = i - 1;
  21628. if (k < 0) k = contour.length - 1;
  21629. //console.log('b', i,j, i-1, k,vertices.length);
  21630. for (let s = 0, sl = steps + bevelSegments * 2; s < sl; s++) {
  21631. const slen1 = vlen * s;
  21632. const slen2 = vlen * (s + 1);
  21633. const a = layeroffset + j + slen1,
  21634. b = layeroffset + k + slen1,
  21635. c = layeroffset + k + slen2,
  21636. d = layeroffset + j + slen2;
  21637. f4(a, b, c, d);
  21638. }
  21639. }
  21640. }
  21641. function v(x, y, z) {
  21642. placeholder.push(x);
  21643. placeholder.push(y);
  21644. placeholder.push(z);
  21645. }
  21646. function f3(a, b, c) {
  21647. addVertex(a);
  21648. addVertex(b);
  21649. addVertex(c);
  21650. const nextIndex = verticesArray.length / 3;
  21651. const uvs = uvgen.generateTopUV(scope, verticesArray, nextIndex - 3, nextIndex - 2, nextIndex - 1);
  21652. addUV(uvs[0]);
  21653. addUV(uvs[1]);
  21654. addUV(uvs[2]);
  21655. }
  21656. function f4(a, b, c, d) {
  21657. addVertex(a);
  21658. addVertex(b);
  21659. addVertex(d);
  21660. addVertex(b);
  21661. addVertex(c);
  21662. addVertex(d);
  21663. const nextIndex = verticesArray.length / 3;
  21664. const uvs = uvgen.generateSideWallUV(scope, verticesArray, nextIndex - 6, nextIndex - 3, nextIndex - 2, nextIndex - 1);
  21665. addUV(uvs[0]);
  21666. addUV(uvs[1]);
  21667. addUV(uvs[3]);
  21668. addUV(uvs[1]);
  21669. addUV(uvs[2]);
  21670. addUV(uvs[3]);
  21671. }
  21672. function addVertex(index) {
  21673. verticesArray.push(placeholder[index * 3 + 0]);
  21674. verticesArray.push(placeholder[index * 3 + 1]);
  21675. verticesArray.push(placeholder[index * 3 + 2]);
  21676. }
  21677. function addUV(vector2) {
  21678. uvArray.push(vector2.x);
  21679. uvArray.push(vector2.y);
  21680. }
  21681. }
  21682. }
  21683. toJSON() {
  21684. const data = super.toJSON();
  21685. const shapes = this.parameters.shapes;
  21686. const options = this.parameters.options;
  21687. return toJSON$1(shapes, options, data);
  21688. }
  21689. static fromJSON(data, shapes) {
  21690. const geometryShapes = [];
  21691. for (let j = 0, jl = data.shapes.length; j < jl; j++) {
  21692. const shape = shapes[data.shapes[j]];
  21693. geometryShapes.push(shape);
  21694. }
  21695. const extrudePath = data.options.extrudePath;
  21696. if (extrudePath !== undefined) {
  21697. data.options.extrudePath = new Curves[extrudePath.type]().fromJSON(extrudePath);
  21698. }
  21699. return new ExtrudeGeometry(geometryShapes, data.options);
  21700. }
  21701. }
  21702. const WorldUVGenerator = {
  21703. generateTopUV: function (geometry, vertices, indexA, indexB, indexC) {
  21704. const a_x = vertices[indexA * 3];
  21705. const a_y = vertices[indexA * 3 + 1];
  21706. const b_x = vertices[indexB * 3];
  21707. const b_y = vertices[indexB * 3 + 1];
  21708. const c_x = vertices[indexC * 3];
  21709. const c_y = vertices[indexC * 3 + 1];
  21710. return [new Vector2(a_x, a_y), new Vector2(b_x, b_y), new Vector2(c_x, c_y)];
  21711. },
  21712. generateSideWallUV: function (geometry, vertices, indexA, indexB, indexC, indexD) {
  21713. const a_x = vertices[indexA * 3];
  21714. const a_y = vertices[indexA * 3 + 1];
  21715. const a_z = vertices[indexA * 3 + 2];
  21716. const b_x = vertices[indexB * 3];
  21717. const b_y = vertices[indexB * 3 + 1];
  21718. const b_z = vertices[indexB * 3 + 2];
  21719. const c_x = vertices[indexC * 3];
  21720. const c_y = vertices[indexC * 3 + 1];
  21721. const c_z = vertices[indexC * 3 + 2];
  21722. const d_x = vertices[indexD * 3];
  21723. const d_y = vertices[indexD * 3 + 1];
  21724. const d_z = vertices[indexD * 3 + 2];
  21725. if (Math.abs(a_y - b_y) < Math.abs(a_x - b_x)) {
  21726. 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)];
  21727. } else {
  21728. 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)];
  21729. }
  21730. }
  21731. };
  21732. function toJSON$1(shapes, options, data) {
  21733. data.shapes = [];
  21734. if (Array.isArray(shapes)) {
  21735. for (let i = 0, l = shapes.length; i < l; i++) {
  21736. const shape = shapes[i];
  21737. data.shapes.push(shape.uuid);
  21738. }
  21739. } else {
  21740. data.shapes.push(shapes.uuid);
  21741. }
  21742. data.options = Object.assign({}, options);
  21743. if (options.extrudePath !== undefined) data.options.extrudePath = options.extrudePath.toJSON();
  21744. return data;
  21745. }
  21746. class IcosahedronGeometry extends PolyhedronGeometry {
  21747. constructor(radius = 1, detail = 0) {
  21748. const t = (1 + Math.sqrt(5)) / 2;
  21749. 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];
  21750. 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];
  21751. super(vertices, indices, radius, detail);
  21752. this.type = 'IcosahedronGeometry';
  21753. this.parameters = {
  21754. radius: radius,
  21755. detail: detail
  21756. };
  21757. }
  21758. static fromJSON(data) {
  21759. return new IcosahedronGeometry(data.radius, data.detail);
  21760. }
  21761. }
  21762. class OctahedronGeometry extends PolyhedronGeometry {
  21763. constructor(radius = 1, detail = 0) {
  21764. const vertices = [1, 0, 0, -1, 0, 0, 0, 1, 0, 0, -1, 0, 0, 0, 1, 0, 0, -1];
  21765. 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];
  21766. super(vertices, indices, radius, detail);
  21767. this.type = 'OctahedronGeometry';
  21768. this.parameters = {
  21769. radius: radius,
  21770. detail: detail
  21771. };
  21772. }
  21773. static fromJSON(data) {
  21774. return new OctahedronGeometry(data.radius, data.detail);
  21775. }
  21776. }
  21777. class RingGeometry extends BufferGeometry {
  21778. constructor(innerRadius = 0.5, outerRadius = 1, thetaSegments = 8, phiSegments = 1, thetaStart = 0, thetaLength = Math.PI * 2) {
  21779. super();
  21780. this.type = 'RingGeometry';
  21781. this.parameters = {
  21782. innerRadius: innerRadius,
  21783. outerRadius: outerRadius,
  21784. thetaSegments: thetaSegments,
  21785. phiSegments: phiSegments,
  21786. thetaStart: thetaStart,
  21787. thetaLength: thetaLength
  21788. };
  21789. thetaSegments = Math.max(3, thetaSegments);
  21790. phiSegments = Math.max(1, phiSegments);
  21791. // buffers
  21792. const indices = [];
  21793. const vertices = [];
  21794. const normals = [];
  21795. const uvs = [];
  21796. // some helper variables
  21797. let radius = innerRadius;
  21798. const radiusStep = (outerRadius - innerRadius) / phiSegments;
  21799. const vertex = new Vector3();
  21800. const uv = new Vector2();
  21801. // generate vertices, normals and uvs
  21802. for (let j = 0; j <= phiSegments; j++) {
  21803. for (let i = 0; i <= thetaSegments; i++) {
  21804. // values are generate from the inside of the ring to the outside
  21805. const segment = thetaStart + i / thetaSegments * thetaLength;
  21806. // vertex
  21807. vertex.x = radius * Math.cos(segment);
  21808. vertex.y = radius * Math.sin(segment);
  21809. vertices.push(vertex.x, vertex.y, vertex.z);
  21810. // normal
  21811. normals.push(0, 0, 1);
  21812. // uv
  21813. uv.x = (vertex.x / outerRadius + 1) / 2;
  21814. uv.y = (vertex.y / outerRadius + 1) / 2;
  21815. uvs.push(uv.x, uv.y);
  21816. }
  21817. // increase the radius for next row of vertices
  21818. radius += radiusStep;
  21819. }
  21820. // indices
  21821. for (let j = 0; j < phiSegments; j++) {
  21822. const thetaSegmentLevel = j * (thetaSegments + 1);
  21823. for (let i = 0; i < thetaSegments; i++) {
  21824. const segment = i + thetaSegmentLevel;
  21825. const a = segment;
  21826. const b = segment + thetaSegments + 1;
  21827. const c = segment + thetaSegments + 2;
  21828. const d = segment + 1;
  21829. // faces
  21830. indices.push(a, b, d);
  21831. indices.push(b, c, d);
  21832. }
  21833. }
  21834. // build geometry
  21835. this.setIndex(indices);
  21836. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  21837. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  21838. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  21839. }
  21840. static fromJSON(data) {
  21841. return new RingGeometry(data.innerRadius, data.outerRadius, data.thetaSegments, data.phiSegments, data.thetaStart, data.thetaLength);
  21842. }
  21843. }
  21844. class ShapeGeometry extends BufferGeometry {
  21845. constructor(shapes = new Shape([new Vector2(0, 0.5), new Vector2(-0.5, -0.5), new Vector2(0.5, -0.5)]), curveSegments = 12) {
  21846. super();
  21847. this.type = 'ShapeGeometry';
  21848. this.parameters = {
  21849. shapes: shapes,
  21850. curveSegments: curveSegments
  21851. };
  21852. // buffers
  21853. const indices = [];
  21854. const vertices = [];
  21855. const normals = [];
  21856. const uvs = [];
  21857. // helper variables
  21858. let groupStart = 0;
  21859. let groupCount = 0;
  21860. // allow single and array values for "shapes" parameter
  21861. if (Array.isArray(shapes) === false) {
  21862. addShape(shapes);
  21863. } else {
  21864. for (let i = 0; i < shapes.length; i++) {
  21865. addShape(shapes[i]);
  21866. this.addGroup(groupStart, groupCount, i); // enables MultiMaterial support
  21867. groupStart += groupCount;
  21868. groupCount = 0;
  21869. }
  21870. }
  21871. // build geometry
  21872. this.setIndex(indices);
  21873. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  21874. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  21875. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  21876. // helper functions
  21877. function addShape(shape) {
  21878. const indexOffset = vertices.length / 3;
  21879. const points = shape.extractPoints(curveSegments);
  21880. let shapeVertices = points.shape;
  21881. const shapeHoles = points.holes;
  21882. // check direction of vertices
  21883. if (ShapeUtils.isClockWise(shapeVertices) === false) {
  21884. shapeVertices = shapeVertices.reverse();
  21885. }
  21886. for (let i = 0, l = shapeHoles.length; i < l; i++) {
  21887. const shapeHole = shapeHoles[i];
  21888. if (ShapeUtils.isClockWise(shapeHole) === true) {
  21889. shapeHoles[i] = shapeHole.reverse();
  21890. }
  21891. }
  21892. const faces = ShapeUtils.triangulateShape(shapeVertices, shapeHoles);
  21893. // join vertices of inner and outer paths to a single array
  21894. for (let i = 0, l = shapeHoles.length; i < l; i++) {
  21895. const shapeHole = shapeHoles[i];
  21896. shapeVertices = shapeVertices.concat(shapeHole);
  21897. }
  21898. // vertices, normals, uvs
  21899. for (let i = 0, l = shapeVertices.length; i < l; i++) {
  21900. const vertex = shapeVertices[i];
  21901. vertices.push(vertex.x, vertex.y, 0);
  21902. normals.push(0, 0, 1);
  21903. uvs.push(vertex.x, vertex.y); // world uvs
  21904. }
  21905. // indices
  21906. for (let i = 0, l = faces.length; i < l; i++) {
  21907. const face = faces[i];
  21908. const a = face[0] + indexOffset;
  21909. const b = face[1] + indexOffset;
  21910. const c = face[2] + indexOffset;
  21911. indices.push(a, b, c);
  21912. groupCount += 3;
  21913. }
  21914. }
  21915. }
  21916. toJSON() {
  21917. const data = super.toJSON();
  21918. const shapes = this.parameters.shapes;
  21919. return toJSON(shapes, data);
  21920. }
  21921. static fromJSON(data, shapes) {
  21922. const geometryShapes = [];
  21923. for (let j = 0, jl = data.shapes.length; j < jl; j++) {
  21924. const shape = shapes[data.shapes[j]];
  21925. geometryShapes.push(shape);
  21926. }
  21927. return new ShapeGeometry(geometryShapes, data.curveSegments);
  21928. }
  21929. }
  21930. function toJSON(shapes, data) {
  21931. data.shapes = [];
  21932. if (Array.isArray(shapes)) {
  21933. for (let i = 0, l = shapes.length; i < l; i++) {
  21934. const shape = shapes[i];
  21935. data.shapes.push(shape.uuid);
  21936. }
  21937. } else {
  21938. data.shapes.push(shapes.uuid);
  21939. }
  21940. return data;
  21941. }
  21942. class SphereGeometry extends BufferGeometry {
  21943. constructor(radius = 1, widthSegments = 32, heightSegments = 16, phiStart = 0, phiLength = Math.PI * 2, thetaStart = 0, thetaLength = Math.PI) {
  21944. super();
  21945. this.type = 'SphereGeometry';
  21946. this.parameters = {
  21947. radius: radius,
  21948. widthSegments: widthSegments,
  21949. heightSegments: heightSegments,
  21950. phiStart: phiStart,
  21951. phiLength: phiLength,
  21952. thetaStart: thetaStart,
  21953. thetaLength: thetaLength
  21954. };
  21955. widthSegments = Math.max(3, Math.floor(widthSegments));
  21956. heightSegments = Math.max(2, Math.floor(heightSegments));
  21957. const thetaEnd = Math.min(thetaStart + thetaLength, Math.PI);
  21958. let index = 0;
  21959. const grid = [];
  21960. const vertex = new Vector3();
  21961. const normal = new Vector3();
  21962. // buffers
  21963. const indices = [];
  21964. const vertices = [];
  21965. const normals = [];
  21966. const uvs = [];
  21967. // generate vertices, normals and uvs
  21968. for (let iy = 0; iy <= heightSegments; iy++) {
  21969. const verticesRow = [];
  21970. const v = iy / heightSegments;
  21971. // special case for the poles
  21972. let uOffset = 0;
  21973. if (iy == 0 && thetaStart == 0) {
  21974. uOffset = 0.5 / widthSegments;
  21975. } else if (iy == heightSegments && thetaEnd == Math.PI) {
  21976. uOffset = -0.5 / widthSegments;
  21977. }
  21978. for (let ix = 0; ix <= widthSegments; ix++) {
  21979. const u = ix / widthSegments;
  21980. // vertex
  21981. vertex.x = -radius * Math.cos(phiStart + u * phiLength) * Math.sin(thetaStart + v * thetaLength);
  21982. vertex.y = radius * Math.cos(thetaStart + v * thetaLength);
  21983. vertex.z = radius * Math.sin(phiStart + u * phiLength) * Math.sin(thetaStart + v * thetaLength);
  21984. vertices.push(vertex.x, vertex.y, vertex.z);
  21985. // normal
  21986. normal.copy(vertex).normalize();
  21987. normals.push(normal.x, normal.y, normal.z);
  21988. // uv
  21989. uvs.push(u + uOffset, 1 - v);
  21990. verticesRow.push(index++);
  21991. }
  21992. grid.push(verticesRow);
  21993. }
  21994. // indices
  21995. for (let iy = 0; iy < heightSegments; iy++) {
  21996. for (let ix = 0; ix < widthSegments; ix++) {
  21997. const a = grid[iy][ix + 1];
  21998. const b = grid[iy][ix];
  21999. const c = grid[iy + 1][ix];
  22000. const d = grid[iy + 1][ix + 1];
  22001. if (iy !== 0 || thetaStart > 0) indices.push(a, b, d);
  22002. if (iy !== heightSegments - 1 || thetaEnd < Math.PI) indices.push(b, c, d);
  22003. }
  22004. }
  22005. // build geometry
  22006. this.setIndex(indices);
  22007. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  22008. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  22009. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  22010. }
  22011. static fromJSON(data) {
  22012. return new SphereGeometry(data.radius, data.widthSegments, data.heightSegments, data.phiStart, data.phiLength, data.thetaStart, data.thetaLength);
  22013. }
  22014. }
  22015. class TetrahedronGeometry extends PolyhedronGeometry {
  22016. constructor(radius = 1, detail = 0) {
  22017. const vertices = [1, 1, 1, -1, -1, 1, -1, 1, -1, 1, -1, -1];
  22018. const indices = [2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1];
  22019. super(vertices, indices, radius, detail);
  22020. this.type = 'TetrahedronGeometry';
  22021. this.parameters = {
  22022. radius: radius,
  22023. detail: detail
  22024. };
  22025. }
  22026. static fromJSON(data) {
  22027. return new TetrahedronGeometry(data.radius, data.detail);
  22028. }
  22029. }
  22030. class TorusGeometry extends BufferGeometry {
  22031. constructor(radius = 1, tube = 0.4, radialSegments = 8, tubularSegments = 6, arc = Math.PI * 2) {
  22032. super();
  22033. this.type = 'TorusGeometry';
  22034. this.parameters = {
  22035. radius: radius,
  22036. tube: tube,
  22037. radialSegments: radialSegments,
  22038. tubularSegments: tubularSegments,
  22039. arc: arc
  22040. };
  22041. radialSegments = Math.floor(radialSegments);
  22042. tubularSegments = Math.floor(tubularSegments);
  22043. // buffers
  22044. const indices = [];
  22045. const vertices = [];
  22046. const normals = [];
  22047. const uvs = [];
  22048. // helper variables
  22049. const center = new Vector3();
  22050. const vertex = new Vector3();
  22051. const normal = new Vector3();
  22052. // generate vertices, normals and uvs
  22053. for (let j = 0; j <= radialSegments; j++) {
  22054. for (let i = 0; i <= tubularSegments; i++) {
  22055. const u = i / tubularSegments * arc;
  22056. const v = j / radialSegments * Math.PI * 2;
  22057. // vertex
  22058. vertex.x = (radius + tube * Math.cos(v)) * Math.cos(u);
  22059. vertex.y = (radius + tube * Math.cos(v)) * Math.sin(u);
  22060. vertex.z = tube * Math.sin(v);
  22061. vertices.push(vertex.x, vertex.y, vertex.z);
  22062. // normal
  22063. center.x = radius * Math.cos(u);
  22064. center.y = radius * Math.sin(u);
  22065. normal.subVectors(vertex, center).normalize();
  22066. normals.push(normal.x, normal.y, normal.z);
  22067. // uv
  22068. uvs.push(i / tubularSegments);
  22069. uvs.push(j / radialSegments);
  22070. }
  22071. }
  22072. // generate indices
  22073. for (let j = 1; j <= radialSegments; j++) {
  22074. for (let i = 1; i <= tubularSegments; i++) {
  22075. // indices
  22076. const a = (tubularSegments + 1) * j + i - 1;
  22077. const b = (tubularSegments + 1) * (j - 1) + i - 1;
  22078. const c = (tubularSegments + 1) * (j - 1) + i;
  22079. const d = (tubularSegments + 1) * j + i;
  22080. // faces
  22081. indices.push(a, b, d);
  22082. indices.push(b, c, d);
  22083. }
  22084. }
  22085. // build geometry
  22086. this.setIndex(indices);
  22087. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  22088. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  22089. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  22090. }
  22091. static fromJSON(data) {
  22092. return new TorusGeometry(data.radius, data.tube, data.radialSegments, data.tubularSegments, data.arc);
  22093. }
  22094. }
  22095. class TorusKnotGeometry extends BufferGeometry {
  22096. constructor(radius = 1, tube = 0.4, tubularSegments = 64, radialSegments = 8, p = 2, q = 3) {
  22097. super();
  22098. this.type = 'TorusKnotGeometry';
  22099. this.parameters = {
  22100. radius: radius,
  22101. tube: tube,
  22102. tubularSegments: tubularSegments,
  22103. radialSegments: radialSegments,
  22104. p: p,
  22105. q: q
  22106. };
  22107. tubularSegments = Math.floor(tubularSegments);
  22108. radialSegments = Math.floor(radialSegments);
  22109. // buffers
  22110. const indices = [];
  22111. const vertices = [];
  22112. const normals = [];
  22113. const uvs = [];
  22114. // helper variables
  22115. const vertex = new Vector3();
  22116. const normal = new Vector3();
  22117. const P1 = new Vector3();
  22118. const P2 = new Vector3();
  22119. const B = new Vector3();
  22120. const T = new Vector3();
  22121. const N = new Vector3();
  22122. // generate vertices, normals and uvs
  22123. for (let i = 0; i <= tubularSegments; ++i) {
  22124. // the radian "u" is used to calculate the position on the torus curve of the current tubular segment
  22125. const u = i / tubularSegments * p * Math.PI * 2;
  22126. // now we calculate two points. P1 is our current position on the curve, P2 is a little farther ahead.
  22127. // these points are used to create a special "coordinate space", which is necessary to calculate the correct vertex positions
  22128. calculatePositionOnCurve(u, p, q, radius, P1);
  22129. calculatePositionOnCurve(u + 0.01, p, q, radius, P2);
  22130. // calculate orthonormal basis
  22131. T.subVectors(P2, P1);
  22132. N.addVectors(P2, P1);
  22133. B.crossVectors(T, N);
  22134. N.crossVectors(B, T);
  22135. // normalize B, N. T can be ignored, we don't use it
  22136. B.normalize();
  22137. N.normalize();
  22138. for (let j = 0; j <= radialSegments; ++j) {
  22139. // now calculate the vertices. they are nothing more than an extrusion of the torus curve.
  22140. // because we extrude a shape in the xy-plane, there is no need to calculate a z-value.
  22141. const v = j / radialSegments * Math.PI * 2;
  22142. const cx = -tube * Math.cos(v);
  22143. const cy = tube * Math.sin(v);
  22144. // now calculate the final vertex position.
  22145. // first we orient the extrusion with our basis vectors, then we add it to the current position on the curve
  22146. vertex.x = P1.x + (cx * N.x + cy * B.x);
  22147. vertex.y = P1.y + (cx * N.y + cy * B.y);
  22148. vertex.z = P1.z + (cx * N.z + cy * B.z);
  22149. vertices.push(vertex.x, vertex.y, vertex.z);
  22150. // normal (P1 is always the center/origin of the extrusion, thus we can use it to calculate the normal)
  22151. normal.subVectors(vertex, P1).normalize();
  22152. normals.push(normal.x, normal.y, normal.z);
  22153. // uv
  22154. uvs.push(i / tubularSegments);
  22155. uvs.push(j / radialSegments);
  22156. }
  22157. }
  22158. // generate indices
  22159. for (let j = 1; j <= tubularSegments; j++) {
  22160. for (let i = 1; i <= radialSegments; i++) {
  22161. // indices
  22162. const a = (radialSegments + 1) * (j - 1) + (i - 1);
  22163. const b = (radialSegments + 1) * j + (i - 1);
  22164. const c = (radialSegments + 1) * j + i;
  22165. const d = (radialSegments + 1) * (j - 1) + i;
  22166. // faces
  22167. indices.push(a, b, d);
  22168. indices.push(b, c, d);
  22169. }
  22170. }
  22171. // build geometry
  22172. this.setIndex(indices);
  22173. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  22174. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  22175. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  22176. // this function calculates the current position on the torus curve
  22177. function calculatePositionOnCurve(u, p, q, radius, position) {
  22178. const cu = Math.cos(u);
  22179. const su = Math.sin(u);
  22180. const quOverP = q / p * u;
  22181. const cs = Math.cos(quOverP);
  22182. position.x = radius * (2 + cs) * 0.5 * cu;
  22183. position.y = radius * (2 + cs) * su * 0.5;
  22184. position.z = radius * Math.sin(quOverP) * 0.5;
  22185. }
  22186. }
  22187. static fromJSON(data) {
  22188. return new TorusKnotGeometry(data.radius, data.tube, data.tubularSegments, data.radialSegments, data.p, data.q);
  22189. }
  22190. }
  22191. class TubeGeometry extends BufferGeometry {
  22192. 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) {
  22193. super();
  22194. this.type = 'TubeGeometry';
  22195. this.parameters = {
  22196. path: path,
  22197. tubularSegments: tubularSegments,
  22198. radius: radius,
  22199. radialSegments: radialSegments,
  22200. closed: closed
  22201. };
  22202. const frames = path.computeFrenetFrames(tubularSegments, closed);
  22203. // expose internals
  22204. this.tangents = frames.tangents;
  22205. this.normals = frames.normals;
  22206. this.binormals = frames.binormals;
  22207. // helper variables
  22208. const vertex = new Vector3();
  22209. const normal = new Vector3();
  22210. const uv = new Vector2();
  22211. let P = new Vector3();
  22212. // buffer
  22213. const vertices = [];
  22214. const normals = [];
  22215. const uvs = [];
  22216. const indices = [];
  22217. // create buffer data
  22218. generateBufferData();
  22219. // build geometry
  22220. this.setIndex(indices);
  22221. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  22222. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  22223. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  22224. // functions
  22225. function generateBufferData() {
  22226. for (let i = 0; i < tubularSegments; i++) {
  22227. generateSegment(i);
  22228. }
  22229. // if the geometry is not closed, generate the last row of vertices and normals
  22230. // at the regular position on the given path
  22231. //
  22232. // if the geometry is closed, duplicate the first row of vertices and normals (uvs will differ)
  22233. generateSegment(closed === false ? tubularSegments : 0);
  22234. // uvs are generated in a separate function.
  22235. // this makes it easy compute correct values for closed geometries
  22236. generateUVs();
  22237. // finally create faces
  22238. generateIndices();
  22239. }
  22240. function generateSegment(i) {
  22241. // we use getPointAt to sample evenly distributed points from the given path
  22242. P = path.getPointAt(i / tubularSegments, P);
  22243. // retrieve corresponding normal and binormal
  22244. const N = frames.normals[i];
  22245. const B = frames.binormals[i];
  22246. // generate normals and vertices for the current segment
  22247. for (let j = 0; j <= radialSegments; j++) {
  22248. const v = j / radialSegments * Math.PI * 2;
  22249. const sin = Math.sin(v);
  22250. const cos = -Math.cos(v);
  22251. // normal
  22252. normal.x = cos * N.x + sin * B.x;
  22253. normal.y = cos * N.y + sin * B.y;
  22254. normal.z = cos * N.z + sin * B.z;
  22255. normal.normalize();
  22256. normals.push(normal.x, normal.y, normal.z);
  22257. // vertex
  22258. vertex.x = P.x + radius * normal.x;
  22259. vertex.y = P.y + radius * normal.y;
  22260. vertex.z = P.z + radius * normal.z;
  22261. vertices.push(vertex.x, vertex.y, vertex.z);
  22262. }
  22263. }
  22264. function generateIndices() {
  22265. for (let j = 1; j <= tubularSegments; j++) {
  22266. for (let i = 1; i <= radialSegments; i++) {
  22267. const a = (radialSegments + 1) * (j - 1) + (i - 1);
  22268. const b = (radialSegments + 1) * j + (i - 1);
  22269. const c = (radialSegments + 1) * j + i;
  22270. const d = (radialSegments + 1) * (j - 1) + i;
  22271. // faces
  22272. indices.push(a, b, d);
  22273. indices.push(b, c, d);
  22274. }
  22275. }
  22276. }
  22277. function generateUVs() {
  22278. for (let i = 0; i <= tubularSegments; i++) {
  22279. for (let j = 0; j <= radialSegments; j++) {
  22280. uv.x = i / tubularSegments;
  22281. uv.y = j / radialSegments;
  22282. uvs.push(uv.x, uv.y);
  22283. }
  22284. }
  22285. }
  22286. }
  22287. toJSON() {
  22288. const data = super.toJSON();
  22289. data.path = this.parameters.path.toJSON();
  22290. return data;
  22291. }
  22292. static fromJSON(data) {
  22293. // This only works for built-in curves (e.g. CatmullRomCurve3).
  22294. // User defined curves or instances of CurvePath will not be deserialized.
  22295. return new TubeGeometry(new Curves[data.path.type]().fromJSON(data.path), data.tubularSegments, data.radius, data.radialSegments, data.closed);
  22296. }
  22297. }
  22298. class WireframeGeometry extends BufferGeometry {
  22299. constructor(geometry = null) {
  22300. super();
  22301. this.type = 'WireframeGeometry';
  22302. this.parameters = {
  22303. geometry: geometry
  22304. };
  22305. if (geometry !== null) {
  22306. // buffer
  22307. const vertices = [];
  22308. const edges = new Set();
  22309. // helper variables
  22310. const start = new Vector3();
  22311. const end = new Vector3();
  22312. if (geometry.index !== null) {
  22313. // indexed BufferGeometry
  22314. const position = geometry.attributes.position;
  22315. const indices = geometry.index;
  22316. let groups = geometry.groups;
  22317. if (groups.length === 0) {
  22318. groups = [{
  22319. start: 0,
  22320. count: indices.count,
  22321. materialIndex: 0
  22322. }];
  22323. }
  22324. // create a data structure that contains all edges without duplicates
  22325. for (let o = 0, ol = groups.length; o < ol; ++o) {
  22326. const group = groups[o];
  22327. const groupStart = group.start;
  22328. const groupCount = group.count;
  22329. for (let i = groupStart, l = groupStart + groupCount; i < l; i += 3) {
  22330. for (let j = 0; j < 3; j++) {
  22331. const index1 = indices.getX(i + j);
  22332. const index2 = indices.getX(i + (j + 1) % 3);
  22333. start.fromBufferAttribute(position, index1);
  22334. end.fromBufferAttribute(position, index2);
  22335. if (isUniqueEdge(start, end, edges) === true) {
  22336. vertices.push(start.x, start.y, start.z);
  22337. vertices.push(end.x, end.y, end.z);
  22338. }
  22339. }
  22340. }
  22341. }
  22342. } else {
  22343. // non-indexed BufferGeometry
  22344. const position = geometry.attributes.position;
  22345. for (let i = 0, l = position.count / 3; i < l; i++) {
  22346. for (let j = 0; j < 3; j++) {
  22347. // three edges per triangle, an edge is represented as (index1, index2)
  22348. // e.g. the first triangle has the following edges: (0,1),(1,2),(2,0)
  22349. const index1 = 3 * i + j;
  22350. const index2 = 3 * i + (j + 1) % 3;
  22351. start.fromBufferAttribute(position, index1);
  22352. end.fromBufferAttribute(position, index2);
  22353. if (isUniqueEdge(start, end, edges) === true) {
  22354. vertices.push(start.x, start.y, start.z);
  22355. vertices.push(end.x, end.y, end.z);
  22356. }
  22357. }
  22358. }
  22359. }
  22360. // build geometry
  22361. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  22362. }
  22363. }
  22364. }
  22365. function isUniqueEdge(start, end, edges) {
  22366. const hash1 = `${start.x},${start.y},${start.z}-${end.x},${end.y},${end.z}`;
  22367. const hash2 = `${end.x},${end.y},${end.z}-${start.x},${start.y},${start.z}`; // coincident edge
  22368. if (edges.has(hash1) === true || edges.has(hash2) === true) {
  22369. return false;
  22370. } else {
  22371. edges.add(hash1);
  22372. edges.add(hash2);
  22373. return true;
  22374. }
  22375. }
  22376. var Geometries = /*#__PURE__*/Object.freeze({
  22377. __proto__: null,
  22378. BoxGeometry: BoxGeometry,
  22379. CapsuleGeometry: CapsuleGeometry,
  22380. CircleGeometry: CircleGeometry,
  22381. ConeGeometry: ConeGeometry,
  22382. CylinderGeometry: CylinderGeometry,
  22383. DodecahedronGeometry: DodecahedronGeometry,
  22384. EdgesGeometry: EdgesGeometry,
  22385. ExtrudeGeometry: ExtrudeGeometry,
  22386. IcosahedronGeometry: IcosahedronGeometry,
  22387. LatheGeometry: LatheGeometry,
  22388. OctahedronGeometry: OctahedronGeometry,
  22389. PlaneGeometry: PlaneGeometry,
  22390. PolyhedronGeometry: PolyhedronGeometry,
  22391. RingGeometry: RingGeometry,
  22392. ShapeGeometry: ShapeGeometry,
  22393. SphereGeometry: SphereGeometry,
  22394. TetrahedronGeometry: TetrahedronGeometry,
  22395. TorusGeometry: TorusGeometry,
  22396. TorusKnotGeometry: TorusKnotGeometry,
  22397. TubeGeometry: TubeGeometry,
  22398. WireframeGeometry: WireframeGeometry
  22399. });
  22400. class ShadowMaterial extends Material {
  22401. constructor(parameters) {
  22402. super();
  22403. this.isShadowMaterial = true;
  22404. this.type = 'ShadowMaterial';
  22405. this.color = new Color(0x000000);
  22406. this.transparent = true;
  22407. this.fog = true;
  22408. this.setValues(parameters);
  22409. }
  22410. copy(source) {
  22411. super.copy(source);
  22412. this.color.copy(source.color);
  22413. this.fog = source.fog;
  22414. return this;
  22415. }
  22416. }
  22417. class RawShaderMaterial extends ShaderMaterial {
  22418. constructor(parameters) {
  22419. super(parameters);
  22420. this.isRawShaderMaterial = true;
  22421. this.type = 'RawShaderMaterial';
  22422. }
  22423. }
  22424. class MeshStandardMaterial extends Material {
  22425. constructor(parameters) {
  22426. super();
  22427. this.isMeshStandardMaterial = true;
  22428. this.defines = {
  22429. 'STANDARD': ''
  22430. };
  22431. this.type = 'MeshStandardMaterial';
  22432. this.color = new Color(0xffffff); // diffuse
  22433. this.roughness = 1.0;
  22434. this.metalness = 0.0;
  22435. this.map = null;
  22436. this.lightMap = null;
  22437. this.lightMapIntensity = 1.0;
  22438. this.aoMap = null;
  22439. this.aoMapIntensity = 1.0;
  22440. this.emissive = new Color(0x000000);
  22441. this.emissiveIntensity = 1.0;
  22442. this.emissiveMap = null;
  22443. this.bumpMap = null;
  22444. this.bumpScale = 1;
  22445. this.normalMap = null;
  22446. this.normalMapType = TangentSpaceNormalMap;
  22447. this.normalScale = new Vector2(1, 1);
  22448. this.displacementMap = null;
  22449. this.displacementScale = 1;
  22450. this.displacementBias = 0;
  22451. this.roughnessMap = null;
  22452. this.metalnessMap = null;
  22453. this.alphaMap = null;
  22454. this.envMap = null;
  22455. this.envMapIntensity = 1.0;
  22456. this.wireframe = false;
  22457. this.wireframeLinewidth = 1;
  22458. this.wireframeLinecap = 'round';
  22459. this.wireframeLinejoin = 'round';
  22460. this.flatShading = false;
  22461. this.fog = true;
  22462. this.setValues(parameters);
  22463. }
  22464. copy(source) {
  22465. super.copy(source);
  22466. this.defines = {
  22467. 'STANDARD': ''
  22468. };
  22469. this.color.copy(source.color);
  22470. this.roughness = source.roughness;
  22471. this.metalness = source.metalness;
  22472. this.map = source.map;
  22473. this.lightMap = source.lightMap;
  22474. this.lightMapIntensity = source.lightMapIntensity;
  22475. this.aoMap = source.aoMap;
  22476. this.aoMapIntensity = source.aoMapIntensity;
  22477. this.emissive.copy(source.emissive);
  22478. this.emissiveMap = source.emissiveMap;
  22479. this.emissiveIntensity = source.emissiveIntensity;
  22480. this.bumpMap = source.bumpMap;
  22481. this.bumpScale = source.bumpScale;
  22482. this.normalMap = source.normalMap;
  22483. this.normalMapType = source.normalMapType;
  22484. this.normalScale.copy(source.normalScale);
  22485. this.displacementMap = source.displacementMap;
  22486. this.displacementScale = source.displacementScale;
  22487. this.displacementBias = source.displacementBias;
  22488. this.roughnessMap = source.roughnessMap;
  22489. this.metalnessMap = source.metalnessMap;
  22490. this.alphaMap = source.alphaMap;
  22491. this.envMap = source.envMap;
  22492. this.envMapIntensity = source.envMapIntensity;
  22493. this.wireframe = source.wireframe;
  22494. this.wireframeLinewidth = source.wireframeLinewidth;
  22495. this.wireframeLinecap = source.wireframeLinecap;
  22496. this.wireframeLinejoin = source.wireframeLinejoin;
  22497. this.flatShading = source.flatShading;
  22498. this.fog = source.fog;
  22499. return this;
  22500. }
  22501. }
  22502. class MeshPhysicalMaterial extends MeshStandardMaterial {
  22503. constructor(parameters) {
  22504. super();
  22505. this.isMeshPhysicalMaterial = true;
  22506. this.defines = {
  22507. 'STANDARD': '',
  22508. 'PHYSICAL': ''
  22509. };
  22510. this.type = 'MeshPhysicalMaterial';
  22511. this.clearcoatMap = null;
  22512. this.clearcoatRoughness = 0.0;
  22513. this.clearcoatRoughnessMap = null;
  22514. this.clearcoatNormalScale = new Vector2(1, 1);
  22515. this.clearcoatNormalMap = null;
  22516. this.ior = 1.5;
  22517. Object.defineProperty(this, 'reflectivity', {
  22518. get: function () {
  22519. return clamp(2.5 * (this.ior - 1) / (this.ior + 1), 0, 1);
  22520. },
  22521. set: function (reflectivity) {
  22522. this.ior = (1 + 0.4 * reflectivity) / (1 - 0.4 * reflectivity);
  22523. }
  22524. });
  22525. this.iridescenceMap = null;
  22526. this.iridescenceIOR = 1.3;
  22527. this.iridescenceThicknessRange = [100, 400];
  22528. this.iridescenceThicknessMap = null;
  22529. this.sheenColor = new Color(0x000000);
  22530. this.sheenColorMap = null;
  22531. this.sheenRoughness = 1.0;
  22532. this.sheenRoughnessMap = null;
  22533. this.transmissionMap = null;
  22534. this.thickness = 0;
  22535. this.thicknessMap = null;
  22536. this.attenuationDistance = Infinity;
  22537. this.attenuationColor = new Color(1, 1, 1);
  22538. this.specularIntensity = 1.0;
  22539. this.specularIntensityMap = null;
  22540. this.specularColor = new Color(1, 1, 1);
  22541. this.specularColorMap = null;
  22542. this._sheen = 0.0;
  22543. this._clearcoat = 0;
  22544. this._iridescence = 0;
  22545. this._transmission = 0;
  22546. this.setValues(parameters);
  22547. }
  22548. get sheen() {
  22549. return this._sheen;
  22550. }
  22551. set sheen(value) {
  22552. if (this._sheen > 0 !== value > 0) {
  22553. this.version++;
  22554. }
  22555. this._sheen = value;
  22556. }
  22557. get clearcoat() {
  22558. return this._clearcoat;
  22559. }
  22560. set clearcoat(value) {
  22561. if (this._clearcoat > 0 !== value > 0) {
  22562. this.version++;
  22563. }
  22564. this._clearcoat = value;
  22565. }
  22566. get iridescence() {
  22567. return this._iridescence;
  22568. }
  22569. set iridescence(value) {
  22570. if (this._iridescence > 0 !== value > 0) {
  22571. this.version++;
  22572. }
  22573. this._iridescence = value;
  22574. }
  22575. get transmission() {
  22576. return this._transmission;
  22577. }
  22578. set transmission(value) {
  22579. if (this._transmission > 0 !== value > 0) {
  22580. this.version++;
  22581. }
  22582. this._transmission = value;
  22583. }
  22584. copy(source) {
  22585. super.copy(source);
  22586. this.defines = {
  22587. 'STANDARD': '',
  22588. 'PHYSICAL': ''
  22589. };
  22590. this.clearcoat = source.clearcoat;
  22591. this.clearcoatMap = source.clearcoatMap;
  22592. this.clearcoatRoughness = source.clearcoatRoughness;
  22593. this.clearcoatRoughnessMap = source.clearcoatRoughnessMap;
  22594. this.clearcoatNormalMap = source.clearcoatNormalMap;
  22595. this.clearcoatNormalScale.copy(source.clearcoatNormalScale);
  22596. this.ior = source.ior;
  22597. this.iridescence = source.iridescence;
  22598. this.iridescenceMap = source.iridescenceMap;
  22599. this.iridescenceIOR = source.iridescenceIOR;
  22600. this.iridescenceThicknessRange = [...source.iridescenceThicknessRange];
  22601. this.iridescenceThicknessMap = source.iridescenceThicknessMap;
  22602. this.sheen = source.sheen;
  22603. this.sheenColor.copy(source.sheenColor);
  22604. this.sheenColorMap = source.sheenColorMap;
  22605. this.sheenRoughness = source.sheenRoughness;
  22606. this.sheenRoughnessMap = source.sheenRoughnessMap;
  22607. this.transmission = source.transmission;
  22608. this.transmissionMap = source.transmissionMap;
  22609. this.thickness = source.thickness;
  22610. this.thicknessMap = source.thicknessMap;
  22611. this.attenuationDistance = source.attenuationDistance;
  22612. this.attenuationColor.copy(source.attenuationColor);
  22613. this.specularIntensity = source.specularIntensity;
  22614. this.specularIntensityMap = source.specularIntensityMap;
  22615. this.specularColor.copy(source.specularColor);
  22616. this.specularColorMap = source.specularColorMap;
  22617. return this;
  22618. }
  22619. }
  22620. class MeshPhongMaterial extends Material {
  22621. constructor(parameters) {
  22622. super();
  22623. this.isMeshPhongMaterial = true;
  22624. this.type = 'MeshPhongMaterial';
  22625. this.color = new Color(0xffffff); // diffuse
  22626. this.specular = new Color(0x111111);
  22627. this.shininess = 30;
  22628. this.map = null;
  22629. this.lightMap = null;
  22630. this.lightMapIntensity = 1.0;
  22631. this.aoMap = null;
  22632. this.aoMapIntensity = 1.0;
  22633. this.emissive = new Color(0x000000);
  22634. this.emissiveIntensity = 1.0;
  22635. this.emissiveMap = null;
  22636. this.bumpMap = null;
  22637. this.bumpScale = 1;
  22638. this.normalMap = null;
  22639. this.normalMapType = TangentSpaceNormalMap;
  22640. this.normalScale = new Vector2(1, 1);
  22641. this.displacementMap = null;
  22642. this.displacementScale = 1;
  22643. this.displacementBias = 0;
  22644. this.specularMap = null;
  22645. this.alphaMap = null;
  22646. this.envMap = null;
  22647. this.combine = MultiplyOperation;
  22648. this.reflectivity = 1;
  22649. this.refractionRatio = 0.98;
  22650. this.wireframe = false;
  22651. this.wireframeLinewidth = 1;
  22652. this.wireframeLinecap = 'round';
  22653. this.wireframeLinejoin = 'round';
  22654. this.flatShading = false;
  22655. this.fog = true;
  22656. this.setValues(parameters);
  22657. }
  22658. copy(source) {
  22659. super.copy(source);
  22660. this.color.copy(source.color);
  22661. this.specular.copy(source.specular);
  22662. this.shininess = source.shininess;
  22663. this.map = source.map;
  22664. this.lightMap = source.lightMap;
  22665. this.lightMapIntensity = source.lightMapIntensity;
  22666. this.aoMap = source.aoMap;
  22667. this.aoMapIntensity = source.aoMapIntensity;
  22668. this.emissive.copy(source.emissive);
  22669. this.emissiveMap = source.emissiveMap;
  22670. this.emissiveIntensity = source.emissiveIntensity;
  22671. this.bumpMap = source.bumpMap;
  22672. this.bumpScale = source.bumpScale;
  22673. this.normalMap = source.normalMap;
  22674. this.normalMapType = source.normalMapType;
  22675. this.normalScale.copy(source.normalScale);
  22676. this.displacementMap = source.displacementMap;
  22677. this.displacementScale = source.displacementScale;
  22678. this.displacementBias = source.displacementBias;
  22679. this.specularMap = source.specularMap;
  22680. this.alphaMap = source.alphaMap;
  22681. this.envMap = source.envMap;
  22682. this.combine = source.combine;
  22683. this.reflectivity = source.reflectivity;
  22684. this.refractionRatio = source.refractionRatio;
  22685. this.wireframe = source.wireframe;
  22686. this.wireframeLinewidth = source.wireframeLinewidth;
  22687. this.wireframeLinecap = source.wireframeLinecap;
  22688. this.wireframeLinejoin = source.wireframeLinejoin;
  22689. this.flatShading = source.flatShading;
  22690. this.fog = source.fog;
  22691. return this;
  22692. }
  22693. }
  22694. class MeshToonMaterial extends Material {
  22695. constructor(parameters) {
  22696. super();
  22697. this.isMeshToonMaterial = true;
  22698. this.defines = {
  22699. 'TOON': ''
  22700. };
  22701. this.type = 'MeshToonMaterial';
  22702. this.color = new Color(0xffffff);
  22703. this.map = null;
  22704. this.gradientMap = null;
  22705. this.lightMap = null;
  22706. this.lightMapIntensity = 1.0;
  22707. this.aoMap = null;
  22708. this.aoMapIntensity = 1.0;
  22709. this.emissive = new Color(0x000000);
  22710. this.emissiveIntensity = 1.0;
  22711. this.emissiveMap = null;
  22712. this.bumpMap = null;
  22713. this.bumpScale = 1;
  22714. this.normalMap = null;
  22715. this.normalMapType = TangentSpaceNormalMap;
  22716. this.normalScale = new Vector2(1, 1);
  22717. this.displacementMap = null;
  22718. this.displacementScale = 1;
  22719. this.displacementBias = 0;
  22720. this.alphaMap = null;
  22721. this.wireframe = false;
  22722. this.wireframeLinewidth = 1;
  22723. this.wireframeLinecap = 'round';
  22724. this.wireframeLinejoin = 'round';
  22725. this.fog = true;
  22726. this.setValues(parameters);
  22727. }
  22728. copy(source) {
  22729. super.copy(source);
  22730. this.color.copy(source.color);
  22731. this.map = source.map;
  22732. this.gradientMap = source.gradientMap;
  22733. this.lightMap = source.lightMap;
  22734. this.lightMapIntensity = source.lightMapIntensity;
  22735. this.aoMap = source.aoMap;
  22736. this.aoMapIntensity = source.aoMapIntensity;
  22737. this.emissive.copy(source.emissive);
  22738. this.emissiveMap = source.emissiveMap;
  22739. this.emissiveIntensity = source.emissiveIntensity;
  22740. this.bumpMap = source.bumpMap;
  22741. this.bumpScale = source.bumpScale;
  22742. this.normalMap = source.normalMap;
  22743. this.normalMapType = source.normalMapType;
  22744. this.normalScale.copy(source.normalScale);
  22745. this.displacementMap = source.displacementMap;
  22746. this.displacementScale = source.displacementScale;
  22747. this.displacementBias = source.displacementBias;
  22748. this.alphaMap = source.alphaMap;
  22749. this.wireframe = source.wireframe;
  22750. this.wireframeLinewidth = source.wireframeLinewidth;
  22751. this.wireframeLinecap = source.wireframeLinecap;
  22752. this.wireframeLinejoin = source.wireframeLinejoin;
  22753. this.fog = source.fog;
  22754. return this;
  22755. }
  22756. }
  22757. class MeshNormalMaterial extends Material {
  22758. constructor(parameters) {
  22759. super();
  22760. this.isMeshNormalMaterial = true;
  22761. this.type = 'MeshNormalMaterial';
  22762. this.bumpMap = null;
  22763. this.bumpScale = 1;
  22764. this.normalMap = null;
  22765. this.normalMapType = TangentSpaceNormalMap;
  22766. this.normalScale = new Vector2(1, 1);
  22767. this.displacementMap = null;
  22768. this.displacementScale = 1;
  22769. this.displacementBias = 0;
  22770. this.wireframe = false;
  22771. this.wireframeLinewidth = 1;
  22772. this.flatShading = false;
  22773. this.setValues(parameters);
  22774. }
  22775. copy(source) {
  22776. super.copy(source);
  22777. this.bumpMap = source.bumpMap;
  22778. this.bumpScale = source.bumpScale;
  22779. this.normalMap = source.normalMap;
  22780. this.normalMapType = source.normalMapType;
  22781. this.normalScale.copy(source.normalScale);
  22782. this.displacementMap = source.displacementMap;
  22783. this.displacementScale = source.displacementScale;
  22784. this.displacementBias = source.displacementBias;
  22785. this.wireframe = source.wireframe;
  22786. this.wireframeLinewidth = source.wireframeLinewidth;
  22787. this.flatShading = source.flatShading;
  22788. return this;
  22789. }
  22790. }
  22791. class MeshLambertMaterial extends Material {
  22792. constructor(parameters) {
  22793. super();
  22794. this.isMeshLambertMaterial = true;
  22795. this.type = 'MeshLambertMaterial';
  22796. this.color = new Color(0xffffff); // diffuse
  22797. this.map = null;
  22798. this.lightMap = null;
  22799. this.lightMapIntensity = 1.0;
  22800. this.aoMap = null;
  22801. this.aoMapIntensity = 1.0;
  22802. this.emissive = new Color(0x000000);
  22803. this.emissiveIntensity = 1.0;
  22804. this.emissiveMap = null;
  22805. this.bumpMap = null;
  22806. this.bumpScale = 1;
  22807. this.normalMap = null;
  22808. this.normalMapType = TangentSpaceNormalMap;
  22809. this.normalScale = new Vector2(1, 1);
  22810. this.displacementMap = null;
  22811. this.displacementScale = 1;
  22812. this.displacementBias = 0;
  22813. this.specularMap = null;
  22814. this.alphaMap = null;
  22815. this.envMap = null;
  22816. this.combine = MultiplyOperation;
  22817. this.reflectivity = 1;
  22818. this.refractionRatio = 0.98;
  22819. this.wireframe = false;
  22820. this.wireframeLinewidth = 1;
  22821. this.wireframeLinecap = 'round';
  22822. this.wireframeLinejoin = 'round';
  22823. this.flatShading = false;
  22824. this.fog = true;
  22825. this.setValues(parameters);
  22826. }
  22827. copy(source) {
  22828. super.copy(source);
  22829. this.color.copy(source.color);
  22830. this.map = source.map;
  22831. this.lightMap = source.lightMap;
  22832. this.lightMapIntensity = source.lightMapIntensity;
  22833. this.aoMap = source.aoMap;
  22834. this.aoMapIntensity = source.aoMapIntensity;
  22835. this.emissive.copy(source.emissive);
  22836. this.emissiveMap = source.emissiveMap;
  22837. this.emissiveIntensity = source.emissiveIntensity;
  22838. this.bumpMap = source.bumpMap;
  22839. this.bumpScale = source.bumpScale;
  22840. this.normalMap = source.normalMap;
  22841. this.normalMapType = source.normalMapType;
  22842. this.normalScale.copy(source.normalScale);
  22843. this.displacementMap = source.displacementMap;
  22844. this.displacementScale = source.displacementScale;
  22845. this.displacementBias = source.displacementBias;
  22846. this.specularMap = source.specularMap;
  22847. this.alphaMap = source.alphaMap;
  22848. this.envMap = source.envMap;
  22849. this.combine = source.combine;
  22850. this.reflectivity = source.reflectivity;
  22851. this.refractionRatio = source.refractionRatio;
  22852. this.wireframe = source.wireframe;
  22853. this.wireframeLinewidth = source.wireframeLinewidth;
  22854. this.wireframeLinecap = source.wireframeLinecap;
  22855. this.wireframeLinejoin = source.wireframeLinejoin;
  22856. this.flatShading = source.flatShading;
  22857. this.fog = source.fog;
  22858. return this;
  22859. }
  22860. }
  22861. class MeshMatcapMaterial extends Material {
  22862. constructor(parameters) {
  22863. super();
  22864. this.isMeshMatcapMaterial = true;
  22865. this.defines = {
  22866. 'MATCAP': ''
  22867. };
  22868. this.type = 'MeshMatcapMaterial';
  22869. this.color = new Color(0xffffff); // diffuse
  22870. this.matcap = null;
  22871. this.map = null;
  22872. this.bumpMap = null;
  22873. this.bumpScale = 1;
  22874. this.normalMap = null;
  22875. this.normalMapType = TangentSpaceNormalMap;
  22876. this.normalScale = new Vector2(1, 1);
  22877. this.displacementMap = null;
  22878. this.displacementScale = 1;
  22879. this.displacementBias = 0;
  22880. this.alphaMap = null;
  22881. this.flatShading = false;
  22882. this.fog = true;
  22883. this.setValues(parameters);
  22884. }
  22885. copy(source) {
  22886. super.copy(source);
  22887. this.defines = {
  22888. 'MATCAP': ''
  22889. };
  22890. this.color.copy(source.color);
  22891. this.matcap = source.matcap;
  22892. this.map = source.map;
  22893. this.bumpMap = source.bumpMap;
  22894. this.bumpScale = source.bumpScale;
  22895. this.normalMap = source.normalMap;
  22896. this.normalMapType = source.normalMapType;
  22897. this.normalScale.copy(source.normalScale);
  22898. this.displacementMap = source.displacementMap;
  22899. this.displacementScale = source.displacementScale;
  22900. this.displacementBias = source.displacementBias;
  22901. this.alphaMap = source.alphaMap;
  22902. this.flatShading = source.flatShading;
  22903. this.fog = source.fog;
  22904. return this;
  22905. }
  22906. }
  22907. class LineDashedMaterial extends LineBasicMaterial {
  22908. constructor(parameters) {
  22909. super();
  22910. this.isLineDashedMaterial = true;
  22911. this.type = 'LineDashedMaterial';
  22912. this.scale = 1;
  22913. this.dashSize = 3;
  22914. this.gapSize = 1;
  22915. this.setValues(parameters);
  22916. }
  22917. copy(source) {
  22918. super.copy(source);
  22919. this.scale = source.scale;
  22920. this.dashSize = source.dashSize;
  22921. this.gapSize = source.gapSize;
  22922. return this;
  22923. }
  22924. }
  22925. // same as Array.prototype.slice, but also works on typed arrays
  22926. function arraySlice(array, from, to) {
  22927. if (isTypedArray(array)) {
  22928. // in ios9 array.subarray(from, undefined) will return empty array
  22929. // but array.subarray(from) or array.subarray(from, len) is correct
  22930. return new array.constructor(array.subarray(from, to !== undefined ? to : array.length));
  22931. }
  22932. return array.slice(from, to);
  22933. }
  22934. // converts an array to a specific type
  22935. function convertArray(array, type, forceClone) {
  22936. if (!array ||
  22937. // let 'undefined' and 'null' pass
  22938. !forceClone && array.constructor === type) return array;
  22939. if (typeof type.BYTES_PER_ELEMENT === 'number') {
  22940. return new type(array); // create typed array
  22941. }
  22942. return Array.prototype.slice.call(array); // create Array
  22943. }
  22944. function isTypedArray(object) {
  22945. return ArrayBuffer.isView(object) && !(object instanceof DataView);
  22946. }
  22947. // returns an array by which times and values can be sorted
  22948. function getKeyframeOrder(times) {
  22949. function compareTime(i, j) {
  22950. return times[i] - times[j];
  22951. }
  22952. const n = times.length;
  22953. const result = new Array(n);
  22954. for (let i = 0; i !== n; ++i) result[i] = i;
  22955. result.sort(compareTime);
  22956. return result;
  22957. }
  22958. // uses the array previously returned by 'getKeyframeOrder' to sort data
  22959. function sortedArray(values, stride, order) {
  22960. const nValues = values.length;
  22961. const result = new values.constructor(nValues);
  22962. for (let i = 0, dstOffset = 0; dstOffset !== nValues; ++i) {
  22963. const srcOffset = order[i] * stride;
  22964. for (let j = 0; j !== stride; ++j) {
  22965. result[dstOffset++] = values[srcOffset + j];
  22966. }
  22967. }
  22968. return result;
  22969. }
  22970. // function for parsing AOS keyframe formats
  22971. function flattenJSON(jsonKeys, times, values, valuePropertyName) {
  22972. let i = 1,
  22973. key = jsonKeys[0];
  22974. while (key !== undefined && key[valuePropertyName] === undefined) {
  22975. key = jsonKeys[i++];
  22976. }
  22977. if (key === undefined) return; // no data
  22978. let value = key[valuePropertyName];
  22979. if (value === undefined) return; // no data
  22980. if (Array.isArray(value)) {
  22981. do {
  22982. value = key[valuePropertyName];
  22983. if (value !== undefined) {
  22984. times.push(key.time);
  22985. values.push.apply(values, value); // push all elements
  22986. }
  22987. key = jsonKeys[i++];
  22988. } while (key !== undefined);
  22989. } else if (value.toArray !== undefined) {
  22990. // ...assume THREE.Math-ish
  22991. do {
  22992. value = key[valuePropertyName];
  22993. if (value !== undefined) {
  22994. times.push(key.time);
  22995. value.toArray(values, values.length);
  22996. }
  22997. key = jsonKeys[i++];
  22998. } while (key !== undefined);
  22999. } else {
  23000. // otherwise push as-is
  23001. do {
  23002. value = key[valuePropertyName];
  23003. if (value !== undefined) {
  23004. times.push(key.time);
  23005. values.push(value);
  23006. }
  23007. key = jsonKeys[i++];
  23008. } while (key !== undefined);
  23009. }
  23010. }
  23011. function subclip(sourceClip, name, startFrame, endFrame, fps = 30) {
  23012. const clip = sourceClip.clone();
  23013. clip.name = name;
  23014. const tracks = [];
  23015. for (let i = 0; i < clip.tracks.length; ++i) {
  23016. const track = clip.tracks[i];
  23017. const valueSize = track.getValueSize();
  23018. const times = [];
  23019. const values = [];
  23020. for (let j = 0; j < track.times.length; ++j) {
  23021. const frame = track.times[j] * fps;
  23022. if (frame < startFrame || frame >= endFrame) continue;
  23023. times.push(track.times[j]);
  23024. for (let k = 0; k < valueSize; ++k) {
  23025. values.push(track.values[j * valueSize + k]);
  23026. }
  23027. }
  23028. if (times.length === 0) continue;
  23029. track.times = convertArray(times, track.times.constructor);
  23030. track.values = convertArray(values, track.values.constructor);
  23031. tracks.push(track);
  23032. }
  23033. clip.tracks = tracks;
  23034. // find minimum .times value across all tracks in the trimmed clip
  23035. let minStartTime = Infinity;
  23036. for (let i = 0; i < clip.tracks.length; ++i) {
  23037. if (minStartTime > clip.tracks[i].times[0]) {
  23038. minStartTime = clip.tracks[i].times[0];
  23039. }
  23040. }
  23041. // shift all tracks such that clip begins at t=0
  23042. for (let i = 0; i < clip.tracks.length; ++i) {
  23043. clip.tracks[i].shift(-1 * minStartTime);
  23044. }
  23045. clip.resetDuration();
  23046. return clip;
  23047. }
  23048. function makeClipAdditive(targetClip, referenceFrame = 0, referenceClip = targetClip, fps = 30) {
  23049. if (fps <= 0) fps = 30;
  23050. const numTracks = referenceClip.tracks.length;
  23051. const referenceTime = referenceFrame / fps;
  23052. // Make each track's values relative to the values at the reference frame
  23053. for (let i = 0; i < numTracks; ++i) {
  23054. const referenceTrack = referenceClip.tracks[i];
  23055. const referenceTrackType = referenceTrack.ValueTypeName;
  23056. // Skip this track if it's non-numeric
  23057. if (referenceTrackType === 'bool' || referenceTrackType === 'string') continue;
  23058. // Find the track in the target clip whose name and type matches the reference track
  23059. const targetTrack = targetClip.tracks.find(function (track) {
  23060. return track.name === referenceTrack.name && track.ValueTypeName === referenceTrackType;
  23061. });
  23062. if (targetTrack === undefined) continue;
  23063. let referenceOffset = 0;
  23064. const referenceValueSize = referenceTrack.getValueSize();
  23065. if (referenceTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline) {
  23066. referenceOffset = referenceValueSize / 3;
  23067. }
  23068. let targetOffset = 0;
  23069. const targetValueSize = targetTrack.getValueSize();
  23070. if (targetTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline) {
  23071. targetOffset = targetValueSize / 3;
  23072. }
  23073. const lastIndex = referenceTrack.times.length - 1;
  23074. let referenceValue;
  23075. // Find the value to subtract out of the track
  23076. if (referenceTime <= referenceTrack.times[0]) {
  23077. // Reference frame is earlier than the first keyframe, so just use the first keyframe
  23078. const startIndex = referenceOffset;
  23079. const endIndex = referenceValueSize - referenceOffset;
  23080. referenceValue = arraySlice(referenceTrack.values, startIndex, endIndex);
  23081. } else if (referenceTime >= referenceTrack.times[lastIndex]) {
  23082. // Reference frame is after the last keyframe, so just use the last keyframe
  23083. const startIndex = lastIndex * referenceValueSize + referenceOffset;
  23084. const endIndex = startIndex + referenceValueSize - referenceOffset;
  23085. referenceValue = arraySlice(referenceTrack.values, startIndex, endIndex);
  23086. } else {
  23087. // Interpolate to the reference value
  23088. const interpolant = referenceTrack.createInterpolant();
  23089. const startIndex = referenceOffset;
  23090. const endIndex = referenceValueSize - referenceOffset;
  23091. interpolant.evaluate(referenceTime);
  23092. referenceValue = arraySlice(interpolant.resultBuffer, startIndex, endIndex);
  23093. }
  23094. // Conjugate the quaternion
  23095. if (referenceTrackType === 'quaternion') {
  23096. const referenceQuat = new Quaternion().fromArray(referenceValue).normalize().conjugate();
  23097. referenceQuat.toArray(referenceValue);
  23098. }
  23099. // Subtract the reference value from all of the track values
  23100. const numTimes = targetTrack.times.length;
  23101. for (let j = 0; j < numTimes; ++j) {
  23102. const valueStart = j * targetValueSize + targetOffset;
  23103. if (referenceTrackType === 'quaternion') {
  23104. // Multiply the conjugate for quaternion track types
  23105. Quaternion.multiplyQuaternionsFlat(targetTrack.values, valueStart, referenceValue, 0, targetTrack.values, valueStart);
  23106. } else {
  23107. const valueEnd = targetValueSize - targetOffset * 2;
  23108. // Subtract each value for all other numeric track types
  23109. for (let k = 0; k < valueEnd; ++k) {
  23110. targetTrack.values[valueStart + k] -= referenceValue[k];
  23111. }
  23112. }
  23113. }
  23114. }
  23115. targetClip.blendMode = AdditiveAnimationBlendMode;
  23116. return targetClip;
  23117. }
  23118. var AnimationUtils = /*#__PURE__*/Object.freeze({
  23119. __proto__: null,
  23120. arraySlice: arraySlice,
  23121. convertArray: convertArray,
  23122. isTypedArray: isTypedArray,
  23123. getKeyframeOrder: getKeyframeOrder,
  23124. sortedArray: sortedArray,
  23125. flattenJSON: flattenJSON,
  23126. subclip: subclip,
  23127. makeClipAdditive: makeClipAdditive
  23128. });
  23129. /**
  23130. * Abstract base class of interpolants over parametric samples.
  23131. *
  23132. * The parameter domain is one dimensional, typically the time or a path
  23133. * along a curve defined by the data.
  23134. *
  23135. * The sample values can have any dimensionality and derived classes may
  23136. * apply special interpretations to the data.
  23137. *
  23138. * This class provides the interval seek in a Template Method, deferring
  23139. * the actual interpolation to derived classes.
  23140. *
  23141. * Time complexity is O(1) for linear access crossing at most two points
  23142. * and O(log N) for random access, where N is the number of positions.
  23143. *
  23144. * References:
  23145. *
  23146. * http://www.oodesign.com/template-method-pattern.html
  23147. *
  23148. */
  23149. class Interpolant {
  23150. constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  23151. this.parameterPositions = parameterPositions;
  23152. this._cachedIndex = 0;
  23153. this.resultBuffer = resultBuffer !== undefined ? resultBuffer : new sampleValues.constructor(sampleSize);
  23154. this.sampleValues = sampleValues;
  23155. this.valueSize = sampleSize;
  23156. this.settings = null;
  23157. this.DefaultSettings_ = {};
  23158. }
  23159. evaluate(t) {
  23160. const pp = this.parameterPositions;
  23161. let i1 = this._cachedIndex,
  23162. t1 = pp[i1],
  23163. t0 = pp[i1 - 1];
  23164. validate_interval: {
  23165. seek: {
  23166. let right;
  23167. linear_scan: {
  23168. //- See http://jsperf.com/comparison-to-undefined/3
  23169. //- slower code:
  23170. //-
  23171. //- if ( t >= t1 || t1 === undefined ) {
  23172. forward_scan: if (!(t < t1)) {
  23173. for (let giveUpAt = i1 + 2;;) {
  23174. if (t1 === undefined) {
  23175. if (t < t0) break forward_scan;
  23176. // after end
  23177. i1 = pp.length;
  23178. this._cachedIndex = i1;
  23179. return this.copySampleValue_(i1 - 1);
  23180. }
  23181. if (i1 === giveUpAt) break; // this loop
  23182. t0 = t1;
  23183. t1 = pp[++i1];
  23184. if (t < t1) {
  23185. // we have arrived at the sought interval
  23186. break seek;
  23187. }
  23188. }
  23189. // prepare binary search on the right side of the index
  23190. right = pp.length;
  23191. break linear_scan;
  23192. }
  23193. //- slower code:
  23194. //- if ( t < t0 || t0 === undefined ) {
  23195. if (!(t >= t0)) {
  23196. // looping?
  23197. const t1global = pp[1];
  23198. if (t < t1global) {
  23199. i1 = 2; // + 1, using the scan for the details
  23200. t0 = t1global;
  23201. }
  23202. // linear reverse scan
  23203. for (let giveUpAt = i1 - 2;;) {
  23204. if (t0 === undefined) {
  23205. // before start
  23206. this._cachedIndex = 0;
  23207. return this.copySampleValue_(0);
  23208. }
  23209. if (i1 === giveUpAt) break; // this loop
  23210. t1 = t0;
  23211. t0 = pp[--i1 - 1];
  23212. if (t >= t0) {
  23213. // we have arrived at the sought interval
  23214. break seek;
  23215. }
  23216. }
  23217. // prepare binary search on the left side of the index
  23218. right = i1;
  23219. i1 = 0;
  23220. break linear_scan;
  23221. }
  23222. // the interval is valid
  23223. break validate_interval;
  23224. } // linear scan
  23225. // binary search
  23226. while (i1 < right) {
  23227. const mid = i1 + right >>> 1;
  23228. if (t < pp[mid]) {
  23229. right = mid;
  23230. } else {
  23231. i1 = mid + 1;
  23232. }
  23233. }
  23234. t1 = pp[i1];
  23235. t0 = pp[i1 - 1];
  23236. // check boundary cases, again
  23237. if (t0 === undefined) {
  23238. this._cachedIndex = 0;
  23239. return this.copySampleValue_(0);
  23240. }
  23241. if (t1 === undefined) {
  23242. i1 = pp.length;
  23243. this._cachedIndex = i1;
  23244. return this.copySampleValue_(i1 - 1);
  23245. }
  23246. } // seek
  23247. this._cachedIndex = i1;
  23248. this.intervalChanged_(i1, t0, t1);
  23249. } // validate_interval
  23250. return this.interpolate_(i1, t0, t, t1);
  23251. }
  23252. getSettings_() {
  23253. return this.settings || this.DefaultSettings_;
  23254. }
  23255. copySampleValue_(index) {
  23256. // copies a sample value to the result buffer
  23257. const result = this.resultBuffer,
  23258. values = this.sampleValues,
  23259. stride = this.valueSize,
  23260. offset = index * stride;
  23261. for (let i = 0; i !== stride; ++i) {
  23262. result[i] = values[offset + i];
  23263. }
  23264. return result;
  23265. }
  23266. // Template methods for derived classes:
  23267. interpolate_( /* i1, t0, t, t1 */
  23268. ) {
  23269. throw new Error('call to abstract method');
  23270. // implementations shall return this.resultBuffer
  23271. }
  23272. intervalChanged_( /* i1, t0, t1 */
  23273. ) {
  23274. // empty
  23275. }
  23276. }
  23277. /**
  23278. * Fast and simple cubic spline interpolant.
  23279. *
  23280. * It was derived from a Hermitian construction setting the first derivative
  23281. * at each sample position to the linear slope between neighboring positions
  23282. * over their parameter interval.
  23283. */
  23284. class CubicInterpolant extends Interpolant {
  23285. constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  23286. super(parameterPositions, sampleValues, sampleSize, resultBuffer);
  23287. this._weightPrev = -0;
  23288. this._offsetPrev = -0;
  23289. this._weightNext = -0;
  23290. this._offsetNext = -0;
  23291. this.DefaultSettings_ = {
  23292. endingStart: ZeroCurvatureEnding,
  23293. endingEnd: ZeroCurvatureEnding
  23294. };
  23295. }
  23296. intervalChanged_(i1, t0, t1) {
  23297. const pp = this.parameterPositions;
  23298. let iPrev = i1 - 2,
  23299. iNext = i1 + 1,
  23300. tPrev = pp[iPrev],
  23301. tNext = pp[iNext];
  23302. if (tPrev === undefined) {
  23303. switch (this.getSettings_().endingStart) {
  23304. case ZeroSlopeEnding:
  23305. // f'(t0) = 0
  23306. iPrev = i1;
  23307. tPrev = 2 * t0 - t1;
  23308. break;
  23309. case WrapAroundEnding:
  23310. // use the other end of the curve
  23311. iPrev = pp.length - 2;
  23312. tPrev = t0 + pp[iPrev] - pp[iPrev + 1];
  23313. break;
  23314. default:
  23315. // ZeroCurvatureEnding
  23316. // f''(t0) = 0 a.k.a. Natural Spline
  23317. iPrev = i1;
  23318. tPrev = t1;
  23319. }
  23320. }
  23321. if (tNext === undefined) {
  23322. switch (this.getSettings_().endingEnd) {
  23323. case ZeroSlopeEnding:
  23324. // f'(tN) = 0
  23325. iNext = i1;
  23326. tNext = 2 * t1 - t0;
  23327. break;
  23328. case WrapAroundEnding:
  23329. // use the other end of the curve
  23330. iNext = 1;
  23331. tNext = t1 + pp[1] - pp[0];
  23332. break;
  23333. default:
  23334. // ZeroCurvatureEnding
  23335. // f''(tN) = 0, a.k.a. Natural Spline
  23336. iNext = i1 - 1;
  23337. tNext = t0;
  23338. }
  23339. }
  23340. const halfDt = (t1 - t0) * 0.5,
  23341. stride = this.valueSize;
  23342. this._weightPrev = halfDt / (t0 - tPrev);
  23343. this._weightNext = halfDt / (tNext - t1);
  23344. this._offsetPrev = iPrev * stride;
  23345. this._offsetNext = iNext * stride;
  23346. }
  23347. interpolate_(i1, t0, t, t1) {
  23348. const result = this.resultBuffer,
  23349. values = this.sampleValues,
  23350. stride = this.valueSize,
  23351. o1 = i1 * stride,
  23352. o0 = o1 - stride,
  23353. oP = this._offsetPrev,
  23354. oN = this._offsetNext,
  23355. wP = this._weightPrev,
  23356. wN = this._weightNext,
  23357. p = (t - t0) / (t1 - t0),
  23358. pp = p * p,
  23359. ppp = pp * p;
  23360. // evaluate polynomials
  23361. const sP = -wP * ppp + 2 * wP * pp - wP * p;
  23362. const s0 = (1 + wP) * ppp + (-1.5 - 2 * wP) * pp + (-0.5 + wP) * p + 1;
  23363. const s1 = (-1 - wN) * ppp + (1.5 + wN) * pp + 0.5 * p;
  23364. const sN = wN * ppp - wN * pp;
  23365. // combine data linearly
  23366. for (let i = 0; i !== stride; ++i) {
  23367. result[i] = sP * values[oP + i] + s0 * values[o0 + i] + s1 * values[o1 + i] + sN * values[oN + i];
  23368. }
  23369. return result;
  23370. }
  23371. }
  23372. class LinearInterpolant extends Interpolant {
  23373. constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  23374. super(parameterPositions, sampleValues, sampleSize, resultBuffer);
  23375. }
  23376. interpolate_(i1, t0, t, t1) {
  23377. const result = this.resultBuffer,
  23378. values = this.sampleValues,
  23379. stride = this.valueSize,
  23380. offset1 = i1 * stride,
  23381. offset0 = offset1 - stride,
  23382. weight1 = (t - t0) / (t1 - t0),
  23383. weight0 = 1 - weight1;
  23384. for (let i = 0; i !== stride; ++i) {
  23385. result[i] = values[offset0 + i] * weight0 + values[offset1 + i] * weight1;
  23386. }
  23387. return result;
  23388. }
  23389. }
  23390. /**
  23391. *
  23392. * Interpolant that evaluates to the sample value at the position preceding
  23393. * the parameter.
  23394. */
  23395. class DiscreteInterpolant extends Interpolant {
  23396. constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  23397. super(parameterPositions, sampleValues, sampleSize, resultBuffer);
  23398. }
  23399. interpolate_(i1 /*, t0, t, t1 */) {
  23400. return this.copySampleValue_(i1 - 1);
  23401. }
  23402. }
  23403. class KeyframeTrack {
  23404. constructor(name, times, values, interpolation) {
  23405. if (name === undefined) throw new Error('THREE.KeyframeTrack: track name is undefined');
  23406. if (times === undefined || times.length === 0) throw new Error('THREE.KeyframeTrack: no keyframes in track named ' + name);
  23407. this.name = name;
  23408. this.times = convertArray(times, this.TimeBufferType);
  23409. this.values = convertArray(values, this.ValueBufferType);
  23410. this.setInterpolation(interpolation || this.DefaultInterpolation);
  23411. }
  23412. // Serialization (in static context, because of constructor invocation
  23413. // and automatic invocation of .toJSON):
  23414. static toJSON(track) {
  23415. const trackType = track.constructor;
  23416. let json;
  23417. // derived classes can define a static toJSON method
  23418. if (trackType.toJSON !== this.toJSON) {
  23419. json = trackType.toJSON(track);
  23420. } else {
  23421. // by default, we assume the data can be serialized as-is
  23422. json = {
  23423. 'name': track.name,
  23424. 'times': convertArray(track.times, Array),
  23425. 'values': convertArray(track.values, Array)
  23426. };
  23427. const interpolation = track.getInterpolation();
  23428. if (interpolation !== track.DefaultInterpolation) {
  23429. json.interpolation = interpolation;
  23430. }
  23431. }
  23432. json.type = track.ValueTypeName; // mandatory
  23433. return json;
  23434. }
  23435. InterpolantFactoryMethodDiscrete(result) {
  23436. return new DiscreteInterpolant(this.times, this.values, this.getValueSize(), result);
  23437. }
  23438. InterpolantFactoryMethodLinear(result) {
  23439. return new LinearInterpolant(this.times, this.values, this.getValueSize(), result);
  23440. }
  23441. InterpolantFactoryMethodSmooth(result) {
  23442. return new CubicInterpolant(this.times, this.values, this.getValueSize(), result);
  23443. }
  23444. setInterpolation(interpolation) {
  23445. let factoryMethod;
  23446. switch (interpolation) {
  23447. case InterpolateDiscrete:
  23448. factoryMethod = this.InterpolantFactoryMethodDiscrete;
  23449. break;
  23450. case InterpolateLinear:
  23451. factoryMethod = this.InterpolantFactoryMethodLinear;
  23452. break;
  23453. case InterpolateSmooth:
  23454. factoryMethod = this.InterpolantFactoryMethodSmooth;
  23455. break;
  23456. }
  23457. if (factoryMethod === undefined) {
  23458. const message = 'unsupported interpolation for ' + this.ValueTypeName + ' keyframe track named ' + this.name;
  23459. if (this.createInterpolant === undefined) {
  23460. // fall back to default, unless the default itself is messed up
  23461. if (interpolation !== this.DefaultInterpolation) {
  23462. this.setInterpolation(this.DefaultInterpolation);
  23463. } else {
  23464. throw new Error(message); // fatal, in this case
  23465. }
  23466. }
  23467. console.warn('THREE.KeyframeTrack:', message);
  23468. return this;
  23469. }
  23470. this.createInterpolant = factoryMethod;
  23471. return this;
  23472. }
  23473. getInterpolation() {
  23474. switch (this.createInterpolant) {
  23475. case this.InterpolantFactoryMethodDiscrete:
  23476. return InterpolateDiscrete;
  23477. case this.InterpolantFactoryMethodLinear:
  23478. return InterpolateLinear;
  23479. case this.InterpolantFactoryMethodSmooth:
  23480. return InterpolateSmooth;
  23481. }
  23482. }
  23483. getValueSize() {
  23484. return this.values.length / this.times.length;
  23485. }
  23486. // move all keyframes either forwards or backwards in time
  23487. shift(timeOffset) {
  23488. if (timeOffset !== 0.0) {
  23489. const times = this.times;
  23490. for (let i = 0, n = times.length; i !== n; ++i) {
  23491. times[i] += timeOffset;
  23492. }
  23493. }
  23494. return this;
  23495. }
  23496. // scale all keyframe times by a factor (useful for frame <-> seconds conversions)
  23497. scale(timeScale) {
  23498. if (timeScale !== 1.0) {
  23499. const times = this.times;
  23500. for (let i = 0, n = times.length; i !== n; ++i) {
  23501. times[i] *= timeScale;
  23502. }
  23503. }
  23504. return this;
  23505. }
  23506. // removes keyframes before and after animation without changing any values within the range [startTime, endTime].
  23507. // IMPORTANT: We do not shift around keys to the start of the track time, because for interpolated keys this will change their values
  23508. trim(startTime, endTime) {
  23509. const times = this.times,
  23510. nKeys = times.length;
  23511. let from = 0,
  23512. to = nKeys - 1;
  23513. while (from !== nKeys && times[from] < startTime) {
  23514. ++from;
  23515. }
  23516. while (to !== -1 && times[to] > endTime) {
  23517. --to;
  23518. }
  23519. ++to; // inclusive -> exclusive bound
  23520. if (from !== 0 || to !== nKeys) {
  23521. // empty tracks are forbidden, so keep at least one keyframe
  23522. if (from >= to) {
  23523. to = Math.max(to, 1);
  23524. from = to - 1;
  23525. }
  23526. const stride = this.getValueSize();
  23527. this.times = arraySlice(times, from, to);
  23528. this.values = arraySlice(this.values, from * stride, to * stride);
  23529. }
  23530. return this;
  23531. }
  23532. // ensure we do not get a GarbageInGarbageOut situation, make sure tracks are at least minimally viable
  23533. validate() {
  23534. let valid = true;
  23535. const valueSize = this.getValueSize();
  23536. if (valueSize - Math.floor(valueSize) !== 0) {
  23537. console.error('THREE.KeyframeTrack: Invalid value size in track.', this);
  23538. valid = false;
  23539. }
  23540. const times = this.times,
  23541. values = this.values,
  23542. nKeys = times.length;
  23543. if (nKeys === 0) {
  23544. console.error('THREE.KeyframeTrack: Track is empty.', this);
  23545. valid = false;
  23546. }
  23547. let prevTime = null;
  23548. for (let i = 0; i !== nKeys; i++) {
  23549. const currTime = times[i];
  23550. if (typeof currTime === 'number' && isNaN(currTime)) {
  23551. console.error('THREE.KeyframeTrack: Time is not a valid number.', this, i, currTime);
  23552. valid = false;
  23553. break;
  23554. }
  23555. if (prevTime !== null && prevTime > currTime) {
  23556. console.error('THREE.KeyframeTrack: Out of order keys.', this, i, currTime, prevTime);
  23557. valid = false;
  23558. break;
  23559. }
  23560. prevTime = currTime;
  23561. }
  23562. if (values !== undefined) {
  23563. if (isTypedArray(values)) {
  23564. for (let i = 0, n = values.length; i !== n; ++i) {
  23565. const value = values[i];
  23566. if (isNaN(value)) {
  23567. console.error('THREE.KeyframeTrack: Value is not a valid number.', this, i, value);
  23568. valid = false;
  23569. break;
  23570. }
  23571. }
  23572. }
  23573. }
  23574. return valid;
  23575. }
  23576. // removes equivalent sequential keys as common in morph target sequences
  23577. // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0)
  23578. optimize() {
  23579. // times or values may be shared with other tracks, so overwriting is unsafe
  23580. const times = arraySlice(this.times),
  23581. values = arraySlice(this.values),
  23582. stride = this.getValueSize(),
  23583. smoothInterpolation = this.getInterpolation() === InterpolateSmooth,
  23584. lastIndex = times.length - 1;
  23585. let writeIndex = 1;
  23586. for (let i = 1; i < lastIndex; ++i) {
  23587. let keep = false;
  23588. const time = times[i];
  23589. const timeNext = times[i + 1];
  23590. // remove adjacent keyframes scheduled at the same time
  23591. if (time !== timeNext && (i !== 1 || time !== times[0])) {
  23592. if (!smoothInterpolation) {
  23593. // remove unnecessary keyframes same as their neighbors
  23594. const offset = i * stride,
  23595. offsetP = offset - stride,
  23596. offsetN = offset + stride;
  23597. for (let j = 0; j !== stride; ++j) {
  23598. const value = values[offset + j];
  23599. if (value !== values[offsetP + j] || value !== values[offsetN + j]) {
  23600. keep = true;
  23601. break;
  23602. }
  23603. }
  23604. } else {
  23605. keep = true;
  23606. }
  23607. }
  23608. // in-place compaction
  23609. if (keep) {
  23610. if (i !== writeIndex) {
  23611. times[writeIndex] = times[i];
  23612. const readOffset = i * stride,
  23613. writeOffset = writeIndex * stride;
  23614. for (let j = 0; j !== stride; ++j) {
  23615. values[writeOffset + j] = values[readOffset + j];
  23616. }
  23617. }
  23618. ++writeIndex;
  23619. }
  23620. }
  23621. // flush last keyframe (compaction looks ahead)
  23622. if (lastIndex > 0) {
  23623. times[writeIndex] = times[lastIndex];
  23624. for (let readOffset = lastIndex * stride, writeOffset = writeIndex * stride, j = 0; j !== stride; ++j) {
  23625. values[writeOffset + j] = values[readOffset + j];
  23626. }
  23627. ++writeIndex;
  23628. }
  23629. if (writeIndex !== times.length) {
  23630. this.times = arraySlice(times, 0, writeIndex);
  23631. this.values = arraySlice(values, 0, writeIndex * stride);
  23632. } else {
  23633. this.times = times;
  23634. this.values = values;
  23635. }
  23636. return this;
  23637. }
  23638. clone() {
  23639. const times = arraySlice(this.times, 0);
  23640. const values = arraySlice(this.values, 0);
  23641. const TypedKeyframeTrack = this.constructor;
  23642. const track = new TypedKeyframeTrack(this.name, times, values);
  23643. // Interpolant argument to constructor is not saved, so copy the factory method directly.
  23644. track.createInterpolant = this.createInterpolant;
  23645. return track;
  23646. }
  23647. }
  23648. KeyframeTrack.prototype.TimeBufferType = Float32Array;
  23649. KeyframeTrack.prototype.ValueBufferType = Float32Array;
  23650. KeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear;
  23651. /**
  23652. * A Track of Boolean keyframe values.
  23653. */
  23654. class BooleanKeyframeTrack extends KeyframeTrack {}
  23655. BooleanKeyframeTrack.prototype.ValueTypeName = 'bool';
  23656. BooleanKeyframeTrack.prototype.ValueBufferType = Array;
  23657. BooleanKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  23658. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  23659. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  23660. /**
  23661. * A Track of keyframe values that represent color.
  23662. */
  23663. class ColorKeyframeTrack extends KeyframeTrack {}
  23664. ColorKeyframeTrack.prototype.ValueTypeName = 'color';
  23665. /**
  23666. * A Track of numeric keyframe values.
  23667. */
  23668. class NumberKeyframeTrack extends KeyframeTrack {}
  23669. NumberKeyframeTrack.prototype.ValueTypeName = 'number';
  23670. /**
  23671. * Spherical linear unit quaternion interpolant.
  23672. */
  23673. class QuaternionLinearInterpolant extends Interpolant {
  23674. constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  23675. super(parameterPositions, sampleValues, sampleSize, resultBuffer);
  23676. }
  23677. interpolate_(i1, t0, t, t1) {
  23678. const result = this.resultBuffer,
  23679. values = this.sampleValues,
  23680. stride = this.valueSize,
  23681. alpha = (t - t0) / (t1 - t0);
  23682. let offset = i1 * stride;
  23683. for (let end = offset + stride; offset !== end; offset += 4) {
  23684. Quaternion.slerpFlat(result, 0, values, offset - stride, values, offset, alpha);
  23685. }
  23686. return result;
  23687. }
  23688. }
  23689. /**
  23690. * A Track of quaternion keyframe values.
  23691. */
  23692. class QuaternionKeyframeTrack extends KeyframeTrack {
  23693. InterpolantFactoryMethodLinear(result) {
  23694. return new QuaternionLinearInterpolant(this.times, this.values, this.getValueSize(), result);
  23695. }
  23696. }
  23697. QuaternionKeyframeTrack.prototype.ValueTypeName = 'quaternion';
  23698. // ValueBufferType is inherited
  23699. QuaternionKeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear;
  23700. QuaternionKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  23701. /**
  23702. * A Track that interpolates Strings
  23703. */
  23704. class StringKeyframeTrack extends KeyframeTrack {}
  23705. StringKeyframeTrack.prototype.ValueTypeName = 'string';
  23706. StringKeyframeTrack.prototype.ValueBufferType = Array;
  23707. StringKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  23708. StringKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  23709. StringKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  23710. /**
  23711. * A Track of vectored keyframe values.
  23712. */
  23713. class VectorKeyframeTrack extends KeyframeTrack {}
  23714. VectorKeyframeTrack.prototype.ValueTypeName = 'vector';
  23715. class AnimationClip {
  23716. constructor(name, duration = -1, tracks, blendMode = NormalAnimationBlendMode) {
  23717. this.name = name;
  23718. this.tracks = tracks;
  23719. this.duration = duration;
  23720. this.blendMode = blendMode;
  23721. this.uuid = generateUUID();
  23722. // this means it should figure out its duration by scanning the tracks
  23723. if (this.duration < 0) {
  23724. this.resetDuration();
  23725. }
  23726. }
  23727. static parse(json) {
  23728. const tracks = [],
  23729. jsonTracks = json.tracks,
  23730. frameTime = 1.0 / (json.fps || 1.0);
  23731. for (let i = 0, n = jsonTracks.length; i !== n; ++i) {
  23732. tracks.push(parseKeyframeTrack(jsonTracks[i]).scale(frameTime));
  23733. }
  23734. const clip = new this(json.name, json.duration, tracks, json.blendMode);
  23735. clip.uuid = json.uuid;
  23736. return clip;
  23737. }
  23738. static toJSON(clip) {
  23739. const tracks = [],
  23740. clipTracks = clip.tracks;
  23741. const json = {
  23742. 'name': clip.name,
  23743. 'duration': clip.duration,
  23744. 'tracks': tracks,
  23745. 'uuid': clip.uuid,
  23746. 'blendMode': clip.blendMode
  23747. };
  23748. for (let i = 0, n = clipTracks.length; i !== n; ++i) {
  23749. tracks.push(KeyframeTrack.toJSON(clipTracks[i]));
  23750. }
  23751. return json;
  23752. }
  23753. static CreateFromMorphTargetSequence(name, morphTargetSequence, fps, noLoop) {
  23754. const numMorphTargets = morphTargetSequence.length;
  23755. const tracks = [];
  23756. for (let i = 0; i < numMorphTargets; i++) {
  23757. let times = [];
  23758. let values = [];
  23759. times.push((i + numMorphTargets - 1) % numMorphTargets, i, (i + 1) % numMorphTargets);
  23760. values.push(0, 1, 0);
  23761. const order = getKeyframeOrder(times);
  23762. times = sortedArray(times, 1, order);
  23763. values = sortedArray(values, 1, order);
  23764. // if there is a key at the first frame, duplicate it as the
  23765. // last frame as well for perfect loop.
  23766. if (!noLoop && times[0] === 0) {
  23767. times.push(numMorphTargets);
  23768. values.push(values[0]);
  23769. }
  23770. tracks.push(new NumberKeyframeTrack('.morphTargetInfluences[' + morphTargetSequence[i].name + ']', times, values).scale(1.0 / fps));
  23771. }
  23772. return new this(name, -1, tracks);
  23773. }
  23774. static findByName(objectOrClipArray, name) {
  23775. let clipArray = objectOrClipArray;
  23776. if (!Array.isArray(objectOrClipArray)) {
  23777. const o = objectOrClipArray;
  23778. clipArray = o.geometry && o.geometry.animations || o.animations;
  23779. }
  23780. for (let i = 0; i < clipArray.length; i++) {
  23781. if (clipArray[i].name === name) {
  23782. return clipArray[i];
  23783. }
  23784. }
  23785. return null;
  23786. }
  23787. static CreateClipsFromMorphTargetSequences(morphTargets, fps, noLoop) {
  23788. const animationToMorphTargets = {};
  23789. // tested with https://regex101.com/ on trick sequences
  23790. // such flamingo_flyA_003, flamingo_run1_003, crdeath0059
  23791. const pattern = /^([\w-]*?)([\d]+)$/;
  23792. // sort morph target names into animation groups based
  23793. // patterns like Walk_001, Walk_002, Run_001, Run_002
  23794. for (let i = 0, il = morphTargets.length; i < il; i++) {
  23795. const morphTarget = morphTargets[i];
  23796. const parts = morphTarget.name.match(pattern);
  23797. if (parts && parts.length > 1) {
  23798. const name = parts[1];
  23799. let animationMorphTargets = animationToMorphTargets[name];
  23800. if (!animationMorphTargets) {
  23801. animationToMorphTargets[name] = animationMorphTargets = [];
  23802. }
  23803. animationMorphTargets.push(morphTarget);
  23804. }
  23805. }
  23806. const clips = [];
  23807. for (const name in animationToMorphTargets) {
  23808. clips.push(this.CreateFromMorphTargetSequence(name, animationToMorphTargets[name], fps, noLoop));
  23809. }
  23810. return clips;
  23811. }
  23812. // parse the animation.hierarchy format
  23813. static parseAnimation(animation, bones) {
  23814. if (!animation) {
  23815. console.error('THREE.AnimationClip: No animation in JSONLoader data.');
  23816. return null;
  23817. }
  23818. const addNonemptyTrack = function (trackType, trackName, animationKeys, propertyName, destTracks) {
  23819. // only return track if there are actually keys.
  23820. if (animationKeys.length !== 0) {
  23821. const times = [];
  23822. const values = [];
  23823. flattenJSON(animationKeys, times, values, propertyName);
  23824. // empty keys are filtered out, so check again
  23825. if (times.length !== 0) {
  23826. destTracks.push(new trackType(trackName, times, values));
  23827. }
  23828. }
  23829. };
  23830. const tracks = [];
  23831. const clipName = animation.name || 'default';
  23832. const fps = animation.fps || 30;
  23833. const blendMode = animation.blendMode;
  23834. // automatic length determination in AnimationClip.
  23835. let duration = animation.length || -1;
  23836. const hierarchyTracks = animation.hierarchy || [];
  23837. for (let h = 0; h < hierarchyTracks.length; h++) {
  23838. const animationKeys = hierarchyTracks[h].keys;
  23839. // skip empty tracks
  23840. if (!animationKeys || animationKeys.length === 0) continue;
  23841. // process morph targets
  23842. if (animationKeys[0].morphTargets) {
  23843. // figure out all morph targets used in this track
  23844. const morphTargetNames = {};
  23845. let k;
  23846. for (k = 0; k < animationKeys.length; k++) {
  23847. if (animationKeys[k].morphTargets) {
  23848. for (let m = 0; m < animationKeys[k].morphTargets.length; m++) {
  23849. morphTargetNames[animationKeys[k].morphTargets[m]] = -1;
  23850. }
  23851. }
  23852. }
  23853. // create a track for each morph target with all zero
  23854. // morphTargetInfluences except for the keys in which
  23855. // the morphTarget is named.
  23856. for (const morphTargetName in morphTargetNames) {
  23857. const times = [];
  23858. const values = [];
  23859. for (let m = 0; m !== animationKeys[k].morphTargets.length; ++m) {
  23860. const animationKey = animationKeys[k];
  23861. times.push(animationKey.time);
  23862. values.push(animationKey.morphTarget === morphTargetName ? 1 : 0);
  23863. }
  23864. tracks.push(new NumberKeyframeTrack('.morphTargetInfluence[' + morphTargetName + ']', times, values));
  23865. }
  23866. duration = morphTargetNames.length * fps;
  23867. } else {
  23868. // ...assume skeletal animation
  23869. const boneName = '.bones[' + bones[h].name + ']';
  23870. addNonemptyTrack(VectorKeyframeTrack, boneName + '.position', animationKeys, 'pos', tracks);
  23871. addNonemptyTrack(QuaternionKeyframeTrack, boneName + '.quaternion', animationKeys, 'rot', tracks);
  23872. addNonemptyTrack(VectorKeyframeTrack, boneName + '.scale', animationKeys, 'scl', tracks);
  23873. }
  23874. }
  23875. if (tracks.length === 0) {
  23876. return null;
  23877. }
  23878. const clip = new this(clipName, duration, tracks, blendMode);
  23879. return clip;
  23880. }
  23881. resetDuration() {
  23882. const tracks = this.tracks;
  23883. let duration = 0;
  23884. for (let i = 0, n = tracks.length; i !== n; ++i) {
  23885. const track = this.tracks[i];
  23886. duration = Math.max(duration, track.times[track.times.length - 1]);
  23887. }
  23888. this.duration = duration;
  23889. return this;
  23890. }
  23891. trim() {
  23892. for (let i = 0; i < this.tracks.length; i++) {
  23893. this.tracks[i].trim(0, this.duration);
  23894. }
  23895. return this;
  23896. }
  23897. validate() {
  23898. let valid = true;
  23899. for (let i = 0; i < this.tracks.length; i++) {
  23900. valid = valid && this.tracks[i].validate();
  23901. }
  23902. return valid;
  23903. }
  23904. optimize() {
  23905. for (let i = 0; i < this.tracks.length; i++) {
  23906. this.tracks[i].optimize();
  23907. }
  23908. return this;
  23909. }
  23910. clone() {
  23911. const tracks = [];
  23912. for (let i = 0; i < this.tracks.length; i++) {
  23913. tracks.push(this.tracks[i].clone());
  23914. }
  23915. return new this.constructor(this.name, this.duration, tracks, this.blendMode);
  23916. }
  23917. toJSON() {
  23918. return this.constructor.toJSON(this);
  23919. }
  23920. }
  23921. function getTrackTypeForValueTypeName(typeName) {
  23922. switch (typeName.toLowerCase()) {
  23923. case 'scalar':
  23924. case 'double':
  23925. case 'float':
  23926. case 'number':
  23927. case 'integer':
  23928. return NumberKeyframeTrack;
  23929. case 'vector':
  23930. case 'vector2':
  23931. case 'vector3':
  23932. case 'vector4':
  23933. return VectorKeyframeTrack;
  23934. case 'color':
  23935. return ColorKeyframeTrack;
  23936. case 'quaternion':
  23937. return QuaternionKeyframeTrack;
  23938. case 'bool':
  23939. case 'boolean':
  23940. return BooleanKeyframeTrack;
  23941. case 'string':
  23942. return StringKeyframeTrack;
  23943. }
  23944. throw new Error('THREE.KeyframeTrack: Unsupported typeName: ' + typeName);
  23945. }
  23946. function parseKeyframeTrack(json) {
  23947. if (json.type === undefined) {
  23948. throw new Error('THREE.KeyframeTrack: track type undefined, can not parse');
  23949. }
  23950. const trackType = getTrackTypeForValueTypeName(json.type);
  23951. if (json.times === undefined) {
  23952. const times = [],
  23953. values = [];
  23954. flattenJSON(json.keys, times, values, 'value');
  23955. json.times = times;
  23956. json.values = values;
  23957. }
  23958. // derived classes can define a static parse method
  23959. if (trackType.parse !== undefined) {
  23960. return trackType.parse(json);
  23961. } else {
  23962. // by default, we assume a constructor compatible with the base
  23963. return new trackType(json.name, json.times, json.values, json.interpolation);
  23964. }
  23965. }
  23966. const Cache = {
  23967. enabled: false,
  23968. files: {},
  23969. add: function (key, file) {
  23970. if (this.enabled === false) return;
  23971. // console.log( 'THREE.Cache', 'Adding key:', key );
  23972. this.files[key] = file;
  23973. },
  23974. get: function (key) {
  23975. if (this.enabled === false) return;
  23976. // console.log( 'THREE.Cache', 'Checking key:', key );
  23977. return this.files[key];
  23978. },
  23979. remove: function (key) {
  23980. delete this.files[key];
  23981. },
  23982. clear: function () {
  23983. this.files = {};
  23984. }
  23985. };
  23986. class LoadingManager {
  23987. constructor(onLoad, onProgress, onError) {
  23988. const scope = this;
  23989. let isLoading = false;
  23990. let itemsLoaded = 0;
  23991. let itemsTotal = 0;
  23992. let urlModifier = undefined;
  23993. const handlers = [];
  23994. // Refer to #5689 for the reason why we don't set .onStart
  23995. // in the constructor
  23996. this.onStart = undefined;
  23997. this.onLoad = onLoad;
  23998. this.onProgress = onProgress;
  23999. this.onError = onError;
  24000. this.itemStart = function (url) {
  24001. itemsTotal++;
  24002. if (isLoading === false) {
  24003. if (scope.onStart !== undefined) {
  24004. scope.onStart(url, itemsLoaded, itemsTotal);
  24005. }
  24006. }
  24007. isLoading = true;
  24008. };
  24009. this.itemEnd = function (url) {
  24010. itemsLoaded++;
  24011. if (scope.onProgress !== undefined) {
  24012. scope.onProgress(url, itemsLoaded, itemsTotal);
  24013. }
  24014. if (itemsLoaded === itemsTotal) {
  24015. isLoading = false;
  24016. if (scope.onLoad !== undefined) {
  24017. scope.onLoad();
  24018. }
  24019. }
  24020. };
  24021. this.itemError = function (url) {
  24022. if (scope.onError !== undefined) {
  24023. scope.onError(url);
  24024. }
  24025. };
  24026. this.resolveURL = function (url) {
  24027. if (urlModifier) {
  24028. return urlModifier(url);
  24029. }
  24030. return url;
  24031. };
  24032. this.setURLModifier = function (transform) {
  24033. urlModifier = transform;
  24034. return this;
  24035. };
  24036. this.addHandler = function (regex, loader) {
  24037. handlers.push(regex, loader);
  24038. return this;
  24039. };
  24040. this.removeHandler = function (regex) {
  24041. const index = handlers.indexOf(regex);
  24042. if (index !== -1) {
  24043. handlers.splice(index, 2);
  24044. }
  24045. return this;
  24046. };
  24047. this.getHandler = function (file) {
  24048. for (let i = 0, l = handlers.length; i < l; i += 2) {
  24049. const regex = handlers[i];
  24050. const loader = handlers[i + 1];
  24051. if (regex.global) regex.lastIndex = 0; // see #17920
  24052. if (regex.test(file)) {
  24053. return loader;
  24054. }
  24055. }
  24056. return null;
  24057. };
  24058. }
  24059. }
  24060. const DefaultLoadingManager = /*@__PURE__*/new LoadingManager();
  24061. class Loader {
  24062. constructor(manager) {
  24063. this.manager = manager !== undefined ? manager : DefaultLoadingManager;
  24064. this.crossOrigin = 'anonymous';
  24065. this.withCredentials = false;
  24066. this.path = '';
  24067. this.resourcePath = '';
  24068. this.requestHeader = {};
  24069. }
  24070. load( /* url, onLoad, onProgress, onError */) {}
  24071. loadAsync(url, onProgress) {
  24072. const scope = this;
  24073. return new Promise(function (resolve, reject) {
  24074. scope.load(url, resolve, onProgress, reject);
  24075. });
  24076. }
  24077. parse( /* data */) {}
  24078. setCrossOrigin(crossOrigin) {
  24079. this.crossOrigin = crossOrigin;
  24080. return this;
  24081. }
  24082. setWithCredentials(value) {
  24083. this.withCredentials = value;
  24084. return this;
  24085. }
  24086. setPath(path) {
  24087. this.path = path;
  24088. return this;
  24089. }
  24090. setResourcePath(resourcePath) {
  24091. this.resourcePath = resourcePath;
  24092. return this;
  24093. }
  24094. setRequestHeader(requestHeader) {
  24095. this.requestHeader = requestHeader;
  24096. return this;
  24097. }
  24098. }
  24099. const loading = {};
  24100. class HttpError extends Error {
  24101. constructor(message, response) {
  24102. super(message);
  24103. this.response = response;
  24104. }
  24105. }
  24106. class FileLoader extends Loader {
  24107. constructor(manager) {
  24108. super(manager);
  24109. }
  24110. load(url, onLoad, onProgress, onError) {
  24111. if (url === undefined) url = '';
  24112. if (this.path !== undefined) url = this.path + url;
  24113. url = this.manager.resolveURL(url);
  24114. const cached = Cache.get(url);
  24115. if (cached !== undefined) {
  24116. this.manager.itemStart(url);
  24117. setTimeout(() => {
  24118. if (onLoad) onLoad(cached);
  24119. this.manager.itemEnd(url);
  24120. }, 0);
  24121. return cached;
  24122. }
  24123. // Check if request is duplicate
  24124. if (loading[url] !== undefined) {
  24125. loading[url].push({
  24126. onLoad: onLoad,
  24127. onProgress: onProgress,
  24128. onError: onError
  24129. });
  24130. return;
  24131. }
  24132. // Initialise array for duplicate requests
  24133. loading[url] = [];
  24134. loading[url].push({
  24135. onLoad: onLoad,
  24136. onProgress: onProgress,
  24137. onError: onError
  24138. });
  24139. // create request
  24140. const req = new Request(url, {
  24141. headers: new Headers(this.requestHeader),
  24142. credentials: this.withCredentials ? 'include' : 'same-origin'
  24143. // An abort controller could be added within a future PR
  24144. });
  24145. // record states ( avoid data race )
  24146. const mimeType = this.mimeType;
  24147. const responseType = this.responseType;
  24148. // start the fetch
  24149. fetch(req).then(response => {
  24150. if (response.status === 200 || response.status === 0) {
  24151. // Some browsers return HTTP Status 0 when using non-http protocol
  24152. // e.g. 'file://' or 'data://'. Handle as success.
  24153. if (response.status === 0) {
  24154. console.warn('THREE.FileLoader: HTTP Status 0 received.');
  24155. }
  24156. // Workaround: Checking if response.body === undefined for Alipay browser #23548
  24157. if (typeof ReadableStream === 'undefined' || response.body === undefined || response.body.getReader === undefined) {
  24158. return response;
  24159. }
  24160. const callbacks = loading[url];
  24161. const reader = response.body.getReader();
  24162. // Nginx needs X-File-Size check
  24163. // https://serverfault.com/questions/482875/why-does-nginx-remove-content-length-header-for-chunked-content
  24164. const contentLength = response.headers.get('Content-Length') || response.headers.get('X-File-Size');
  24165. const total = contentLength ? parseInt(contentLength) : 0;
  24166. const lengthComputable = total !== 0;
  24167. let loaded = 0;
  24168. // periodically read data into the new stream tracking while download progress
  24169. const stream = new ReadableStream({
  24170. start(controller) {
  24171. readData();
  24172. function readData() {
  24173. reader.read().then(({
  24174. done,
  24175. value
  24176. }) => {
  24177. if (done) {
  24178. controller.close();
  24179. } else {
  24180. loaded += value.byteLength;
  24181. const event = new ProgressEvent('progress', {
  24182. lengthComputable,
  24183. loaded,
  24184. total
  24185. });
  24186. for (let i = 0, il = callbacks.length; i < il; i++) {
  24187. const callback = callbacks[i];
  24188. if (callback.onProgress) callback.onProgress(event);
  24189. }
  24190. controller.enqueue(value);
  24191. readData();
  24192. }
  24193. });
  24194. }
  24195. }
  24196. });
  24197. return new Response(stream);
  24198. } else {
  24199. throw new HttpError(`fetch for "${response.url}" responded with ${response.status}: ${response.statusText}`, response);
  24200. }
  24201. }).then(response => {
  24202. switch (responseType) {
  24203. case 'arraybuffer':
  24204. return response.arrayBuffer();
  24205. case 'blob':
  24206. return response.blob();
  24207. case 'document':
  24208. return response.text().then(text => {
  24209. const parser = new DOMParser();
  24210. return parser.parseFromString(text, mimeType);
  24211. });
  24212. case 'json':
  24213. return response.json();
  24214. default:
  24215. if (mimeType === undefined) {
  24216. return response.text();
  24217. } else {
  24218. // sniff encoding
  24219. const re = /charset="?([^;"\s]*)"?/i;
  24220. const exec = re.exec(mimeType);
  24221. const label = exec && exec[1] ? exec[1].toLowerCase() : undefined;
  24222. const decoder = new TextDecoder(label);
  24223. return response.arrayBuffer().then(ab => decoder.decode(ab));
  24224. }
  24225. }
  24226. }).then(data => {
  24227. // Add to cache only on HTTP success, so that we do not cache
  24228. // error response bodies as proper responses to requests.
  24229. Cache.add(url, data);
  24230. const callbacks = loading[url];
  24231. delete loading[url];
  24232. for (let i = 0, il = callbacks.length; i < il; i++) {
  24233. const callback = callbacks[i];
  24234. if (callback.onLoad) callback.onLoad(data);
  24235. }
  24236. }).catch(err => {
  24237. // Abort errors and other errors are handled the same
  24238. const callbacks = loading[url];
  24239. if (callbacks === undefined) {
  24240. // When onLoad was called and url was deleted in `loading`
  24241. this.manager.itemError(url);
  24242. throw err;
  24243. }
  24244. delete loading[url];
  24245. for (let i = 0, il = callbacks.length; i < il; i++) {
  24246. const callback = callbacks[i];
  24247. if (callback.onError) callback.onError(err);
  24248. }
  24249. this.manager.itemError(url);
  24250. }).finally(() => {
  24251. this.manager.itemEnd(url);
  24252. });
  24253. this.manager.itemStart(url);
  24254. }
  24255. setResponseType(value) {
  24256. this.responseType = value;
  24257. return this;
  24258. }
  24259. setMimeType(value) {
  24260. this.mimeType = value;
  24261. return this;
  24262. }
  24263. }
  24264. class AnimationLoader extends Loader {
  24265. constructor(manager) {
  24266. super(manager);
  24267. }
  24268. load(url, onLoad, onProgress, onError) {
  24269. const scope = this;
  24270. const loader = new FileLoader(this.manager);
  24271. loader.setPath(this.path);
  24272. loader.setRequestHeader(this.requestHeader);
  24273. loader.setWithCredentials(this.withCredentials);
  24274. loader.load(url, function (text) {
  24275. try {
  24276. onLoad(scope.parse(JSON.parse(text)));
  24277. } catch (e) {
  24278. if (onError) {
  24279. onError(e);
  24280. } else {
  24281. console.error(e);
  24282. }
  24283. scope.manager.itemError(url);
  24284. }
  24285. }, onProgress, onError);
  24286. }
  24287. parse(json) {
  24288. const animations = [];
  24289. for (let i = 0; i < json.length; i++) {
  24290. const clip = AnimationClip.parse(json[i]);
  24291. animations.push(clip);
  24292. }
  24293. return animations;
  24294. }
  24295. }
  24296. /**
  24297. * Abstract Base class to block based textures loader (dds, pvr, ...)
  24298. *
  24299. * Sub classes have to implement the parse() method which will be used in load().
  24300. */
  24301. class CompressedTextureLoader extends Loader {
  24302. constructor(manager) {
  24303. super(manager);
  24304. }
  24305. load(url, onLoad, onProgress, onError) {
  24306. const scope = this;
  24307. const images = [];
  24308. const texture = new CompressedTexture();
  24309. const loader = new FileLoader(this.manager);
  24310. loader.setPath(this.path);
  24311. loader.setResponseType('arraybuffer');
  24312. loader.setRequestHeader(this.requestHeader);
  24313. loader.setWithCredentials(scope.withCredentials);
  24314. let loaded = 0;
  24315. function loadTexture(i) {
  24316. loader.load(url[i], function (buffer) {
  24317. const texDatas = scope.parse(buffer, true);
  24318. images[i] = {
  24319. width: texDatas.width,
  24320. height: texDatas.height,
  24321. format: texDatas.format,
  24322. mipmaps: texDatas.mipmaps
  24323. };
  24324. loaded += 1;
  24325. if (loaded === 6) {
  24326. if (texDatas.mipmapCount === 1) texture.minFilter = LinearFilter;
  24327. texture.image = images;
  24328. texture.format = texDatas.format;
  24329. texture.needsUpdate = true;
  24330. if (onLoad) onLoad(texture);
  24331. }
  24332. }, onProgress, onError);
  24333. }
  24334. if (Array.isArray(url)) {
  24335. for (let i = 0, il = url.length; i < il; ++i) {
  24336. loadTexture(i);
  24337. }
  24338. } else {
  24339. // compressed cubemap texture stored in a single DDS file
  24340. loader.load(url, function (buffer) {
  24341. const texDatas = scope.parse(buffer, true);
  24342. if (texDatas.isCubemap) {
  24343. const faces = texDatas.mipmaps.length / texDatas.mipmapCount;
  24344. for (let f = 0; f < faces; f++) {
  24345. images[f] = {
  24346. mipmaps: []
  24347. };
  24348. for (let i = 0; i < texDatas.mipmapCount; i++) {
  24349. images[f].mipmaps.push(texDatas.mipmaps[f * texDatas.mipmapCount + i]);
  24350. images[f].format = texDatas.format;
  24351. images[f].width = texDatas.width;
  24352. images[f].height = texDatas.height;
  24353. }
  24354. }
  24355. texture.image = images;
  24356. } else {
  24357. texture.image.width = texDatas.width;
  24358. texture.image.height = texDatas.height;
  24359. texture.mipmaps = texDatas.mipmaps;
  24360. }
  24361. if (texDatas.mipmapCount === 1) {
  24362. texture.minFilter = LinearFilter;
  24363. }
  24364. texture.format = texDatas.format;
  24365. texture.needsUpdate = true;
  24366. if (onLoad) onLoad(texture);
  24367. }, onProgress, onError);
  24368. }
  24369. return texture;
  24370. }
  24371. }
  24372. class ImageLoader extends Loader {
  24373. constructor(manager) {
  24374. super(manager);
  24375. }
  24376. load(url, onLoad, onProgress, onError) {
  24377. if (this.path !== undefined) url = this.path + url;
  24378. url = this.manager.resolveURL(url);
  24379. const scope = this;
  24380. const cached = Cache.get(url);
  24381. if (cached !== undefined) {
  24382. scope.manager.itemStart(url);
  24383. setTimeout(function () {
  24384. if (onLoad) onLoad(cached);
  24385. scope.manager.itemEnd(url);
  24386. }, 0);
  24387. return cached;
  24388. }
  24389. const image = createElementNS('img');
  24390. function onImageLoad() {
  24391. removeEventListeners();
  24392. Cache.add(url, this);
  24393. if (onLoad) onLoad(this);
  24394. scope.manager.itemEnd(url);
  24395. }
  24396. function onImageError(event) {
  24397. removeEventListeners();
  24398. if (onError) onError(event);
  24399. scope.manager.itemError(url);
  24400. scope.manager.itemEnd(url);
  24401. }
  24402. function removeEventListeners() {
  24403. image.removeEventListener('load', onImageLoad, false);
  24404. image.removeEventListener('error', onImageError, false);
  24405. }
  24406. image.addEventListener('load', onImageLoad, false);
  24407. image.addEventListener('error', onImageError, false);
  24408. if (url.slice(0, 5) !== 'data:') {
  24409. if (this.crossOrigin !== undefined) image.crossOrigin = this.crossOrigin;
  24410. }
  24411. scope.manager.itemStart(url);
  24412. image.src = url;
  24413. return image;
  24414. }
  24415. }
  24416. class CubeTextureLoader extends Loader {
  24417. constructor(manager) {
  24418. super(manager);
  24419. }
  24420. load(urls, onLoad, onProgress, onError) {
  24421. const texture = new CubeTexture();
  24422. const loader = new ImageLoader(this.manager);
  24423. loader.setCrossOrigin(this.crossOrigin);
  24424. loader.setPath(this.path);
  24425. let loaded = 0;
  24426. function loadTexture(i) {
  24427. loader.load(urls[i], function (image) {
  24428. texture.images[i] = image;
  24429. loaded++;
  24430. if (loaded === 6) {
  24431. texture.needsUpdate = true;
  24432. if (onLoad) onLoad(texture);
  24433. }
  24434. }, undefined, onError);
  24435. }
  24436. for (let i = 0; i < urls.length; ++i) {
  24437. loadTexture(i);
  24438. }
  24439. return texture;
  24440. }
  24441. }
  24442. /**
  24443. * Abstract Base class to load generic binary textures formats (rgbe, hdr, ...)
  24444. *
  24445. * Sub classes have to implement the parse() method which will be used in load().
  24446. */
  24447. class DataTextureLoader extends Loader {
  24448. constructor(manager) {
  24449. super(manager);
  24450. }
  24451. load(url, onLoad, onProgress, onError) {
  24452. const scope = this;
  24453. const texture = new DataTexture();
  24454. const loader = new FileLoader(this.manager);
  24455. loader.setResponseType('arraybuffer');
  24456. loader.setRequestHeader(this.requestHeader);
  24457. loader.setPath(this.path);
  24458. loader.setWithCredentials(scope.withCredentials);
  24459. loader.load(url, function (buffer) {
  24460. const texData = scope.parse(buffer);
  24461. if (!texData) return;
  24462. if (texData.image !== undefined) {
  24463. texture.image = texData.image;
  24464. } else if (texData.data !== undefined) {
  24465. texture.image.width = texData.width;
  24466. texture.image.height = texData.height;
  24467. texture.image.data = texData.data;
  24468. }
  24469. texture.wrapS = texData.wrapS !== undefined ? texData.wrapS : ClampToEdgeWrapping;
  24470. texture.wrapT = texData.wrapT !== undefined ? texData.wrapT : ClampToEdgeWrapping;
  24471. texture.magFilter = texData.magFilter !== undefined ? texData.magFilter : LinearFilter;
  24472. texture.minFilter = texData.minFilter !== undefined ? texData.minFilter : LinearFilter;
  24473. texture.anisotropy = texData.anisotropy !== undefined ? texData.anisotropy : 1;
  24474. if (texData.encoding !== undefined) {
  24475. texture.encoding = texData.encoding;
  24476. }
  24477. if (texData.flipY !== undefined) {
  24478. texture.flipY = texData.flipY;
  24479. }
  24480. if (texData.format !== undefined) {
  24481. texture.format = texData.format;
  24482. }
  24483. if (texData.type !== undefined) {
  24484. texture.type = texData.type;
  24485. }
  24486. if (texData.mipmaps !== undefined) {
  24487. texture.mipmaps = texData.mipmaps;
  24488. texture.minFilter = LinearMipmapLinearFilter; // presumably...
  24489. }
  24490. if (texData.mipmapCount === 1) {
  24491. texture.minFilter = LinearFilter;
  24492. }
  24493. if (texData.generateMipmaps !== undefined) {
  24494. texture.generateMipmaps = texData.generateMipmaps;
  24495. }
  24496. texture.needsUpdate = true;
  24497. if (onLoad) onLoad(texture, texData);
  24498. }, onProgress, onError);
  24499. return texture;
  24500. }
  24501. }
  24502. class TextureLoader extends Loader {
  24503. constructor(manager) {
  24504. super(manager);
  24505. }
  24506. load(url, onLoad, onProgress, onError) {
  24507. const texture = new Texture();
  24508. const loader = new ImageLoader(this.manager);
  24509. loader.setCrossOrigin(this.crossOrigin);
  24510. loader.setPath(this.path);
  24511. loader.load(url, function (image) {
  24512. texture.image = image;
  24513. texture.needsUpdate = true;
  24514. if (onLoad !== undefined) {
  24515. onLoad(texture);
  24516. }
  24517. }, onProgress, onError);
  24518. return texture;
  24519. }
  24520. }
  24521. class Light extends Object3D {
  24522. constructor(color, intensity = 1) {
  24523. super();
  24524. this.isLight = true;
  24525. this.type = 'Light';
  24526. this.color = new Color(color);
  24527. this.intensity = intensity;
  24528. }
  24529. dispose() {
  24530. // Empty here in base class; some subclasses override.
  24531. }
  24532. copy(source, recursive) {
  24533. super.copy(source, recursive);
  24534. this.color.copy(source.color);
  24535. this.intensity = source.intensity;
  24536. return this;
  24537. }
  24538. toJSON(meta) {
  24539. const data = super.toJSON(meta);
  24540. data.object.color = this.color.getHex();
  24541. data.object.intensity = this.intensity;
  24542. if (this.groundColor !== undefined) data.object.groundColor = this.groundColor.getHex();
  24543. if (this.distance !== undefined) data.object.distance = this.distance;
  24544. if (this.angle !== undefined) data.object.angle = this.angle;
  24545. if (this.decay !== undefined) data.object.decay = this.decay;
  24546. if (this.penumbra !== undefined) data.object.penumbra = this.penumbra;
  24547. if (this.shadow !== undefined) data.object.shadow = this.shadow.toJSON();
  24548. return data;
  24549. }
  24550. }
  24551. class HemisphereLight extends Light {
  24552. constructor(skyColor, groundColor, intensity) {
  24553. super(skyColor, intensity);
  24554. this.isHemisphereLight = true;
  24555. this.type = 'HemisphereLight';
  24556. this.position.copy(Object3D.DefaultUp);
  24557. this.updateMatrix();
  24558. this.groundColor = new Color(groundColor);
  24559. }
  24560. copy(source, recursive) {
  24561. super.copy(source, recursive);
  24562. this.groundColor.copy(source.groundColor);
  24563. return this;
  24564. }
  24565. }
  24566. const _projScreenMatrix$1 = /*@__PURE__*/new Matrix4();
  24567. const _lightPositionWorld$1 = /*@__PURE__*/new Vector3();
  24568. const _lookTarget$1 = /*@__PURE__*/new Vector3();
  24569. class LightShadow {
  24570. constructor(camera) {
  24571. this.camera = camera;
  24572. this.bias = 0;
  24573. this.normalBias = 0;
  24574. this.radius = 1;
  24575. this.blurSamples = 8;
  24576. this.mapSize = new Vector2(512, 512);
  24577. this.map = null;
  24578. this.mapPass = null;
  24579. this.matrix = new Matrix4();
  24580. this.autoUpdate = true;
  24581. this.needsUpdate = false;
  24582. this._frustum = new Frustum();
  24583. this._frameExtents = new Vector2(1, 1);
  24584. this._viewportCount = 1;
  24585. this._viewports = [new Vector4(0, 0, 1, 1)];
  24586. }
  24587. getViewportCount() {
  24588. return this._viewportCount;
  24589. }
  24590. getFrustum() {
  24591. return this._frustum;
  24592. }
  24593. updateMatrices(light) {
  24594. const shadowCamera = this.camera;
  24595. const shadowMatrix = this.matrix;
  24596. _lightPositionWorld$1.setFromMatrixPosition(light.matrixWorld);
  24597. shadowCamera.position.copy(_lightPositionWorld$1);
  24598. _lookTarget$1.setFromMatrixPosition(light.target.matrixWorld);
  24599. shadowCamera.lookAt(_lookTarget$1);
  24600. shadowCamera.updateMatrixWorld();
  24601. _projScreenMatrix$1.multiplyMatrices(shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse);
  24602. this._frustum.setFromProjectionMatrix(_projScreenMatrix$1);
  24603. 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);
  24604. shadowMatrix.multiply(_projScreenMatrix$1);
  24605. }
  24606. getViewport(viewportIndex) {
  24607. return this._viewports[viewportIndex];
  24608. }
  24609. getFrameExtents() {
  24610. return this._frameExtents;
  24611. }
  24612. dispose() {
  24613. if (this.map) {
  24614. this.map.dispose();
  24615. }
  24616. if (this.mapPass) {
  24617. this.mapPass.dispose();
  24618. }
  24619. }
  24620. copy(source) {
  24621. this.camera = source.camera.clone();
  24622. this.bias = source.bias;
  24623. this.radius = source.radius;
  24624. this.mapSize.copy(source.mapSize);
  24625. return this;
  24626. }
  24627. clone() {
  24628. return new this.constructor().copy(this);
  24629. }
  24630. toJSON() {
  24631. const object = {};
  24632. if (this.bias !== 0) object.bias = this.bias;
  24633. if (this.normalBias !== 0) object.normalBias = this.normalBias;
  24634. if (this.radius !== 1) object.radius = this.radius;
  24635. if (this.mapSize.x !== 512 || this.mapSize.y !== 512) object.mapSize = this.mapSize.toArray();
  24636. object.camera = this.camera.toJSON(false).object;
  24637. delete object.camera.matrix;
  24638. return object;
  24639. }
  24640. }
  24641. class SpotLightShadow extends LightShadow {
  24642. constructor() {
  24643. super(new PerspectiveCamera(50, 1, 0.5, 500));
  24644. this.isSpotLightShadow = true;
  24645. this.focus = 1;
  24646. }
  24647. updateMatrices(light) {
  24648. const camera = this.camera;
  24649. const fov = RAD2DEG * 2 * light.angle * this.focus;
  24650. const aspect = this.mapSize.width / this.mapSize.height;
  24651. const far = light.distance || camera.far;
  24652. if (fov !== camera.fov || aspect !== camera.aspect || far !== camera.far) {
  24653. camera.fov = fov;
  24654. camera.aspect = aspect;
  24655. camera.far = far;
  24656. camera.updateProjectionMatrix();
  24657. }
  24658. super.updateMatrices(light);
  24659. }
  24660. copy(source) {
  24661. super.copy(source);
  24662. this.focus = source.focus;
  24663. return this;
  24664. }
  24665. }
  24666. class SpotLight extends Light {
  24667. constructor(color, intensity, distance = 0, angle = Math.PI / 3, penumbra = 0, decay = 2) {
  24668. super(color, intensity);
  24669. this.isSpotLight = true;
  24670. this.type = 'SpotLight';
  24671. this.position.copy(Object3D.DefaultUp);
  24672. this.updateMatrix();
  24673. this.target = new Object3D();
  24674. this.distance = distance;
  24675. this.angle = angle;
  24676. this.penumbra = penumbra;
  24677. this.decay = decay;
  24678. this.map = null;
  24679. this.shadow = new SpotLightShadow();
  24680. }
  24681. get power() {
  24682. // compute the light's luminous power (in lumens) from its intensity (in candela)
  24683. // by convention for a spotlight, luminous power (lm) = π * luminous intensity (cd)
  24684. return this.intensity * Math.PI;
  24685. }
  24686. set power(power) {
  24687. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  24688. this.intensity = power / Math.PI;
  24689. }
  24690. dispose() {
  24691. this.shadow.dispose();
  24692. }
  24693. copy(source, recursive) {
  24694. super.copy(source, recursive);
  24695. this.distance = source.distance;
  24696. this.angle = source.angle;
  24697. this.penumbra = source.penumbra;
  24698. this.decay = source.decay;
  24699. this.target = source.target.clone();
  24700. this.shadow = source.shadow.clone();
  24701. return this;
  24702. }
  24703. }
  24704. const _projScreenMatrix = /*@__PURE__*/new Matrix4();
  24705. const _lightPositionWorld = /*@__PURE__*/new Vector3();
  24706. const _lookTarget = /*@__PURE__*/new Vector3();
  24707. class PointLightShadow extends LightShadow {
  24708. constructor() {
  24709. super(new PerspectiveCamera(90, 1, 0.5, 500));
  24710. this.isPointLightShadow = true;
  24711. this._frameExtents = new Vector2(4, 2);
  24712. this._viewportCount = 6;
  24713. this._viewports = [
  24714. // These viewports map a cube-map onto a 2D texture with the
  24715. // following orientation:
  24716. //
  24717. // xzXZ
  24718. // y Y
  24719. //
  24720. // X - Positive x direction
  24721. // x - Negative x direction
  24722. // Y - Positive y direction
  24723. // y - Negative y direction
  24724. // Z - Positive z direction
  24725. // z - Negative z direction
  24726. // positive X
  24727. new Vector4(2, 1, 1, 1),
  24728. // negative X
  24729. new Vector4(0, 1, 1, 1),
  24730. // positive Z
  24731. new Vector4(3, 1, 1, 1),
  24732. // negative Z
  24733. new Vector4(1, 1, 1, 1),
  24734. // positive Y
  24735. new Vector4(3, 0, 1, 1),
  24736. // negative Y
  24737. new Vector4(1, 0, 1, 1)];
  24738. 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)];
  24739. 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)];
  24740. }
  24741. updateMatrices(light, viewportIndex = 0) {
  24742. const camera = this.camera;
  24743. const shadowMatrix = this.matrix;
  24744. const far = light.distance || camera.far;
  24745. if (far !== camera.far) {
  24746. camera.far = far;
  24747. camera.updateProjectionMatrix();
  24748. }
  24749. _lightPositionWorld.setFromMatrixPosition(light.matrixWorld);
  24750. camera.position.copy(_lightPositionWorld);
  24751. _lookTarget.copy(camera.position);
  24752. _lookTarget.add(this._cubeDirections[viewportIndex]);
  24753. camera.up.copy(this._cubeUps[viewportIndex]);
  24754. camera.lookAt(_lookTarget);
  24755. camera.updateMatrixWorld();
  24756. shadowMatrix.makeTranslation(-_lightPositionWorld.x, -_lightPositionWorld.y, -_lightPositionWorld.z);
  24757. _projScreenMatrix.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse);
  24758. this._frustum.setFromProjectionMatrix(_projScreenMatrix);
  24759. }
  24760. }
  24761. class PointLight extends Light {
  24762. constructor(color, intensity, distance = 0, decay = 2) {
  24763. super(color, intensity);
  24764. this.isPointLight = true;
  24765. this.type = 'PointLight';
  24766. this.distance = distance;
  24767. this.decay = decay;
  24768. this.shadow = new PointLightShadow();
  24769. }
  24770. get power() {
  24771. // compute the light's luminous power (in lumens) from its intensity (in candela)
  24772. // for an isotropic light source, luminous power (lm) = 4 π luminous intensity (cd)
  24773. return this.intensity * 4 * Math.PI;
  24774. }
  24775. set power(power) {
  24776. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  24777. this.intensity = power / (4 * Math.PI);
  24778. }
  24779. dispose() {
  24780. this.shadow.dispose();
  24781. }
  24782. copy(source, recursive) {
  24783. super.copy(source, recursive);
  24784. this.distance = source.distance;
  24785. this.decay = source.decay;
  24786. this.shadow = source.shadow.clone();
  24787. return this;
  24788. }
  24789. }
  24790. class DirectionalLightShadow extends LightShadow {
  24791. constructor() {
  24792. super(new OrthographicCamera(-5, 5, 5, -5, 0.5, 500));
  24793. this.isDirectionalLightShadow = true;
  24794. }
  24795. }
  24796. class DirectionalLight extends Light {
  24797. constructor(color, intensity) {
  24798. super(color, intensity);
  24799. this.isDirectionalLight = true;
  24800. this.type = 'DirectionalLight';
  24801. this.position.copy(Object3D.DefaultUp);
  24802. this.updateMatrix();
  24803. this.target = new Object3D();
  24804. this.shadow = new DirectionalLightShadow();
  24805. }
  24806. dispose() {
  24807. this.shadow.dispose();
  24808. }
  24809. copy(source) {
  24810. super.copy(source);
  24811. this.target = source.target.clone();
  24812. this.shadow = source.shadow.clone();
  24813. return this;
  24814. }
  24815. }
  24816. class AmbientLight extends Light {
  24817. constructor(color, intensity) {
  24818. super(color, intensity);
  24819. this.isAmbientLight = true;
  24820. this.type = 'AmbientLight';
  24821. }
  24822. }
  24823. class RectAreaLight extends Light {
  24824. constructor(color, intensity, width = 10, height = 10) {
  24825. super(color, intensity);
  24826. this.isRectAreaLight = true;
  24827. this.type = 'RectAreaLight';
  24828. this.width = width;
  24829. this.height = height;
  24830. }
  24831. get power() {
  24832. // compute the light's luminous power (in lumens) from its intensity (in nits)
  24833. return this.intensity * this.width * this.height * Math.PI;
  24834. }
  24835. set power(power) {
  24836. // set the light's intensity (in nits) from the desired luminous power (in lumens)
  24837. this.intensity = power / (this.width * this.height * Math.PI);
  24838. }
  24839. copy(source) {
  24840. super.copy(source);
  24841. this.width = source.width;
  24842. this.height = source.height;
  24843. return this;
  24844. }
  24845. toJSON(meta) {
  24846. const data = super.toJSON(meta);
  24847. data.object.width = this.width;
  24848. data.object.height = this.height;
  24849. return data;
  24850. }
  24851. }
  24852. /**
  24853. * Primary reference:
  24854. * https://graphics.stanford.edu/papers/envmap/envmap.pdf
  24855. *
  24856. * Secondary reference:
  24857. * https://www.ppsloan.org/publications/StupidSH36.pdf
  24858. */
  24859. // 3-band SH defined by 9 coefficients
  24860. class SphericalHarmonics3 {
  24861. constructor() {
  24862. this.isSphericalHarmonics3 = true;
  24863. this.coefficients = [];
  24864. for (let i = 0; i < 9; i++) {
  24865. this.coefficients.push(new Vector3());
  24866. }
  24867. }
  24868. set(coefficients) {
  24869. for (let i = 0; i < 9; i++) {
  24870. this.coefficients[i].copy(coefficients[i]);
  24871. }
  24872. return this;
  24873. }
  24874. zero() {
  24875. for (let i = 0; i < 9; i++) {
  24876. this.coefficients[i].set(0, 0, 0);
  24877. }
  24878. return this;
  24879. }
  24880. // get the radiance in the direction of the normal
  24881. // target is a Vector3
  24882. getAt(normal, target) {
  24883. // normal is assumed to be unit length
  24884. const x = normal.x,
  24885. y = normal.y,
  24886. z = normal.z;
  24887. const coeff = this.coefficients;
  24888. // band 0
  24889. target.copy(coeff[0]).multiplyScalar(0.282095);
  24890. // band 1
  24891. target.addScaledVector(coeff[1], 0.488603 * y);
  24892. target.addScaledVector(coeff[2], 0.488603 * z);
  24893. target.addScaledVector(coeff[3], 0.488603 * x);
  24894. // band 2
  24895. target.addScaledVector(coeff[4], 1.092548 * (x * y));
  24896. target.addScaledVector(coeff[5], 1.092548 * (y * z));
  24897. target.addScaledVector(coeff[6], 0.315392 * (3.0 * z * z - 1.0));
  24898. target.addScaledVector(coeff[7], 1.092548 * (x * z));
  24899. target.addScaledVector(coeff[8], 0.546274 * (x * x - y * y));
  24900. return target;
  24901. }
  24902. // get the irradiance (radiance convolved with cosine lobe) in the direction of the normal
  24903. // target is a Vector3
  24904. // https://graphics.stanford.edu/papers/envmap/envmap.pdf
  24905. getIrradianceAt(normal, target) {
  24906. // normal is assumed to be unit length
  24907. const x = normal.x,
  24908. y = normal.y,
  24909. z = normal.z;
  24910. const coeff = this.coefficients;
  24911. // band 0
  24912. target.copy(coeff[0]).multiplyScalar(0.886227); // π * 0.282095
  24913. // band 1
  24914. target.addScaledVector(coeff[1], 2.0 * 0.511664 * y); // ( 2 * π / 3 ) * 0.488603
  24915. target.addScaledVector(coeff[2], 2.0 * 0.511664 * z);
  24916. target.addScaledVector(coeff[3], 2.0 * 0.511664 * x);
  24917. // band 2
  24918. target.addScaledVector(coeff[4], 2.0 * 0.429043 * x * y); // ( π / 4 ) * 1.092548
  24919. target.addScaledVector(coeff[5], 2.0 * 0.429043 * y * z);
  24920. target.addScaledVector(coeff[6], 0.743125 * z * z - 0.247708); // ( π / 4 ) * 0.315392 * 3
  24921. target.addScaledVector(coeff[7], 2.0 * 0.429043 * x * z);
  24922. target.addScaledVector(coeff[8], 0.429043 * (x * x - y * y)); // ( π / 4 ) * 0.546274
  24923. return target;
  24924. }
  24925. add(sh) {
  24926. for (let i = 0; i < 9; i++) {
  24927. this.coefficients[i].add(sh.coefficients[i]);
  24928. }
  24929. return this;
  24930. }
  24931. addScaledSH(sh, s) {
  24932. for (let i = 0; i < 9; i++) {
  24933. this.coefficients[i].addScaledVector(sh.coefficients[i], s);
  24934. }
  24935. return this;
  24936. }
  24937. scale(s) {
  24938. for (let i = 0; i < 9; i++) {
  24939. this.coefficients[i].multiplyScalar(s);
  24940. }
  24941. return this;
  24942. }
  24943. lerp(sh, alpha) {
  24944. for (let i = 0; i < 9; i++) {
  24945. this.coefficients[i].lerp(sh.coefficients[i], alpha);
  24946. }
  24947. return this;
  24948. }
  24949. equals(sh) {
  24950. for (let i = 0; i < 9; i++) {
  24951. if (!this.coefficients[i].equals(sh.coefficients[i])) {
  24952. return false;
  24953. }
  24954. }
  24955. return true;
  24956. }
  24957. copy(sh) {
  24958. return this.set(sh.coefficients);
  24959. }
  24960. clone() {
  24961. return new this.constructor().copy(this);
  24962. }
  24963. fromArray(array, offset = 0) {
  24964. const coefficients = this.coefficients;
  24965. for (let i = 0; i < 9; i++) {
  24966. coefficients[i].fromArray(array, offset + i * 3);
  24967. }
  24968. return this;
  24969. }
  24970. toArray(array = [], offset = 0) {
  24971. const coefficients = this.coefficients;
  24972. for (let i = 0; i < 9; i++) {
  24973. coefficients[i].toArray(array, offset + i * 3);
  24974. }
  24975. return array;
  24976. }
  24977. // evaluate the basis functions
  24978. // shBasis is an Array[ 9 ]
  24979. static getBasisAt(normal, shBasis) {
  24980. // normal is assumed to be unit length
  24981. const x = normal.x,
  24982. y = normal.y,
  24983. z = normal.z;
  24984. // band 0
  24985. shBasis[0] = 0.282095;
  24986. // band 1
  24987. shBasis[1] = 0.488603 * y;
  24988. shBasis[2] = 0.488603 * z;
  24989. shBasis[3] = 0.488603 * x;
  24990. // band 2
  24991. shBasis[4] = 1.092548 * x * y;
  24992. shBasis[5] = 1.092548 * y * z;
  24993. shBasis[6] = 0.315392 * (3 * z * z - 1);
  24994. shBasis[7] = 1.092548 * x * z;
  24995. shBasis[8] = 0.546274 * (x * x - y * y);
  24996. }
  24997. }
  24998. class LightProbe extends Light {
  24999. constructor(sh = new SphericalHarmonics3(), intensity = 1) {
  25000. super(undefined, intensity);
  25001. this.isLightProbe = true;
  25002. this.sh = sh;
  25003. }
  25004. copy(source) {
  25005. super.copy(source);
  25006. this.sh.copy(source.sh);
  25007. return this;
  25008. }
  25009. fromJSON(json) {
  25010. this.intensity = json.intensity; // TODO: Move this bit to Light.fromJSON();
  25011. this.sh.fromArray(json.sh);
  25012. return this;
  25013. }
  25014. toJSON(meta) {
  25015. const data = super.toJSON(meta);
  25016. data.object.sh = this.sh.toArray();
  25017. return data;
  25018. }
  25019. }
  25020. class MaterialLoader extends Loader {
  25021. constructor(manager) {
  25022. super(manager);
  25023. this.textures = {};
  25024. }
  25025. load(url, onLoad, onProgress, onError) {
  25026. const scope = this;
  25027. const loader = new FileLoader(scope.manager);
  25028. loader.setPath(scope.path);
  25029. loader.setRequestHeader(scope.requestHeader);
  25030. loader.setWithCredentials(scope.withCredentials);
  25031. loader.load(url, function (text) {
  25032. try {
  25033. onLoad(scope.parse(JSON.parse(text)));
  25034. } catch (e) {
  25035. if (onError) {
  25036. onError(e);
  25037. } else {
  25038. console.error(e);
  25039. }
  25040. scope.manager.itemError(url);
  25041. }
  25042. }, onProgress, onError);
  25043. }
  25044. parse(json) {
  25045. const textures = this.textures;
  25046. function getTexture(name) {
  25047. if (textures[name] === undefined) {
  25048. console.warn('THREE.MaterialLoader: Undefined texture', name);
  25049. }
  25050. return textures[name];
  25051. }
  25052. const material = MaterialLoader.createMaterialFromType(json.type);
  25053. if (json.uuid !== undefined) material.uuid = json.uuid;
  25054. if (json.name !== undefined) material.name = json.name;
  25055. if (json.color !== undefined && material.color !== undefined) material.color.setHex(json.color);
  25056. if (json.roughness !== undefined) material.roughness = json.roughness;
  25057. if (json.metalness !== undefined) material.metalness = json.metalness;
  25058. if (json.sheen !== undefined) material.sheen = json.sheen;
  25059. if (json.sheenColor !== undefined) material.sheenColor = new Color().setHex(json.sheenColor);
  25060. if (json.sheenRoughness !== undefined) material.sheenRoughness = json.sheenRoughness;
  25061. if (json.emissive !== undefined && material.emissive !== undefined) material.emissive.setHex(json.emissive);
  25062. if (json.specular !== undefined && material.specular !== undefined) material.specular.setHex(json.specular);
  25063. if (json.specularIntensity !== undefined) material.specularIntensity = json.specularIntensity;
  25064. if (json.specularColor !== undefined && material.specularColor !== undefined) material.specularColor.setHex(json.specularColor);
  25065. if (json.shininess !== undefined) material.shininess = json.shininess;
  25066. if (json.clearcoat !== undefined) material.clearcoat = json.clearcoat;
  25067. if (json.clearcoatRoughness !== undefined) material.clearcoatRoughness = json.clearcoatRoughness;
  25068. if (json.iridescence !== undefined) material.iridescence = json.iridescence;
  25069. if (json.iridescenceIOR !== undefined) material.iridescenceIOR = json.iridescenceIOR;
  25070. if (json.iridescenceThicknessRange !== undefined) material.iridescenceThicknessRange = json.iridescenceThicknessRange;
  25071. if (json.transmission !== undefined) material.transmission = json.transmission;
  25072. if (json.thickness !== undefined) material.thickness = json.thickness;
  25073. if (json.attenuationDistance !== undefined) material.attenuationDistance = json.attenuationDistance;
  25074. if (json.attenuationColor !== undefined && material.attenuationColor !== undefined) material.attenuationColor.setHex(json.attenuationColor);
  25075. if (json.fog !== undefined) material.fog = json.fog;
  25076. if (json.flatShading !== undefined) material.flatShading = json.flatShading;
  25077. if (json.blending !== undefined) material.blending = json.blending;
  25078. if (json.combine !== undefined) material.combine = json.combine;
  25079. if (json.side !== undefined) material.side = json.side;
  25080. if (json.shadowSide !== undefined) material.shadowSide = json.shadowSide;
  25081. if (json.opacity !== undefined) material.opacity = json.opacity;
  25082. if (json.transparent !== undefined) material.transparent = json.transparent;
  25083. if (json.alphaTest !== undefined) material.alphaTest = json.alphaTest;
  25084. if (json.depthTest !== undefined) material.depthTest = json.depthTest;
  25085. if (json.depthWrite !== undefined) material.depthWrite = json.depthWrite;
  25086. if (json.colorWrite !== undefined) material.colorWrite = json.colorWrite;
  25087. if (json.stencilWrite !== undefined) material.stencilWrite = json.stencilWrite;
  25088. if (json.stencilWriteMask !== undefined) material.stencilWriteMask = json.stencilWriteMask;
  25089. if (json.stencilFunc !== undefined) material.stencilFunc = json.stencilFunc;
  25090. if (json.stencilRef !== undefined) material.stencilRef = json.stencilRef;
  25091. if (json.stencilFuncMask !== undefined) material.stencilFuncMask = json.stencilFuncMask;
  25092. if (json.stencilFail !== undefined) material.stencilFail = json.stencilFail;
  25093. if (json.stencilZFail !== undefined) material.stencilZFail = json.stencilZFail;
  25094. if (json.stencilZPass !== undefined) material.stencilZPass = json.stencilZPass;
  25095. if (json.wireframe !== undefined) material.wireframe = json.wireframe;
  25096. if (json.wireframeLinewidth !== undefined) material.wireframeLinewidth = json.wireframeLinewidth;
  25097. if (json.wireframeLinecap !== undefined) material.wireframeLinecap = json.wireframeLinecap;
  25098. if (json.wireframeLinejoin !== undefined) material.wireframeLinejoin = json.wireframeLinejoin;
  25099. if (json.rotation !== undefined) material.rotation = json.rotation;
  25100. if (json.linewidth !== 1) material.linewidth = json.linewidth;
  25101. if (json.dashSize !== undefined) material.dashSize = json.dashSize;
  25102. if (json.gapSize !== undefined) material.gapSize = json.gapSize;
  25103. if (json.scale !== undefined) material.scale = json.scale;
  25104. if (json.polygonOffset !== undefined) material.polygonOffset = json.polygonOffset;
  25105. if (json.polygonOffsetFactor !== undefined) material.polygonOffsetFactor = json.polygonOffsetFactor;
  25106. if (json.polygonOffsetUnits !== undefined) material.polygonOffsetUnits = json.polygonOffsetUnits;
  25107. if (json.dithering !== undefined) material.dithering = json.dithering;
  25108. if (json.alphaToCoverage !== undefined) material.alphaToCoverage = json.alphaToCoverage;
  25109. if (json.premultipliedAlpha !== undefined) material.premultipliedAlpha = json.premultipliedAlpha;
  25110. if (json.visible !== undefined) material.visible = json.visible;
  25111. if (json.toneMapped !== undefined) material.toneMapped = json.toneMapped;
  25112. if (json.userData !== undefined) material.userData = json.userData;
  25113. if (json.vertexColors !== undefined) {
  25114. if (typeof json.vertexColors === 'number') {
  25115. material.vertexColors = json.vertexColors > 0 ? true : false;
  25116. } else {
  25117. material.vertexColors = json.vertexColors;
  25118. }
  25119. }
  25120. // Shader Material
  25121. if (json.uniforms !== undefined) {
  25122. for (const name in json.uniforms) {
  25123. const uniform = json.uniforms[name];
  25124. material.uniforms[name] = {};
  25125. switch (uniform.type) {
  25126. case 't':
  25127. material.uniforms[name].value = getTexture(uniform.value);
  25128. break;
  25129. case 'c':
  25130. material.uniforms[name].value = new Color().setHex(uniform.value);
  25131. break;
  25132. case 'v2':
  25133. material.uniforms[name].value = new Vector2().fromArray(uniform.value);
  25134. break;
  25135. case 'v3':
  25136. material.uniforms[name].value = new Vector3().fromArray(uniform.value);
  25137. break;
  25138. case 'v4':
  25139. material.uniforms[name].value = new Vector4().fromArray(uniform.value);
  25140. break;
  25141. case 'm3':
  25142. material.uniforms[name].value = new Matrix3().fromArray(uniform.value);
  25143. break;
  25144. case 'm4':
  25145. material.uniforms[name].value = new Matrix4().fromArray(uniform.value);
  25146. break;
  25147. default:
  25148. material.uniforms[name].value = uniform.value;
  25149. }
  25150. }
  25151. }
  25152. if (json.defines !== undefined) material.defines = json.defines;
  25153. if (json.vertexShader !== undefined) material.vertexShader = json.vertexShader;
  25154. if (json.fragmentShader !== undefined) material.fragmentShader = json.fragmentShader;
  25155. if (json.glslVersion !== undefined) material.glslVersion = json.glslVersion;
  25156. if (json.extensions !== undefined) {
  25157. for (const key in json.extensions) {
  25158. material.extensions[key] = json.extensions[key];
  25159. }
  25160. }
  25161. // for PointsMaterial
  25162. if (json.size !== undefined) material.size = json.size;
  25163. if (json.sizeAttenuation !== undefined) material.sizeAttenuation = json.sizeAttenuation;
  25164. // maps
  25165. if (json.map !== undefined) material.map = getTexture(json.map);
  25166. if (json.matcap !== undefined) material.matcap = getTexture(json.matcap);
  25167. if (json.alphaMap !== undefined) material.alphaMap = getTexture(json.alphaMap);
  25168. if (json.bumpMap !== undefined) material.bumpMap = getTexture(json.bumpMap);
  25169. if (json.bumpScale !== undefined) material.bumpScale = json.bumpScale;
  25170. if (json.normalMap !== undefined) material.normalMap = getTexture(json.normalMap);
  25171. if (json.normalMapType !== undefined) material.normalMapType = json.normalMapType;
  25172. if (json.normalScale !== undefined) {
  25173. let normalScale = json.normalScale;
  25174. if (Array.isArray(normalScale) === false) {
  25175. // Blender exporter used to export a scalar. See #7459
  25176. normalScale = [normalScale, normalScale];
  25177. }
  25178. material.normalScale = new Vector2().fromArray(normalScale);
  25179. }
  25180. if (json.displacementMap !== undefined) material.displacementMap = getTexture(json.displacementMap);
  25181. if (json.displacementScale !== undefined) material.displacementScale = json.displacementScale;
  25182. if (json.displacementBias !== undefined) material.displacementBias = json.displacementBias;
  25183. if (json.roughnessMap !== undefined) material.roughnessMap = getTexture(json.roughnessMap);
  25184. if (json.metalnessMap !== undefined) material.metalnessMap = getTexture(json.metalnessMap);
  25185. if (json.emissiveMap !== undefined) material.emissiveMap = getTexture(json.emissiveMap);
  25186. if (json.emissiveIntensity !== undefined) material.emissiveIntensity = json.emissiveIntensity;
  25187. if (json.specularMap !== undefined) material.specularMap = getTexture(json.specularMap);
  25188. if (json.specularIntensityMap !== undefined) material.specularIntensityMap = getTexture(json.specularIntensityMap);
  25189. if (json.specularColorMap !== undefined) material.specularColorMap = getTexture(json.specularColorMap);
  25190. if (json.envMap !== undefined) material.envMap = getTexture(json.envMap);
  25191. if (json.envMapIntensity !== undefined) material.envMapIntensity = json.envMapIntensity;
  25192. if (json.reflectivity !== undefined) material.reflectivity = json.reflectivity;
  25193. if (json.refractionRatio !== undefined) material.refractionRatio = json.refractionRatio;
  25194. if (json.lightMap !== undefined) material.lightMap = getTexture(json.lightMap);
  25195. if (json.lightMapIntensity !== undefined) material.lightMapIntensity = json.lightMapIntensity;
  25196. if (json.aoMap !== undefined) material.aoMap = getTexture(json.aoMap);
  25197. if (json.aoMapIntensity !== undefined) material.aoMapIntensity = json.aoMapIntensity;
  25198. if (json.gradientMap !== undefined) material.gradientMap = getTexture(json.gradientMap);
  25199. if (json.clearcoatMap !== undefined) material.clearcoatMap = getTexture(json.clearcoatMap);
  25200. if (json.clearcoatRoughnessMap !== undefined) material.clearcoatRoughnessMap = getTexture(json.clearcoatRoughnessMap);
  25201. if (json.clearcoatNormalMap !== undefined) material.clearcoatNormalMap = getTexture(json.clearcoatNormalMap);
  25202. if (json.clearcoatNormalScale !== undefined) material.clearcoatNormalScale = new Vector2().fromArray(json.clearcoatNormalScale);
  25203. if (json.iridescenceMap !== undefined) material.iridescenceMap = getTexture(json.iridescenceMap);
  25204. if (json.iridescenceThicknessMap !== undefined) material.iridescenceThicknessMap = getTexture(json.iridescenceThicknessMap);
  25205. if (json.transmissionMap !== undefined) material.transmissionMap = getTexture(json.transmissionMap);
  25206. if (json.thicknessMap !== undefined) material.thicknessMap = getTexture(json.thicknessMap);
  25207. if (json.sheenColorMap !== undefined) material.sheenColorMap = getTexture(json.sheenColorMap);
  25208. if (json.sheenRoughnessMap !== undefined) material.sheenRoughnessMap = getTexture(json.sheenRoughnessMap);
  25209. return material;
  25210. }
  25211. setTextures(value) {
  25212. this.textures = value;
  25213. return this;
  25214. }
  25215. static createMaterialFromType(type) {
  25216. const materialLib = {
  25217. ShadowMaterial,
  25218. SpriteMaterial,
  25219. RawShaderMaterial,
  25220. ShaderMaterial,
  25221. PointsMaterial,
  25222. MeshPhysicalMaterial,
  25223. MeshStandardMaterial,
  25224. MeshPhongMaterial,
  25225. MeshToonMaterial,
  25226. MeshNormalMaterial,
  25227. MeshLambertMaterial,
  25228. MeshDepthMaterial,
  25229. MeshDistanceMaterial,
  25230. MeshBasicMaterial,
  25231. MeshMatcapMaterial,
  25232. LineDashedMaterial,
  25233. LineBasicMaterial,
  25234. Material
  25235. };
  25236. return new materialLib[type]();
  25237. }
  25238. }
  25239. class LoaderUtils {
  25240. static decodeText(array) {
  25241. if (typeof TextDecoder !== 'undefined') {
  25242. return new TextDecoder().decode(array);
  25243. }
  25244. // Avoid the String.fromCharCode.apply(null, array) shortcut, which
  25245. // throws a "maximum call stack size exceeded" error for large arrays.
  25246. let s = '';
  25247. for (let i = 0, il = array.length; i < il; i++) {
  25248. // Implicitly assumes little-endian.
  25249. s += String.fromCharCode(array[i]);
  25250. }
  25251. try {
  25252. // merges multi-byte utf-8 characters.
  25253. return decodeURIComponent(escape(s));
  25254. } catch (e) {
  25255. // see #16358
  25256. return s;
  25257. }
  25258. }
  25259. static extractUrlBase(url) {
  25260. const index = url.lastIndexOf('/');
  25261. if (index === -1) return './';
  25262. return url.slice(0, index + 1);
  25263. }
  25264. static resolveURL(url, path) {
  25265. // Invalid URL
  25266. if (typeof url !== 'string' || url === '') return '';
  25267. // Host Relative URL
  25268. if (/^https?:\/\//i.test(path) && /^\//.test(url)) {
  25269. path = path.replace(/(^https?:\/\/[^\/]+).*/i, '$1');
  25270. }
  25271. // Absolute URL http://,https://,//
  25272. if (/^(https?:)?\/\//i.test(url)) return url;
  25273. // Data URI
  25274. if (/^data:.*,.*$/i.test(url)) return url;
  25275. // Blob URL
  25276. if (/^blob:.*$/i.test(url)) return url;
  25277. // Relative URL
  25278. return path + url;
  25279. }
  25280. }
  25281. class InstancedBufferGeometry extends BufferGeometry {
  25282. constructor() {
  25283. super();
  25284. this.isInstancedBufferGeometry = true;
  25285. this.type = 'InstancedBufferGeometry';
  25286. this.instanceCount = Infinity;
  25287. }
  25288. copy(source) {
  25289. super.copy(source);
  25290. this.instanceCount = source.instanceCount;
  25291. return this;
  25292. }
  25293. toJSON() {
  25294. const data = super.toJSON();
  25295. data.instanceCount = this.instanceCount;
  25296. data.isInstancedBufferGeometry = true;
  25297. return data;
  25298. }
  25299. }
  25300. class BufferGeometryLoader extends Loader {
  25301. constructor(manager) {
  25302. super(manager);
  25303. }
  25304. load(url, onLoad, onProgress, onError) {
  25305. const scope = this;
  25306. const loader = new FileLoader(scope.manager);
  25307. loader.setPath(scope.path);
  25308. loader.setRequestHeader(scope.requestHeader);
  25309. loader.setWithCredentials(scope.withCredentials);
  25310. loader.load(url, function (text) {
  25311. try {
  25312. onLoad(scope.parse(JSON.parse(text)));
  25313. } catch (e) {
  25314. if (onError) {
  25315. onError(e);
  25316. } else {
  25317. console.error(e);
  25318. }
  25319. scope.manager.itemError(url);
  25320. }
  25321. }, onProgress, onError);
  25322. }
  25323. parse(json) {
  25324. const interleavedBufferMap = {};
  25325. const arrayBufferMap = {};
  25326. function getInterleavedBuffer(json, uuid) {
  25327. if (interleavedBufferMap[uuid] !== undefined) return interleavedBufferMap[uuid];
  25328. const interleavedBuffers = json.interleavedBuffers;
  25329. const interleavedBuffer = interleavedBuffers[uuid];
  25330. const buffer = getArrayBuffer(json, interleavedBuffer.buffer);
  25331. const array = getTypedArray(interleavedBuffer.type, buffer);
  25332. const ib = new InterleavedBuffer(array, interleavedBuffer.stride);
  25333. ib.uuid = interleavedBuffer.uuid;
  25334. interleavedBufferMap[uuid] = ib;
  25335. return ib;
  25336. }
  25337. function getArrayBuffer(json, uuid) {
  25338. if (arrayBufferMap[uuid] !== undefined) return arrayBufferMap[uuid];
  25339. const arrayBuffers = json.arrayBuffers;
  25340. const arrayBuffer = arrayBuffers[uuid];
  25341. const ab = new Uint32Array(arrayBuffer).buffer;
  25342. arrayBufferMap[uuid] = ab;
  25343. return ab;
  25344. }
  25345. const geometry = json.isInstancedBufferGeometry ? new InstancedBufferGeometry() : new BufferGeometry();
  25346. const index = json.data.index;
  25347. if (index !== undefined) {
  25348. const typedArray = getTypedArray(index.type, index.array);
  25349. geometry.setIndex(new BufferAttribute(typedArray, 1));
  25350. }
  25351. const attributes = json.data.attributes;
  25352. for (const key in attributes) {
  25353. const attribute = attributes[key];
  25354. let bufferAttribute;
  25355. if (attribute.isInterleavedBufferAttribute) {
  25356. const interleavedBuffer = getInterleavedBuffer(json.data, attribute.data);
  25357. bufferAttribute = new InterleavedBufferAttribute(interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized);
  25358. } else {
  25359. const typedArray = getTypedArray(attribute.type, attribute.array);
  25360. const bufferAttributeConstr = attribute.isInstancedBufferAttribute ? InstancedBufferAttribute : BufferAttribute;
  25361. bufferAttribute = new bufferAttributeConstr(typedArray, attribute.itemSize, attribute.normalized);
  25362. }
  25363. if (attribute.name !== undefined) bufferAttribute.name = attribute.name;
  25364. if (attribute.usage !== undefined) bufferAttribute.setUsage(attribute.usage);
  25365. if (attribute.updateRange !== undefined) {
  25366. bufferAttribute.updateRange.offset = attribute.updateRange.offset;
  25367. bufferAttribute.updateRange.count = attribute.updateRange.count;
  25368. }
  25369. geometry.setAttribute(key, bufferAttribute);
  25370. }
  25371. const morphAttributes = json.data.morphAttributes;
  25372. if (morphAttributes) {
  25373. for (const key in morphAttributes) {
  25374. const attributeArray = morphAttributes[key];
  25375. const array = [];
  25376. for (let i = 0, il = attributeArray.length; i < il; i++) {
  25377. const attribute = attributeArray[i];
  25378. let bufferAttribute;
  25379. if (attribute.isInterleavedBufferAttribute) {
  25380. const interleavedBuffer = getInterleavedBuffer(json.data, attribute.data);
  25381. bufferAttribute = new InterleavedBufferAttribute(interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized);
  25382. } else {
  25383. const typedArray = getTypedArray(attribute.type, attribute.array);
  25384. bufferAttribute = new BufferAttribute(typedArray, attribute.itemSize, attribute.normalized);
  25385. }
  25386. if (attribute.name !== undefined) bufferAttribute.name = attribute.name;
  25387. array.push(bufferAttribute);
  25388. }
  25389. geometry.morphAttributes[key] = array;
  25390. }
  25391. }
  25392. const morphTargetsRelative = json.data.morphTargetsRelative;
  25393. if (morphTargetsRelative) {
  25394. geometry.morphTargetsRelative = true;
  25395. }
  25396. const groups = json.data.groups || json.data.drawcalls || json.data.offsets;
  25397. if (groups !== undefined) {
  25398. for (let i = 0, n = groups.length; i !== n; ++i) {
  25399. const group = groups[i];
  25400. geometry.addGroup(group.start, group.count, group.materialIndex);
  25401. }
  25402. }
  25403. const boundingSphere = json.data.boundingSphere;
  25404. if (boundingSphere !== undefined) {
  25405. const center = new Vector3();
  25406. if (boundingSphere.center !== undefined) {
  25407. center.fromArray(boundingSphere.center);
  25408. }
  25409. geometry.boundingSphere = new Sphere(center, boundingSphere.radius);
  25410. }
  25411. if (json.name) geometry.name = json.name;
  25412. if (json.userData) geometry.userData = json.userData;
  25413. return geometry;
  25414. }
  25415. }
  25416. class ObjectLoader extends Loader {
  25417. constructor(manager) {
  25418. super(manager);
  25419. }
  25420. load(url, onLoad, onProgress, onError) {
  25421. const scope = this;
  25422. const path = this.path === '' ? LoaderUtils.extractUrlBase(url) : this.path;
  25423. this.resourcePath = this.resourcePath || path;
  25424. const loader = new FileLoader(this.manager);
  25425. loader.setPath(this.path);
  25426. loader.setRequestHeader(this.requestHeader);
  25427. loader.setWithCredentials(this.withCredentials);
  25428. loader.load(url, function (text) {
  25429. let json = null;
  25430. try {
  25431. json = JSON.parse(text);
  25432. } catch (error) {
  25433. if (onError !== undefined) onError(error);
  25434. console.error('THREE:ObjectLoader: Can\'t parse ' + url + '.', error.message);
  25435. return;
  25436. }
  25437. const metadata = json.metadata;
  25438. if (metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry') {
  25439. if (onError !== undefined) onError(new Error('THREE.ObjectLoader: Can\'t load ' + url));
  25440. console.error('THREE.ObjectLoader: Can\'t load ' + url);
  25441. return;
  25442. }
  25443. scope.parse(json, onLoad);
  25444. }, onProgress, onError);
  25445. }
  25446. async loadAsync(url, onProgress) {
  25447. const scope = this;
  25448. const path = this.path === '' ? LoaderUtils.extractUrlBase(url) : this.path;
  25449. this.resourcePath = this.resourcePath || path;
  25450. const loader = new FileLoader(this.manager);
  25451. loader.setPath(this.path);
  25452. loader.setRequestHeader(this.requestHeader);
  25453. loader.setWithCredentials(this.withCredentials);
  25454. const text = await loader.loadAsync(url, onProgress);
  25455. const json = JSON.parse(text);
  25456. const metadata = json.metadata;
  25457. if (metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry') {
  25458. throw new Error('THREE.ObjectLoader: Can\'t load ' + url);
  25459. }
  25460. return await scope.parseAsync(json);
  25461. }
  25462. parse(json, onLoad) {
  25463. const animations = this.parseAnimations(json.animations);
  25464. const shapes = this.parseShapes(json.shapes);
  25465. const geometries = this.parseGeometries(json.geometries, shapes);
  25466. const images = this.parseImages(json.images, function () {
  25467. if (onLoad !== undefined) onLoad(object);
  25468. });
  25469. const textures = this.parseTextures(json.textures, images);
  25470. const materials = this.parseMaterials(json.materials, textures);
  25471. const object = this.parseObject(json.object, geometries, materials, textures, animations);
  25472. const skeletons = this.parseSkeletons(json.skeletons, object);
  25473. this.bindSkeletons(object, skeletons);
  25474. //
  25475. if (onLoad !== undefined) {
  25476. let hasImages = false;
  25477. for (const uuid in images) {
  25478. if (images[uuid].data instanceof HTMLImageElement) {
  25479. hasImages = true;
  25480. break;
  25481. }
  25482. }
  25483. if (hasImages === false) onLoad(object);
  25484. }
  25485. return object;
  25486. }
  25487. async parseAsync(json) {
  25488. const animations = this.parseAnimations(json.animations);
  25489. const shapes = this.parseShapes(json.shapes);
  25490. const geometries = this.parseGeometries(json.geometries, shapes);
  25491. const images = await this.parseImagesAsync(json.images);
  25492. const textures = this.parseTextures(json.textures, images);
  25493. const materials = this.parseMaterials(json.materials, textures);
  25494. const object = this.parseObject(json.object, geometries, materials, textures, animations);
  25495. const skeletons = this.parseSkeletons(json.skeletons, object);
  25496. this.bindSkeletons(object, skeletons);
  25497. return object;
  25498. }
  25499. parseShapes(json) {
  25500. const shapes = {};
  25501. if (json !== undefined) {
  25502. for (let i = 0, l = json.length; i < l; i++) {
  25503. const shape = new Shape().fromJSON(json[i]);
  25504. shapes[shape.uuid] = shape;
  25505. }
  25506. }
  25507. return shapes;
  25508. }
  25509. parseSkeletons(json, object) {
  25510. const skeletons = {};
  25511. const bones = {};
  25512. // generate bone lookup table
  25513. object.traverse(function (child) {
  25514. if (child.isBone) bones[child.uuid] = child;
  25515. });
  25516. // create skeletons
  25517. if (json !== undefined) {
  25518. for (let i = 0, l = json.length; i < l; i++) {
  25519. const skeleton = new Skeleton().fromJSON(json[i], bones);
  25520. skeletons[skeleton.uuid] = skeleton;
  25521. }
  25522. }
  25523. return skeletons;
  25524. }
  25525. parseGeometries(json, shapes) {
  25526. const geometries = {};
  25527. if (json !== undefined) {
  25528. const bufferGeometryLoader = new BufferGeometryLoader();
  25529. for (let i = 0, l = json.length; i < l; i++) {
  25530. let geometry;
  25531. const data = json[i];
  25532. switch (data.type) {
  25533. case 'BufferGeometry':
  25534. case 'InstancedBufferGeometry':
  25535. geometry = bufferGeometryLoader.parse(data);
  25536. break;
  25537. default:
  25538. if (data.type in Geometries) {
  25539. geometry = Geometries[data.type].fromJSON(data, shapes);
  25540. } else {
  25541. console.warn(`THREE.ObjectLoader: Unsupported geometry type "${data.type}"`);
  25542. }
  25543. }
  25544. geometry.uuid = data.uuid;
  25545. if (data.name !== undefined) geometry.name = data.name;
  25546. if (geometry.isBufferGeometry === true && data.userData !== undefined) geometry.userData = data.userData;
  25547. geometries[data.uuid] = geometry;
  25548. }
  25549. }
  25550. return geometries;
  25551. }
  25552. parseMaterials(json, textures) {
  25553. const cache = {}; // MultiMaterial
  25554. const materials = {};
  25555. if (json !== undefined) {
  25556. const loader = new MaterialLoader();
  25557. loader.setTextures(textures);
  25558. for (let i = 0, l = json.length; i < l; i++) {
  25559. const data = json[i];
  25560. if (cache[data.uuid] === undefined) {
  25561. cache[data.uuid] = loader.parse(data);
  25562. }
  25563. materials[data.uuid] = cache[data.uuid];
  25564. }
  25565. }
  25566. return materials;
  25567. }
  25568. parseAnimations(json) {
  25569. const animations = {};
  25570. if (json !== undefined) {
  25571. for (let i = 0; i < json.length; i++) {
  25572. const data = json[i];
  25573. const clip = AnimationClip.parse(data);
  25574. animations[clip.uuid] = clip;
  25575. }
  25576. }
  25577. return animations;
  25578. }
  25579. parseImages(json, onLoad) {
  25580. const scope = this;
  25581. const images = {};
  25582. let loader;
  25583. function loadImage(url) {
  25584. scope.manager.itemStart(url);
  25585. return loader.load(url, function () {
  25586. scope.manager.itemEnd(url);
  25587. }, undefined, function () {
  25588. scope.manager.itemError(url);
  25589. scope.manager.itemEnd(url);
  25590. });
  25591. }
  25592. function deserializeImage(image) {
  25593. if (typeof image === 'string') {
  25594. const url = image;
  25595. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test(url) ? url : scope.resourcePath + url;
  25596. return loadImage(path);
  25597. } else {
  25598. if (image.data) {
  25599. return {
  25600. data: getTypedArray(image.type, image.data),
  25601. width: image.width,
  25602. height: image.height
  25603. };
  25604. } else {
  25605. return null;
  25606. }
  25607. }
  25608. }
  25609. if (json !== undefined && json.length > 0) {
  25610. const manager = new LoadingManager(onLoad);
  25611. loader = new ImageLoader(manager);
  25612. loader.setCrossOrigin(this.crossOrigin);
  25613. for (let i = 0, il = json.length; i < il; i++) {
  25614. const image = json[i];
  25615. const url = image.url;
  25616. if (Array.isArray(url)) {
  25617. // load array of images e.g CubeTexture
  25618. const imageArray = [];
  25619. for (let j = 0, jl = url.length; j < jl; j++) {
  25620. const currentUrl = url[j];
  25621. const deserializedImage = deserializeImage(currentUrl);
  25622. if (deserializedImage !== null) {
  25623. if (deserializedImage instanceof HTMLImageElement) {
  25624. imageArray.push(deserializedImage);
  25625. } else {
  25626. // special case: handle array of data textures for cube textures
  25627. imageArray.push(new DataTexture(deserializedImage.data, deserializedImage.width, deserializedImage.height));
  25628. }
  25629. }
  25630. }
  25631. images[image.uuid] = new Source(imageArray);
  25632. } else {
  25633. // load single image
  25634. const deserializedImage = deserializeImage(image.url);
  25635. images[image.uuid] = new Source(deserializedImage);
  25636. }
  25637. }
  25638. }
  25639. return images;
  25640. }
  25641. async parseImagesAsync(json) {
  25642. const scope = this;
  25643. const images = {};
  25644. let loader;
  25645. async function deserializeImage(image) {
  25646. if (typeof image === 'string') {
  25647. const url = image;
  25648. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test(url) ? url : scope.resourcePath + url;
  25649. return await loader.loadAsync(path);
  25650. } else {
  25651. if (image.data) {
  25652. return {
  25653. data: getTypedArray(image.type, image.data),
  25654. width: image.width,
  25655. height: image.height
  25656. };
  25657. } else {
  25658. return null;
  25659. }
  25660. }
  25661. }
  25662. if (json !== undefined && json.length > 0) {
  25663. loader = new ImageLoader(this.manager);
  25664. loader.setCrossOrigin(this.crossOrigin);
  25665. for (let i = 0, il = json.length; i < il; i++) {
  25666. const image = json[i];
  25667. const url = image.url;
  25668. if (Array.isArray(url)) {
  25669. // load array of images e.g CubeTexture
  25670. const imageArray = [];
  25671. for (let j = 0, jl = url.length; j < jl; j++) {
  25672. const currentUrl = url[j];
  25673. const deserializedImage = await deserializeImage(currentUrl);
  25674. if (deserializedImage !== null) {
  25675. if (deserializedImage instanceof HTMLImageElement) {
  25676. imageArray.push(deserializedImage);
  25677. } else {
  25678. // special case: handle array of data textures for cube textures
  25679. imageArray.push(new DataTexture(deserializedImage.data, deserializedImage.width, deserializedImage.height));
  25680. }
  25681. }
  25682. }
  25683. images[image.uuid] = new Source(imageArray);
  25684. } else {
  25685. // load single image
  25686. const deserializedImage = await deserializeImage(image.url);
  25687. images[image.uuid] = new Source(deserializedImage);
  25688. }
  25689. }
  25690. }
  25691. return images;
  25692. }
  25693. parseTextures(json, images) {
  25694. function parseConstant(value, type) {
  25695. if (typeof value === 'number') return value;
  25696. console.warn('THREE.ObjectLoader.parseTexture: Constant should be in numeric form.', value);
  25697. return type[value];
  25698. }
  25699. const textures = {};
  25700. if (json !== undefined) {
  25701. for (let i = 0, l = json.length; i < l; i++) {
  25702. const data = json[i];
  25703. if (data.image === undefined) {
  25704. console.warn('THREE.ObjectLoader: No "image" specified for', data.uuid);
  25705. }
  25706. if (images[data.image] === undefined) {
  25707. console.warn('THREE.ObjectLoader: Undefined image', data.image);
  25708. }
  25709. const source = images[data.image];
  25710. const image = source.data;
  25711. let texture;
  25712. if (Array.isArray(image)) {
  25713. texture = new CubeTexture();
  25714. if (image.length === 6) texture.needsUpdate = true;
  25715. } else {
  25716. if (image && image.data) {
  25717. texture = new DataTexture();
  25718. } else {
  25719. texture = new Texture();
  25720. }
  25721. if (image) texture.needsUpdate = true; // textures can have undefined image data
  25722. }
  25723. texture.source = source;
  25724. texture.uuid = data.uuid;
  25725. if (data.name !== undefined) texture.name = data.name;
  25726. if (data.mapping !== undefined) texture.mapping = parseConstant(data.mapping, TEXTURE_MAPPING);
  25727. if (data.offset !== undefined) texture.offset.fromArray(data.offset);
  25728. if (data.repeat !== undefined) texture.repeat.fromArray(data.repeat);
  25729. if (data.center !== undefined) texture.center.fromArray(data.center);
  25730. if (data.rotation !== undefined) texture.rotation = data.rotation;
  25731. if (data.wrap !== undefined) {
  25732. texture.wrapS = parseConstant(data.wrap[0], TEXTURE_WRAPPING);
  25733. texture.wrapT = parseConstant(data.wrap[1], TEXTURE_WRAPPING);
  25734. }
  25735. if (data.format !== undefined) texture.format = data.format;
  25736. if (data.type !== undefined) texture.type = data.type;
  25737. if (data.encoding !== undefined) texture.encoding = data.encoding;
  25738. if (data.minFilter !== undefined) texture.minFilter = parseConstant(data.minFilter, TEXTURE_FILTER);
  25739. if (data.magFilter !== undefined) texture.magFilter = parseConstant(data.magFilter, TEXTURE_FILTER);
  25740. if (data.anisotropy !== undefined) texture.anisotropy = data.anisotropy;
  25741. if (data.flipY !== undefined) texture.flipY = data.flipY;
  25742. if (data.generateMipmaps !== undefined) texture.generateMipmaps = data.generateMipmaps;
  25743. if (data.premultiplyAlpha !== undefined) texture.premultiplyAlpha = data.premultiplyAlpha;
  25744. if (data.unpackAlignment !== undefined) texture.unpackAlignment = data.unpackAlignment;
  25745. if (data.userData !== undefined) texture.userData = data.userData;
  25746. textures[data.uuid] = texture;
  25747. }
  25748. }
  25749. return textures;
  25750. }
  25751. parseObject(data, geometries, materials, textures, animations) {
  25752. let object;
  25753. function getGeometry(name) {
  25754. if (geometries[name] === undefined) {
  25755. console.warn('THREE.ObjectLoader: Undefined geometry', name);
  25756. }
  25757. return geometries[name];
  25758. }
  25759. function getMaterial(name) {
  25760. if (name === undefined) return undefined;
  25761. if (Array.isArray(name)) {
  25762. const array = [];
  25763. for (let i = 0, l = name.length; i < l; i++) {
  25764. const uuid = name[i];
  25765. if (materials[uuid] === undefined) {
  25766. console.warn('THREE.ObjectLoader: Undefined material', uuid);
  25767. }
  25768. array.push(materials[uuid]);
  25769. }
  25770. return array;
  25771. }
  25772. if (materials[name] === undefined) {
  25773. console.warn('THREE.ObjectLoader: Undefined material', name);
  25774. }
  25775. return materials[name];
  25776. }
  25777. function getTexture(uuid) {
  25778. if (textures[uuid] === undefined) {
  25779. console.warn('THREE.ObjectLoader: Undefined texture', uuid);
  25780. }
  25781. return textures[uuid];
  25782. }
  25783. let geometry, material;
  25784. switch (data.type) {
  25785. case 'Scene':
  25786. object = new Scene();
  25787. if (data.background !== undefined) {
  25788. if (Number.isInteger(data.background)) {
  25789. object.background = new Color(data.background);
  25790. } else {
  25791. object.background = getTexture(data.background);
  25792. }
  25793. }
  25794. if (data.environment !== undefined) {
  25795. object.environment = getTexture(data.environment);
  25796. }
  25797. if (data.fog !== undefined) {
  25798. if (data.fog.type === 'Fog') {
  25799. object.fog = new Fog(data.fog.color, data.fog.near, data.fog.far);
  25800. } else if (data.fog.type === 'FogExp2') {
  25801. object.fog = new FogExp2(data.fog.color, data.fog.density);
  25802. }
  25803. }
  25804. if (data.backgroundBlurriness !== undefined) object.backgroundBlurriness = data.backgroundBlurriness;
  25805. break;
  25806. case 'PerspectiveCamera':
  25807. object = new PerspectiveCamera(data.fov, data.aspect, data.near, data.far);
  25808. if (data.focus !== undefined) object.focus = data.focus;
  25809. if (data.zoom !== undefined) object.zoom = data.zoom;
  25810. if (data.filmGauge !== undefined) object.filmGauge = data.filmGauge;
  25811. if (data.filmOffset !== undefined) object.filmOffset = data.filmOffset;
  25812. if (data.view !== undefined) object.view = Object.assign({}, data.view);
  25813. break;
  25814. case 'OrthographicCamera':
  25815. object = new OrthographicCamera(data.left, data.right, data.top, data.bottom, data.near, data.far);
  25816. if (data.zoom !== undefined) object.zoom = data.zoom;
  25817. if (data.view !== undefined) object.view = Object.assign({}, data.view);
  25818. break;
  25819. case 'AmbientLight':
  25820. object = new AmbientLight(data.color, data.intensity);
  25821. break;
  25822. case 'DirectionalLight':
  25823. object = new DirectionalLight(data.color, data.intensity);
  25824. break;
  25825. case 'PointLight':
  25826. object = new PointLight(data.color, data.intensity, data.distance, data.decay);
  25827. break;
  25828. case 'RectAreaLight':
  25829. object = new RectAreaLight(data.color, data.intensity, data.width, data.height);
  25830. break;
  25831. case 'SpotLight':
  25832. object = new SpotLight(data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay);
  25833. break;
  25834. case 'HemisphereLight':
  25835. object = new HemisphereLight(data.color, data.groundColor, data.intensity);
  25836. break;
  25837. case 'LightProbe':
  25838. object = new LightProbe().fromJSON(data);
  25839. break;
  25840. case 'SkinnedMesh':
  25841. geometry = getGeometry(data.geometry);
  25842. material = getMaterial(data.material);
  25843. object = new SkinnedMesh(geometry, material);
  25844. if (data.bindMode !== undefined) object.bindMode = data.bindMode;
  25845. if (data.bindMatrix !== undefined) object.bindMatrix.fromArray(data.bindMatrix);
  25846. if (data.skeleton !== undefined) object.skeleton = data.skeleton;
  25847. break;
  25848. case 'Mesh':
  25849. geometry = getGeometry(data.geometry);
  25850. material = getMaterial(data.material);
  25851. object = new Mesh(geometry, material);
  25852. break;
  25853. case 'InstancedMesh':
  25854. geometry = getGeometry(data.geometry);
  25855. material = getMaterial(data.material);
  25856. const count = data.count;
  25857. const instanceMatrix = data.instanceMatrix;
  25858. const instanceColor = data.instanceColor;
  25859. object = new InstancedMesh(geometry, material, count);
  25860. object.instanceMatrix = new InstancedBufferAttribute(new Float32Array(instanceMatrix.array), 16);
  25861. if (instanceColor !== undefined) object.instanceColor = new InstancedBufferAttribute(new Float32Array(instanceColor.array), instanceColor.itemSize);
  25862. break;
  25863. case 'LOD':
  25864. object = new LOD();
  25865. break;
  25866. case 'Line':
  25867. object = new Line(getGeometry(data.geometry), getMaterial(data.material));
  25868. break;
  25869. case 'LineLoop':
  25870. object = new LineLoop(getGeometry(data.geometry), getMaterial(data.material));
  25871. break;
  25872. case 'LineSegments':
  25873. object = new LineSegments(getGeometry(data.geometry), getMaterial(data.material));
  25874. break;
  25875. case 'PointCloud':
  25876. case 'Points':
  25877. object = new Points(getGeometry(data.geometry), getMaterial(data.material));
  25878. break;
  25879. case 'Sprite':
  25880. object = new Sprite(getMaterial(data.material));
  25881. break;
  25882. case 'Group':
  25883. object = new Group();
  25884. break;
  25885. case 'Bone':
  25886. object = new Bone();
  25887. break;
  25888. default:
  25889. object = new Object3D();
  25890. }
  25891. object.uuid = data.uuid;
  25892. if (data.name !== undefined) object.name = data.name;
  25893. if (data.matrix !== undefined) {
  25894. object.matrix.fromArray(data.matrix);
  25895. if (data.matrixAutoUpdate !== undefined) object.matrixAutoUpdate = data.matrixAutoUpdate;
  25896. if (object.matrixAutoUpdate) object.matrix.decompose(object.position, object.quaternion, object.scale);
  25897. } else {
  25898. if (data.position !== undefined) object.position.fromArray(data.position);
  25899. if (data.rotation !== undefined) object.rotation.fromArray(data.rotation);
  25900. if (data.quaternion !== undefined) object.quaternion.fromArray(data.quaternion);
  25901. if (data.scale !== undefined) object.scale.fromArray(data.scale);
  25902. }
  25903. if (data.castShadow !== undefined) object.castShadow = data.castShadow;
  25904. if (data.receiveShadow !== undefined) object.receiveShadow = data.receiveShadow;
  25905. if (data.shadow) {
  25906. if (data.shadow.bias !== undefined) object.shadow.bias = data.shadow.bias;
  25907. if (data.shadow.normalBias !== undefined) object.shadow.normalBias = data.shadow.normalBias;
  25908. if (data.shadow.radius !== undefined) object.shadow.radius = data.shadow.radius;
  25909. if (data.shadow.mapSize !== undefined) object.shadow.mapSize.fromArray(data.shadow.mapSize);
  25910. if (data.shadow.camera !== undefined) object.shadow.camera = this.parseObject(data.shadow.camera);
  25911. }
  25912. if (data.visible !== undefined) object.visible = data.visible;
  25913. if (data.frustumCulled !== undefined) object.frustumCulled = data.frustumCulled;
  25914. if (data.renderOrder !== undefined) object.renderOrder = data.renderOrder;
  25915. if (data.userData !== undefined) object.userData = data.userData;
  25916. if (data.layers !== undefined) object.layers.mask = data.layers;
  25917. if (data.children !== undefined) {
  25918. const children = data.children;
  25919. for (let i = 0; i < children.length; i++) {
  25920. object.add(this.parseObject(children[i], geometries, materials, textures, animations));
  25921. }
  25922. }
  25923. if (data.animations !== undefined) {
  25924. const objectAnimations = data.animations;
  25925. for (let i = 0; i < objectAnimations.length; i++) {
  25926. const uuid = objectAnimations[i];
  25927. object.animations.push(animations[uuid]);
  25928. }
  25929. }
  25930. if (data.type === 'LOD') {
  25931. if (data.autoUpdate !== undefined) object.autoUpdate = data.autoUpdate;
  25932. const levels = data.levels;
  25933. for (let l = 0; l < levels.length; l++) {
  25934. const level = levels[l];
  25935. const child = object.getObjectByProperty('uuid', level.object);
  25936. if (child !== undefined) {
  25937. object.addLevel(child, level.distance, level.hysteresis);
  25938. }
  25939. }
  25940. }
  25941. return object;
  25942. }
  25943. bindSkeletons(object, skeletons) {
  25944. if (Object.keys(skeletons).length === 0) return;
  25945. object.traverse(function (child) {
  25946. if (child.isSkinnedMesh === true && child.skeleton !== undefined) {
  25947. const skeleton = skeletons[child.skeleton];
  25948. if (skeleton === undefined) {
  25949. console.warn('THREE.ObjectLoader: No skeleton found with UUID:', child.skeleton);
  25950. } else {
  25951. child.bind(skeleton, child.bindMatrix);
  25952. }
  25953. }
  25954. });
  25955. }
  25956. }
  25957. const TEXTURE_MAPPING = {
  25958. UVMapping: UVMapping,
  25959. CubeReflectionMapping: CubeReflectionMapping,
  25960. CubeRefractionMapping: CubeRefractionMapping,
  25961. EquirectangularReflectionMapping: EquirectangularReflectionMapping,
  25962. EquirectangularRefractionMapping: EquirectangularRefractionMapping,
  25963. CubeUVReflectionMapping: CubeUVReflectionMapping
  25964. };
  25965. const TEXTURE_WRAPPING = {
  25966. RepeatWrapping: RepeatWrapping,
  25967. ClampToEdgeWrapping: ClampToEdgeWrapping,
  25968. MirroredRepeatWrapping: MirroredRepeatWrapping
  25969. };
  25970. const TEXTURE_FILTER = {
  25971. NearestFilter: NearestFilter,
  25972. NearestMipmapNearestFilter: NearestMipmapNearestFilter,
  25973. NearestMipmapLinearFilter: NearestMipmapLinearFilter,
  25974. LinearFilter: LinearFilter,
  25975. LinearMipmapNearestFilter: LinearMipmapNearestFilter,
  25976. LinearMipmapLinearFilter: LinearMipmapLinearFilter
  25977. };
  25978. class ImageBitmapLoader extends Loader {
  25979. constructor(manager) {
  25980. super(manager);
  25981. this.isImageBitmapLoader = true;
  25982. if (typeof createImageBitmap === 'undefined') {
  25983. console.warn('THREE.ImageBitmapLoader: createImageBitmap() not supported.');
  25984. }
  25985. if (typeof fetch === 'undefined') {
  25986. console.warn('THREE.ImageBitmapLoader: fetch() not supported.');
  25987. }
  25988. this.options = {
  25989. premultiplyAlpha: 'none'
  25990. };
  25991. }
  25992. setOptions(options) {
  25993. this.options = options;
  25994. return this;
  25995. }
  25996. load(url, onLoad, onProgress, onError) {
  25997. if (url === undefined) url = '';
  25998. if (this.path !== undefined) url = this.path + url;
  25999. url = this.manager.resolveURL(url);
  26000. const scope = this;
  26001. const cached = Cache.get(url);
  26002. if (cached !== undefined) {
  26003. scope.manager.itemStart(url);
  26004. setTimeout(function () {
  26005. if (onLoad) onLoad(cached);
  26006. scope.manager.itemEnd(url);
  26007. }, 0);
  26008. return cached;
  26009. }
  26010. const fetchOptions = {};
  26011. fetchOptions.credentials = this.crossOrigin === 'anonymous' ? 'same-origin' : 'include';
  26012. fetchOptions.headers = this.requestHeader;
  26013. fetch(url, fetchOptions).then(function (res) {
  26014. return res.blob();
  26015. }).then(function (blob) {
  26016. return createImageBitmap(blob, Object.assign(scope.options, {
  26017. colorSpaceConversion: 'none'
  26018. }));
  26019. }).then(function (imageBitmap) {
  26020. Cache.add(url, imageBitmap);
  26021. if (onLoad) onLoad(imageBitmap);
  26022. scope.manager.itemEnd(url);
  26023. }).catch(function (e) {
  26024. if (onError) onError(e);
  26025. scope.manager.itemError(url);
  26026. scope.manager.itemEnd(url);
  26027. });
  26028. scope.manager.itemStart(url);
  26029. }
  26030. }
  26031. let _context;
  26032. class AudioContext {
  26033. static getContext() {
  26034. if (_context === undefined) {
  26035. _context = new (window.AudioContext || window.webkitAudioContext)();
  26036. }
  26037. return _context;
  26038. }
  26039. static setContext(value) {
  26040. _context = value;
  26041. }
  26042. }
  26043. class AudioLoader extends Loader {
  26044. constructor(manager) {
  26045. super(manager);
  26046. }
  26047. load(url, onLoad, onProgress, onError) {
  26048. const scope = this;
  26049. const loader = new FileLoader(this.manager);
  26050. loader.setResponseType('arraybuffer');
  26051. loader.setPath(this.path);
  26052. loader.setRequestHeader(this.requestHeader);
  26053. loader.setWithCredentials(this.withCredentials);
  26054. loader.load(url, function (buffer) {
  26055. try {
  26056. // Create a copy of the buffer. The `decodeAudioData` method
  26057. // detaches the buffer when complete, preventing reuse.
  26058. const bufferCopy = buffer.slice(0);
  26059. const context = AudioContext.getContext();
  26060. context.decodeAudioData(bufferCopy, function (audioBuffer) {
  26061. onLoad(audioBuffer);
  26062. });
  26063. } catch (e) {
  26064. if (onError) {
  26065. onError(e);
  26066. } else {
  26067. console.error(e);
  26068. }
  26069. scope.manager.itemError(url);
  26070. }
  26071. }, onProgress, onError);
  26072. }
  26073. }
  26074. class HemisphereLightProbe extends LightProbe {
  26075. constructor(skyColor, groundColor, intensity = 1) {
  26076. super(undefined, intensity);
  26077. this.isHemisphereLightProbe = true;
  26078. const color1 = new Color().set(skyColor);
  26079. const color2 = new Color().set(groundColor);
  26080. const sky = new Vector3(color1.r, color1.g, color1.b);
  26081. const ground = new Vector3(color2.r, color2.g, color2.b);
  26082. // without extra factor of PI in the shader, should = 1 / Math.sqrt( Math.PI );
  26083. const c0 = Math.sqrt(Math.PI);
  26084. const c1 = c0 * Math.sqrt(0.75);
  26085. this.sh.coefficients[0].copy(sky).add(ground).multiplyScalar(c0);
  26086. this.sh.coefficients[1].copy(sky).sub(ground).multiplyScalar(c1);
  26087. }
  26088. }
  26089. class AmbientLightProbe extends LightProbe {
  26090. constructor(color, intensity = 1) {
  26091. super(undefined, intensity);
  26092. this.isAmbientLightProbe = true;
  26093. const color1 = new Color().set(color);
  26094. // without extra factor of PI in the shader, would be 2 / Math.sqrt( Math.PI );
  26095. this.sh.coefficients[0].set(color1.r, color1.g, color1.b).multiplyScalar(2 * Math.sqrt(Math.PI));
  26096. }
  26097. }
  26098. const _eyeRight = /*@__PURE__*/new Matrix4();
  26099. const _eyeLeft = /*@__PURE__*/new Matrix4();
  26100. const _projectionMatrix = /*@__PURE__*/new Matrix4();
  26101. class StereoCamera {
  26102. constructor() {
  26103. this.type = 'StereoCamera';
  26104. this.aspect = 1;
  26105. this.eyeSep = 0.064;
  26106. this.cameraL = new PerspectiveCamera();
  26107. this.cameraL.layers.enable(1);
  26108. this.cameraL.matrixAutoUpdate = false;
  26109. this.cameraR = new PerspectiveCamera();
  26110. this.cameraR.layers.enable(2);
  26111. this.cameraR.matrixAutoUpdate = false;
  26112. this._cache = {
  26113. focus: null,
  26114. fov: null,
  26115. aspect: null,
  26116. near: null,
  26117. far: null,
  26118. zoom: null,
  26119. eyeSep: null
  26120. };
  26121. }
  26122. update(camera) {
  26123. const cache = this._cache;
  26124. 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;
  26125. if (needsUpdate) {
  26126. cache.focus = camera.focus;
  26127. cache.fov = camera.fov;
  26128. cache.aspect = camera.aspect * this.aspect;
  26129. cache.near = camera.near;
  26130. cache.far = camera.far;
  26131. cache.zoom = camera.zoom;
  26132. cache.eyeSep = this.eyeSep;
  26133. // Off-axis stereoscopic effect based on
  26134. // http://paulbourke.net/stereographics/stereorender/
  26135. _projectionMatrix.copy(camera.projectionMatrix);
  26136. const eyeSepHalf = cache.eyeSep / 2;
  26137. const eyeSepOnProjection = eyeSepHalf * cache.near / cache.focus;
  26138. const ymax = cache.near * Math.tan(DEG2RAD * cache.fov * 0.5) / cache.zoom;
  26139. let xmin, xmax;
  26140. // translate xOffset
  26141. _eyeLeft.elements[12] = -eyeSepHalf;
  26142. _eyeRight.elements[12] = eyeSepHalf;
  26143. // for left eye
  26144. xmin = -ymax * cache.aspect + eyeSepOnProjection;
  26145. xmax = ymax * cache.aspect + eyeSepOnProjection;
  26146. _projectionMatrix.elements[0] = 2 * cache.near / (xmax - xmin);
  26147. _projectionMatrix.elements[8] = (xmax + xmin) / (xmax - xmin);
  26148. this.cameraL.projectionMatrix.copy(_projectionMatrix);
  26149. // for right eye
  26150. xmin = -ymax * cache.aspect - eyeSepOnProjection;
  26151. xmax = ymax * cache.aspect - eyeSepOnProjection;
  26152. _projectionMatrix.elements[0] = 2 * cache.near / (xmax - xmin);
  26153. _projectionMatrix.elements[8] = (xmax + xmin) / (xmax - xmin);
  26154. this.cameraR.projectionMatrix.copy(_projectionMatrix);
  26155. }
  26156. this.cameraL.matrixWorld.copy(camera.matrixWorld).multiply(_eyeLeft);
  26157. this.cameraR.matrixWorld.copy(camera.matrixWorld).multiply(_eyeRight);
  26158. }
  26159. }
  26160. class Clock {
  26161. constructor(autoStart = true) {
  26162. this.autoStart = autoStart;
  26163. this.startTime = 0;
  26164. this.oldTime = 0;
  26165. this.elapsedTime = 0;
  26166. this.running = false;
  26167. }
  26168. start() {
  26169. this.startTime = now();
  26170. this.oldTime = this.startTime;
  26171. this.elapsedTime = 0;
  26172. this.running = true;
  26173. }
  26174. stop() {
  26175. this.getElapsedTime();
  26176. this.running = false;
  26177. this.autoStart = false;
  26178. }
  26179. getElapsedTime() {
  26180. this.getDelta();
  26181. return this.elapsedTime;
  26182. }
  26183. getDelta() {
  26184. let diff = 0;
  26185. if (this.autoStart && !this.running) {
  26186. this.start();
  26187. return 0;
  26188. }
  26189. if (this.running) {
  26190. const newTime = now();
  26191. diff = (newTime - this.oldTime) / 1000;
  26192. this.oldTime = newTime;
  26193. this.elapsedTime += diff;
  26194. }
  26195. return diff;
  26196. }
  26197. }
  26198. function now() {
  26199. return (typeof performance === 'undefined' ? Date : performance).now(); // see #10732
  26200. }
  26201. const _position$1 = /*@__PURE__*/new Vector3();
  26202. const _quaternion$1 = /*@__PURE__*/new Quaternion();
  26203. const _scale$1 = /*@__PURE__*/new Vector3();
  26204. const _orientation$1 = /*@__PURE__*/new Vector3();
  26205. class AudioListener extends Object3D {
  26206. constructor() {
  26207. super();
  26208. this.type = 'AudioListener';
  26209. this.context = AudioContext.getContext();
  26210. this.gain = this.context.createGain();
  26211. this.gain.connect(this.context.destination);
  26212. this.filter = null;
  26213. this.timeDelta = 0;
  26214. // private
  26215. this._clock = new Clock();
  26216. }
  26217. getInput() {
  26218. return this.gain;
  26219. }
  26220. removeFilter() {
  26221. if (this.filter !== null) {
  26222. this.gain.disconnect(this.filter);
  26223. this.filter.disconnect(this.context.destination);
  26224. this.gain.connect(this.context.destination);
  26225. this.filter = null;
  26226. }
  26227. return this;
  26228. }
  26229. getFilter() {
  26230. return this.filter;
  26231. }
  26232. setFilter(value) {
  26233. if (this.filter !== null) {
  26234. this.gain.disconnect(this.filter);
  26235. this.filter.disconnect(this.context.destination);
  26236. } else {
  26237. this.gain.disconnect(this.context.destination);
  26238. }
  26239. this.filter = value;
  26240. this.gain.connect(this.filter);
  26241. this.filter.connect(this.context.destination);
  26242. return this;
  26243. }
  26244. getMasterVolume() {
  26245. return this.gain.gain.value;
  26246. }
  26247. setMasterVolume(value) {
  26248. this.gain.gain.setTargetAtTime(value, this.context.currentTime, 0.01);
  26249. return this;
  26250. }
  26251. updateMatrixWorld(force) {
  26252. super.updateMatrixWorld(force);
  26253. const listener = this.context.listener;
  26254. const up = this.up;
  26255. this.timeDelta = this._clock.getDelta();
  26256. this.matrixWorld.decompose(_position$1, _quaternion$1, _scale$1);
  26257. _orientation$1.set(0, 0, -1).applyQuaternion(_quaternion$1);
  26258. if (listener.positionX) {
  26259. // code path for Chrome (see #14393)
  26260. const endTime = this.context.currentTime + this.timeDelta;
  26261. listener.positionX.linearRampToValueAtTime(_position$1.x, endTime);
  26262. listener.positionY.linearRampToValueAtTime(_position$1.y, endTime);
  26263. listener.positionZ.linearRampToValueAtTime(_position$1.z, endTime);
  26264. listener.forwardX.linearRampToValueAtTime(_orientation$1.x, endTime);
  26265. listener.forwardY.linearRampToValueAtTime(_orientation$1.y, endTime);
  26266. listener.forwardZ.linearRampToValueAtTime(_orientation$1.z, endTime);
  26267. listener.upX.linearRampToValueAtTime(up.x, endTime);
  26268. listener.upY.linearRampToValueAtTime(up.y, endTime);
  26269. listener.upZ.linearRampToValueAtTime(up.z, endTime);
  26270. } else {
  26271. listener.setPosition(_position$1.x, _position$1.y, _position$1.z);
  26272. listener.setOrientation(_orientation$1.x, _orientation$1.y, _orientation$1.z, up.x, up.y, up.z);
  26273. }
  26274. }
  26275. }
  26276. class Audio extends Object3D {
  26277. constructor(listener) {
  26278. super();
  26279. this.type = 'Audio';
  26280. this.listener = listener;
  26281. this.context = listener.context;
  26282. this.gain = this.context.createGain();
  26283. this.gain.connect(listener.getInput());
  26284. this.autoplay = false;
  26285. this.buffer = null;
  26286. this.detune = 0;
  26287. this.loop = false;
  26288. this.loopStart = 0;
  26289. this.loopEnd = 0;
  26290. this.offset = 0;
  26291. this.duration = undefined;
  26292. this.playbackRate = 1;
  26293. this.isPlaying = false;
  26294. this.hasPlaybackControl = true;
  26295. this.source = null;
  26296. this.sourceType = 'empty';
  26297. this._startedAt = 0;
  26298. this._progress = 0;
  26299. this._connected = false;
  26300. this.filters = [];
  26301. }
  26302. getOutput() {
  26303. return this.gain;
  26304. }
  26305. setNodeSource(audioNode) {
  26306. this.hasPlaybackControl = false;
  26307. this.sourceType = 'audioNode';
  26308. this.source = audioNode;
  26309. this.connect();
  26310. return this;
  26311. }
  26312. setMediaElementSource(mediaElement) {
  26313. this.hasPlaybackControl = false;
  26314. this.sourceType = 'mediaNode';
  26315. this.source = this.context.createMediaElementSource(mediaElement);
  26316. this.connect();
  26317. return this;
  26318. }
  26319. setMediaStreamSource(mediaStream) {
  26320. this.hasPlaybackControl = false;
  26321. this.sourceType = 'mediaStreamNode';
  26322. this.source = this.context.createMediaStreamSource(mediaStream);
  26323. this.connect();
  26324. return this;
  26325. }
  26326. setBuffer(audioBuffer) {
  26327. this.buffer = audioBuffer;
  26328. this.sourceType = 'buffer';
  26329. if (this.autoplay) this.play();
  26330. return this;
  26331. }
  26332. play(delay = 0) {
  26333. if (this.isPlaying === true) {
  26334. console.warn('THREE.Audio: Audio is already playing.');
  26335. return;
  26336. }
  26337. if (this.hasPlaybackControl === false) {
  26338. console.warn('THREE.Audio: this Audio has no playback control.');
  26339. return;
  26340. }
  26341. this._startedAt = this.context.currentTime + delay;
  26342. const source = this.context.createBufferSource();
  26343. source.buffer = this.buffer;
  26344. source.loop = this.loop;
  26345. source.loopStart = this.loopStart;
  26346. source.loopEnd = this.loopEnd;
  26347. source.onended = this.onEnded.bind(this);
  26348. source.start(this._startedAt, this._progress + this.offset, this.duration);
  26349. this.isPlaying = true;
  26350. this.source = source;
  26351. this.setDetune(this.detune);
  26352. this.setPlaybackRate(this.playbackRate);
  26353. return this.connect();
  26354. }
  26355. pause() {
  26356. if (this.hasPlaybackControl === false) {
  26357. console.warn('THREE.Audio: this Audio has no playback control.');
  26358. return;
  26359. }
  26360. if (this.isPlaying === true) {
  26361. // update current progress
  26362. this._progress += Math.max(this.context.currentTime - this._startedAt, 0) * this.playbackRate;
  26363. if (this.loop === true) {
  26364. // ensure _progress does not exceed duration with looped audios
  26365. this._progress = this._progress % (this.duration || this.buffer.duration);
  26366. }
  26367. this.source.stop();
  26368. this.source.onended = null;
  26369. this.isPlaying = false;
  26370. }
  26371. return this;
  26372. }
  26373. stop() {
  26374. if (this.hasPlaybackControl === false) {
  26375. console.warn('THREE.Audio: this Audio has no playback control.');
  26376. return;
  26377. }
  26378. this._progress = 0;
  26379. this.source.stop();
  26380. this.source.onended = null;
  26381. this.isPlaying = false;
  26382. return this;
  26383. }
  26384. connect() {
  26385. if (this.filters.length > 0) {
  26386. this.source.connect(this.filters[0]);
  26387. for (let i = 1, l = this.filters.length; i < l; i++) {
  26388. this.filters[i - 1].connect(this.filters[i]);
  26389. }
  26390. this.filters[this.filters.length - 1].connect(this.getOutput());
  26391. } else {
  26392. this.source.connect(this.getOutput());
  26393. }
  26394. this._connected = true;
  26395. return this;
  26396. }
  26397. disconnect() {
  26398. if (this.filters.length > 0) {
  26399. this.source.disconnect(this.filters[0]);
  26400. for (let i = 1, l = this.filters.length; i < l; i++) {
  26401. this.filters[i - 1].disconnect(this.filters[i]);
  26402. }
  26403. this.filters[this.filters.length - 1].disconnect(this.getOutput());
  26404. } else {
  26405. this.source.disconnect(this.getOutput());
  26406. }
  26407. this._connected = false;
  26408. return this;
  26409. }
  26410. getFilters() {
  26411. return this.filters;
  26412. }
  26413. setFilters(value) {
  26414. if (!value) value = [];
  26415. if (this._connected === true) {
  26416. this.disconnect();
  26417. this.filters = value.slice();
  26418. this.connect();
  26419. } else {
  26420. this.filters = value.slice();
  26421. }
  26422. return this;
  26423. }
  26424. setDetune(value) {
  26425. this.detune = value;
  26426. if (this.source.detune === undefined) return; // only set detune when available
  26427. if (this.isPlaying === true) {
  26428. this.source.detune.setTargetAtTime(this.detune, this.context.currentTime, 0.01);
  26429. }
  26430. return this;
  26431. }
  26432. getDetune() {
  26433. return this.detune;
  26434. }
  26435. getFilter() {
  26436. return this.getFilters()[0];
  26437. }
  26438. setFilter(filter) {
  26439. return this.setFilters(filter ? [filter] : []);
  26440. }
  26441. setPlaybackRate(value) {
  26442. if (this.hasPlaybackControl === false) {
  26443. console.warn('THREE.Audio: this Audio has no playback control.');
  26444. return;
  26445. }
  26446. this.playbackRate = value;
  26447. if (this.isPlaying === true) {
  26448. this.source.playbackRate.setTargetAtTime(this.playbackRate, this.context.currentTime, 0.01);
  26449. }
  26450. return this;
  26451. }
  26452. getPlaybackRate() {
  26453. return this.playbackRate;
  26454. }
  26455. onEnded() {
  26456. this.isPlaying = false;
  26457. }
  26458. getLoop() {
  26459. if (this.hasPlaybackControl === false) {
  26460. console.warn('THREE.Audio: this Audio has no playback control.');
  26461. return false;
  26462. }
  26463. return this.loop;
  26464. }
  26465. setLoop(value) {
  26466. if (this.hasPlaybackControl === false) {
  26467. console.warn('THREE.Audio: this Audio has no playback control.');
  26468. return;
  26469. }
  26470. this.loop = value;
  26471. if (this.isPlaying === true) {
  26472. this.source.loop = this.loop;
  26473. }
  26474. return this;
  26475. }
  26476. setLoopStart(value) {
  26477. this.loopStart = value;
  26478. return this;
  26479. }
  26480. setLoopEnd(value) {
  26481. this.loopEnd = value;
  26482. return this;
  26483. }
  26484. getVolume() {
  26485. return this.gain.gain.value;
  26486. }
  26487. setVolume(value) {
  26488. this.gain.gain.setTargetAtTime(value, this.context.currentTime, 0.01);
  26489. return this;
  26490. }
  26491. }
  26492. const _position = /*@__PURE__*/new Vector3();
  26493. const _quaternion = /*@__PURE__*/new Quaternion();
  26494. const _scale = /*@__PURE__*/new Vector3();
  26495. const _orientation = /*@__PURE__*/new Vector3();
  26496. class PositionalAudio extends Audio {
  26497. constructor(listener) {
  26498. super(listener);
  26499. this.panner = this.context.createPanner();
  26500. this.panner.panningModel = 'HRTF';
  26501. this.panner.connect(this.gain);
  26502. }
  26503. disconnect() {
  26504. super.disconnect();
  26505. this.panner.disconnect(this.gain);
  26506. }
  26507. getOutput() {
  26508. return this.panner;
  26509. }
  26510. getRefDistance() {
  26511. return this.panner.refDistance;
  26512. }
  26513. setRefDistance(value) {
  26514. this.panner.refDistance = value;
  26515. return this;
  26516. }
  26517. getRolloffFactor() {
  26518. return this.panner.rolloffFactor;
  26519. }
  26520. setRolloffFactor(value) {
  26521. this.panner.rolloffFactor = value;
  26522. return this;
  26523. }
  26524. getDistanceModel() {
  26525. return this.panner.distanceModel;
  26526. }
  26527. setDistanceModel(value) {
  26528. this.panner.distanceModel = value;
  26529. return this;
  26530. }
  26531. getMaxDistance() {
  26532. return this.panner.maxDistance;
  26533. }
  26534. setMaxDistance(value) {
  26535. this.panner.maxDistance = value;
  26536. return this;
  26537. }
  26538. setDirectionalCone(coneInnerAngle, coneOuterAngle, coneOuterGain) {
  26539. this.panner.coneInnerAngle = coneInnerAngle;
  26540. this.panner.coneOuterAngle = coneOuterAngle;
  26541. this.panner.coneOuterGain = coneOuterGain;
  26542. return this;
  26543. }
  26544. updateMatrixWorld(force) {
  26545. super.updateMatrixWorld(force);
  26546. if (this.hasPlaybackControl === true && this.isPlaying === false) return;
  26547. this.matrixWorld.decompose(_position, _quaternion, _scale);
  26548. _orientation.set(0, 0, 1).applyQuaternion(_quaternion);
  26549. const panner = this.panner;
  26550. if (panner.positionX) {
  26551. // code path for Chrome and Firefox (see #14393)
  26552. const endTime = this.context.currentTime + this.listener.timeDelta;
  26553. panner.positionX.linearRampToValueAtTime(_position.x, endTime);
  26554. panner.positionY.linearRampToValueAtTime(_position.y, endTime);
  26555. panner.positionZ.linearRampToValueAtTime(_position.z, endTime);
  26556. panner.orientationX.linearRampToValueAtTime(_orientation.x, endTime);
  26557. panner.orientationY.linearRampToValueAtTime(_orientation.y, endTime);
  26558. panner.orientationZ.linearRampToValueAtTime(_orientation.z, endTime);
  26559. } else {
  26560. panner.setPosition(_position.x, _position.y, _position.z);
  26561. panner.setOrientation(_orientation.x, _orientation.y, _orientation.z);
  26562. }
  26563. }
  26564. }
  26565. class AudioAnalyser {
  26566. constructor(audio, fftSize = 2048) {
  26567. this.analyser = audio.context.createAnalyser();
  26568. this.analyser.fftSize = fftSize;
  26569. this.data = new Uint8Array(this.analyser.frequencyBinCount);
  26570. audio.getOutput().connect(this.analyser);
  26571. }
  26572. getFrequencyData() {
  26573. this.analyser.getByteFrequencyData(this.data);
  26574. return this.data;
  26575. }
  26576. getAverageFrequency() {
  26577. let value = 0;
  26578. const data = this.getFrequencyData();
  26579. for (let i = 0; i < data.length; i++) {
  26580. value += data[i];
  26581. }
  26582. return value / data.length;
  26583. }
  26584. }
  26585. class PropertyMixer {
  26586. constructor(binding, typeName, valueSize) {
  26587. this.binding = binding;
  26588. this.valueSize = valueSize;
  26589. let mixFunction, mixFunctionAdditive, setIdentity;
  26590. // buffer layout: [ incoming | accu0 | accu1 | orig | addAccu | (optional work) ]
  26591. //
  26592. // interpolators can use .buffer as their .result
  26593. // the data then goes to 'incoming'
  26594. //
  26595. // 'accu0' and 'accu1' are used frame-interleaved for
  26596. // the cumulative result and are compared to detect
  26597. // changes
  26598. //
  26599. // 'orig' stores the original state of the property
  26600. //
  26601. // 'add' is used for additive cumulative results
  26602. //
  26603. // 'work' is optional and is only present for quaternion types. It is used
  26604. // to store intermediate quaternion multiplication results
  26605. switch (typeName) {
  26606. case 'quaternion':
  26607. mixFunction = this._slerp;
  26608. mixFunctionAdditive = this._slerpAdditive;
  26609. setIdentity = this._setAdditiveIdentityQuaternion;
  26610. this.buffer = new Float64Array(valueSize * 6);
  26611. this._workIndex = 5;
  26612. break;
  26613. case 'string':
  26614. case 'bool':
  26615. mixFunction = this._select;
  26616. // Use the regular mix function and for additive on these types,
  26617. // additive is not relevant for non-numeric types
  26618. mixFunctionAdditive = this._select;
  26619. setIdentity = this._setAdditiveIdentityOther;
  26620. this.buffer = new Array(valueSize * 5);
  26621. break;
  26622. default:
  26623. mixFunction = this._lerp;
  26624. mixFunctionAdditive = this._lerpAdditive;
  26625. setIdentity = this._setAdditiveIdentityNumeric;
  26626. this.buffer = new Float64Array(valueSize * 5);
  26627. }
  26628. this._mixBufferRegion = mixFunction;
  26629. this._mixBufferRegionAdditive = mixFunctionAdditive;
  26630. this._setIdentity = setIdentity;
  26631. this._origIndex = 3;
  26632. this._addIndex = 4;
  26633. this.cumulativeWeight = 0;
  26634. this.cumulativeWeightAdditive = 0;
  26635. this.useCount = 0;
  26636. this.referenceCount = 0;
  26637. }
  26638. // accumulate data in the 'incoming' region into 'accu<i>'
  26639. accumulate(accuIndex, weight) {
  26640. // note: happily accumulating nothing when weight = 0, the caller knows
  26641. // the weight and shouldn't have made the call in the first place
  26642. const buffer = this.buffer,
  26643. stride = this.valueSize,
  26644. offset = accuIndex * stride + stride;
  26645. let currentWeight = this.cumulativeWeight;
  26646. if (currentWeight === 0) {
  26647. // accuN := incoming * weight
  26648. for (let i = 0; i !== stride; ++i) {
  26649. buffer[offset + i] = buffer[i];
  26650. }
  26651. currentWeight = weight;
  26652. } else {
  26653. // accuN := accuN + incoming * weight
  26654. currentWeight += weight;
  26655. const mix = weight / currentWeight;
  26656. this._mixBufferRegion(buffer, offset, 0, mix, stride);
  26657. }
  26658. this.cumulativeWeight = currentWeight;
  26659. }
  26660. // accumulate data in the 'incoming' region into 'add'
  26661. accumulateAdditive(weight) {
  26662. const buffer = this.buffer,
  26663. stride = this.valueSize,
  26664. offset = stride * this._addIndex;
  26665. if (this.cumulativeWeightAdditive === 0) {
  26666. // add = identity
  26667. this._setIdentity();
  26668. }
  26669. // add := add + incoming * weight
  26670. this._mixBufferRegionAdditive(buffer, offset, 0, weight, stride);
  26671. this.cumulativeWeightAdditive += weight;
  26672. }
  26673. // apply the state of 'accu<i>' to the binding when accus differ
  26674. apply(accuIndex) {
  26675. const stride = this.valueSize,
  26676. buffer = this.buffer,
  26677. offset = accuIndex * stride + stride,
  26678. weight = this.cumulativeWeight,
  26679. weightAdditive = this.cumulativeWeightAdditive,
  26680. binding = this.binding;
  26681. this.cumulativeWeight = 0;
  26682. this.cumulativeWeightAdditive = 0;
  26683. if (weight < 1) {
  26684. // accuN := accuN + original * ( 1 - cumulativeWeight )
  26685. const originalValueOffset = stride * this._origIndex;
  26686. this._mixBufferRegion(buffer, offset, originalValueOffset, 1 - weight, stride);
  26687. }
  26688. if (weightAdditive > 0) {
  26689. // accuN := accuN + additive accuN
  26690. this._mixBufferRegionAdditive(buffer, offset, this._addIndex * stride, 1, stride);
  26691. }
  26692. for (let i = stride, e = stride + stride; i !== e; ++i) {
  26693. if (buffer[i] !== buffer[i + stride]) {
  26694. // value has changed -> update scene graph
  26695. binding.setValue(buffer, offset);
  26696. break;
  26697. }
  26698. }
  26699. }
  26700. // remember the state of the bound property and copy it to both accus
  26701. saveOriginalState() {
  26702. const binding = this.binding;
  26703. const buffer = this.buffer,
  26704. stride = this.valueSize,
  26705. originalValueOffset = stride * this._origIndex;
  26706. binding.getValue(buffer, originalValueOffset);
  26707. // accu[0..1] := orig -- initially detect changes against the original
  26708. for (let i = stride, e = originalValueOffset; i !== e; ++i) {
  26709. buffer[i] = buffer[originalValueOffset + i % stride];
  26710. }
  26711. // Add to identity for additive
  26712. this._setIdentity();
  26713. this.cumulativeWeight = 0;
  26714. this.cumulativeWeightAdditive = 0;
  26715. }
  26716. // apply the state previously taken via 'saveOriginalState' to the binding
  26717. restoreOriginalState() {
  26718. const originalValueOffset = this.valueSize * 3;
  26719. this.binding.setValue(this.buffer, originalValueOffset);
  26720. }
  26721. _setAdditiveIdentityNumeric() {
  26722. const startIndex = this._addIndex * this.valueSize;
  26723. const endIndex = startIndex + this.valueSize;
  26724. for (let i = startIndex; i < endIndex; i++) {
  26725. this.buffer[i] = 0;
  26726. }
  26727. }
  26728. _setAdditiveIdentityQuaternion() {
  26729. this._setAdditiveIdentityNumeric();
  26730. this.buffer[this._addIndex * this.valueSize + 3] = 1;
  26731. }
  26732. _setAdditiveIdentityOther() {
  26733. const startIndex = this._origIndex * this.valueSize;
  26734. const targetIndex = this._addIndex * this.valueSize;
  26735. for (let i = 0; i < this.valueSize; i++) {
  26736. this.buffer[targetIndex + i] = this.buffer[startIndex + i];
  26737. }
  26738. }
  26739. // mix functions
  26740. _select(buffer, dstOffset, srcOffset, t, stride) {
  26741. if (t >= 0.5) {
  26742. for (let i = 0; i !== stride; ++i) {
  26743. buffer[dstOffset + i] = buffer[srcOffset + i];
  26744. }
  26745. }
  26746. }
  26747. _slerp(buffer, dstOffset, srcOffset, t) {
  26748. Quaternion.slerpFlat(buffer, dstOffset, buffer, dstOffset, buffer, srcOffset, t);
  26749. }
  26750. _slerpAdditive(buffer, dstOffset, srcOffset, t, stride) {
  26751. const workOffset = this._workIndex * stride;
  26752. // Store result in intermediate buffer offset
  26753. Quaternion.multiplyQuaternionsFlat(buffer, workOffset, buffer, dstOffset, buffer, srcOffset);
  26754. // Slerp to the intermediate result
  26755. Quaternion.slerpFlat(buffer, dstOffset, buffer, dstOffset, buffer, workOffset, t);
  26756. }
  26757. _lerp(buffer, dstOffset, srcOffset, t, stride) {
  26758. const s = 1 - t;
  26759. for (let i = 0; i !== stride; ++i) {
  26760. const j = dstOffset + i;
  26761. buffer[j] = buffer[j] * s + buffer[srcOffset + i] * t;
  26762. }
  26763. }
  26764. _lerpAdditive(buffer, dstOffset, srcOffset, t, stride) {
  26765. for (let i = 0; i !== stride; ++i) {
  26766. const j = dstOffset + i;
  26767. buffer[j] = buffer[j] + buffer[srcOffset + i] * t;
  26768. }
  26769. }
  26770. }
  26771. // Characters [].:/ are reserved for track binding syntax.
  26772. const _RESERVED_CHARS_RE = '\\[\\]\\.:\\/';
  26773. const _reservedRe = new RegExp('[' + _RESERVED_CHARS_RE + ']', 'g');
  26774. // Attempts to allow node names from any language. ES5's `\w` regexp matches
  26775. // only latin characters, and the unicode \p{L} is not yet supported. So
  26776. // instead, we exclude reserved characters and match everything else.
  26777. const _wordChar = '[^' + _RESERVED_CHARS_RE + ']';
  26778. const _wordCharOrDot = '[^' + _RESERVED_CHARS_RE.replace('\\.', '') + ']';
  26779. // Parent directories, delimited by '/' or ':'. Currently unused, but must
  26780. // be matched to parse the rest of the track name.
  26781. const _directoryRe = /*@__PURE__*/ /((?:WC+[\/:])*)/.source.replace('WC', _wordChar);
  26782. // Target node. May contain word characters (a-zA-Z0-9_) and '.' or '-'.
  26783. const _nodeRe = /*@__PURE__*/ /(WCOD+)?/.source.replace('WCOD', _wordCharOrDot);
  26784. // Object on target node, and accessor. May not contain reserved
  26785. // characters. Accessor may contain any character except closing bracket.
  26786. const _objectRe = /*@__PURE__*/ /(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace('WC', _wordChar);
  26787. // Property and accessor. May not contain reserved characters. Accessor may
  26788. // contain any non-bracket characters.
  26789. const _propertyRe = /*@__PURE__*/ /\.(WC+)(?:\[(.+)\])?/.source.replace('WC', _wordChar);
  26790. const _trackRe = new RegExp('' + '^' + _directoryRe + _nodeRe + _objectRe + _propertyRe + '$');
  26791. const _supportedObjectNames = ['material', 'materials', 'bones', 'map'];
  26792. class Composite {
  26793. constructor(targetGroup, path, optionalParsedPath) {
  26794. const parsedPath = optionalParsedPath || PropertyBinding.parseTrackName(path);
  26795. this._targetGroup = targetGroup;
  26796. this._bindings = targetGroup.subscribe_(path, parsedPath);
  26797. }
  26798. getValue(array, offset) {
  26799. this.bind(); // bind all binding
  26800. const firstValidIndex = this._targetGroup.nCachedObjects_,
  26801. binding = this._bindings[firstValidIndex];
  26802. // and only call .getValue on the first
  26803. if (binding !== undefined) binding.getValue(array, offset);
  26804. }
  26805. setValue(array, offset) {
  26806. const bindings = this._bindings;
  26807. for (let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++i) {
  26808. bindings[i].setValue(array, offset);
  26809. }
  26810. }
  26811. bind() {
  26812. const bindings = this._bindings;
  26813. for (let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++i) {
  26814. bindings[i].bind();
  26815. }
  26816. }
  26817. unbind() {
  26818. const bindings = this._bindings;
  26819. for (let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++i) {
  26820. bindings[i].unbind();
  26821. }
  26822. }
  26823. }
  26824. // Note: This class uses a State pattern on a per-method basis:
  26825. // 'bind' sets 'this.getValue' / 'setValue' and shadows the
  26826. // prototype version of these methods with one that represents
  26827. // the bound state. When the property is not found, the methods
  26828. // become no-ops.
  26829. class PropertyBinding {
  26830. constructor(rootNode, path, parsedPath) {
  26831. this.path = path;
  26832. this.parsedPath = parsedPath || PropertyBinding.parseTrackName(path);
  26833. this.node = PropertyBinding.findNode(rootNode, this.parsedPath.nodeName) || rootNode;
  26834. this.rootNode = rootNode;
  26835. // initial state of these methods that calls 'bind'
  26836. this.getValue = this._getValue_unbound;
  26837. this.setValue = this._setValue_unbound;
  26838. }
  26839. static create(root, path, parsedPath) {
  26840. if (!(root && root.isAnimationObjectGroup)) {
  26841. return new PropertyBinding(root, path, parsedPath);
  26842. } else {
  26843. return new PropertyBinding.Composite(root, path, parsedPath);
  26844. }
  26845. }
  26846. /**
  26847. * Replaces spaces with underscores and removes unsupported characters from
  26848. * node names, to ensure compatibility with parseTrackName().
  26849. *
  26850. * @param {string} name Node name to be sanitized.
  26851. * @return {string}
  26852. */
  26853. static sanitizeNodeName(name) {
  26854. return name.replace(/\s/g, '_').replace(_reservedRe, '');
  26855. }
  26856. static parseTrackName(trackName) {
  26857. const matches = _trackRe.exec(trackName);
  26858. if (matches === null) {
  26859. throw new Error('PropertyBinding: Cannot parse trackName: ' + trackName);
  26860. }
  26861. const results = {
  26862. // directoryName: matches[ 1 ], // (tschw) currently unused
  26863. nodeName: matches[2],
  26864. objectName: matches[3],
  26865. objectIndex: matches[4],
  26866. propertyName: matches[5],
  26867. // required
  26868. propertyIndex: matches[6]
  26869. };
  26870. const lastDot = results.nodeName && results.nodeName.lastIndexOf('.');
  26871. if (lastDot !== undefined && lastDot !== -1) {
  26872. const objectName = results.nodeName.substring(lastDot + 1);
  26873. // Object names must be checked against an allowlist. Otherwise, there
  26874. // is no way to parse 'foo.bar.baz': 'baz' must be a property, but
  26875. // 'bar' could be the objectName, or part of a nodeName (which can
  26876. // include '.' characters).
  26877. if (_supportedObjectNames.indexOf(objectName) !== -1) {
  26878. results.nodeName = results.nodeName.substring(0, lastDot);
  26879. results.objectName = objectName;
  26880. }
  26881. }
  26882. if (results.propertyName === null || results.propertyName.length === 0) {
  26883. throw new Error('PropertyBinding: can not parse propertyName from trackName: ' + trackName);
  26884. }
  26885. return results;
  26886. }
  26887. static findNode(root, nodeName) {
  26888. if (nodeName === undefined || nodeName === '' || nodeName === '.' || nodeName === -1 || nodeName === root.name || nodeName === root.uuid) {
  26889. return root;
  26890. }
  26891. // search into skeleton bones.
  26892. if (root.skeleton) {
  26893. const bone = root.skeleton.getBoneByName(nodeName);
  26894. if (bone !== undefined) {
  26895. return bone;
  26896. }
  26897. }
  26898. // search into node subtree.
  26899. if (root.children) {
  26900. const searchNodeSubtree = function (children) {
  26901. for (let i = 0; i < children.length; i++) {
  26902. const childNode = children[i];
  26903. if (childNode.name === nodeName || childNode.uuid === nodeName) {
  26904. return childNode;
  26905. }
  26906. const result = searchNodeSubtree(childNode.children);
  26907. if (result) return result;
  26908. }
  26909. return null;
  26910. };
  26911. const subTreeNode = searchNodeSubtree(root.children);
  26912. if (subTreeNode) {
  26913. return subTreeNode;
  26914. }
  26915. }
  26916. return null;
  26917. }
  26918. // these are used to "bind" a nonexistent property
  26919. _getValue_unavailable() {}
  26920. _setValue_unavailable() {}
  26921. // Getters
  26922. _getValue_direct(buffer, offset) {
  26923. buffer[offset] = this.targetObject[this.propertyName];
  26924. }
  26925. _getValue_array(buffer, offset) {
  26926. const source = this.resolvedProperty;
  26927. for (let i = 0, n = source.length; i !== n; ++i) {
  26928. buffer[offset++] = source[i];
  26929. }
  26930. }
  26931. _getValue_arrayElement(buffer, offset) {
  26932. buffer[offset] = this.resolvedProperty[this.propertyIndex];
  26933. }
  26934. _getValue_toArray(buffer, offset) {
  26935. this.resolvedProperty.toArray(buffer, offset);
  26936. }
  26937. // Direct
  26938. _setValue_direct(buffer, offset) {
  26939. this.targetObject[this.propertyName] = buffer[offset];
  26940. }
  26941. _setValue_direct_setNeedsUpdate(buffer, offset) {
  26942. this.targetObject[this.propertyName] = buffer[offset];
  26943. this.targetObject.needsUpdate = true;
  26944. }
  26945. _setValue_direct_setMatrixWorldNeedsUpdate(buffer, offset) {
  26946. this.targetObject[this.propertyName] = buffer[offset];
  26947. this.targetObject.matrixWorldNeedsUpdate = true;
  26948. }
  26949. // EntireArray
  26950. _setValue_array(buffer, offset) {
  26951. const dest = this.resolvedProperty;
  26952. for (let i = 0, n = dest.length; i !== n; ++i) {
  26953. dest[i] = buffer[offset++];
  26954. }
  26955. }
  26956. _setValue_array_setNeedsUpdate(buffer, offset) {
  26957. const dest = this.resolvedProperty;
  26958. for (let i = 0, n = dest.length; i !== n; ++i) {
  26959. dest[i] = buffer[offset++];
  26960. }
  26961. this.targetObject.needsUpdate = true;
  26962. }
  26963. _setValue_array_setMatrixWorldNeedsUpdate(buffer, offset) {
  26964. const dest = this.resolvedProperty;
  26965. for (let i = 0, n = dest.length; i !== n; ++i) {
  26966. dest[i] = buffer[offset++];
  26967. }
  26968. this.targetObject.matrixWorldNeedsUpdate = true;
  26969. }
  26970. // ArrayElement
  26971. _setValue_arrayElement(buffer, offset) {
  26972. this.resolvedProperty[this.propertyIndex] = buffer[offset];
  26973. }
  26974. _setValue_arrayElement_setNeedsUpdate(buffer, offset) {
  26975. this.resolvedProperty[this.propertyIndex] = buffer[offset];
  26976. this.targetObject.needsUpdate = true;
  26977. }
  26978. _setValue_arrayElement_setMatrixWorldNeedsUpdate(buffer, offset) {
  26979. this.resolvedProperty[this.propertyIndex] = buffer[offset];
  26980. this.targetObject.matrixWorldNeedsUpdate = true;
  26981. }
  26982. // HasToFromArray
  26983. _setValue_fromArray(buffer, offset) {
  26984. this.resolvedProperty.fromArray(buffer, offset);
  26985. }
  26986. _setValue_fromArray_setNeedsUpdate(buffer, offset) {
  26987. this.resolvedProperty.fromArray(buffer, offset);
  26988. this.targetObject.needsUpdate = true;
  26989. }
  26990. _setValue_fromArray_setMatrixWorldNeedsUpdate(buffer, offset) {
  26991. this.resolvedProperty.fromArray(buffer, offset);
  26992. this.targetObject.matrixWorldNeedsUpdate = true;
  26993. }
  26994. _getValue_unbound(targetArray, offset) {
  26995. this.bind();
  26996. this.getValue(targetArray, offset);
  26997. }
  26998. _setValue_unbound(sourceArray, offset) {
  26999. this.bind();
  27000. this.setValue(sourceArray, offset);
  27001. }
  27002. // create getter / setter pair for a property in the scene graph
  27003. bind() {
  27004. let targetObject = this.node;
  27005. const parsedPath = this.parsedPath;
  27006. const objectName = parsedPath.objectName;
  27007. const propertyName = parsedPath.propertyName;
  27008. let propertyIndex = parsedPath.propertyIndex;
  27009. if (!targetObject) {
  27010. targetObject = PropertyBinding.findNode(this.rootNode, parsedPath.nodeName) || this.rootNode;
  27011. this.node = targetObject;
  27012. }
  27013. // set fail state so we can just 'return' on error
  27014. this.getValue = this._getValue_unavailable;
  27015. this.setValue = this._setValue_unavailable;
  27016. // ensure there is a value node
  27017. if (!targetObject) {
  27018. console.error('THREE.PropertyBinding: Trying to update node for track: ' + this.path + ' but it wasn\'t found.');
  27019. return;
  27020. }
  27021. if (objectName) {
  27022. let objectIndex = parsedPath.objectIndex;
  27023. // special cases were we need to reach deeper into the hierarchy to get the face materials....
  27024. switch (objectName) {
  27025. case 'materials':
  27026. if (!targetObject.material) {
  27027. console.error('THREE.PropertyBinding: Can not bind to material as node does not have a material.', this);
  27028. return;
  27029. }
  27030. if (!targetObject.material.materials) {
  27031. console.error('THREE.PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.', this);
  27032. return;
  27033. }
  27034. targetObject = targetObject.material.materials;
  27035. break;
  27036. case 'bones':
  27037. if (!targetObject.skeleton) {
  27038. console.error('THREE.PropertyBinding: Can not bind to bones as node does not have a skeleton.', this);
  27039. return;
  27040. }
  27041. // potential future optimization: skip this if propertyIndex is already an integer
  27042. // and convert the integer string to a true integer.
  27043. targetObject = targetObject.skeleton.bones;
  27044. // support resolving morphTarget names into indices.
  27045. for (let i = 0; i < targetObject.length; i++) {
  27046. if (targetObject[i].name === objectIndex) {
  27047. objectIndex = i;
  27048. break;
  27049. }
  27050. }
  27051. break;
  27052. case 'map':
  27053. if ('map' in targetObject) {
  27054. targetObject = targetObject.map;
  27055. break;
  27056. }
  27057. if (!targetObject.material) {
  27058. console.error('THREE.PropertyBinding: Can not bind to material as node does not have a material.', this);
  27059. return;
  27060. }
  27061. if (!targetObject.material.map) {
  27062. console.error('THREE.PropertyBinding: Can not bind to material.map as node.material does not have a map.', this);
  27063. return;
  27064. }
  27065. targetObject = targetObject.material.map;
  27066. break;
  27067. default:
  27068. if (targetObject[objectName] === undefined) {
  27069. console.error('THREE.PropertyBinding: Can not bind to objectName of node undefined.', this);
  27070. return;
  27071. }
  27072. targetObject = targetObject[objectName];
  27073. }
  27074. if (objectIndex !== undefined) {
  27075. if (targetObject[objectIndex] === undefined) {
  27076. console.error('THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.', this, targetObject);
  27077. return;
  27078. }
  27079. targetObject = targetObject[objectIndex];
  27080. }
  27081. }
  27082. // resolve property
  27083. const nodeProperty = targetObject[propertyName];
  27084. if (nodeProperty === undefined) {
  27085. const nodeName = parsedPath.nodeName;
  27086. console.error('THREE.PropertyBinding: Trying to update property for track: ' + nodeName + '.' + propertyName + ' but it wasn\'t found.', targetObject);
  27087. return;
  27088. }
  27089. // determine versioning scheme
  27090. let versioning = this.Versioning.None;
  27091. this.targetObject = targetObject;
  27092. if (targetObject.needsUpdate !== undefined) {
  27093. // material
  27094. versioning = this.Versioning.NeedsUpdate;
  27095. } else if (targetObject.matrixWorldNeedsUpdate !== undefined) {
  27096. // node transform
  27097. versioning = this.Versioning.MatrixWorldNeedsUpdate;
  27098. }
  27099. // determine how the property gets bound
  27100. let bindingType = this.BindingType.Direct;
  27101. if (propertyIndex !== undefined) {
  27102. // access a sub element of the property array (only primitives are supported right now)
  27103. if (propertyName === 'morphTargetInfluences') {
  27104. // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer.
  27105. // support resolving morphTarget names into indices.
  27106. if (!targetObject.geometry) {
  27107. console.error('THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.', this);
  27108. return;
  27109. }
  27110. if (!targetObject.geometry.morphAttributes) {
  27111. console.error('THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.', this);
  27112. return;
  27113. }
  27114. if (targetObject.morphTargetDictionary[propertyIndex] !== undefined) {
  27115. propertyIndex = targetObject.morphTargetDictionary[propertyIndex];
  27116. }
  27117. }
  27118. bindingType = this.BindingType.ArrayElement;
  27119. this.resolvedProperty = nodeProperty;
  27120. this.propertyIndex = propertyIndex;
  27121. } else if (nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined) {
  27122. // must use copy for Object3D.Euler/Quaternion
  27123. bindingType = this.BindingType.HasFromToArray;
  27124. this.resolvedProperty = nodeProperty;
  27125. } else if (Array.isArray(nodeProperty)) {
  27126. bindingType = this.BindingType.EntireArray;
  27127. this.resolvedProperty = nodeProperty;
  27128. } else {
  27129. this.propertyName = propertyName;
  27130. }
  27131. // select getter / setter
  27132. this.getValue = this.GetterByBindingType[bindingType];
  27133. this.setValue = this.SetterByBindingTypeAndVersioning[bindingType][versioning];
  27134. }
  27135. unbind() {
  27136. this.node = null;
  27137. // back to the prototype version of getValue / setValue
  27138. // note: avoiding to mutate the shape of 'this' via 'delete'
  27139. this.getValue = this._getValue_unbound;
  27140. this.setValue = this._setValue_unbound;
  27141. }
  27142. }
  27143. PropertyBinding.Composite = Composite;
  27144. PropertyBinding.prototype.BindingType = {
  27145. Direct: 0,
  27146. EntireArray: 1,
  27147. ArrayElement: 2,
  27148. HasFromToArray: 3
  27149. };
  27150. PropertyBinding.prototype.Versioning = {
  27151. None: 0,
  27152. NeedsUpdate: 1,
  27153. MatrixWorldNeedsUpdate: 2
  27154. };
  27155. PropertyBinding.prototype.GetterByBindingType = [PropertyBinding.prototype._getValue_direct, PropertyBinding.prototype._getValue_array, PropertyBinding.prototype._getValue_arrayElement, PropertyBinding.prototype._getValue_toArray];
  27156. PropertyBinding.prototype.SetterByBindingTypeAndVersioning = [[
  27157. // Direct
  27158. PropertyBinding.prototype._setValue_direct, PropertyBinding.prototype._setValue_direct_setNeedsUpdate, PropertyBinding.prototype._setValue_direct_setMatrixWorldNeedsUpdate], [
  27159. // EntireArray
  27160. PropertyBinding.prototype._setValue_array, PropertyBinding.prototype._setValue_array_setNeedsUpdate, PropertyBinding.prototype._setValue_array_setMatrixWorldNeedsUpdate], [
  27161. // ArrayElement
  27162. PropertyBinding.prototype._setValue_arrayElement, PropertyBinding.prototype._setValue_arrayElement_setNeedsUpdate, PropertyBinding.prototype._setValue_arrayElement_setMatrixWorldNeedsUpdate], [
  27163. // HasToFromArray
  27164. PropertyBinding.prototype._setValue_fromArray, PropertyBinding.prototype._setValue_fromArray_setNeedsUpdate, PropertyBinding.prototype._setValue_fromArray_setMatrixWorldNeedsUpdate]];
  27165. /**
  27166. *
  27167. * A group of objects that receives a shared animation state.
  27168. *
  27169. * Usage:
  27170. *
  27171. * - Add objects you would otherwise pass as 'root' to the
  27172. * constructor or the .clipAction method of AnimationMixer.
  27173. *
  27174. * - Instead pass this object as 'root'.
  27175. *
  27176. * - You can also add and remove objects later when the mixer
  27177. * is running.
  27178. *
  27179. * Note:
  27180. *
  27181. * Objects of this class appear as one object to the mixer,
  27182. * so cache control of the individual objects must be done
  27183. * on the group.
  27184. *
  27185. * Limitation:
  27186. *
  27187. * - The animated properties must be compatible among the
  27188. * all objects in the group.
  27189. *
  27190. * - A single property can either be controlled through a
  27191. * target group or directly, but not both.
  27192. */
  27193. class AnimationObjectGroup {
  27194. constructor() {
  27195. this.isAnimationObjectGroup = true;
  27196. this.uuid = generateUUID();
  27197. // cached objects followed by the active ones
  27198. this._objects = Array.prototype.slice.call(arguments);
  27199. this.nCachedObjects_ = 0; // threshold
  27200. // note: read by PropertyBinding.Composite
  27201. const indices = {};
  27202. this._indicesByUUID = indices; // for bookkeeping
  27203. for (let i = 0, n = arguments.length; i !== n; ++i) {
  27204. indices[arguments[i].uuid] = i;
  27205. }
  27206. this._paths = []; // inside: string
  27207. this._parsedPaths = []; // inside: { we don't care, here }
  27208. this._bindings = []; // inside: Array< PropertyBinding >
  27209. this._bindingsIndicesByPath = {}; // inside: indices in these arrays
  27210. const scope = this;
  27211. this.stats = {
  27212. objects: {
  27213. get total() {
  27214. return scope._objects.length;
  27215. },
  27216. get inUse() {
  27217. return this.total - scope.nCachedObjects_;
  27218. }
  27219. },
  27220. get bindingsPerObject() {
  27221. return scope._bindings.length;
  27222. }
  27223. };
  27224. }
  27225. add() {
  27226. const objects = this._objects,
  27227. indicesByUUID = this._indicesByUUID,
  27228. paths = this._paths,
  27229. parsedPaths = this._parsedPaths,
  27230. bindings = this._bindings,
  27231. nBindings = bindings.length;
  27232. let knownObject = undefined,
  27233. nObjects = objects.length,
  27234. nCachedObjects = this.nCachedObjects_;
  27235. for (let i = 0, n = arguments.length; i !== n; ++i) {
  27236. const object = arguments[i],
  27237. uuid = object.uuid;
  27238. let index = indicesByUUID[uuid];
  27239. if (index === undefined) {
  27240. // unknown object -> add it to the ACTIVE region
  27241. index = nObjects++;
  27242. indicesByUUID[uuid] = index;
  27243. objects.push(object);
  27244. // accounting is done, now do the same for all bindings
  27245. for (let j = 0, m = nBindings; j !== m; ++j) {
  27246. bindings[j].push(new PropertyBinding(object, paths[j], parsedPaths[j]));
  27247. }
  27248. } else if (index < nCachedObjects) {
  27249. knownObject = objects[index];
  27250. // move existing object to the ACTIVE region
  27251. const firstActiveIndex = --nCachedObjects,
  27252. lastCachedObject = objects[firstActiveIndex];
  27253. indicesByUUID[lastCachedObject.uuid] = index;
  27254. objects[index] = lastCachedObject;
  27255. indicesByUUID[uuid] = firstActiveIndex;
  27256. objects[firstActiveIndex] = object;
  27257. // accounting is done, now do the same for all bindings
  27258. for (let j = 0, m = nBindings; j !== m; ++j) {
  27259. const bindingsForPath = bindings[j],
  27260. lastCached = bindingsForPath[firstActiveIndex];
  27261. let binding = bindingsForPath[index];
  27262. bindingsForPath[index] = lastCached;
  27263. if (binding === undefined) {
  27264. // since we do not bother to create new bindings
  27265. // for objects that are cached, the binding may
  27266. // or may not exist
  27267. binding = new PropertyBinding(object, paths[j], parsedPaths[j]);
  27268. }
  27269. bindingsForPath[firstActiveIndex] = binding;
  27270. }
  27271. } else if (objects[index] !== knownObject) {
  27272. console.error('THREE.AnimationObjectGroup: Different objects with the same UUID ' + 'detected. Clean the caches or recreate your infrastructure when reloading scenes.');
  27273. } // else the object is already where we want it to be
  27274. } // for arguments
  27275. this.nCachedObjects_ = nCachedObjects;
  27276. }
  27277. remove() {
  27278. const objects = this._objects,
  27279. indicesByUUID = this._indicesByUUID,
  27280. bindings = this._bindings,
  27281. nBindings = bindings.length;
  27282. let nCachedObjects = this.nCachedObjects_;
  27283. for (let i = 0, n = arguments.length; i !== n; ++i) {
  27284. const object = arguments[i],
  27285. uuid = object.uuid,
  27286. index = indicesByUUID[uuid];
  27287. if (index !== undefined && index >= nCachedObjects) {
  27288. // move existing object into the CACHED region
  27289. const lastCachedIndex = nCachedObjects++,
  27290. firstActiveObject = objects[lastCachedIndex];
  27291. indicesByUUID[firstActiveObject.uuid] = index;
  27292. objects[index] = firstActiveObject;
  27293. indicesByUUID[uuid] = lastCachedIndex;
  27294. objects[lastCachedIndex] = object;
  27295. // accounting is done, now do the same for all bindings
  27296. for (let j = 0, m = nBindings; j !== m; ++j) {
  27297. const bindingsForPath = bindings[j],
  27298. firstActive = bindingsForPath[lastCachedIndex],
  27299. binding = bindingsForPath[index];
  27300. bindingsForPath[index] = firstActive;
  27301. bindingsForPath[lastCachedIndex] = binding;
  27302. }
  27303. }
  27304. } // for arguments
  27305. this.nCachedObjects_ = nCachedObjects;
  27306. }
  27307. // remove & forget
  27308. uncache() {
  27309. const objects = this._objects,
  27310. indicesByUUID = this._indicesByUUID,
  27311. bindings = this._bindings,
  27312. nBindings = bindings.length;
  27313. let nCachedObjects = this.nCachedObjects_,
  27314. nObjects = objects.length;
  27315. for (let i = 0, n = arguments.length; i !== n; ++i) {
  27316. const object = arguments[i],
  27317. uuid = object.uuid,
  27318. index = indicesByUUID[uuid];
  27319. if (index !== undefined) {
  27320. delete indicesByUUID[uuid];
  27321. if (index < nCachedObjects) {
  27322. // object is cached, shrink the CACHED region
  27323. const firstActiveIndex = --nCachedObjects,
  27324. lastCachedObject = objects[firstActiveIndex],
  27325. lastIndex = --nObjects,
  27326. lastObject = objects[lastIndex];
  27327. // last cached object takes this object's place
  27328. indicesByUUID[lastCachedObject.uuid] = index;
  27329. objects[index] = lastCachedObject;
  27330. // last object goes to the activated slot and pop
  27331. indicesByUUID[lastObject.uuid] = firstActiveIndex;
  27332. objects[firstActiveIndex] = lastObject;
  27333. objects.pop();
  27334. // accounting is done, now do the same for all bindings
  27335. for (let j = 0, m = nBindings; j !== m; ++j) {
  27336. const bindingsForPath = bindings[j],
  27337. lastCached = bindingsForPath[firstActiveIndex],
  27338. last = bindingsForPath[lastIndex];
  27339. bindingsForPath[index] = lastCached;
  27340. bindingsForPath[firstActiveIndex] = last;
  27341. bindingsForPath.pop();
  27342. }
  27343. } else {
  27344. // object is active, just swap with the last and pop
  27345. const lastIndex = --nObjects,
  27346. lastObject = objects[lastIndex];
  27347. if (lastIndex > 0) {
  27348. indicesByUUID[lastObject.uuid] = index;
  27349. }
  27350. objects[index] = lastObject;
  27351. objects.pop();
  27352. // accounting is done, now do the same for all bindings
  27353. for (let j = 0, m = nBindings; j !== m; ++j) {
  27354. const bindingsForPath = bindings[j];
  27355. bindingsForPath[index] = bindingsForPath[lastIndex];
  27356. bindingsForPath.pop();
  27357. }
  27358. } // cached or active
  27359. } // if object is known
  27360. } // for arguments
  27361. this.nCachedObjects_ = nCachedObjects;
  27362. }
  27363. // Internal interface used by befriended PropertyBinding.Composite:
  27364. subscribe_(path, parsedPath) {
  27365. // returns an array of bindings for the given path that is changed
  27366. // according to the contained objects in the group
  27367. const indicesByPath = this._bindingsIndicesByPath;
  27368. let index = indicesByPath[path];
  27369. const bindings = this._bindings;
  27370. if (index !== undefined) return bindings[index];
  27371. const paths = this._paths,
  27372. parsedPaths = this._parsedPaths,
  27373. objects = this._objects,
  27374. nObjects = objects.length,
  27375. nCachedObjects = this.nCachedObjects_,
  27376. bindingsForPath = new Array(nObjects);
  27377. index = bindings.length;
  27378. indicesByPath[path] = index;
  27379. paths.push(path);
  27380. parsedPaths.push(parsedPath);
  27381. bindings.push(bindingsForPath);
  27382. for (let i = nCachedObjects, n = objects.length; i !== n; ++i) {
  27383. const object = objects[i];
  27384. bindingsForPath[i] = new PropertyBinding(object, path, parsedPath);
  27385. }
  27386. return bindingsForPath;
  27387. }
  27388. unsubscribe_(path) {
  27389. // tells the group to forget about a property path and no longer
  27390. // update the array previously obtained with 'subscribe_'
  27391. const indicesByPath = this._bindingsIndicesByPath,
  27392. index = indicesByPath[path];
  27393. if (index !== undefined) {
  27394. const paths = this._paths,
  27395. parsedPaths = this._parsedPaths,
  27396. bindings = this._bindings,
  27397. lastBindingsIndex = bindings.length - 1,
  27398. lastBindings = bindings[lastBindingsIndex],
  27399. lastBindingsPath = path[lastBindingsIndex];
  27400. indicesByPath[lastBindingsPath] = index;
  27401. bindings[index] = lastBindings;
  27402. bindings.pop();
  27403. parsedPaths[index] = parsedPaths[lastBindingsIndex];
  27404. parsedPaths.pop();
  27405. paths[index] = paths[lastBindingsIndex];
  27406. paths.pop();
  27407. }
  27408. }
  27409. }
  27410. class AnimationAction {
  27411. constructor(mixer, clip, localRoot = null, blendMode = clip.blendMode) {
  27412. this._mixer = mixer;
  27413. this._clip = clip;
  27414. this._localRoot = localRoot;
  27415. this.blendMode = blendMode;
  27416. const tracks = clip.tracks,
  27417. nTracks = tracks.length,
  27418. interpolants = new Array(nTracks);
  27419. const interpolantSettings = {
  27420. endingStart: ZeroCurvatureEnding,
  27421. endingEnd: ZeroCurvatureEnding
  27422. };
  27423. for (let i = 0; i !== nTracks; ++i) {
  27424. const interpolant = tracks[i].createInterpolant(null);
  27425. interpolants[i] = interpolant;
  27426. interpolant.settings = interpolantSettings;
  27427. }
  27428. this._interpolantSettings = interpolantSettings;
  27429. this._interpolants = interpolants; // bound by the mixer
  27430. // inside: PropertyMixer (managed by the mixer)
  27431. this._propertyBindings = new Array(nTracks);
  27432. this._cacheIndex = null; // for the memory manager
  27433. this._byClipCacheIndex = null; // for the memory manager
  27434. this._timeScaleInterpolant = null;
  27435. this._weightInterpolant = null;
  27436. this.loop = LoopRepeat;
  27437. this._loopCount = -1;
  27438. // global mixer time when the action is to be started
  27439. // it's set back to 'null' upon start of the action
  27440. this._startTime = null;
  27441. // scaled local time of the action
  27442. // gets clamped or wrapped to 0..clip.duration according to loop
  27443. this.time = 0;
  27444. this.timeScale = 1;
  27445. this._effectiveTimeScale = 1;
  27446. this.weight = 1;
  27447. this._effectiveWeight = 1;
  27448. this.repetitions = Infinity; // no. of repetitions when looping
  27449. this.paused = false; // true -> zero effective time scale
  27450. this.enabled = true; // false -> zero effective weight
  27451. this.clampWhenFinished = false; // keep feeding the last frame?
  27452. this.zeroSlopeAtStart = true; // for smooth interpolation w/o separate
  27453. this.zeroSlopeAtEnd = true; // clips for start, loop and end
  27454. }
  27455. // State & Scheduling
  27456. play() {
  27457. this._mixer._activateAction(this);
  27458. return this;
  27459. }
  27460. stop() {
  27461. this._mixer._deactivateAction(this);
  27462. return this.reset();
  27463. }
  27464. reset() {
  27465. this.paused = false;
  27466. this.enabled = true;
  27467. this.time = 0; // restart clip
  27468. this._loopCount = -1; // forget previous loops
  27469. this._startTime = null; // forget scheduling
  27470. return this.stopFading().stopWarping();
  27471. }
  27472. isRunning() {
  27473. return this.enabled && !this.paused && this.timeScale !== 0 && this._startTime === null && this._mixer._isActiveAction(this);
  27474. }
  27475. // return true when play has been called
  27476. isScheduled() {
  27477. return this._mixer._isActiveAction(this);
  27478. }
  27479. startAt(time) {
  27480. this._startTime = time;
  27481. return this;
  27482. }
  27483. setLoop(mode, repetitions) {
  27484. this.loop = mode;
  27485. this.repetitions = repetitions;
  27486. return this;
  27487. }
  27488. // Weight
  27489. // set the weight stopping any scheduled fading
  27490. // although .enabled = false yields an effective weight of zero, this
  27491. // method does *not* change .enabled, because it would be confusing
  27492. setEffectiveWeight(weight) {
  27493. this.weight = weight;
  27494. // note: same logic as when updated at runtime
  27495. this._effectiveWeight = this.enabled ? weight : 0;
  27496. return this.stopFading();
  27497. }
  27498. // return the weight considering fading and .enabled
  27499. getEffectiveWeight() {
  27500. return this._effectiveWeight;
  27501. }
  27502. fadeIn(duration) {
  27503. return this._scheduleFading(duration, 0, 1);
  27504. }
  27505. fadeOut(duration) {
  27506. return this._scheduleFading(duration, 1, 0);
  27507. }
  27508. crossFadeFrom(fadeOutAction, duration, warp) {
  27509. fadeOutAction.fadeOut(duration);
  27510. this.fadeIn(duration);
  27511. if (warp) {
  27512. const fadeInDuration = this._clip.duration,
  27513. fadeOutDuration = fadeOutAction._clip.duration,
  27514. startEndRatio = fadeOutDuration / fadeInDuration,
  27515. endStartRatio = fadeInDuration / fadeOutDuration;
  27516. fadeOutAction.warp(1.0, startEndRatio, duration);
  27517. this.warp(endStartRatio, 1.0, duration);
  27518. }
  27519. return this;
  27520. }
  27521. crossFadeTo(fadeInAction, duration, warp) {
  27522. return fadeInAction.crossFadeFrom(this, duration, warp);
  27523. }
  27524. stopFading() {
  27525. const weightInterpolant = this._weightInterpolant;
  27526. if (weightInterpolant !== null) {
  27527. this._weightInterpolant = null;
  27528. this._mixer._takeBackControlInterpolant(weightInterpolant);
  27529. }
  27530. return this;
  27531. }
  27532. // Time Scale Control
  27533. // set the time scale stopping any scheduled warping
  27534. // although .paused = true yields an effective time scale of zero, this
  27535. // method does *not* change .paused, because it would be confusing
  27536. setEffectiveTimeScale(timeScale) {
  27537. this.timeScale = timeScale;
  27538. this._effectiveTimeScale = this.paused ? 0 : timeScale;
  27539. return this.stopWarping();
  27540. }
  27541. // return the time scale considering warping and .paused
  27542. getEffectiveTimeScale() {
  27543. return this._effectiveTimeScale;
  27544. }
  27545. setDuration(duration) {
  27546. this.timeScale = this._clip.duration / duration;
  27547. return this.stopWarping();
  27548. }
  27549. syncWith(action) {
  27550. this.time = action.time;
  27551. this.timeScale = action.timeScale;
  27552. return this.stopWarping();
  27553. }
  27554. halt(duration) {
  27555. return this.warp(this._effectiveTimeScale, 0, duration);
  27556. }
  27557. warp(startTimeScale, endTimeScale, duration) {
  27558. const mixer = this._mixer,
  27559. now = mixer.time,
  27560. timeScale = this.timeScale;
  27561. let interpolant = this._timeScaleInterpolant;
  27562. if (interpolant === null) {
  27563. interpolant = mixer._lendControlInterpolant();
  27564. this._timeScaleInterpolant = interpolant;
  27565. }
  27566. const times = interpolant.parameterPositions,
  27567. values = interpolant.sampleValues;
  27568. times[0] = now;
  27569. times[1] = now + duration;
  27570. values[0] = startTimeScale / timeScale;
  27571. values[1] = endTimeScale / timeScale;
  27572. return this;
  27573. }
  27574. stopWarping() {
  27575. const timeScaleInterpolant = this._timeScaleInterpolant;
  27576. if (timeScaleInterpolant !== null) {
  27577. this._timeScaleInterpolant = null;
  27578. this._mixer._takeBackControlInterpolant(timeScaleInterpolant);
  27579. }
  27580. return this;
  27581. }
  27582. // Object Accessors
  27583. getMixer() {
  27584. return this._mixer;
  27585. }
  27586. getClip() {
  27587. return this._clip;
  27588. }
  27589. getRoot() {
  27590. return this._localRoot || this._mixer._root;
  27591. }
  27592. // Interna
  27593. _update(time, deltaTime, timeDirection, accuIndex) {
  27594. // called by the mixer
  27595. if (!this.enabled) {
  27596. // call ._updateWeight() to update ._effectiveWeight
  27597. this._updateWeight(time);
  27598. return;
  27599. }
  27600. const startTime = this._startTime;
  27601. if (startTime !== null) {
  27602. // check for scheduled start of action
  27603. const timeRunning = (time - startTime) * timeDirection;
  27604. if (timeRunning < 0 || timeDirection === 0) {
  27605. deltaTime = 0;
  27606. } else {
  27607. this._startTime = null; // unschedule
  27608. deltaTime = timeDirection * timeRunning;
  27609. }
  27610. }
  27611. // apply time scale and advance time
  27612. deltaTime *= this._updateTimeScale(time);
  27613. const clipTime = this._updateTime(deltaTime);
  27614. // note: _updateTime may disable the action resulting in
  27615. // an effective weight of 0
  27616. const weight = this._updateWeight(time);
  27617. if (weight > 0) {
  27618. const interpolants = this._interpolants;
  27619. const propertyMixers = this._propertyBindings;
  27620. switch (this.blendMode) {
  27621. case AdditiveAnimationBlendMode:
  27622. for (let j = 0, m = interpolants.length; j !== m; ++j) {
  27623. interpolants[j].evaluate(clipTime);
  27624. propertyMixers[j].accumulateAdditive(weight);
  27625. }
  27626. break;
  27627. case NormalAnimationBlendMode:
  27628. default:
  27629. for (let j = 0, m = interpolants.length; j !== m; ++j) {
  27630. interpolants[j].evaluate(clipTime);
  27631. propertyMixers[j].accumulate(accuIndex, weight);
  27632. }
  27633. }
  27634. }
  27635. }
  27636. _updateWeight(time) {
  27637. let weight = 0;
  27638. if (this.enabled) {
  27639. weight = this.weight;
  27640. const interpolant = this._weightInterpolant;
  27641. if (interpolant !== null) {
  27642. const interpolantValue = interpolant.evaluate(time)[0];
  27643. weight *= interpolantValue;
  27644. if (time > interpolant.parameterPositions[1]) {
  27645. this.stopFading();
  27646. if (interpolantValue === 0) {
  27647. // faded out, disable
  27648. this.enabled = false;
  27649. }
  27650. }
  27651. }
  27652. }
  27653. this._effectiveWeight = weight;
  27654. return weight;
  27655. }
  27656. _updateTimeScale(time) {
  27657. let timeScale = 0;
  27658. if (!this.paused) {
  27659. timeScale = this.timeScale;
  27660. const interpolant = this._timeScaleInterpolant;
  27661. if (interpolant !== null) {
  27662. const interpolantValue = interpolant.evaluate(time)[0];
  27663. timeScale *= interpolantValue;
  27664. if (time > interpolant.parameterPositions[1]) {
  27665. this.stopWarping();
  27666. if (timeScale === 0) {
  27667. // motion has halted, pause
  27668. this.paused = true;
  27669. } else {
  27670. // warp done - apply final time scale
  27671. this.timeScale = timeScale;
  27672. }
  27673. }
  27674. }
  27675. }
  27676. this._effectiveTimeScale = timeScale;
  27677. return timeScale;
  27678. }
  27679. _updateTime(deltaTime) {
  27680. const duration = this._clip.duration;
  27681. const loop = this.loop;
  27682. let time = this.time + deltaTime;
  27683. let loopCount = this._loopCount;
  27684. const pingPong = loop === LoopPingPong;
  27685. if (deltaTime === 0) {
  27686. if (loopCount === -1) return time;
  27687. return pingPong && (loopCount & 1) === 1 ? duration - time : time;
  27688. }
  27689. if (loop === LoopOnce) {
  27690. if (loopCount === -1) {
  27691. // just started
  27692. this._loopCount = 0;
  27693. this._setEndings(true, true, false);
  27694. }
  27695. handle_stop: {
  27696. if (time >= duration) {
  27697. time = duration;
  27698. } else if (time < 0) {
  27699. time = 0;
  27700. } else {
  27701. this.time = time;
  27702. break handle_stop;
  27703. }
  27704. if (this.clampWhenFinished) this.paused = true;else this.enabled = false;
  27705. this.time = time;
  27706. this._mixer.dispatchEvent({
  27707. type: 'finished',
  27708. action: this,
  27709. direction: deltaTime < 0 ? -1 : 1
  27710. });
  27711. }
  27712. } else {
  27713. // repetitive Repeat or PingPong
  27714. if (loopCount === -1) {
  27715. // just started
  27716. if (deltaTime >= 0) {
  27717. loopCount = 0;
  27718. this._setEndings(true, this.repetitions === 0, pingPong);
  27719. } else {
  27720. // when looping in reverse direction, the initial
  27721. // transition through zero counts as a repetition,
  27722. // so leave loopCount at -1
  27723. this._setEndings(this.repetitions === 0, true, pingPong);
  27724. }
  27725. }
  27726. if (time >= duration || time < 0) {
  27727. // wrap around
  27728. const loopDelta = Math.floor(time / duration); // signed
  27729. time -= duration * loopDelta;
  27730. loopCount += Math.abs(loopDelta);
  27731. const pending = this.repetitions - loopCount;
  27732. if (pending <= 0) {
  27733. // have to stop (switch state, clamp time, fire event)
  27734. if (this.clampWhenFinished) this.paused = true;else this.enabled = false;
  27735. time = deltaTime > 0 ? duration : 0;
  27736. this.time = time;
  27737. this._mixer.dispatchEvent({
  27738. type: 'finished',
  27739. action: this,
  27740. direction: deltaTime > 0 ? 1 : -1
  27741. });
  27742. } else {
  27743. // keep running
  27744. if (pending === 1) {
  27745. // entering the last round
  27746. const atStart = deltaTime < 0;
  27747. this._setEndings(atStart, !atStart, pingPong);
  27748. } else {
  27749. this._setEndings(false, false, pingPong);
  27750. }
  27751. this._loopCount = loopCount;
  27752. this.time = time;
  27753. this._mixer.dispatchEvent({
  27754. type: 'loop',
  27755. action: this,
  27756. loopDelta: loopDelta
  27757. });
  27758. }
  27759. } else {
  27760. this.time = time;
  27761. }
  27762. if (pingPong && (loopCount & 1) === 1) {
  27763. // invert time for the "pong round"
  27764. return duration - time;
  27765. }
  27766. }
  27767. return time;
  27768. }
  27769. _setEndings(atStart, atEnd, pingPong) {
  27770. const settings = this._interpolantSettings;
  27771. if (pingPong) {
  27772. settings.endingStart = ZeroSlopeEnding;
  27773. settings.endingEnd = ZeroSlopeEnding;
  27774. } else {
  27775. // assuming for LoopOnce atStart == atEnd == true
  27776. if (atStart) {
  27777. settings.endingStart = this.zeroSlopeAtStart ? ZeroSlopeEnding : ZeroCurvatureEnding;
  27778. } else {
  27779. settings.endingStart = WrapAroundEnding;
  27780. }
  27781. if (atEnd) {
  27782. settings.endingEnd = this.zeroSlopeAtEnd ? ZeroSlopeEnding : ZeroCurvatureEnding;
  27783. } else {
  27784. settings.endingEnd = WrapAroundEnding;
  27785. }
  27786. }
  27787. }
  27788. _scheduleFading(duration, weightNow, weightThen) {
  27789. const mixer = this._mixer,
  27790. now = mixer.time;
  27791. let interpolant = this._weightInterpolant;
  27792. if (interpolant === null) {
  27793. interpolant = mixer._lendControlInterpolant();
  27794. this._weightInterpolant = interpolant;
  27795. }
  27796. const times = interpolant.parameterPositions,
  27797. values = interpolant.sampleValues;
  27798. times[0] = now;
  27799. values[0] = weightNow;
  27800. times[1] = now + duration;
  27801. values[1] = weightThen;
  27802. return this;
  27803. }
  27804. }
  27805. const _controlInterpolantsResultBuffer = new Float32Array(1);
  27806. class AnimationMixer extends EventDispatcher {
  27807. constructor(root) {
  27808. super();
  27809. this._root = root;
  27810. this._initMemoryManager();
  27811. this._accuIndex = 0;
  27812. this.time = 0;
  27813. this.timeScale = 1.0;
  27814. }
  27815. _bindAction(action, prototypeAction) {
  27816. const root = action._localRoot || this._root,
  27817. tracks = action._clip.tracks,
  27818. nTracks = tracks.length,
  27819. bindings = action._propertyBindings,
  27820. interpolants = action._interpolants,
  27821. rootUuid = root.uuid,
  27822. bindingsByRoot = this._bindingsByRootAndName;
  27823. let bindingsByName = bindingsByRoot[rootUuid];
  27824. if (bindingsByName === undefined) {
  27825. bindingsByName = {};
  27826. bindingsByRoot[rootUuid] = bindingsByName;
  27827. }
  27828. for (let i = 0; i !== nTracks; ++i) {
  27829. const track = tracks[i],
  27830. trackName = track.name;
  27831. let binding = bindingsByName[trackName];
  27832. if (binding !== undefined) {
  27833. ++binding.referenceCount;
  27834. bindings[i] = binding;
  27835. } else {
  27836. binding = bindings[i];
  27837. if (binding !== undefined) {
  27838. // existing binding, make sure the cache knows
  27839. if (binding._cacheIndex === null) {
  27840. ++binding.referenceCount;
  27841. this._addInactiveBinding(binding, rootUuid, trackName);
  27842. }
  27843. continue;
  27844. }
  27845. const path = prototypeAction && prototypeAction._propertyBindings[i].binding.parsedPath;
  27846. binding = new PropertyMixer(PropertyBinding.create(root, trackName, path), track.ValueTypeName, track.getValueSize());
  27847. ++binding.referenceCount;
  27848. this._addInactiveBinding(binding, rootUuid, trackName);
  27849. bindings[i] = binding;
  27850. }
  27851. interpolants[i].resultBuffer = binding.buffer;
  27852. }
  27853. }
  27854. _activateAction(action) {
  27855. if (!this._isActiveAction(action)) {
  27856. if (action._cacheIndex === null) {
  27857. // this action has been forgotten by the cache, but the user
  27858. // appears to be still using it -> rebind
  27859. const rootUuid = (action._localRoot || this._root).uuid,
  27860. clipUuid = action._clip.uuid,
  27861. actionsForClip = this._actionsByClip[clipUuid];
  27862. this._bindAction(action, actionsForClip && actionsForClip.knownActions[0]);
  27863. this._addInactiveAction(action, clipUuid, rootUuid);
  27864. }
  27865. const bindings = action._propertyBindings;
  27866. // increment reference counts / sort out state
  27867. for (let i = 0, n = bindings.length; i !== n; ++i) {
  27868. const binding = bindings[i];
  27869. if (binding.useCount++ === 0) {
  27870. this._lendBinding(binding);
  27871. binding.saveOriginalState();
  27872. }
  27873. }
  27874. this._lendAction(action);
  27875. }
  27876. }
  27877. _deactivateAction(action) {
  27878. if (this._isActiveAction(action)) {
  27879. const bindings = action._propertyBindings;
  27880. // decrement reference counts / sort out state
  27881. for (let i = 0, n = bindings.length; i !== n; ++i) {
  27882. const binding = bindings[i];
  27883. if (--binding.useCount === 0) {
  27884. binding.restoreOriginalState();
  27885. this._takeBackBinding(binding);
  27886. }
  27887. }
  27888. this._takeBackAction(action);
  27889. }
  27890. }
  27891. // Memory manager
  27892. _initMemoryManager() {
  27893. this._actions = []; // 'nActiveActions' followed by inactive ones
  27894. this._nActiveActions = 0;
  27895. this._actionsByClip = {};
  27896. // inside:
  27897. // {
  27898. // knownActions: Array< AnimationAction > - used as prototypes
  27899. // actionByRoot: AnimationAction - lookup
  27900. // }
  27901. this._bindings = []; // 'nActiveBindings' followed by inactive ones
  27902. this._nActiveBindings = 0;
  27903. this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer >
  27904. this._controlInterpolants = []; // same game as above
  27905. this._nActiveControlInterpolants = 0;
  27906. const scope = this;
  27907. this.stats = {
  27908. actions: {
  27909. get total() {
  27910. return scope._actions.length;
  27911. },
  27912. get inUse() {
  27913. return scope._nActiveActions;
  27914. }
  27915. },
  27916. bindings: {
  27917. get total() {
  27918. return scope._bindings.length;
  27919. },
  27920. get inUse() {
  27921. return scope._nActiveBindings;
  27922. }
  27923. },
  27924. controlInterpolants: {
  27925. get total() {
  27926. return scope._controlInterpolants.length;
  27927. },
  27928. get inUse() {
  27929. return scope._nActiveControlInterpolants;
  27930. }
  27931. }
  27932. };
  27933. }
  27934. // Memory management for AnimationAction objects
  27935. _isActiveAction(action) {
  27936. const index = action._cacheIndex;
  27937. return index !== null && index < this._nActiveActions;
  27938. }
  27939. _addInactiveAction(action, clipUuid, rootUuid) {
  27940. const actions = this._actions,
  27941. actionsByClip = this._actionsByClip;
  27942. let actionsForClip = actionsByClip[clipUuid];
  27943. if (actionsForClip === undefined) {
  27944. actionsForClip = {
  27945. knownActions: [action],
  27946. actionByRoot: {}
  27947. };
  27948. action._byClipCacheIndex = 0;
  27949. actionsByClip[clipUuid] = actionsForClip;
  27950. } else {
  27951. const knownActions = actionsForClip.knownActions;
  27952. action._byClipCacheIndex = knownActions.length;
  27953. knownActions.push(action);
  27954. }
  27955. action._cacheIndex = actions.length;
  27956. actions.push(action);
  27957. actionsForClip.actionByRoot[rootUuid] = action;
  27958. }
  27959. _removeInactiveAction(action) {
  27960. const actions = this._actions,
  27961. lastInactiveAction = actions[actions.length - 1],
  27962. cacheIndex = action._cacheIndex;
  27963. lastInactiveAction._cacheIndex = cacheIndex;
  27964. actions[cacheIndex] = lastInactiveAction;
  27965. actions.pop();
  27966. action._cacheIndex = null;
  27967. const clipUuid = action._clip.uuid,
  27968. actionsByClip = this._actionsByClip,
  27969. actionsForClip = actionsByClip[clipUuid],
  27970. knownActionsForClip = actionsForClip.knownActions,
  27971. lastKnownAction = knownActionsForClip[knownActionsForClip.length - 1],
  27972. byClipCacheIndex = action._byClipCacheIndex;
  27973. lastKnownAction._byClipCacheIndex = byClipCacheIndex;
  27974. knownActionsForClip[byClipCacheIndex] = lastKnownAction;
  27975. knownActionsForClip.pop();
  27976. action._byClipCacheIndex = null;
  27977. const actionByRoot = actionsForClip.actionByRoot,
  27978. rootUuid = (action._localRoot || this._root).uuid;
  27979. delete actionByRoot[rootUuid];
  27980. if (knownActionsForClip.length === 0) {
  27981. delete actionsByClip[clipUuid];
  27982. }
  27983. this._removeInactiveBindingsForAction(action);
  27984. }
  27985. _removeInactiveBindingsForAction(action) {
  27986. const bindings = action._propertyBindings;
  27987. for (let i = 0, n = bindings.length; i !== n; ++i) {
  27988. const binding = bindings[i];
  27989. if (--binding.referenceCount === 0) {
  27990. this._removeInactiveBinding(binding);
  27991. }
  27992. }
  27993. }
  27994. _lendAction(action) {
  27995. // [ active actions | inactive actions ]
  27996. // [ active actions >| inactive actions ]
  27997. // s a
  27998. // <-swap->
  27999. // a s
  28000. const actions = this._actions,
  28001. prevIndex = action._cacheIndex,
  28002. lastActiveIndex = this._nActiveActions++,
  28003. firstInactiveAction = actions[lastActiveIndex];
  28004. action._cacheIndex = lastActiveIndex;
  28005. actions[lastActiveIndex] = action;
  28006. firstInactiveAction._cacheIndex = prevIndex;
  28007. actions[prevIndex] = firstInactiveAction;
  28008. }
  28009. _takeBackAction(action) {
  28010. // [ active actions | inactive actions ]
  28011. // [ active actions |< inactive actions ]
  28012. // a s
  28013. // <-swap->
  28014. // s a
  28015. const actions = this._actions,
  28016. prevIndex = action._cacheIndex,
  28017. firstInactiveIndex = --this._nActiveActions,
  28018. lastActiveAction = actions[firstInactiveIndex];
  28019. action._cacheIndex = firstInactiveIndex;
  28020. actions[firstInactiveIndex] = action;
  28021. lastActiveAction._cacheIndex = prevIndex;
  28022. actions[prevIndex] = lastActiveAction;
  28023. }
  28024. // Memory management for PropertyMixer objects
  28025. _addInactiveBinding(binding, rootUuid, trackName) {
  28026. const bindingsByRoot = this._bindingsByRootAndName,
  28027. bindings = this._bindings;
  28028. let bindingByName = bindingsByRoot[rootUuid];
  28029. if (bindingByName === undefined) {
  28030. bindingByName = {};
  28031. bindingsByRoot[rootUuid] = bindingByName;
  28032. }
  28033. bindingByName[trackName] = binding;
  28034. binding._cacheIndex = bindings.length;
  28035. bindings.push(binding);
  28036. }
  28037. _removeInactiveBinding(binding) {
  28038. const bindings = this._bindings,
  28039. propBinding = binding.binding,
  28040. rootUuid = propBinding.rootNode.uuid,
  28041. trackName = propBinding.path,
  28042. bindingsByRoot = this._bindingsByRootAndName,
  28043. bindingByName = bindingsByRoot[rootUuid],
  28044. lastInactiveBinding = bindings[bindings.length - 1],
  28045. cacheIndex = binding._cacheIndex;
  28046. lastInactiveBinding._cacheIndex = cacheIndex;
  28047. bindings[cacheIndex] = lastInactiveBinding;
  28048. bindings.pop();
  28049. delete bindingByName[trackName];
  28050. if (Object.keys(bindingByName).length === 0) {
  28051. delete bindingsByRoot[rootUuid];
  28052. }
  28053. }
  28054. _lendBinding(binding) {
  28055. const bindings = this._bindings,
  28056. prevIndex = binding._cacheIndex,
  28057. lastActiveIndex = this._nActiveBindings++,
  28058. firstInactiveBinding = bindings[lastActiveIndex];
  28059. binding._cacheIndex = lastActiveIndex;
  28060. bindings[lastActiveIndex] = binding;
  28061. firstInactiveBinding._cacheIndex = prevIndex;
  28062. bindings[prevIndex] = firstInactiveBinding;
  28063. }
  28064. _takeBackBinding(binding) {
  28065. const bindings = this._bindings,
  28066. prevIndex = binding._cacheIndex,
  28067. firstInactiveIndex = --this._nActiveBindings,
  28068. lastActiveBinding = bindings[firstInactiveIndex];
  28069. binding._cacheIndex = firstInactiveIndex;
  28070. bindings[firstInactiveIndex] = binding;
  28071. lastActiveBinding._cacheIndex = prevIndex;
  28072. bindings[prevIndex] = lastActiveBinding;
  28073. }
  28074. // Memory management of Interpolants for weight and time scale
  28075. _lendControlInterpolant() {
  28076. const interpolants = this._controlInterpolants,
  28077. lastActiveIndex = this._nActiveControlInterpolants++;
  28078. let interpolant = interpolants[lastActiveIndex];
  28079. if (interpolant === undefined) {
  28080. interpolant = new LinearInterpolant(new Float32Array(2), new Float32Array(2), 1, _controlInterpolantsResultBuffer);
  28081. interpolant.__cacheIndex = lastActiveIndex;
  28082. interpolants[lastActiveIndex] = interpolant;
  28083. }
  28084. return interpolant;
  28085. }
  28086. _takeBackControlInterpolant(interpolant) {
  28087. const interpolants = this._controlInterpolants,
  28088. prevIndex = interpolant.__cacheIndex,
  28089. firstInactiveIndex = --this._nActiveControlInterpolants,
  28090. lastActiveInterpolant = interpolants[firstInactiveIndex];
  28091. interpolant.__cacheIndex = firstInactiveIndex;
  28092. interpolants[firstInactiveIndex] = interpolant;
  28093. lastActiveInterpolant.__cacheIndex = prevIndex;
  28094. interpolants[prevIndex] = lastActiveInterpolant;
  28095. }
  28096. // return an action for a clip optionally using a custom root target
  28097. // object (this method allocates a lot of dynamic memory in case a
  28098. // previously unknown clip/root combination is specified)
  28099. clipAction(clip, optionalRoot, blendMode) {
  28100. const root = optionalRoot || this._root,
  28101. rootUuid = root.uuid;
  28102. let clipObject = typeof clip === 'string' ? AnimationClip.findByName(root, clip) : clip;
  28103. const clipUuid = clipObject !== null ? clipObject.uuid : clip;
  28104. const actionsForClip = this._actionsByClip[clipUuid];
  28105. let prototypeAction = null;
  28106. if (blendMode === undefined) {
  28107. if (clipObject !== null) {
  28108. blendMode = clipObject.blendMode;
  28109. } else {
  28110. blendMode = NormalAnimationBlendMode;
  28111. }
  28112. }
  28113. if (actionsForClip !== undefined) {
  28114. const existingAction = actionsForClip.actionByRoot[rootUuid];
  28115. if (existingAction !== undefined && existingAction.blendMode === blendMode) {
  28116. return existingAction;
  28117. }
  28118. // we know the clip, so we don't have to parse all
  28119. // the bindings again but can just copy
  28120. prototypeAction = actionsForClip.knownActions[0];
  28121. // also, take the clip from the prototype action
  28122. if (clipObject === null) clipObject = prototypeAction._clip;
  28123. }
  28124. // clip must be known when specified via string
  28125. if (clipObject === null) return null;
  28126. // allocate all resources required to run it
  28127. const newAction = new AnimationAction(this, clipObject, optionalRoot, blendMode);
  28128. this._bindAction(newAction, prototypeAction);
  28129. // and make the action known to the memory manager
  28130. this._addInactiveAction(newAction, clipUuid, rootUuid);
  28131. return newAction;
  28132. }
  28133. // get an existing action
  28134. existingAction(clip, optionalRoot) {
  28135. const root = optionalRoot || this._root,
  28136. rootUuid = root.uuid,
  28137. clipObject = typeof clip === 'string' ? AnimationClip.findByName(root, clip) : clip,
  28138. clipUuid = clipObject ? clipObject.uuid : clip,
  28139. actionsForClip = this._actionsByClip[clipUuid];
  28140. if (actionsForClip !== undefined) {
  28141. return actionsForClip.actionByRoot[rootUuid] || null;
  28142. }
  28143. return null;
  28144. }
  28145. // deactivates all previously scheduled actions
  28146. stopAllAction() {
  28147. const actions = this._actions,
  28148. nActions = this._nActiveActions;
  28149. for (let i = nActions - 1; i >= 0; --i) {
  28150. actions[i].stop();
  28151. }
  28152. return this;
  28153. }
  28154. // advance the time and update apply the animation
  28155. update(deltaTime) {
  28156. deltaTime *= this.timeScale;
  28157. const actions = this._actions,
  28158. nActions = this._nActiveActions,
  28159. time = this.time += deltaTime,
  28160. timeDirection = Math.sign(deltaTime),
  28161. accuIndex = this._accuIndex ^= 1;
  28162. // run active actions
  28163. for (let i = 0; i !== nActions; ++i) {
  28164. const action = actions[i];
  28165. action._update(time, deltaTime, timeDirection, accuIndex);
  28166. }
  28167. // update scene graph
  28168. const bindings = this._bindings,
  28169. nBindings = this._nActiveBindings;
  28170. for (let i = 0; i !== nBindings; ++i) {
  28171. bindings[i].apply(accuIndex);
  28172. }
  28173. return this;
  28174. }
  28175. // Allows you to seek to a specific time in an animation.
  28176. setTime(timeInSeconds) {
  28177. this.time = 0; // Zero out time attribute for AnimationMixer object;
  28178. for (let i = 0; i < this._actions.length; i++) {
  28179. this._actions[i].time = 0; // Zero out time attribute for all associated AnimationAction objects.
  28180. }
  28181. return this.update(timeInSeconds); // Update used to set exact time. Returns "this" AnimationMixer object.
  28182. }
  28183. // return this mixer's root target object
  28184. getRoot() {
  28185. return this._root;
  28186. }
  28187. // free all resources specific to a particular clip
  28188. uncacheClip(clip) {
  28189. const actions = this._actions,
  28190. clipUuid = clip.uuid,
  28191. actionsByClip = this._actionsByClip,
  28192. actionsForClip = actionsByClip[clipUuid];
  28193. if (actionsForClip !== undefined) {
  28194. // note: just calling _removeInactiveAction would mess up the
  28195. // iteration state and also require updating the state we can
  28196. // just throw away
  28197. const actionsToRemove = actionsForClip.knownActions;
  28198. for (let i = 0, n = actionsToRemove.length; i !== n; ++i) {
  28199. const action = actionsToRemove[i];
  28200. this._deactivateAction(action);
  28201. const cacheIndex = action._cacheIndex,
  28202. lastInactiveAction = actions[actions.length - 1];
  28203. action._cacheIndex = null;
  28204. action._byClipCacheIndex = null;
  28205. lastInactiveAction._cacheIndex = cacheIndex;
  28206. actions[cacheIndex] = lastInactiveAction;
  28207. actions.pop();
  28208. this._removeInactiveBindingsForAction(action);
  28209. }
  28210. delete actionsByClip[clipUuid];
  28211. }
  28212. }
  28213. // free all resources specific to a particular root target object
  28214. uncacheRoot(root) {
  28215. const rootUuid = root.uuid,
  28216. actionsByClip = this._actionsByClip;
  28217. for (const clipUuid in actionsByClip) {
  28218. const actionByRoot = actionsByClip[clipUuid].actionByRoot,
  28219. action = actionByRoot[rootUuid];
  28220. if (action !== undefined) {
  28221. this._deactivateAction(action);
  28222. this._removeInactiveAction(action);
  28223. }
  28224. }
  28225. const bindingsByRoot = this._bindingsByRootAndName,
  28226. bindingByName = bindingsByRoot[rootUuid];
  28227. if (bindingByName !== undefined) {
  28228. for (const trackName in bindingByName) {
  28229. const binding = bindingByName[trackName];
  28230. binding.restoreOriginalState();
  28231. this._removeInactiveBinding(binding);
  28232. }
  28233. }
  28234. }
  28235. // remove a targeted clip from the cache
  28236. uncacheAction(clip, optionalRoot) {
  28237. const action = this.existingAction(clip, optionalRoot);
  28238. if (action !== null) {
  28239. this._deactivateAction(action);
  28240. this._removeInactiveAction(action);
  28241. }
  28242. }
  28243. }
  28244. class Uniform {
  28245. constructor(value) {
  28246. this.value = value;
  28247. }
  28248. clone() {
  28249. return new Uniform(this.value.clone === undefined ? this.value : this.value.clone());
  28250. }
  28251. }
  28252. let id = 0;
  28253. class UniformsGroup extends EventDispatcher {
  28254. constructor() {
  28255. super();
  28256. this.isUniformsGroup = true;
  28257. Object.defineProperty(this, 'id', {
  28258. value: id++
  28259. });
  28260. this.name = '';
  28261. this.usage = StaticDrawUsage;
  28262. this.uniforms = [];
  28263. }
  28264. add(uniform) {
  28265. this.uniforms.push(uniform);
  28266. return this;
  28267. }
  28268. remove(uniform) {
  28269. const index = this.uniforms.indexOf(uniform);
  28270. if (index !== -1) this.uniforms.splice(index, 1);
  28271. return this;
  28272. }
  28273. setName(name) {
  28274. this.name = name;
  28275. return this;
  28276. }
  28277. setUsage(value) {
  28278. this.usage = value;
  28279. return this;
  28280. }
  28281. dispose() {
  28282. this.dispatchEvent({
  28283. type: 'dispose'
  28284. });
  28285. return this;
  28286. }
  28287. copy(source) {
  28288. this.name = source.name;
  28289. this.usage = source.usage;
  28290. const uniformsSource = source.uniforms;
  28291. this.uniforms.length = 0;
  28292. for (let i = 0, l = uniformsSource.length; i < l; i++) {
  28293. this.uniforms.push(uniformsSource[i].clone());
  28294. }
  28295. return this;
  28296. }
  28297. clone() {
  28298. return new this.constructor().copy(this);
  28299. }
  28300. }
  28301. class InstancedInterleavedBuffer extends InterleavedBuffer {
  28302. constructor(array, stride, meshPerAttribute = 1) {
  28303. super(array, stride);
  28304. this.isInstancedInterleavedBuffer = true;
  28305. this.meshPerAttribute = meshPerAttribute;
  28306. }
  28307. copy(source) {
  28308. super.copy(source);
  28309. this.meshPerAttribute = source.meshPerAttribute;
  28310. return this;
  28311. }
  28312. clone(data) {
  28313. const ib = super.clone(data);
  28314. ib.meshPerAttribute = this.meshPerAttribute;
  28315. return ib;
  28316. }
  28317. toJSON(data) {
  28318. const json = super.toJSON(data);
  28319. json.isInstancedInterleavedBuffer = true;
  28320. json.meshPerAttribute = this.meshPerAttribute;
  28321. return json;
  28322. }
  28323. }
  28324. class GLBufferAttribute {
  28325. constructor(buffer, type, itemSize, elementSize, count) {
  28326. this.isGLBufferAttribute = true;
  28327. this.buffer = buffer;
  28328. this.type = type;
  28329. this.itemSize = itemSize;
  28330. this.elementSize = elementSize;
  28331. this.count = count;
  28332. this.version = 0;
  28333. }
  28334. set needsUpdate(value) {
  28335. if (value === true) this.version++;
  28336. }
  28337. setBuffer(buffer) {
  28338. this.buffer = buffer;
  28339. return this;
  28340. }
  28341. setType(type, elementSize) {
  28342. this.type = type;
  28343. this.elementSize = elementSize;
  28344. return this;
  28345. }
  28346. setItemSize(itemSize) {
  28347. this.itemSize = itemSize;
  28348. return this;
  28349. }
  28350. setCount(count) {
  28351. this.count = count;
  28352. return this;
  28353. }
  28354. }
  28355. class Raycaster {
  28356. constructor(origin, direction, near = 0, far = Infinity) {
  28357. this.ray = new Ray(origin, direction);
  28358. // direction is assumed to be normalized (for accurate distance calculations)
  28359. this.near = near;
  28360. this.far = far;
  28361. this.camera = null;
  28362. this.layers = new Layers();
  28363. this.params = {
  28364. Mesh: {},
  28365. Line: {
  28366. threshold: 1
  28367. },
  28368. LOD: {},
  28369. Points: {
  28370. threshold: 1
  28371. },
  28372. Sprite: {}
  28373. };
  28374. }
  28375. set(origin, direction) {
  28376. // direction is assumed to be normalized (for accurate distance calculations)
  28377. this.ray.set(origin, direction);
  28378. }
  28379. setFromCamera(coords, camera) {
  28380. if (camera.isPerspectiveCamera) {
  28381. this.ray.origin.setFromMatrixPosition(camera.matrixWorld);
  28382. this.ray.direction.set(coords.x, coords.y, 0.5).unproject(camera).sub(this.ray.origin).normalize();
  28383. this.camera = camera;
  28384. } else if (camera.isOrthographicCamera) {
  28385. this.ray.origin.set(coords.x, coords.y, (camera.near + camera.far) / (camera.near - camera.far)).unproject(camera); // set origin in plane of camera
  28386. this.ray.direction.set(0, 0, -1).transformDirection(camera.matrixWorld);
  28387. this.camera = camera;
  28388. } else {
  28389. console.error('THREE.Raycaster: Unsupported camera type: ' + camera.type);
  28390. }
  28391. }
  28392. intersectObject(object, recursive = true, intersects = []) {
  28393. intersectObject(object, this, intersects, recursive);
  28394. intersects.sort(ascSort);
  28395. return intersects;
  28396. }
  28397. intersectObjects(objects, recursive = true, intersects = []) {
  28398. for (let i = 0, l = objects.length; i < l; i++) {
  28399. intersectObject(objects[i], this, intersects, recursive);
  28400. }
  28401. intersects.sort(ascSort);
  28402. return intersects;
  28403. }
  28404. }
  28405. function ascSort(a, b) {
  28406. return a.distance - b.distance;
  28407. }
  28408. function intersectObject(object, raycaster, intersects, recursive) {
  28409. if (object.layers.test(raycaster.layers)) {
  28410. object.raycast(raycaster, intersects);
  28411. }
  28412. if (recursive === true) {
  28413. const children = object.children;
  28414. for (let i = 0, l = children.length; i < l; i++) {
  28415. intersectObject(children[i], raycaster, intersects, true);
  28416. }
  28417. }
  28418. }
  28419. /**
  28420. * Ref: https://en.wikipedia.org/wiki/Spherical_coordinate_system
  28421. *
  28422. * The polar angle (phi) is measured from the positive y-axis. The positive y-axis is up.
  28423. * The azimuthal angle (theta) is measured from the positive z-axis.
  28424. */
  28425. class Spherical {
  28426. constructor(radius = 1, phi = 0, theta = 0) {
  28427. this.radius = radius;
  28428. this.phi = phi; // polar angle
  28429. this.theta = theta; // azimuthal angle
  28430. return this;
  28431. }
  28432. set(radius, phi, theta) {
  28433. this.radius = radius;
  28434. this.phi = phi;
  28435. this.theta = theta;
  28436. return this;
  28437. }
  28438. copy(other) {
  28439. this.radius = other.radius;
  28440. this.phi = other.phi;
  28441. this.theta = other.theta;
  28442. return this;
  28443. }
  28444. // restrict phi to be between EPS and PI-EPS
  28445. makeSafe() {
  28446. const EPS = 0.000001;
  28447. this.phi = Math.max(EPS, Math.min(Math.PI - EPS, this.phi));
  28448. return this;
  28449. }
  28450. setFromVector3(v) {
  28451. return this.setFromCartesianCoords(v.x, v.y, v.z);
  28452. }
  28453. setFromCartesianCoords(x, y, z) {
  28454. this.radius = Math.sqrt(x * x + y * y + z * z);
  28455. if (this.radius === 0) {
  28456. this.theta = 0;
  28457. this.phi = 0;
  28458. } else {
  28459. this.theta = Math.atan2(x, z);
  28460. this.phi = Math.acos(clamp(y / this.radius, -1, 1));
  28461. }
  28462. return this;
  28463. }
  28464. clone() {
  28465. return new this.constructor().copy(this);
  28466. }
  28467. }
  28468. /**
  28469. * Ref: https://en.wikipedia.org/wiki/Cylindrical_coordinate_system
  28470. */
  28471. class Cylindrical {
  28472. constructor(radius = 1, theta = 0, y = 0) {
  28473. this.radius = radius; // distance from the origin to a point in the x-z plane
  28474. this.theta = theta; // counterclockwise angle in the x-z plane measured in radians from the positive z-axis
  28475. this.y = y; // height above the x-z plane
  28476. return this;
  28477. }
  28478. set(radius, theta, y) {
  28479. this.radius = radius;
  28480. this.theta = theta;
  28481. this.y = y;
  28482. return this;
  28483. }
  28484. copy(other) {
  28485. this.radius = other.radius;
  28486. this.theta = other.theta;
  28487. this.y = other.y;
  28488. return this;
  28489. }
  28490. setFromVector3(v) {
  28491. return this.setFromCartesianCoords(v.x, v.y, v.z);
  28492. }
  28493. setFromCartesianCoords(x, y, z) {
  28494. this.radius = Math.sqrt(x * x + z * z);
  28495. this.theta = Math.atan2(x, z);
  28496. this.y = y;
  28497. return this;
  28498. }
  28499. clone() {
  28500. return new this.constructor().copy(this);
  28501. }
  28502. }
  28503. const _vector$4 = /*@__PURE__*/new Vector2();
  28504. class Box2 {
  28505. constructor(min = new Vector2(+Infinity, +Infinity), max = new Vector2(-Infinity, -Infinity)) {
  28506. this.isBox2 = true;
  28507. this.min = min;
  28508. this.max = max;
  28509. }
  28510. set(min, max) {
  28511. this.min.copy(min);
  28512. this.max.copy(max);
  28513. return this;
  28514. }
  28515. setFromPoints(points) {
  28516. this.makeEmpty();
  28517. for (let i = 0, il = points.length; i < il; i++) {
  28518. this.expandByPoint(points[i]);
  28519. }
  28520. return this;
  28521. }
  28522. setFromCenterAndSize(center, size) {
  28523. const halfSize = _vector$4.copy(size).multiplyScalar(0.5);
  28524. this.min.copy(center).sub(halfSize);
  28525. this.max.copy(center).add(halfSize);
  28526. return this;
  28527. }
  28528. clone() {
  28529. return new this.constructor().copy(this);
  28530. }
  28531. copy(box) {
  28532. this.min.copy(box.min);
  28533. this.max.copy(box.max);
  28534. return this;
  28535. }
  28536. makeEmpty() {
  28537. this.min.x = this.min.y = +Infinity;
  28538. this.max.x = this.max.y = -Infinity;
  28539. return this;
  28540. }
  28541. isEmpty() {
  28542. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  28543. return this.max.x < this.min.x || this.max.y < this.min.y;
  28544. }
  28545. getCenter(target) {
  28546. return this.isEmpty() ? target.set(0, 0) : target.addVectors(this.min, this.max).multiplyScalar(0.5);
  28547. }
  28548. getSize(target) {
  28549. return this.isEmpty() ? target.set(0, 0) : target.subVectors(this.max, this.min);
  28550. }
  28551. expandByPoint(point) {
  28552. this.min.min(point);
  28553. this.max.max(point);
  28554. return this;
  28555. }
  28556. expandByVector(vector) {
  28557. this.min.sub(vector);
  28558. this.max.add(vector);
  28559. return this;
  28560. }
  28561. expandByScalar(scalar) {
  28562. this.min.addScalar(-scalar);
  28563. this.max.addScalar(scalar);
  28564. return this;
  28565. }
  28566. containsPoint(point) {
  28567. return point.x < this.min.x || point.x > this.max.x || point.y < this.min.y || point.y > this.max.y ? false : true;
  28568. }
  28569. containsBox(box) {
  28570. 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;
  28571. }
  28572. getParameter(point, target) {
  28573. // This can potentially have a divide by zero if the box
  28574. // has a size dimension of 0.
  28575. 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));
  28576. }
  28577. intersectsBox(box) {
  28578. // using 4 splitting planes to rule out intersections
  28579. 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;
  28580. }
  28581. clampPoint(point, target) {
  28582. return target.copy(point).clamp(this.min, this.max);
  28583. }
  28584. distanceToPoint(point) {
  28585. const clampedPoint = _vector$4.copy(point).clamp(this.min, this.max);
  28586. return clampedPoint.sub(point).length();
  28587. }
  28588. intersect(box) {
  28589. this.min.max(box.min);
  28590. this.max.min(box.max);
  28591. return this;
  28592. }
  28593. union(box) {
  28594. this.min.min(box.min);
  28595. this.max.max(box.max);
  28596. return this;
  28597. }
  28598. translate(offset) {
  28599. this.min.add(offset);
  28600. this.max.add(offset);
  28601. return this;
  28602. }
  28603. equals(box) {
  28604. return box.min.equals(this.min) && box.max.equals(this.max);
  28605. }
  28606. }
  28607. const _startP = /*@__PURE__*/new Vector3();
  28608. const _startEnd = /*@__PURE__*/new Vector3();
  28609. class Line3 {
  28610. constructor(start = new Vector3(), end = new Vector3()) {
  28611. this.start = start;
  28612. this.end = end;
  28613. }
  28614. set(start, end) {
  28615. this.start.copy(start);
  28616. this.end.copy(end);
  28617. return this;
  28618. }
  28619. copy(line) {
  28620. this.start.copy(line.start);
  28621. this.end.copy(line.end);
  28622. return this;
  28623. }
  28624. getCenter(target) {
  28625. return target.addVectors(this.start, this.end).multiplyScalar(0.5);
  28626. }
  28627. delta(target) {
  28628. return target.subVectors(this.end, this.start);
  28629. }
  28630. distanceSq() {
  28631. return this.start.distanceToSquared(this.end);
  28632. }
  28633. distance() {
  28634. return this.start.distanceTo(this.end);
  28635. }
  28636. at(t, target) {
  28637. return this.delta(target).multiplyScalar(t).add(this.start);
  28638. }
  28639. closestPointToPointParameter(point, clampToLine) {
  28640. _startP.subVectors(point, this.start);
  28641. _startEnd.subVectors(this.end, this.start);
  28642. const startEnd2 = _startEnd.dot(_startEnd);
  28643. const startEnd_startP = _startEnd.dot(_startP);
  28644. let t = startEnd_startP / startEnd2;
  28645. if (clampToLine) {
  28646. t = clamp(t, 0, 1);
  28647. }
  28648. return t;
  28649. }
  28650. closestPointToPoint(point, clampToLine, target) {
  28651. const t = this.closestPointToPointParameter(point, clampToLine);
  28652. return this.delta(target).multiplyScalar(t).add(this.start);
  28653. }
  28654. applyMatrix4(matrix) {
  28655. this.start.applyMatrix4(matrix);
  28656. this.end.applyMatrix4(matrix);
  28657. return this;
  28658. }
  28659. equals(line) {
  28660. return line.start.equals(this.start) && line.end.equals(this.end);
  28661. }
  28662. clone() {
  28663. return new this.constructor().copy(this);
  28664. }
  28665. }
  28666. const _vector$3 = /*@__PURE__*/new Vector3();
  28667. class SpotLightHelper extends Object3D {
  28668. constructor(light, color) {
  28669. super();
  28670. this.light = light;
  28671. this.matrix = light.matrixWorld;
  28672. this.matrixAutoUpdate = false;
  28673. this.color = color;
  28674. this.type = 'SpotLightHelper';
  28675. const geometry = new BufferGeometry();
  28676. 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];
  28677. for (let i = 0, j = 1, l = 32; i < l; i++, j++) {
  28678. const p1 = i / l * Math.PI * 2;
  28679. const p2 = j / l * Math.PI * 2;
  28680. positions.push(Math.cos(p1), Math.sin(p1), 1, Math.cos(p2), Math.sin(p2), 1);
  28681. }
  28682. geometry.setAttribute('position', new Float32BufferAttribute(positions, 3));
  28683. const material = new LineBasicMaterial({
  28684. fog: false,
  28685. toneMapped: false
  28686. });
  28687. this.cone = new LineSegments(geometry, material);
  28688. this.add(this.cone);
  28689. this.update();
  28690. }
  28691. dispose() {
  28692. this.cone.geometry.dispose();
  28693. this.cone.material.dispose();
  28694. }
  28695. update() {
  28696. this.light.updateWorldMatrix(true, false);
  28697. this.light.target.updateWorldMatrix(true, false);
  28698. const coneLength = this.light.distance ? this.light.distance : 1000;
  28699. const coneWidth = coneLength * Math.tan(this.light.angle);
  28700. this.cone.scale.set(coneWidth, coneWidth, coneLength);
  28701. _vector$3.setFromMatrixPosition(this.light.target.matrixWorld);
  28702. this.cone.lookAt(_vector$3);
  28703. if (this.color !== undefined) {
  28704. this.cone.material.color.set(this.color);
  28705. } else {
  28706. this.cone.material.color.copy(this.light.color);
  28707. }
  28708. }
  28709. }
  28710. const _vector$2 = /*@__PURE__*/new Vector3();
  28711. const _boneMatrix = /*@__PURE__*/new Matrix4();
  28712. const _matrixWorldInv = /*@__PURE__*/new Matrix4();
  28713. class SkeletonHelper extends LineSegments {
  28714. constructor(object) {
  28715. const bones = getBoneList(object);
  28716. const geometry = new BufferGeometry();
  28717. const vertices = [];
  28718. const colors = [];
  28719. const color1 = new Color(0, 0, 1);
  28720. const color2 = new Color(0, 1, 0);
  28721. for (let i = 0; i < bones.length; i++) {
  28722. const bone = bones[i];
  28723. if (bone.parent && bone.parent.isBone) {
  28724. vertices.push(0, 0, 0);
  28725. vertices.push(0, 0, 0);
  28726. colors.push(color1.r, color1.g, color1.b);
  28727. colors.push(color2.r, color2.g, color2.b);
  28728. }
  28729. }
  28730. geometry.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  28731. geometry.setAttribute('color', new Float32BufferAttribute(colors, 3));
  28732. const material = new LineBasicMaterial({
  28733. vertexColors: true,
  28734. depthTest: false,
  28735. depthWrite: false,
  28736. toneMapped: false,
  28737. transparent: true
  28738. });
  28739. super(geometry, material);
  28740. this.isSkeletonHelper = true;
  28741. this.type = 'SkeletonHelper';
  28742. this.root = object;
  28743. this.bones = bones;
  28744. this.matrix = object.matrixWorld;
  28745. this.matrixAutoUpdate = false;
  28746. }
  28747. updateMatrixWorld(force) {
  28748. const bones = this.bones;
  28749. const geometry = this.geometry;
  28750. const position = geometry.getAttribute('position');
  28751. _matrixWorldInv.copy(this.root.matrixWorld).invert();
  28752. for (let i = 0, j = 0; i < bones.length; i++) {
  28753. const bone = bones[i];
  28754. if (bone.parent && bone.parent.isBone) {
  28755. _boneMatrix.multiplyMatrices(_matrixWorldInv, bone.matrixWorld);
  28756. _vector$2.setFromMatrixPosition(_boneMatrix);
  28757. position.setXYZ(j, _vector$2.x, _vector$2.y, _vector$2.z);
  28758. _boneMatrix.multiplyMatrices(_matrixWorldInv, bone.parent.matrixWorld);
  28759. _vector$2.setFromMatrixPosition(_boneMatrix);
  28760. position.setXYZ(j + 1, _vector$2.x, _vector$2.y, _vector$2.z);
  28761. j += 2;
  28762. }
  28763. }
  28764. geometry.getAttribute('position').needsUpdate = true;
  28765. super.updateMatrixWorld(force);
  28766. }
  28767. dispose() {
  28768. this.geometry.dispose();
  28769. this.material.dispose();
  28770. }
  28771. }
  28772. function getBoneList(object) {
  28773. const boneList = [];
  28774. if (object.isBone === true) {
  28775. boneList.push(object);
  28776. }
  28777. for (let i = 0; i < object.children.length; i++) {
  28778. boneList.push.apply(boneList, getBoneList(object.children[i]));
  28779. }
  28780. return boneList;
  28781. }
  28782. class PointLightHelper extends Mesh {
  28783. constructor(light, sphereSize, color) {
  28784. const geometry = new SphereGeometry(sphereSize, 4, 2);
  28785. const material = new MeshBasicMaterial({
  28786. wireframe: true,
  28787. fog: false,
  28788. toneMapped: false
  28789. });
  28790. super(geometry, material);
  28791. this.light = light;
  28792. this.color = color;
  28793. this.type = 'PointLightHelper';
  28794. this.matrix = this.light.matrixWorld;
  28795. this.matrixAutoUpdate = false;
  28796. this.update();
  28797. /*
  28798. // TODO: delete this comment?
  28799. const distanceGeometry = new THREE.IcosahedronGeometry( 1, 2 );
  28800. const distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  28801. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  28802. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  28803. const d = light.distance;
  28804. if ( d === 0.0 ) {
  28805. this.lightDistance.visible = false;
  28806. } else {
  28807. this.lightDistance.scale.set( d, d, d );
  28808. }
  28809. this.add( this.lightDistance );
  28810. */
  28811. }
  28812. dispose() {
  28813. this.geometry.dispose();
  28814. this.material.dispose();
  28815. }
  28816. update() {
  28817. this.light.updateWorldMatrix(true, false);
  28818. if (this.color !== undefined) {
  28819. this.material.color.set(this.color);
  28820. } else {
  28821. this.material.color.copy(this.light.color);
  28822. }
  28823. /*
  28824. const d = this.light.distance;
  28825. if ( d === 0.0 ) {
  28826. this.lightDistance.visible = false;
  28827. } else {
  28828. this.lightDistance.visible = true;
  28829. this.lightDistance.scale.set( d, d, d );
  28830. }
  28831. */
  28832. }
  28833. }
  28834. const _vector$1 = /*@__PURE__*/new Vector3();
  28835. const _color1 = /*@__PURE__*/new Color();
  28836. const _color2 = /*@__PURE__*/new Color();
  28837. class HemisphereLightHelper extends Object3D {
  28838. constructor(light, size, color) {
  28839. super();
  28840. this.light = light;
  28841. this.matrix = light.matrixWorld;
  28842. this.matrixAutoUpdate = false;
  28843. this.color = color;
  28844. this.type = 'HemisphereLightHelper';
  28845. const geometry = new OctahedronGeometry(size);
  28846. geometry.rotateY(Math.PI * 0.5);
  28847. this.material = new MeshBasicMaterial({
  28848. wireframe: true,
  28849. fog: false,
  28850. toneMapped: false
  28851. });
  28852. if (this.color === undefined) this.material.vertexColors = true;
  28853. const position = geometry.getAttribute('position');
  28854. const colors = new Float32Array(position.count * 3);
  28855. geometry.setAttribute('color', new BufferAttribute(colors, 3));
  28856. this.add(new Mesh(geometry, this.material));
  28857. this.update();
  28858. }
  28859. dispose() {
  28860. this.children[0].geometry.dispose();
  28861. this.children[0].material.dispose();
  28862. }
  28863. update() {
  28864. const mesh = this.children[0];
  28865. if (this.color !== undefined) {
  28866. this.material.color.set(this.color);
  28867. } else {
  28868. const colors = mesh.geometry.getAttribute('color');
  28869. _color1.copy(this.light.color);
  28870. _color2.copy(this.light.groundColor);
  28871. for (let i = 0, l = colors.count; i < l; i++) {
  28872. const color = i < l / 2 ? _color1 : _color2;
  28873. colors.setXYZ(i, color.r, color.g, color.b);
  28874. }
  28875. colors.needsUpdate = true;
  28876. }
  28877. this.light.updateWorldMatrix(true, false);
  28878. mesh.lookAt(_vector$1.setFromMatrixPosition(this.light.matrixWorld).negate());
  28879. }
  28880. }
  28881. class GridHelper extends LineSegments {
  28882. constructor(size = 10, divisions = 10, color1 = 0x444444, color2 = 0x888888) {
  28883. color1 = new Color(color1);
  28884. color2 = new Color(color2);
  28885. const center = divisions / 2;
  28886. const step = size / divisions;
  28887. const halfSize = size / 2;
  28888. const vertices = [],
  28889. colors = [];
  28890. for (let i = 0, j = 0, k = -halfSize; i <= divisions; i++, k += step) {
  28891. vertices.push(-halfSize, 0, k, halfSize, 0, k);
  28892. vertices.push(k, 0, -halfSize, k, 0, halfSize);
  28893. const color = i === center ? color1 : color2;
  28894. color.toArray(colors, j);
  28895. j += 3;
  28896. color.toArray(colors, j);
  28897. j += 3;
  28898. color.toArray(colors, j);
  28899. j += 3;
  28900. color.toArray(colors, j);
  28901. j += 3;
  28902. }
  28903. const geometry = new BufferGeometry();
  28904. geometry.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  28905. geometry.setAttribute('color', new Float32BufferAttribute(colors, 3));
  28906. const material = new LineBasicMaterial({
  28907. vertexColors: true,
  28908. toneMapped: false
  28909. });
  28910. super(geometry, material);
  28911. this.type = 'GridHelper';
  28912. }
  28913. dispose() {
  28914. this.geometry.dispose();
  28915. this.material.dispose();
  28916. }
  28917. }
  28918. class PolarGridHelper extends LineSegments {
  28919. constructor(radius = 10, sectors = 16, rings = 8, divisions = 64, color1 = 0x444444, color2 = 0x888888) {
  28920. color1 = new Color(color1);
  28921. color2 = new Color(color2);
  28922. const vertices = [];
  28923. const colors = [];
  28924. // create the sectors
  28925. if (sectors > 1) {
  28926. for (let i = 0; i < sectors; i++) {
  28927. const v = i / sectors * (Math.PI * 2);
  28928. const x = Math.sin(v) * radius;
  28929. const z = Math.cos(v) * radius;
  28930. vertices.push(0, 0, 0);
  28931. vertices.push(x, 0, z);
  28932. const color = i & 1 ? color1 : color2;
  28933. colors.push(color.r, color.g, color.b);
  28934. colors.push(color.r, color.g, color.b);
  28935. }
  28936. }
  28937. // create the rings
  28938. for (let i = 0; i < rings; i++) {
  28939. const color = i & 1 ? color1 : color2;
  28940. const r = radius - radius / rings * i;
  28941. for (let j = 0; j < divisions; j++) {
  28942. // first vertex
  28943. let v = j / divisions * (Math.PI * 2);
  28944. let x = Math.sin(v) * r;
  28945. let z = Math.cos(v) * r;
  28946. vertices.push(x, 0, z);
  28947. colors.push(color.r, color.g, color.b);
  28948. // second vertex
  28949. v = (j + 1) / divisions * (Math.PI * 2);
  28950. x = Math.sin(v) * r;
  28951. z = Math.cos(v) * r;
  28952. vertices.push(x, 0, z);
  28953. colors.push(color.r, color.g, color.b);
  28954. }
  28955. }
  28956. const geometry = new BufferGeometry();
  28957. geometry.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  28958. geometry.setAttribute('color', new Float32BufferAttribute(colors, 3));
  28959. const material = new LineBasicMaterial({
  28960. vertexColors: true,
  28961. toneMapped: false
  28962. });
  28963. super(geometry, material);
  28964. this.type = 'PolarGridHelper';
  28965. }
  28966. dispose() {
  28967. this.geometry.dispose();
  28968. this.material.dispose();
  28969. }
  28970. }
  28971. const _v1 = /*@__PURE__*/new Vector3();
  28972. const _v2 = /*@__PURE__*/new Vector3();
  28973. const _v3 = /*@__PURE__*/new Vector3();
  28974. class DirectionalLightHelper extends Object3D {
  28975. constructor(light, size, color) {
  28976. super();
  28977. this.light = light;
  28978. this.matrix = light.matrixWorld;
  28979. this.matrixAutoUpdate = false;
  28980. this.color = color;
  28981. this.type = 'DirectionalLightHelper';
  28982. if (size === undefined) size = 1;
  28983. let geometry = new BufferGeometry();
  28984. geometry.setAttribute('position', new Float32BufferAttribute([-size, size, 0, size, size, 0, size, -size, 0, -size, -size, 0, -size, size, 0], 3));
  28985. const material = new LineBasicMaterial({
  28986. fog: false,
  28987. toneMapped: false
  28988. });
  28989. this.lightPlane = new Line(geometry, material);
  28990. this.add(this.lightPlane);
  28991. geometry = new BufferGeometry();
  28992. geometry.setAttribute('position', new Float32BufferAttribute([0, 0, 0, 0, 0, 1], 3));
  28993. this.targetLine = new Line(geometry, material);
  28994. this.add(this.targetLine);
  28995. this.update();
  28996. }
  28997. dispose() {
  28998. this.lightPlane.geometry.dispose();
  28999. this.lightPlane.material.dispose();
  29000. this.targetLine.geometry.dispose();
  29001. this.targetLine.material.dispose();
  29002. }
  29003. update() {
  29004. this.light.updateWorldMatrix(true, false);
  29005. this.light.target.updateWorldMatrix(true, false);
  29006. _v1.setFromMatrixPosition(this.light.matrixWorld);
  29007. _v2.setFromMatrixPosition(this.light.target.matrixWorld);
  29008. _v3.subVectors(_v2, _v1);
  29009. this.lightPlane.lookAt(_v2);
  29010. if (this.color !== undefined) {
  29011. this.lightPlane.material.color.set(this.color);
  29012. this.targetLine.material.color.set(this.color);
  29013. } else {
  29014. this.lightPlane.material.color.copy(this.light.color);
  29015. this.targetLine.material.color.copy(this.light.color);
  29016. }
  29017. this.targetLine.lookAt(_v2);
  29018. this.targetLine.scale.z = _v3.length();
  29019. }
  29020. }
  29021. const _vector = /*@__PURE__*/new Vector3();
  29022. const _camera = /*@__PURE__*/new Camera();
  29023. /**
  29024. * - shows frustum, line of sight and up of the camera
  29025. * - suitable for fast updates
  29026. * - based on frustum visualization in lightgl.js shadowmap example
  29027. * https://github.com/evanw/lightgl.js/blob/master/tests/shadowmap.html
  29028. */
  29029. class CameraHelper extends LineSegments {
  29030. constructor(camera) {
  29031. const geometry = new BufferGeometry();
  29032. const material = new LineBasicMaterial({
  29033. color: 0xffffff,
  29034. vertexColors: true,
  29035. toneMapped: false
  29036. });
  29037. const vertices = [];
  29038. const colors = [];
  29039. const pointMap = {};
  29040. // near
  29041. addLine('n1', 'n2');
  29042. addLine('n2', 'n4');
  29043. addLine('n4', 'n3');
  29044. addLine('n3', 'n1');
  29045. // far
  29046. addLine('f1', 'f2');
  29047. addLine('f2', 'f4');
  29048. addLine('f4', 'f3');
  29049. addLine('f3', 'f1');
  29050. // sides
  29051. addLine('n1', 'f1');
  29052. addLine('n2', 'f2');
  29053. addLine('n3', 'f3');
  29054. addLine('n4', 'f4');
  29055. // cone
  29056. addLine('p', 'n1');
  29057. addLine('p', 'n2');
  29058. addLine('p', 'n3');
  29059. addLine('p', 'n4');
  29060. // up
  29061. addLine('u1', 'u2');
  29062. addLine('u2', 'u3');
  29063. addLine('u3', 'u1');
  29064. // target
  29065. addLine('c', 't');
  29066. addLine('p', 'c');
  29067. // cross
  29068. addLine('cn1', 'cn2');
  29069. addLine('cn3', 'cn4');
  29070. addLine('cf1', 'cf2');
  29071. addLine('cf3', 'cf4');
  29072. function addLine(a, b) {
  29073. addPoint(a);
  29074. addPoint(b);
  29075. }
  29076. function addPoint(id) {
  29077. vertices.push(0, 0, 0);
  29078. colors.push(0, 0, 0);
  29079. if (pointMap[id] === undefined) {
  29080. pointMap[id] = [];
  29081. }
  29082. pointMap[id].push(vertices.length / 3 - 1);
  29083. }
  29084. geometry.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  29085. geometry.setAttribute('color', new Float32BufferAttribute(colors, 3));
  29086. super(geometry, material);
  29087. this.type = 'CameraHelper';
  29088. this.camera = camera;
  29089. if (this.camera.updateProjectionMatrix) this.camera.updateProjectionMatrix();
  29090. this.matrix = camera.matrixWorld;
  29091. this.matrixAutoUpdate = false;
  29092. this.pointMap = pointMap;
  29093. this.update();
  29094. // colors
  29095. const colorFrustum = new Color(0xffaa00);
  29096. const colorCone = new Color(0xff0000);
  29097. const colorUp = new Color(0x00aaff);
  29098. const colorTarget = new Color(0xffffff);
  29099. const colorCross = new Color(0x333333);
  29100. this.setColors(colorFrustum, colorCone, colorUp, colorTarget, colorCross);
  29101. }
  29102. setColors(frustum, cone, up, target, cross) {
  29103. const geometry = this.geometry;
  29104. const colorAttribute = geometry.getAttribute('color');
  29105. // near
  29106. colorAttribute.setXYZ(0, frustum.r, frustum.g, frustum.b);
  29107. colorAttribute.setXYZ(1, frustum.r, frustum.g, frustum.b); // n1, n2
  29108. colorAttribute.setXYZ(2, frustum.r, frustum.g, frustum.b);
  29109. colorAttribute.setXYZ(3, frustum.r, frustum.g, frustum.b); // n2, n4
  29110. colorAttribute.setXYZ(4, frustum.r, frustum.g, frustum.b);
  29111. colorAttribute.setXYZ(5, frustum.r, frustum.g, frustum.b); // n4, n3
  29112. colorAttribute.setXYZ(6, frustum.r, frustum.g, frustum.b);
  29113. colorAttribute.setXYZ(7, frustum.r, frustum.g, frustum.b); // n3, n1
  29114. // far
  29115. colorAttribute.setXYZ(8, frustum.r, frustum.g, frustum.b);
  29116. colorAttribute.setXYZ(9, frustum.r, frustum.g, frustum.b); // f1, f2
  29117. colorAttribute.setXYZ(10, frustum.r, frustum.g, frustum.b);
  29118. colorAttribute.setXYZ(11, frustum.r, frustum.g, frustum.b); // f2, f4
  29119. colorAttribute.setXYZ(12, frustum.r, frustum.g, frustum.b);
  29120. colorAttribute.setXYZ(13, frustum.r, frustum.g, frustum.b); // f4, f3
  29121. colorAttribute.setXYZ(14, frustum.r, frustum.g, frustum.b);
  29122. colorAttribute.setXYZ(15, frustum.r, frustum.g, frustum.b); // f3, f1
  29123. // sides
  29124. colorAttribute.setXYZ(16, frustum.r, frustum.g, frustum.b);
  29125. colorAttribute.setXYZ(17, frustum.r, frustum.g, frustum.b); // n1, f1
  29126. colorAttribute.setXYZ(18, frustum.r, frustum.g, frustum.b);
  29127. colorAttribute.setXYZ(19, frustum.r, frustum.g, frustum.b); // n2, f2
  29128. colorAttribute.setXYZ(20, frustum.r, frustum.g, frustum.b);
  29129. colorAttribute.setXYZ(21, frustum.r, frustum.g, frustum.b); // n3, f3
  29130. colorAttribute.setXYZ(22, frustum.r, frustum.g, frustum.b);
  29131. colorAttribute.setXYZ(23, frustum.r, frustum.g, frustum.b); // n4, f4
  29132. // cone
  29133. colorAttribute.setXYZ(24, cone.r, cone.g, cone.b);
  29134. colorAttribute.setXYZ(25, cone.r, cone.g, cone.b); // p, n1
  29135. colorAttribute.setXYZ(26, cone.r, cone.g, cone.b);
  29136. colorAttribute.setXYZ(27, cone.r, cone.g, cone.b); // p, n2
  29137. colorAttribute.setXYZ(28, cone.r, cone.g, cone.b);
  29138. colorAttribute.setXYZ(29, cone.r, cone.g, cone.b); // p, n3
  29139. colorAttribute.setXYZ(30, cone.r, cone.g, cone.b);
  29140. colorAttribute.setXYZ(31, cone.r, cone.g, cone.b); // p, n4
  29141. // up
  29142. colorAttribute.setXYZ(32, up.r, up.g, up.b);
  29143. colorAttribute.setXYZ(33, up.r, up.g, up.b); // u1, u2
  29144. colorAttribute.setXYZ(34, up.r, up.g, up.b);
  29145. colorAttribute.setXYZ(35, up.r, up.g, up.b); // u2, u3
  29146. colorAttribute.setXYZ(36, up.r, up.g, up.b);
  29147. colorAttribute.setXYZ(37, up.r, up.g, up.b); // u3, u1
  29148. // target
  29149. colorAttribute.setXYZ(38, target.r, target.g, target.b);
  29150. colorAttribute.setXYZ(39, target.r, target.g, target.b); // c, t
  29151. colorAttribute.setXYZ(40, cross.r, cross.g, cross.b);
  29152. colorAttribute.setXYZ(41, cross.r, cross.g, cross.b); // p, c
  29153. // cross
  29154. colorAttribute.setXYZ(42, cross.r, cross.g, cross.b);
  29155. colorAttribute.setXYZ(43, cross.r, cross.g, cross.b); // cn1, cn2
  29156. colorAttribute.setXYZ(44, cross.r, cross.g, cross.b);
  29157. colorAttribute.setXYZ(45, cross.r, cross.g, cross.b); // cn3, cn4
  29158. colorAttribute.setXYZ(46, cross.r, cross.g, cross.b);
  29159. colorAttribute.setXYZ(47, cross.r, cross.g, cross.b); // cf1, cf2
  29160. colorAttribute.setXYZ(48, cross.r, cross.g, cross.b);
  29161. colorAttribute.setXYZ(49, cross.r, cross.g, cross.b); // cf3, cf4
  29162. colorAttribute.needsUpdate = true;
  29163. }
  29164. update() {
  29165. const geometry = this.geometry;
  29166. const pointMap = this.pointMap;
  29167. const w = 1,
  29168. h = 1;
  29169. // we need just camera projection matrix inverse
  29170. // world matrix must be identity
  29171. _camera.projectionMatrixInverse.copy(this.camera.projectionMatrixInverse);
  29172. // center / target
  29173. setPoint('c', pointMap, geometry, _camera, 0, 0, -1);
  29174. setPoint('t', pointMap, geometry, _camera, 0, 0, 1);
  29175. // near
  29176. setPoint('n1', pointMap, geometry, _camera, -w, -h, -1);
  29177. setPoint('n2', pointMap, geometry, _camera, w, -h, -1);
  29178. setPoint('n3', pointMap, geometry, _camera, -w, h, -1);
  29179. setPoint('n4', pointMap, geometry, _camera, w, h, -1);
  29180. // far
  29181. setPoint('f1', pointMap, geometry, _camera, -w, -h, 1);
  29182. setPoint('f2', pointMap, geometry, _camera, w, -h, 1);
  29183. setPoint('f3', pointMap, geometry, _camera, -w, h, 1);
  29184. setPoint('f4', pointMap, geometry, _camera, w, h, 1);
  29185. // up
  29186. setPoint('u1', pointMap, geometry, _camera, w * 0.7, h * 1.1, -1);
  29187. setPoint('u2', pointMap, geometry, _camera, -w * 0.7, h * 1.1, -1);
  29188. setPoint('u3', pointMap, geometry, _camera, 0, h * 2, -1);
  29189. // cross
  29190. setPoint('cf1', pointMap, geometry, _camera, -w, 0, 1);
  29191. setPoint('cf2', pointMap, geometry, _camera, w, 0, 1);
  29192. setPoint('cf3', pointMap, geometry, _camera, 0, -h, 1);
  29193. setPoint('cf4', pointMap, geometry, _camera, 0, h, 1);
  29194. setPoint('cn1', pointMap, geometry, _camera, -w, 0, -1);
  29195. setPoint('cn2', pointMap, geometry, _camera, w, 0, -1);
  29196. setPoint('cn3', pointMap, geometry, _camera, 0, -h, -1);
  29197. setPoint('cn4', pointMap, geometry, _camera, 0, h, -1);
  29198. geometry.getAttribute('position').needsUpdate = true;
  29199. }
  29200. dispose() {
  29201. this.geometry.dispose();
  29202. this.material.dispose();
  29203. }
  29204. }
  29205. function setPoint(point, pointMap, geometry, camera, x, y, z) {
  29206. _vector.set(x, y, z).unproject(camera);
  29207. const points = pointMap[point];
  29208. if (points !== undefined) {
  29209. const position = geometry.getAttribute('position');
  29210. for (let i = 0, l = points.length; i < l; i++) {
  29211. position.setXYZ(points[i], _vector.x, _vector.y, _vector.z);
  29212. }
  29213. }
  29214. }
  29215. const _box = /*@__PURE__*/new Box3();
  29216. class BoxHelper extends LineSegments {
  29217. constructor(object, color = 0xffff00) {
  29218. 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]);
  29219. const positions = new Float32Array(8 * 3);
  29220. const geometry = new BufferGeometry();
  29221. geometry.setIndex(new BufferAttribute(indices, 1));
  29222. geometry.setAttribute('position', new BufferAttribute(positions, 3));
  29223. super(geometry, new LineBasicMaterial({
  29224. color: color,
  29225. toneMapped: false
  29226. }));
  29227. this.object = object;
  29228. this.type = 'BoxHelper';
  29229. this.matrixAutoUpdate = false;
  29230. this.update();
  29231. }
  29232. update(object) {
  29233. if (object !== undefined) {
  29234. console.warn('THREE.BoxHelper: .update() has no longer arguments.');
  29235. }
  29236. if (this.object !== undefined) {
  29237. _box.setFromObject(this.object);
  29238. }
  29239. if (_box.isEmpty()) return;
  29240. const min = _box.min;
  29241. const max = _box.max;
  29242. /*
  29243. 5____4
  29244. 1/___0/|
  29245. | 6__|_7
  29246. 2/___3/
  29247. 0: max.x, max.y, max.z
  29248. 1: min.x, max.y, max.z
  29249. 2: min.x, min.y, max.z
  29250. 3: max.x, min.y, max.z
  29251. 4: max.x, max.y, min.z
  29252. 5: min.x, max.y, min.z
  29253. 6: min.x, min.y, min.z
  29254. 7: max.x, min.y, min.z
  29255. */
  29256. const position = this.geometry.attributes.position;
  29257. const array = position.array;
  29258. array[0] = max.x;
  29259. array[1] = max.y;
  29260. array[2] = max.z;
  29261. array[3] = min.x;
  29262. array[4] = max.y;
  29263. array[5] = max.z;
  29264. array[6] = min.x;
  29265. array[7] = min.y;
  29266. array[8] = max.z;
  29267. array[9] = max.x;
  29268. array[10] = min.y;
  29269. array[11] = max.z;
  29270. array[12] = max.x;
  29271. array[13] = max.y;
  29272. array[14] = min.z;
  29273. array[15] = min.x;
  29274. array[16] = max.y;
  29275. array[17] = min.z;
  29276. array[18] = min.x;
  29277. array[19] = min.y;
  29278. array[20] = min.z;
  29279. array[21] = max.x;
  29280. array[22] = min.y;
  29281. array[23] = min.z;
  29282. position.needsUpdate = true;
  29283. this.geometry.computeBoundingSphere();
  29284. }
  29285. setFromObject(object) {
  29286. this.object = object;
  29287. this.update();
  29288. return this;
  29289. }
  29290. copy(source, recursive) {
  29291. super.copy(source, recursive);
  29292. this.object = source.object;
  29293. return this;
  29294. }
  29295. dispose() {
  29296. this.geometry.dispose();
  29297. this.material.dispose();
  29298. }
  29299. }
  29300. class Box3Helper extends LineSegments {
  29301. constructor(box, color = 0xffff00) {
  29302. 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]);
  29303. 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];
  29304. const geometry = new BufferGeometry();
  29305. geometry.setIndex(new BufferAttribute(indices, 1));
  29306. geometry.setAttribute('position', new Float32BufferAttribute(positions, 3));
  29307. super(geometry, new LineBasicMaterial({
  29308. color: color,
  29309. toneMapped: false
  29310. }));
  29311. this.box = box;
  29312. this.type = 'Box3Helper';
  29313. this.geometry.computeBoundingSphere();
  29314. }
  29315. updateMatrixWorld(force) {
  29316. const box = this.box;
  29317. if (box.isEmpty()) return;
  29318. box.getCenter(this.position);
  29319. box.getSize(this.scale);
  29320. this.scale.multiplyScalar(0.5);
  29321. super.updateMatrixWorld(force);
  29322. }
  29323. dispose() {
  29324. this.geometry.dispose();
  29325. this.material.dispose();
  29326. }
  29327. }
  29328. class PlaneHelper extends Line {
  29329. constructor(plane, size = 1, hex = 0xffff00) {
  29330. const color = hex;
  29331. 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];
  29332. const geometry = new BufferGeometry();
  29333. geometry.setAttribute('position', new Float32BufferAttribute(positions, 3));
  29334. geometry.computeBoundingSphere();
  29335. super(geometry, new LineBasicMaterial({
  29336. color: color,
  29337. toneMapped: false
  29338. }));
  29339. this.type = 'PlaneHelper';
  29340. this.plane = plane;
  29341. this.size = size;
  29342. const positions2 = [1, 1, 0, -1, 1, 0, -1, -1, 0, 1, 1, 0, -1, -1, 0, 1, -1, 0];
  29343. const geometry2 = new BufferGeometry();
  29344. geometry2.setAttribute('position', new Float32BufferAttribute(positions2, 3));
  29345. geometry2.computeBoundingSphere();
  29346. this.add(new Mesh(geometry2, new MeshBasicMaterial({
  29347. color: color,
  29348. opacity: 0.2,
  29349. transparent: true,
  29350. depthWrite: false,
  29351. toneMapped: false
  29352. })));
  29353. }
  29354. updateMatrixWorld(force) {
  29355. this.position.set(0, 0, 0);
  29356. this.scale.set(0.5 * this.size, 0.5 * this.size, 1);
  29357. this.lookAt(this.plane.normal);
  29358. this.translateZ(-this.plane.constant);
  29359. super.updateMatrixWorld(force);
  29360. }
  29361. dispose() {
  29362. this.geometry.dispose();
  29363. this.material.dispose();
  29364. this.children[0].geometry.dispose();
  29365. this.children[0].material.dispose();
  29366. }
  29367. }
  29368. const _axis = /*@__PURE__*/new Vector3();
  29369. let _lineGeometry, _coneGeometry;
  29370. class ArrowHelper extends Object3D {
  29371. // dir is assumed to be normalized
  29372. 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) {
  29373. super();
  29374. this.type = 'ArrowHelper';
  29375. if (_lineGeometry === undefined) {
  29376. _lineGeometry = new BufferGeometry();
  29377. _lineGeometry.setAttribute('position', new Float32BufferAttribute([0, 0, 0, 0, 1, 0], 3));
  29378. _coneGeometry = new CylinderGeometry(0, 0.5, 1, 5, 1);
  29379. _coneGeometry.translate(0, -0.5, 0);
  29380. }
  29381. this.position.copy(origin);
  29382. this.line = new Line(_lineGeometry, new LineBasicMaterial({
  29383. color: color,
  29384. toneMapped: false
  29385. }));
  29386. this.line.matrixAutoUpdate = false;
  29387. this.add(this.line);
  29388. this.cone = new Mesh(_coneGeometry, new MeshBasicMaterial({
  29389. color: color,
  29390. toneMapped: false
  29391. }));
  29392. this.cone.matrixAutoUpdate = false;
  29393. this.add(this.cone);
  29394. this.setDirection(dir);
  29395. this.setLength(length, headLength, headWidth);
  29396. }
  29397. setDirection(dir) {
  29398. // dir is assumed to be normalized
  29399. if (dir.y > 0.99999) {
  29400. this.quaternion.set(0, 0, 0, 1);
  29401. } else if (dir.y < -0.99999) {
  29402. this.quaternion.set(1, 0, 0, 0);
  29403. } else {
  29404. _axis.set(dir.z, 0, -dir.x).normalize();
  29405. const radians = Math.acos(dir.y);
  29406. this.quaternion.setFromAxisAngle(_axis, radians);
  29407. }
  29408. }
  29409. setLength(length, headLength = length * 0.2, headWidth = headLength * 0.2) {
  29410. this.line.scale.set(1, Math.max(0.0001, length - headLength), 1); // see #17458
  29411. this.line.updateMatrix();
  29412. this.cone.scale.set(headWidth, headLength, headWidth);
  29413. this.cone.position.y = length;
  29414. this.cone.updateMatrix();
  29415. }
  29416. setColor(color) {
  29417. this.line.material.color.set(color);
  29418. this.cone.material.color.set(color);
  29419. }
  29420. copy(source) {
  29421. super.copy(source, false);
  29422. this.line.copy(source.line);
  29423. this.cone.copy(source.cone);
  29424. return this;
  29425. }
  29426. dispose() {
  29427. this.line.geometry.dispose();
  29428. this.line.material.dispose();
  29429. this.cone.geometry.dispose();
  29430. this.cone.material.dispose();
  29431. }
  29432. }
  29433. class AxesHelper extends LineSegments {
  29434. constructor(size = 1) {
  29435. const vertices = [0, 0, 0, size, 0, 0, 0, 0, 0, 0, size, 0, 0, 0, 0, 0, 0, size];
  29436. const colors = [1, 0, 0, 1, 0.6, 0, 0, 1, 0, 0.6, 1, 0, 0, 0, 1, 0, 0.6, 1];
  29437. const geometry = new BufferGeometry();
  29438. geometry.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  29439. geometry.setAttribute('color', new Float32BufferAttribute(colors, 3));
  29440. const material = new LineBasicMaterial({
  29441. vertexColors: true,
  29442. toneMapped: false
  29443. });
  29444. super(geometry, material);
  29445. this.type = 'AxesHelper';
  29446. }
  29447. setColors(xAxisColor, yAxisColor, zAxisColor) {
  29448. const color = new Color();
  29449. const array = this.geometry.attributes.color.array;
  29450. color.set(xAxisColor);
  29451. color.toArray(array, 0);
  29452. color.toArray(array, 3);
  29453. color.set(yAxisColor);
  29454. color.toArray(array, 6);
  29455. color.toArray(array, 9);
  29456. color.set(zAxisColor);
  29457. color.toArray(array, 12);
  29458. color.toArray(array, 15);
  29459. this.geometry.attributes.color.needsUpdate = true;
  29460. return this;
  29461. }
  29462. dispose() {
  29463. this.geometry.dispose();
  29464. this.material.dispose();
  29465. }
  29466. }
  29467. class ShapePath {
  29468. constructor() {
  29469. this.type = 'ShapePath';
  29470. this.color = new Color();
  29471. this.subPaths = [];
  29472. this.currentPath = null;
  29473. }
  29474. moveTo(x, y) {
  29475. this.currentPath = new Path();
  29476. this.subPaths.push(this.currentPath);
  29477. this.currentPath.moveTo(x, y);
  29478. return this;
  29479. }
  29480. lineTo(x, y) {
  29481. this.currentPath.lineTo(x, y);
  29482. return this;
  29483. }
  29484. quadraticCurveTo(aCPx, aCPy, aX, aY) {
  29485. this.currentPath.quadraticCurveTo(aCPx, aCPy, aX, aY);
  29486. return this;
  29487. }
  29488. bezierCurveTo(aCP1x, aCP1y, aCP2x, aCP2y, aX, aY) {
  29489. this.currentPath.bezierCurveTo(aCP1x, aCP1y, aCP2x, aCP2y, aX, aY);
  29490. return this;
  29491. }
  29492. splineThru(pts) {
  29493. this.currentPath.splineThru(pts);
  29494. return this;
  29495. }
  29496. toShapes(isCCW) {
  29497. function toShapesNoHoles(inSubpaths) {
  29498. const shapes = [];
  29499. for (let i = 0, l = inSubpaths.length; i < l; i++) {
  29500. const tmpPath = inSubpaths[i];
  29501. const tmpShape = new Shape();
  29502. tmpShape.curves = tmpPath.curves;
  29503. shapes.push(tmpShape);
  29504. }
  29505. return shapes;
  29506. }
  29507. function isPointInsidePolygon(inPt, inPolygon) {
  29508. const polyLen = inPolygon.length;
  29509. // inPt on polygon contour => immediate success or
  29510. // toggling of inside/outside at every single! intersection point of an edge
  29511. // with the horizontal line through inPt, left of inPt
  29512. // not counting lowerY endpoints of edges and whole edges on that line
  29513. let inside = false;
  29514. for (let p = polyLen - 1, q = 0; q < polyLen; p = q++) {
  29515. let edgeLowPt = inPolygon[p];
  29516. let edgeHighPt = inPolygon[q];
  29517. let edgeDx = edgeHighPt.x - edgeLowPt.x;
  29518. let edgeDy = edgeHighPt.y - edgeLowPt.y;
  29519. if (Math.abs(edgeDy) > Number.EPSILON) {
  29520. // not parallel
  29521. if (edgeDy < 0) {
  29522. edgeLowPt = inPolygon[q];
  29523. edgeDx = -edgeDx;
  29524. edgeHighPt = inPolygon[p];
  29525. edgeDy = -edgeDy;
  29526. }
  29527. if (inPt.y < edgeLowPt.y || inPt.y > edgeHighPt.y) continue;
  29528. if (inPt.y === edgeLowPt.y) {
  29529. if (inPt.x === edgeLowPt.x) return true; // inPt is on contour ?
  29530. // continue; // no intersection or edgeLowPt => doesn't count !!!
  29531. } else {
  29532. const perpEdge = edgeDy * (inPt.x - edgeLowPt.x) - edgeDx * (inPt.y - edgeLowPt.y);
  29533. if (perpEdge === 0) return true; // inPt is on contour ?
  29534. if (perpEdge < 0) continue;
  29535. inside = !inside; // true intersection left of inPt
  29536. }
  29537. } else {
  29538. // parallel or collinear
  29539. if (inPt.y !== edgeLowPt.y) continue; // parallel
  29540. // edge lies on the same horizontal line as inPt
  29541. if (edgeHighPt.x <= inPt.x && inPt.x <= edgeLowPt.x || edgeLowPt.x <= inPt.x && inPt.x <= edgeHighPt.x) return true; // inPt: Point on contour !
  29542. // continue;
  29543. }
  29544. }
  29545. return inside;
  29546. }
  29547. const isClockWise = ShapeUtils.isClockWise;
  29548. const subPaths = this.subPaths;
  29549. if (subPaths.length === 0) return [];
  29550. let solid, tmpPath, tmpShape;
  29551. const shapes = [];
  29552. if (subPaths.length === 1) {
  29553. tmpPath = subPaths[0];
  29554. tmpShape = new Shape();
  29555. tmpShape.curves = tmpPath.curves;
  29556. shapes.push(tmpShape);
  29557. return shapes;
  29558. }
  29559. let holesFirst = !isClockWise(subPaths[0].getPoints());
  29560. holesFirst = isCCW ? !holesFirst : holesFirst;
  29561. // console.log("Holes first", holesFirst);
  29562. const betterShapeHoles = [];
  29563. const newShapes = [];
  29564. let newShapeHoles = [];
  29565. let mainIdx = 0;
  29566. let tmpPoints;
  29567. newShapes[mainIdx] = undefined;
  29568. newShapeHoles[mainIdx] = [];
  29569. for (let i = 0, l = subPaths.length; i < l; i++) {
  29570. tmpPath = subPaths[i];
  29571. tmpPoints = tmpPath.getPoints();
  29572. solid = isClockWise(tmpPoints);
  29573. solid = isCCW ? !solid : solid;
  29574. if (solid) {
  29575. if (!holesFirst && newShapes[mainIdx]) mainIdx++;
  29576. newShapes[mainIdx] = {
  29577. s: new Shape(),
  29578. p: tmpPoints
  29579. };
  29580. newShapes[mainIdx].s.curves = tmpPath.curves;
  29581. if (holesFirst) mainIdx++;
  29582. newShapeHoles[mainIdx] = [];
  29583. //console.log('cw', i);
  29584. } else {
  29585. newShapeHoles[mainIdx].push({
  29586. h: tmpPath,
  29587. p: tmpPoints[0]
  29588. });
  29589. //console.log('ccw', i);
  29590. }
  29591. }
  29592. // only Holes? -> probably all Shapes with wrong orientation
  29593. if (!newShapes[0]) return toShapesNoHoles(subPaths);
  29594. if (newShapes.length > 1) {
  29595. let ambiguous = false;
  29596. let toChange = 0;
  29597. for (let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx++) {
  29598. betterShapeHoles[sIdx] = [];
  29599. }
  29600. for (let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx++) {
  29601. const sho = newShapeHoles[sIdx];
  29602. for (let hIdx = 0; hIdx < sho.length; hIdx++) {
  29603. const ho = sho[hIdx];
  29604. let hole_unassigned = true;
  29605. for (let s2Idx = 0; s2Idx < newShapes.length; s2Idx++) {
  29606. if (isPointInsidePolygon(ho.p, newShapes[s2Idx].p)) {
  29607. if (sIdx !== s2Idx) toChange++;
  29608. if (hole_unassigned) {
  29609. hole_unassigned = false;
  29610. betterShapeHoles[s2Idx].push(ho);
  29611. } else {
  29612. ambiguous = true;
  29613. }
  29614. }
  29615. }
  29616. if (hole_unassigned) {
  29617. betterShapeHoles[sIdx].push(ho);
  29618. }
  29619. }
  29620. }
  29621. if (toChange > 0 && ambiguous === false) {
  29622. newShapeHoles = betterShapeHoles;
  29623. }
  29624. }
  29625. let tmpHoles;
  29626. for (let i = 0, il = newShapes.length; i < il; i++) {
  29627. tmpShape = newShapes[i].s;
  29628. shapes.push(tmpShape);
  29629. tmpHoles = newShapeHoles[i];
  29630. for (let j = 0, jl = tmpHoles.length; j < jl; j++) {
  29631. tmpShape.holes.push(tmpHoles[j].h);
  29632. }
  29633. }
  29634. //console.log("shape", shapes);
  29635. return shapes;
  29636. }
  29637. }
  29638. // Fast Half Float Conversions, http://www.fox-toolkit.org/ftp/fasthalffloatconversion.pdf
  29639. const _tables = /*@__PURE__*/_generateTables();
  29640. function _generateTables() {
  29641. // float32 to float16 helpers
  29642. const buffer = new ArrayBuffer(4);
  29643. const floatView = new Float32Array(buffer);
  29644. const uint32View = new Uint32Array(buffer);
  29645. const baseTable = new Uint32Array(512);
  29646. const shiftTable = new Uint32Array(512);
  29647. for (let i = 0; i < 256; ++i) {
  29648. const e = i - 127;
  29649. // very small number (0, -0)
  29650. if (e < -27) {
  29651. baseTable[i] = 0x0000;
  29652. baseTable[i | 0x100] = 0x8000;
  29653. shiftTable[i] = 24;
  29654. shiftTable[i | 0x100] = 24;
  29655. // small number (denorm)
  29656. } else if (e < -14) {
  29657. baseTable[i] = 0x0400 >> -e - 14;
  29658. baseTable[i | 0x100] = 0x0400 >> -e - 14 | 0x8000;
  29659. shiftTable[i] = -e - 1;
  29660. shiftTable[i | 0x100] = -e - 1;
  29661. // normal number
  29662. } else if (e <= 15) {
  29663. baseTable[i] = e + 15 << 10;
  29664. baseTable[i | 0x100] = e + 15 << 10 | 0x8000;
  29665. shiftTable[i] = 13;
  29666. shiftTable[i | 0x100] = 13;
  29667. // large number (Infinity, -Infinity)
  29668. } else if (e < 128) {
  29669. baseTable[i] = 0x7c00;
  29670. baseTable[i | 0x100] = 0xfc00;
  29671. shiftTable[i] = 24;
  29672. shiftTable[i | 0x100] = 24;
  29673. // stay (NaN, Infinity, -Infinity)
  29674. } else {
  29675. baseTable[i] = 0x7c00;
  29676. baseTable[i | 0x100] = 0xfc00;
  29677. shiftTable[i] = 13;
  29678. shiftTable[i | 0x100] = 13;
  29679. }
  29680. }
  29681. // float16 to float32 helpers
  29682. const mantissaTable = new Uint32Array(2048);
  29683. const exponentTable = new Uint32Array(64);
  29684. const offsetTable = new Uint32Array(64);
  29685. for (let i = 1; i < 1024; ++i) {
  29686. let m = i << 13; // zero pad mantissa bits
  29687. let e = 0; // zero exponent
  29688. // normalized
  29689. while ((m & 0x00800000) === 0) {
  29690. m <<= 1;
  29691. e -= 0x00800000; // decrement exponent
  29692. }
  29693. m &= ~0x00800000; // clear leading 1 bit
  29694. e += 0x38800000; // adjust bias
  29695. mantissaTable[i] = m | e;
  29696. }
  29697. for (let i = 1024; i < 2048; ++i) {
  29698. mantissaTable[i] = 0x38000000 + (i - 1024 << 13);
  29699. }
  29700. for (let i = 1; i < 31; ++i) {
  29701. exponentTable[i] = i << 23;
  29702. }
  29703. exponentTable[31] = 0x47800000;
  29704. exponentTable[32] = 0x80000000;
  29705. for (let i = 33; i < 63; ++i) {
  29706. exponentTable[i] = 0x80000000 + (i - 32 << 23);
  29707. }
  29708. exponentTable[63] = 0xc7800000;
  29709. for (let i = 1; i < 64; ++i) {
  29710. if (i !== 32) {
  29711. offsetTable[i] = 1024;
  29712. }
  29713. }
  29714. return {
  29715. floatView: floatView,
  29716. uint32View: uint32View,
  29717. baseTable: baseTable,
  29718. shiftTable: shiftTable,
  29719. mantissaTable: mantissaTable,
  29720. exponentTable: exponentTable,
  29721. offsetTable: offsetTable
  29722. };
  29723. }
  29724. // float32 to float16
  29725. function toHalfFloat(val) {
  29726. if (Math.abs(val) > 65504) console.warn('THREE.DataUtils.toHalfFloat(): Value out of range.');
  29727. val = clamp(val, -65504, 65504);
  29728. _tables.floatView[0] = val;
  29729. const f = _tables.uint32View[0];
  29730. const e = f >> 23 & 0x1ff;
  29731. return _tables.baseTable[e] + ((f & 0x007fffff) >> _tables.shiftTable[e]);
  29732. }
  29733. // float16 to float32
  29734. function fromHalfFloat(val) {
  29735. const m = val >> 10;
  29736. _tables.uint32View[0] = _tables.mantissaTable[_tables.offsetTable[m] + (val & 0x3ff)] + _tables.exponentTable[m];
  29737. return _tables.floatView[0];
  29738. }
  29739. var DataUtils = /*#__PURE__*/Object.freeze({
  29740. __proto__: null,
  29741. toHalfFloat: toHalfFloat,
  29742. fromHalfFloat: fromHalfFloat
  29743. });
  29744. // r134, d65e0af06644fe5a84a6fc0e372f4318f95a04c0
  29745. function ImmediateRenderObject() {
  29746. console.error('THREE.ImmediateRenderObject has been removed.');
  29747. }
  29748. // r138, 48b05d3500acc084df50be9b4c90781ad9b8cb17
  29749. class WebGLMultisampleRenderTarget extends WebGLRenderTarget {
  29750. constructor(width, height, options) {
  29751. console.error('THREE.WebGLMultisampleRenderTarget has been removed. Use a normal render target and set the "samples" property to greater 0 to enable multisampling.');
  29752. super(width, height, options);
  29753. this.samples = 4;
  29754. }
  29755. }
  29756. // r138, f9cd9cab03b7b64244e304900a3a2eeaa3a588ce
  29757. class DataTexture2DArray extends DataArrayTexture {
  29758. constructor(data, width, height, depth) {
  29759. console.warn('THREE.DataTexture2DArray has been renamed to DataArrayTexture.');
  29760. super(data, width, height, depth);
  29761. }
  29762. }
  29763. // r138, f9cd9cab03b7b64244e304900a3a2eeaa3a588ce
  29764. class DataTexture3D extends Data3DTexture {
  29765. constructor(data, width, height, depth) {
  29766. console.warn('THREE.DataTexture3D has been renamed to Data3DTexture.');
  29767. super(data, width, height, depth);
  29768. }
  29769. }
  29770. // r144
  29771. class BoxBufferGeometry extends BoxGeometry {
  29772. constructor(width, height, depth, widthSegments, heightSegments, depthSegments) {
  29773. console.warn('THREE.BoxBufferGeometry has been renamed to THREE.BoxGeometry.');
  29774. super(width, height, depth, widthSegments, heightSegments, depthSegments);
  29775. }
  29776. }
  29777. // r144
  29778. class CapsuleBufferGeometry extends CapsuleGeometry {
  29779. constructor(radius, length, capSegments, radialSegments) {
  29780. console.warn('THREE.CapsuleBufferGeometry has been renamed to THREE.CapsuleGeometry.');
  29781. super(radius, length, capSegments, radialSegments);
  29782. }
  29783. }
  29784. // r144
  29785. class CircleBufferGeometry extends CircleGeometry {
  29786. constructor(radius, segments, thetaStart, thetaLength) {
  29787. console.warn('THREE.CircleBufferGeometry has been renamed to THREE.CircleGeometry.');
  29788. super(radius, segments, thetaStart, thetaLength);
  29789. }
  29790. }
  29791. // r144
  29792. class ConeBufferGeometry extends ConeGeometry {
  29793. constructor(radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength) {
  29794. console.warn('THREE.ConeBufferGeometry has been renamed to THREE.ConeGeometry.');
  29795. super(radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength);
  29796. }
  29797. }
  29798. // r144
  29799. class CylinderBufferGeometry extends CylinderGeometry {
  29800. constructor(radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength) {
  29801. console.warn('THREE.CylinderBufferGeometry has been renamed to THREE.CylinderGeometry.');
  29802. super(radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength);
  29803. }
  29804. }
  29805. // r144
  29806. class DodecahedronBufferGeometry extends DodecahedronGeometry {
  29807. constructor(radius, detail) {
  29808. console.warn('THREE.DodecahedronBufferGeometry has been renamed to THREE.DodecahedronGeometry.');
  29809. super(radius, detail);
  29810. }
  29811. }
  29812. // r144
  29813. class ExtrudeBufferGeometry extends ExtrudeGeometry {
  29814. constructor(shapes, options) {
  29815. console.warn('THREE.ExtrudeBufferGeometry has been renamed to THREE.ExtrudeGeometry.');
  29816. super(shapes, options);
  29817. }
  29818. }
  29819. // r144
  29820. class IcosahedronBufferGeometry extends IcosahedronGeometry {
  29821. constructor(radius, detail) {
  29822. console.warn('THREE.IcosahedronBufferGeometry has been renamed to THREE.IcosahedronGeometry.');
  29823. super(radius, detail);
  29824. }
  29825. }
  29826. // r144
  29827. class LatheBufferGeometry extends LatheGeometry {
  29828. constructor(points, segments, phiStart, phiLength) {
  29829. console.warn('THREE.LatheBufferGeometry has been renamed to THREE.LatheGeometry.');
  29830. super(points, segments, phiStart, phiLength);
  29831. }
  29832. }
  29833. // r144
  29834. class OctahedronBufferGeometry extends OctahedronGeometry {
  29835. constructor(radius, detail) {
  29836. console.warn('THREE.OctahedronBufferGeometry has been renamed to THREE.OctahedronGeometry.');
  29837. super(radius, detail);
  29838. }
  29839. }
  29840. // r144
  29841. class PlaneBufferGeometry extends PlaneGeometry {
  29842. constructor(width, height, widthSegments, heightSegments) {
  29843. console.warn('THREE.PlaneBufferGeometry has been renamed to THREE.PlaneGeometry.');
  29844. super(width, height, widthSegments, heightSegments);
  29845. }
  29846. }
  29847. // r144
  29848. class PolyhedronBufferGeometry extends PolyhedronGeometry {
  29849. constructor(vertices, indices, radius, detail) {
  29850. console.warn('THREE.PolyhedronBufferGeometry has been renamed to THREE.PolyhedronGeometry.');
  29851. super(vertices, indices, radius, detail);
  29852. }
  29853. }
  29854. // r144
  29855. class RingBufferGeometry extends RingGeometry {
  29856. constructor(innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength) {
  29857. console.warn('THREE.RingBufferGeometry has been renamed to THREE.RingGeometry.');
  29858. super(innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength);
  29859. }
  29860. }
  29861. // r144
  29862. class ShapeBufferGeometry extends ShapeGeometry {
  29863. constructor(shapes, curveSegments) {
  29864. console.warn('THREE.ShapeBufferGeometry has been renamed to THREE.ShapeGeometry.');
  29865. super(shapes, curveSegments);
  29866. }
  29867. }
  29868. // r144
  29869. class SphereBufferGeometry extends SphereGeometry {
  29870. constructor(radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength) {
  29871. console.warn('THREE.SphereBufferGeometry has been renamed to THREE.SphereGeometry.');
  29872. super(radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength);
  29873. }
  29874. }
  29875. // r144
  29876. class TetrahedronBufferGeometry extends TetrahedronGeometry {
  29877. constructor(radius, detail) {
  29878. console.warn('THREE.TetrahedronBufferGeometry has been renamed to THREE.TetrahedronGeometry.');
  29879. super(radius, detail);
  29880. }
  29881. }
  29882. // r144
  29883. class TorusBufferGeometry extends TorusGeometry {
  29884. constructor(radius, tube, radialSegments, tubularSegments, arc) {
  29885. console.warn('THREE.TorusBufferGeometry has been renamed to THREE.TorusGeometry.');
  29886. super(radius, tube, radialSegments, tubularSegments, arc);
  29887. }
  29888. }
  29889. // r144
  29890. class TorusKnotBufferGeometry extends TorusKnotGeometry {
  29891. constructor(radius, tube, tubularSegments, radialSegments, p, q) {
  29892. console.warn('THREE.TorusKnotBufferGeometry has been renamed to THREE.TorusKnotGeometry.');
  29893. super(radius, tube, tubularSegments, radialSegments, p, q);
  29894. }
  29895. }
  29896. // r144
  29897. class TubeBufferGeometry extends TubeGeometry {
  29898. constructor(path, tubularSegments, radius, radialSegments, closed) {
  29899. console.warn('THREE.TubeBufferGeometry has been renamed to THREE.TubeGeometry.');
  29900. super(path, tubularSegments, radius, radialSegments, closed);
  29901. }
  29902. }
  29903. if (typeof __THREE_DEVTOOLS__ !== 'undefined') {
  29904. __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent('register', {
  29905. detail: {
  29906. revision: REVISION
  29907. }
  29908. }));
  29909. }
  29910. if (typeof window !== 'undefined') {
  29911. if (window.__THREE__) {
  29912. console.warn('WARNING: Multiple instances of Three.js being imported.');
  29913. } else {
  29914. window.__THREE__ = REVISION;
  29915. }
  29916. }
  29917. exports.ACESFilmicToneMapping = ACESFilmicToneMapping;
  29918. exports.AddEquation = AddEquation;
  29919. exports.AddOperation = AddOperation;
  29920. exports.AdditiveAnimationBlendMode = AdditiveAnimationBlendMode;
  29921. exports.AdditiveBlending = AdditiveBlending;
  29922. exports.AlphaFormat = AlphaFormat;
  29923. exports.AlwaysDepth = AlwaysDepth;
  29924. exports.AlwaysStencilFunc = AlwaysStencilFunc;
  29925. exports.AmbientLight = AmbientLight;
  29926. exports.AmbientLightProbe = AmbientLightProbe;
  29927. exports.AnimationClip = AnimationClip;
  29928. exports.AnimationLoader = AnimationLoader;
  29929. exports.AnimationMixer = AnimationMixer;
  29930. exports.AnimationObjectGroup = AnimationObjectGroup;
  29931. exports.AnimationUtils = AnimationUtils;
  29932. exports.ArcCurve = ArcCurve;
  29933. exports.ArrayCamera = ArrayCamera;
  29934. exports.ArrowHelper = ArrowHelper;
  29935. exports.Audio = Audio;
  29936. exports.AudioAnalyser = AudioAnalyser;
  29937. exports.AudioContext = AudioContext;
  29938. exports.AudioListener = AudioListener;
  29939. exports.AudioLoader = AudioLoader;
  29940. exports.AxesHelper = AxesHelper;
  29941. exports.BackSide = BackSide;
  29942. exports.BasicDepthPacking = BasicDepthPacking;
  29943. exports.BasicShadowMap = BasicShadowMap;
  29944. exports.Bone = Bone;
  29945. exports.BooleanKeyframeTrack = BooleanKeyframeTrack;
  29946. exports.Box2 = Box2;
  29947. exports.Box3 = Box3;
  29948. exports.Box3Helper = Box3Helper;
  29949. exports.BoxBufferGeometry = BoxBufferGeometry;
  29950. exports.BoxGeometry = BoxGeometry;
  29951. exports.BoxHelper = BoxHelper;
  29952. exports.BufferAttribute = BufferAttribute;
  29953. exports.BufferGeometry = BufferGeometry;
  29954. exports.BufferGeometryLoader = BufferGeometryLoader;
  29955. exports.ByteType = ByteType;
  29956. exports.Cache = Cache;
  29957. exports.Camera = Camera;
  29958. exports.CameraHelper = CameraHelper;
  29959. exports.CanvasTexture = CanvasTexture;
  29960. exports.CapsuleBufferGeometry = CapsuleBufferGeometry;
  29961. exports.CapsuleGeometry = CapsuleGeometry;
  29962. exports.CatmullRomCurve3 = CatmullRomCurve3;
  29963. exports.CineonToneMapping = CineonToneMapping;
  29964. exports.CircleBufferGeometry = CircleBufferGeometry;
  29965. exports.CircleGeometry = CircleGeometry;
  29966. exports.ClampToEdgeWrapping = ClampToEdgeWrapping;
  29967. exports.Clock = Clock;
  29968. exports.Color = Color;
  29969. exports.ColorKeyframeTrack = ColorKeyframeTrack;
  29970. exports.ColorManagement = ColorManagement;
  29971. exports.CompressedArrayTexture = CompressedArrayTexture;
  29972. exports.CompressedTexture = CompressedTexture;
  29973. exports.CompressedTextureLoader = CompressedTextureLoader;
  29974. exports.ConeBufferGeometry = ConeBufferGeometry;
  29975. exports.ConeGeometry = ConeGeometry;
  29976. exports.CubeCamera = CubeCamera;
  29977. exports.CubeReflectionMapping = CubeReflectionMapping;
  29978. exports.CubeRefractionMapping = CubeRefractionMapping;
  29979. exports.CubeTexture = CubeTexture;
  29980. exports.CubeTextureLoader = CubeTextureLoader;
  29981. exports.CubeUVReflectionMapping = CubeUVReflectionMapping;
  29982. exports.CubicBezierCurve = CubicBezierCurve;
  29983. exports.CubicBezierCurve3 = CubicBezierCurve3;
  29984. exports.CubicInterpolant = CubicInterpolant;
  29985. exports.CullFaceBack = CullFaceBack;
  29986. exports.CullFaceFront = CullFaceFront;
  29987. exports.CullFaceFrontBack = CullFaceFrontBack;
  29988. exports.CullFaceNone = CullFaceNone;
  29989. exports.Curve = Curve;
  29990. exports.CurvePath = CurvePath;
  29991. exports.CustomBlending = CustomBlending;
  29992. exports.CustomToneMapping = CustomToneMapping;
  29993. exports.CylinderBufferGeometry = CylinderBufferGeometry;
  29994. exports.CylinderGeometry = CylinderGeometry;
  29995. exports.Cylindrical = Cylindrical;
  29996. exports.Data3DTexture = Data3DTexture;
  29997. exports.DataArrayTexture = DataArrayTexture;
  29998. exports.DataTexture = DataTexture;
  29999. exports.DataTexture2DArray = DataTexture2DArray;
  30000. exports.DataTexture3D = DataTexture3D;
  30001. exports.DataTextureLoader = DataTextureLoader;
  30002. exports.DataUtils = DataUtils;
  30003. exports.DecrementStencilOp = DecrementStencilOp;
  30004. exports.DecrementWrapStencilOp = DecrementWrapStencilOp;
  30005. exports.DefaultLoadingManager = DefaultLoadingManager;
  30006. exports.DepthFormat = DepthFormat;
  30007. exports.DepthStencilFormat = DepthStencilFormat;
  30008. exports.DepthTexture = DepthTexture;
  30009. exports.DirectionalLight = DirectionalLight;
  30010. exports.DirectionalLightHelper = DirectionalLightHelper;
  30011. exports.DiscreteInterpolant = DiscreteInterpolant;
  30012. exports.DodecahedronBufferGeometry = DodecahedronBufferGeometry;
  30013. exports.DodecahedronGeometry = DodecahedronGeometry;
  30014. exports.DoubleSide = DoubleSide;
  30015. exports.DstAlphaFactor = DstAlphaFactor;
  30016. exports.DstColorFactor = DstColorFactor;
  30017. exports.DynamicCopyUsage = DynamicCopyUsage;
  30018. exports.DynamicDrawUsage = DynamicDrawUsage;
  30019. exports.DynamicReadUsage = DynamicReadUsage;
  30020. exports.EdgesGeometry = EdgesGeometry;
  30021. exports.EllipseCurve = EllipseCurve;
  30022. exports.EqualDepth = EqualDepth;
  30023. exports.EqualStencilFunc = EqualStencilFunc;
  30024. exports.EquirectangularReflectionMapping = EquirectangularReflectionMapping;
  30025. exports.EquirectangularRefractionMapping = EquirectangularRefractionMapping;
  30026. exports.Euler = Euler;
  30027. exports.EventDispatcher = EventDispatcher;
  30028. exports.ExtrudeBufferGeometry = ExtrudeBufferGeometry;
  30029. exports.ExtrudeGeometry = ExtrudeGeometry;
  30030. exports.FileLoader = FileLoader;
  30031. exports.Float16BufferAttribute = Float16BufferAttribute;
  30032. exports.Float32BufferAttribute = Float32BufferAttribute;
  30033. exports.Float64BufferAttribute = Float64BufferAttribute;
  30034. exports.FloatType = FloatType;
  30035. exports.Fog = Fog;
  30036. exports.FogExp2 = FogExp2;
  30037. exports.FramebufferTexture = FramebufferTexture;
  30038. exports.FrontSide = FrontSide;
  30039. exports.Frustum = Frustum;
  30040. exports.GLBufferAttribute = GLBufferAttribute;
  30041. exports.GLSL1 = GLSL1;
  30042. exports.GLSL3 = GLSL3;
  30043. exports.GreaterDepth = GreaterDepth;
  30044. exports.GreaterEqualDepth = GreaterEqualDepth;
  30045. exports.GreaterEqualStencilFunc = GreaterEqualStencilFunc;
  30046. exports.GreaterStencilFunc = GreaterStencilFunc;
  30047. exports.GridHelper = GridHelper;
  30048. exports.Group = Group;
  30049. exports.HalfFloatType = HalfFloatType;
  30050. exports.HemisphereLight = HemisphereLight;
  30051. exports.HemisphereLightHelper = HemisphereLightHelper;
  30052. exports.HemisphereLightProbe = HemisphereLightProbe;
  30053. exports.IcosahedronBufferGeometry = IcosahedronBufferGeometry;
  30054. exports.IcosahedronGeometry = IcosahedronGeometry;
  30055. exports.ImageBitmapLoader = ImageBitmapLoader;
  30056. exports.ImageLoader = ImageLoader;
  30057. exports.ImageUtils = ImageUtils;
  30058. exports.ImmediateRenderObject = ImmediateRenderObject;
  30059. exports.IncrementStencilOp = IncrementStencilOp;
  30060. exports.IncrementWrapStencilOp = IncrementWrapStencilOp;
  30061. exports.InstancedBufferAttribute = InstancedBufferAttribute;
  30062. exports.InstancedBufferGeometry = InstancedBufferGeometry;
  30063. exports.InstancedInterleavedBuffer = InstancedInterleavedBuffer;
  30064. exports.InstancedMesh = InstancedMesh;
  30065. exports.Int16BufferAttribute = Int16BufferAttribute;
  30066. exports.Int32BufferAttribute = Int32BufferAttribute;
  30067. exports.Int8BufferAttribute = Int8BufferAttribute;
  30068. exports.IntType = IntType;
  30069. exports.InterleavedBuffer = InterleavedBuffer;
  30070. exports.InterleavedBufferAttribute = InterleavedBufferAttribute;
  30071. exports.Interpolant = Interpolant;
  30072. exports.InterpolateDiscrete = InterpolateDiscrete;
  30073. exports.InterpolateLinear = InterpolateLinear;
  30074. exports.InterpolateSmooth = InterpolateSmooth;
  30075. exports.InvertStencilOp = InvertStencilOp;
  30076. exports.KeepStencilOp = KeepStencilOp;
  30077. exports.KeyframeTrack = KeyframeTrack;
  30078. exports.LOD = LOD;
  30079. exports.LatheBufferGeometry = LatheBufferGeometry;
  30080. exports.LatheGeometry = LatheGeometry;
  30081. exports.Layers = Layers;
  30082. exports.LessDepth = LessDepth;
  30083. exports.LessEqualDepth = LessEqualDepth;
  30084. exports.LessEqualStencilFunc = LessEqualStencilFunc;
  30085. exports.LessStencilFunc = LessStencilFunc;
  30086. exports.Light = Light;
  30087. exports.LightProbe = LightProbe;
  30088. exports.Line = Line;
  30089. exports.Line3 = Line3;
  30090. exports.LineBasicMaterial = LineBasicMaterial;
  30091. exports.LineCurve = LineCurve;
  30092. exports.LineCurve3 = LineCurve3;
  30093. exports.LineDashedMaterial = LineDashedMaterial;
  30094. exports.LineLoop = LineLoop;
  30095. exports.LineSegments = LineSegments;
  30096. exports.LinearEncoding = LinearEncoding;
  30097. exports.LinearFilter = LinearFilter;
  30098. exports.LinearInterpolant = LinearInterpolant;
  30099. exports.LinearMipMapLinearFilter = LinearMipMapLinearFilter;
  30100. exports.LinearMipMapNearestFilter = LinearMipMapNearestFilter;
  30101. exports.LinearMipmapLinearFilter = LinearMipmapLinearFilter;
  30102. exports.LinearMipmapNearestFilter = LinearMipmapNearestFilter;
  30103. exports.LinearSRGBColorSpace = LinearSRGBColorSpace;
  30104. exports.LinearToneMapping = LinearToneMapping;
  30105. exports.Loader = Loader;
  30106. exports.LoaderUtils = LoaderUtils;
  30107. exports.LoadingManager = LoadingManager;
  30108. exports.LoopOnce = LoopOnce;
  30109. exports.LoopPingPong = LoopPingPong;
  30110. exports.LoopRepeat = LoopRepeat;
  30111. exports.LuminanceAlphaFormat = LuminanceAlphaFormat;
  30112. exports.LuminanceFormat = LuminanceFormat;
  30113. exports.MOUSE = MOUSE;
  30114. exports.Material = Material;
  30115. exports.MaterialLoader = MaterialLoader;
  30116. exports.MathUtils = MathUtils;
  30117. exports.Matrix3 = Matrix3;
  30118. exports.Matrix4 = Matrix4;
  30119. exports.MaxEquation = MaxEquation;
  30120. exports.Mesh = Mesh;
  30121. exports.MeshBasicMaterial = MeshBasicMaterial;
  30122. exports.MeshDepthMaterial = MeshDepthMaterial;
  30123. exports.MeshDistanceMaterial = MeshDistanceMaterial;
  30124. exports.MeshLambertMaterial = MeshLambertMaterial;
  30125. exports.MeshMatcapMaterial = MeshMatcapMaterial;
  30126. exports.MeshNormalMaterial = MeshNormalMaterial;
  30127. exports.MeshPhongMaterial = MeshPhongMaterial;
  30128. exports.MeshPhysicalMaterial = MeshPhysicalMaterial;
  30129. exports.MeshStandardMaterial = MeshStandardMaterial;
  30130. exports.MeshToonMaterial = MeshToonMaterial;
  30131. exports.MinEquation = MinEquation;
  30132. exports.MirroredRepeatWrapping = MirroredRepeatWrapping;
  30133. exports.MixOperation = MixOperation;
  30134. exports.MultiplyBlending = MultiplyBlending;
  30135. exports.MultiplyOperation = MultiplyOperation;
  30136. exports.NearestFilter = NearestFilter;
  30137. exports.NearestMipMapLinearFilter = NearestMipMapLinearFilter;
  30138. exports.NearestMipMapNearestFilter = NearestMipMapNearestFilter;
  30139. exports.NearestMipmapLinearFilter = NearestMipmapLinearFilter;
  30140. exports.NearestMipmapNearestFilter = NearestMipmapNearestFilter;
  30141. exports.NeverDepth = NeverDepth;
  30142. exports.NeverStencilFunc = NeverStencilFunc;
  30143. exports.NoBlending = NoBlending;
  30144. exports.NoColorSpace = NoColorSpace;
  30145. exports.NoToneMapping = NoToneMapping;
  30146. exports.NormalAnimationBlendMode = NormalAnimationBlendMode;
  30147. exports.NormalBlending = NormalBlending;
  30148. exports.NotEqualDepth = NotEqualDepth;
  30149. exports.NotEqualStencilFunc = NotEqualStencilFunc;
  30150. exports.NumberKeyframeTrack = NumberKeyframeTrack;
  30151. exports.Object3D = Object3D;
  30152. exports.ObjectLoader = ObjectLoader;
  30153. exports.ObjectSpaceNormalMap = ObjectSpaceNormalMap;
  30154. exports.OctahedronBufferGeometry = OctahedronBufferGeometry;
  30155. exports.OctahedronGeometry = OctahedronGeometry;
  30156. exports.OneFactor = OneFactor;
  30157. exports.OneMinusDstAlphaFactor = OneMinusDstAlphaFactor;
  30158. exports.OneMinusDstColorFactor = OneMinusDstColorFactor;
  30159. exports.OneMinusSrcAlphaFactor = OneMinusSrcAlphaFactor;
  30160. exports.OneMinusSrcColorFactor = OneMinusSrcColorFactor;
  30161. exports.OrthographicCamera = OrthographicCamera;
  30162. exports.PCFShadowMap = PCFShadowMap;
  30163. exports.PCFSoftShadowMap = PCFSoftShadowMap;
  30164. exports.PMREMGenerator = PMREMGenerator;
  30165. exports.Path = Path;
  30166. exports.PerspectiveCamera = PerspectiveCamera;
  30167. exports.Plane = Plane;
  30168. exports.PlaneBufferGeometry = PlaneBufferGeometry;
  30169. exports.PlaneGeometry = PlaneGeometry;
  30170. exports.PlaneHelper = PlaneHelper;
  30171. exports.PointLight = PointLight;
  30172. exports.PointLightHelper = PointLightHelper;
  30173. exports.Points = Points;
  30174. exports.PointsMaterial = PointsMaterial;
  30175. exports.PolarGridHelper = PolarGridHelper;
  30176. exports.PolyhedronBufferGeometry = PolyhedronBufferGeometry;
  30177. exports.PolyhedronGeometry = PolyhedronGeometry;
  30178. exports.PositionalAudio = PositionalAudio;
  30179. exports.PropertyBinding = PropertyBinding;
  30180. exports.PropertyMixer = PropertyMixer;
  30181. exports.QuadraticBezierCurve = QuadraticBezierCurve;
  30182. exports.QuadraticBezierCurve3 = QuadraticBezierCurve3;
  30183. exports.Quaternion = Quaternion;
  30184. exports.QuaternionKeyframeTrack = QuaternionKeyframeTrack;
  30185. exports.QuaternionLinearInterpolant = QuaternionLinearInterpolant;
  30186. exports.REVISION = REVISION;
  30187. exports.RGBADepthPacking = RGBADepthPacking;
  30188. exports.RGBAFormat = RGBAFormat;
  30189. exports.RGBAIntegerFormat = RGBAIntegerFormat;
  30190. exports.RGBA_ASTC_10x10_Format = RGBA_ASTC_10x10_Format;
  30191. exports.RGBA_ASTC_10x5_Format = RGBA_ASTC_10x5_Format;
  30192. exports.RGBA_ASTC_10x6_Format = RGBA_ASTC_10x6_Format;
  30193. exports.RGBA_ASTC_10x8_Format = RGBA_ASTC_10x8_Format;
  30194. exports.RGBA_ASTC_12x10_Format = RGBA_ASTC_12x10_Format;
  30195. exports.RGBA_ASTC_12x12_Format = RGBA_ASTC_12x12_Format;
  30196. exports.RGBA_ASTC_4x4_Format = RGBA_ASTC_4x4_Format;
  30197. exports.RGBA_ASTC_5x4_Format = RGBA_ASTC_5x4_Format;
  30198. exports.RGBA_ASTC_5x5_Format = RGBA_ASTC_5x5_Format;
  30199. exports.RGBA_ASTC_6x5_Format = RGBA_ASTC_6x5_Format;
  30200. exports.RGBA_ASTC_6x6_Format = RGBA_ASTC_6x6_Format;
  30201. exports.RGBA_ASTC_8x5_Format = RGBA_ASTC_8x5_Format;
  30202. exports.RGBA_ASTC_8x6_Format = RGBA_ASTC_8x6_Format;
  30203. exports.RGBA_ASTC_8x8_Format = RGBA_ASTC_8x8_Format;
  30204. exports.RGBA_BPTC_Format = RGBA_BPTC_Format;
  30205. exports.RGBA_ETC2_EAC_Format = RGBA_ETC2_EAC_Format;
  30206. exports.RGBA_PVRTC_2BPPV1_Format = RGBA_PVRTC_2BPPV1_Format;
  30207. exports.RGBA_PVRTC_4BPPV1_Format = RGBA_PVRTC_4BPPV1_Format;
  30208. exports.RGBA_S3TC_DXT1_Format = RGBA_S3TC_DXT1_Format;
  30209. exports.RGBA_S3TC_DXT3_Format = RGBA_S3TC_DXT3_Format;
  30210. exports.RGBA_S3TC_DXT5_Format = RGBA_S3TC_DXT5_Format;
  30211. exports.RGBFormat = RGBFormat;
  30212. exports.RGB_ETC1_Format = RGB_ETC1_Format;
  30213. exports.RGB_ETC2_Format = RGB_ETC2_Format;
  30214. exports.RGB_PVRTC_2BPPV1_Format = RGB_PVRTC_2BPPV1_Format;
  30215. exports.RGB_PVRTC_4BPPV1_Format = RGB_PVRTC_4BPPV1_Format;
  30216. exports.RGB_S3TC_DXT1_Format = RGB_S3TC_DXT1_Format;
  30217. exports.RGFormat = RGFormat;
  30218. exports.RGIntegerFormat = RGIntegerFormat;
  30219. exports.RawShaderMaterial = RawShaderMaterial;
  30220. exports.Ray = Ray;
  30221. exports.Raycaster = Raycaster;
  30222. exports.RectAreaLight = RectAreaLight;
  30223. exports.RedFormat = RedFormat;
  30224. exports.RedIntegerFormat = RedIntegerFormat;
  30225. exports.ReinhardToneMapping = ReinhardToneMapping;
  30226. exports.RepeatWrapping = RepeatWrapping;
  30227. exports.ReplaceStencilOp = ReplaceStencilOp;
  30228. exports.ReverseSubtractEquation = ReverseSubtractEquation;
  30229. exports.RingBufferGeometry = RingBufferGeometry;
  30230. exports.RingGeometry = RingGeometry;
  30231. exports.SRGBColorSpace = SRGBColorSpace;
  30232. exports.Scene = Scene;
  30233. exports.ShaderChunk = ShaderChunk;
  30234. exports.ShaderLib = ShaderLib;
  30235. exports.ShaderMaterial = ShaderMaterial;
  30236. exports.ShadowMaterial = ShadowMaterial;
  30237. exports.Shape = Shape;
  30238. exports.ShapeBufferGeometry = ShapeBufferGeometry;
  30239. exports.ShapeGeometry = ShapeGeometry;
  30240. exports.ShapePath = ShapePath;
  30241. exports.ShapeUtils = ShapeUtils;
  30242. exports.ShortType = ShortType;
  30243. exports.Skeleton = Skeleton;
  30244. exports.SkeletonHelper = SkeletonHelper;
  30245. exports.SkinnedMesh = SkinnedMesh;
  30246. exports.Source = Source;
  30247. exports.Sphere = Sphere;
  30248. exports.SphereBufferGeometry = SphereBufferGeometry;
  30249. exports.SphereGeometry = SphereGeometry;
  30250. exports.Spherical = Spherical;
  30251. exports.SphericalHarmonics3 = SphericalHarmonics3;
  30252. exports.SplineCurve = SplineCurve;
  30253. exports.SpotLight = SpotLight;
  30254. exports.SpotLightHelper = SpotLightHelper;
  30255. exports.Sprite = Sprite;
  30256. exports.SpriteMaterial = SpriteMaterial;
  30257. exports.SrcAlphaFactor = SrcAlphaFactor;
  30258. exports.SrcAlphaSaturateFactor = SrcAlphaSaturateFactor;
  30259. exports.SrcColorFactor = SrcColorFactor;
  30260. exports.StaticCopyUsage = StaticCopyUsage;
  30261. exports.StaticDrawUsage = StaticDrawUsage;
  30262. exports.StaticReadUsage = StaticReadUsage;
  30263. exports.StereoCamera = StereoCamera;
  30264. exports.StreamCopyUsage = StreamCopyUsage;
  30265. exports.StreamDrawUsage = StreamDrawUsage;
  30266. exports.StreamReadUsage = StreamReadUsage;
  30267. exports.StringKeyframeTrack = StringKeyframeTrack;
  30268. exports.SubtractEquation = SubtractEquation;
  30269. exports.SubtractiveBlending = SubtractiveBlending;
  30270. exports.TOUCH = TOUCH;
  30271. exports.TangentSpaceNormalMap = TangentSpaceNormalMap;
  30272. exports.TetrahedronBufferGeometry = TetrahedronBufferGeometry;
  30273. exports.TetrahedronGeometry = TetrahedronGeometry;
  30274. exports.Texture = Texture;
  30275. exports.TextureLoader = TextureLoader;
  30276. exports.TorusBufferGeometry = TorusBufferGeometry;
  30277. exports.TorusGeometry = TorusGeometry;
  30278. exports.TorusKnotBufferGeometry = TorusKnotBufferGeometry;
  30279. exports.TorusKnotGeometry = TorusKnotGeometry;
  30280. exports.Triangle = Triangle;
  30281. exports.TriangleFanDrawMode = TriangleFanDrawMode;
  30282. exports.TriangleStripDrawMode = TriangleStripDrawMode;
  30283. exports.TrianglesDrawMode = TrianglesDrawMode;
  30284. exports.TubeBufferGeometry = TubeBufferGeometry;
  30285. exports.TubeGeometry = TubeGeometry;
  30286. exports.UVMapping = UVMapping;
  30287. exports.Uint16BufferAttribute = Uint16BufferAttribute;
  30288. exports.Uint32BufferAttribute = Uint32BufferAttribute;
  30289. exports.Uint8BufferAttribute = Uint8BufferAttribute;
  30290. exports.Uint8ClampedBufferAttribute = Uint8ClampedBufferAttribute;
  30291. exports.Uniform = Uniform;
  30292. exports.UniformsGroup = UniformsGroup;
  30293. exports.UniformsLib = UniformsLib;
  30294. exports.UniformsUtils = UniformsUtils;
  30295. exports.UnsignedByteType = UnsignedByteType;
  30296. exports.UnsignedInt248Type = UnsignedInt248Type;
  30297. exports.UnsignedIntType = UnsignedIntType;
  30298. exports.UnsignedShort4444Type = UnsignedShort4444Type;
  30299. exports.UnsignedShort5551Type = UnsignedShort5551Type;
  30300. exports.UnsignedShortType = UnsignedShortType;
  30301. exports.VSMShadowMap = VSMShadowMap;
  30302. exports.Vector2 = Vector2;
  30303. exports.Vector3 = Vector3;
  30304. exports.Vector4 = Vector4;
  30305. exports.VectorKeyframeTrack = VectorKeyframeTrack;
  30306. exports.VideoTexture = VideoTexture;
  30307. exports.WebGL1Renderer = WebGL1Renderer;
  30308. exports.WebGL3DRenderTarget = WebGL3DRenderTarget;
  30309. exports.WebGLArrayRenderTarget = WebGLArrayRenderTarget;
  30310. exports.WebGLCubeRenderTarget = WebGLCubeRenderTarget;
  30311. exports.WebGLMultipleRenderTargets = WebGLMultipleRenderTargets;
  30312. exports.WebGLMultisampleRenderTarget = WebGLMultisampleRenderTarget;
  30313. exports.WebGLRenderTarget = WebGLRenderTarget;
  30314. exports.WebGLRenderer = WebGLRenderer;
  30315. exports.WebGLUtils = WebGLUtils;
  30316. exports.WireframeGeometry = WireframeGeometry;
  30317. exports.WrapAroundEnding = WrapAroundEnding;
  30318. exports.ZeroCurvatureEnding = ZeroCurvatureEnding;
  30319. exports.ZeroFactor = ZeroFactor;
  30320. exports.ZeroSlopeEnding = ZeroSlopeEnding;
  30321. exports.ZeroStencilOp = ZeroStencilOp;
  30322. exports._SRGBAFormat = _SRGBAFormat;
  30323. exports.sRGBEncoding = sRGBEncoding;